diff options
379 files changed, 2280 insertions, 2200 deletions
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index ba255b7..c2b48b4 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -1588,9 +1588,10 @@ public: QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped); - QualType getSubstTemplateTypeParmType(QualType Replacement, - Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) const; + QualType + getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, + unsigned Index, + std::optional<unsigned> PackIndex) const; QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack); @@ -1653,7 +1654,7 @@ public: /// elsewhere, such as if the pattern contains a placeholder type or /// if this is the canonical type of another pack expansion type. QualType getPackExpansionType(QualType Pattern, - Optional<unsigned> NumExpansions, + std::optional<unsigned> NumExpansions, bool ExpectPackInType = true); QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, @@ -2172,10 +2173,10 @@ public: const IdentifierInfo *Name) const; TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, OverloadedOperatorKind Operator) const; - TemplateName getSubstTemplateTemplateParm(TemplateName replacement, - Decl *AssociatedDecl, - unsigned Index, - Optional<unsigned> PackIndex) const; + TemplateName + getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, + unsigned Index, + std::optional<unsigned> PackIndex) const; TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, @@ -2289,13 +2290,13 @@ public: CharUnits getTypeSizeInChars(QualType T) const; CharUnits getTypeSizeInChars(const Type *T) const; - Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { + std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { if (Ty->isIncompleteType() || Ty->isDependentType()) return std::nullopt; return getTypeSizeInChars(Ty); } - Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { + std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { return getTypeSizeInCharsIfKnown(QualType(Ty, 0)); } diff --git a/clang/include/clang/AST/ASTImporter.h b/clang/include/clang/AST/ASTImporter.h index 690ddce..39a4b77 100644 --- a/clang/include/clang/AST/ASTImporter.h +++ b/clang/include/clang/AST/ASTImporter.h @@ -368,7 +368,7 @@ class TypeSourceInfo; /// in the "to" context was imported. If it was not imported or of the wrong /// type a null value is returned. template <typename DeclT> - llvm::Optional<DeclT *> getImportedFromDecl(const DeclT *ToD) const { + std::optional<DeclT *> getImportedFromDecl(const DeclT *ToD) const { auto FromI = ImportedFromDecls.find(ToD); if (FromI == ImportedFromDecls.end()) return {}; @@ -565,7 +565,7 @@ class TypeSourceInfo; /// Return if import of the given declaration has failed and if yes /// the kind of the problem. This gives the first error encountered with /// the node. - llvm::Optional<ASTImportError> getImportDeclErrorIfAny(Decl *FromD) const; + std::optional<ASTImportError> getImportDeclErrorIfAny(Decl *FromD) const; /// Mark (newly) imported declaration with error. void setImportDeclError(Decl *From, ASTImportError Error); @@ -579,7 +579,7 @@ class TypeSourceInfo; /// F should be a field (or indirect field) declaration. /// \returns The index of the field in its parent context (starting from 0). /// On error `std::nullopt` is returned (parent context is non-record). - static llvm::Optional<unsigned> getFieldIndex(Decl *F); + static std::optional<unsigned> getFieldIndex(Decl *F); }; } // namespace clang diff --git a/clang/include/clang/AST/ASTImporterSharedState.h b/clang/include/clang/AST/ASTImporterSharedState.h index 519ed27..446d7ee 100644 --- a/clang/include/clang/AST/ASTImporterSharedState.h +++ b/clang/include/clang/AST/ASTImporterSharedState.h @@ -66,7 +66,7 @@ public: LookupTable->remove(ND); } - llvm::Optional<ASTImportError> getImportDeclErrorIfAny(Decl *ToD) const { + std::optional<ASTImportError> getImportDeclErrorIfAny(Decl *ToD) const { auto Pos = ImportErrors.find(ToD); if (Pos != ImportErrors.end()) return Pos->second; diff --git a/clang/include/clang/AST/ASTStructuralEquivalence.h b/clang/include/clang/AST/ASTStructuralEquivalence.h index 4550b50..af6edfd 100644 --- a/clang/include/clang/AST/ASTStructuralEquivalence.h +++ b/clang/include/clang/AST/ASTStructuralEquivalence.h @@ -115,7 +115,7 @@ struct StructuralEquivalenceContext { /// /// FIXME: This is needed by ASTImporter and ASTStructureEquivalence. It /// probably makes more sense in some other common place then here. - static llvm::Optional<unsigned> + static std::optional<unsigned> findUntaggedStructOrUnionIndex(RecordDecl *Anon); // If ErrorOnTagTypeMismatch is set, return the error, otherwise get the diff --git a/clang/include/clang/AST/AbstractBasicReader.h b/clang/include/clang/AST/AbstractBasicReader.h index ea28b4e..1f2797cc7 100644 --- a/clang/include/clang/AST/AbstractBasicReader.h +++ b/clang/include/clang/AST/AbstractBasicReader.h @@ -16,12 +16,11 @@ namespace clang { namespace serialization { template <class T> -inline T makeNullableFromOptional(const Optional<T> &value) { +inline T makeNullableFromOptional(const std::optional<T> &value) { return (value ? *value : T()); } -template <class T> -inline T *makePointerFromOptional(Optional<T *> value) { +template <class T> inline T *makePointerFromOptional(std::optional<T *> value) { return value.value_or(nullptr); } @@ -50,7 +49,7 @@ inline T *makePointerFromOptional(Optional<T *> value) { // type-specific readers for all the enum types. // // template <class ValueType> -// Optional<ValueType> writeOptional(); +// std::optional<ValueType> writeOptional(); // // Reads an optional value from the current property. // @@ -158,7 +157,7 @@ public: } template <class T, class... Args> - llvm::Optional<T> readOptional(Args &&...args) { + std::optional<T> readOptional(Args &&...args) { return UnpackOptionalValue<T>::unpack( ReadDispatcher<T>::read(asImpl(), std::forward<Args>(args)...)); } diff --git a/clang/include/clang/AST/AbstractBasicWriter.h b/clang/include/clang/AST/AbstractBasicWriter.h index 6624a6e..07afa38 100644 --- a/clang/include/clang/AST/AbstractBasicWriter.h +++ b/clang/include/clang/AST/AbstractBasicWriter.h @@ -17,15 +17,12 @@ namespace clang { namespace serialization { template <class T> -inline llvm::Optional<T> makeOptionalFromNullable(const T &value) { - return (value.isNull() - ? llvm::Optional<T>() - : llvm::Optional<T>(value)); +inline std::optional<T> makeOptionalFromNullable(const T &value) { + return (value.isNull() ? std::optional<T>() : std::optional<T>(value)); } -template <class T> -inline llvm::Optional<T*> makeOptionalFromPointer(T *value) { - return (value ? llvm::Optional<T*>(value) : llvm::Optional<T*>()); +template <class T> inline std::optional<T *> makeOptionalFromPointer(T *value) { + return (value ? std::optional<T *>(value) : std::optional<T *>()); } // PropertyWriter is a class concept that requires the following method: @@ -52,7 +49,7 @@ inline llvm::Optional<T*> makeOptionalFromPointer(T *value) { // type-specific writers for all the enum types. // // template <class ValueType> -// void writeOptional(Optional<ValueType> value); +// void writeOptional(std::optional<ValueType> value); // // Writes an optional value as the current property. // @@ -149,8 +146,7 @@ public: } } - template <class T> - void writeOptional(llvm::Optional<T> value) { + template <class T> void writeOptional(std::optional<T> value) { WriteDispatcher<T>::write(asImpl(), PackOptionalValue<T>::pack(value)); } diff --git a/clang/include/clang/AST/ComparisonCategories.h b/clang/include/clang/AST/ComparisonCategories.h index aac8124..1c94cee 100644 --- a/clang/include/clang/AST/ComparisonCategories.h +++ b/clang/include/clang/AST/ComparisonCategories.h @@ -59,7 +59,8 @@ inline ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, /// Get the comparison category that should be used when comparing values of /// type \c T. -Optional<ComparisonCategoryType> getComparisonCategoryForBuiltinCmp(QualType T); +std::optional<ComparisonCategoryType> +getComparisonCategoryForBuiltinCmp(QualType T); /// An enumeration representing the possible results of a three-way /// comparison. These values map onto instances of comparison category types diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index 388cb51..5b58fd9 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -438,7 +438,7 @@ public: /// If visibility was explicitly specified for this /// declaration, return that visibility. - Optional<Visibility> + std::optional<Visibility> getExplicitVisibility(ExplicitVisibilityKind kind) const; /// True if the computed linkage is valid. Used for consistency @@ -2475,7 +2475,7 @@ public: /// If this function is an allocation/deallocation function that takes /// the `std::nothrow_t` tag, return true through IsNothrow, bool isReplaceableGlobalAllocationFunction( - Optional<unsigned> *AlignmentParam = nullptr, + std::optional<unsigned> *AlignmentParam = nullptr, bool *IsNothrow = nullptr) const; /// Determine if this function provides an inline implementation of a builtin. diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h index 085bd2e..ead51d1 100644 --- a/clang/include/clang/AST/DeclTemplate.h +++ b/clang/include/clang/AST/DeclTemplate.h @@ -1237,7 +1237,8 @@ class TemplateTypeParmDecl final : public TypeDecl, TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Typename, - bool HasTypeConstraint, Optional<unsigned> NumExpanded) + bool HasTypeConstraint, + std::optional<unsigned> NumExpanded) : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename), HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false), ExpandedParameterPack(NumExpanded), @@ -1248,7 +1249,7 @@ public: Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint = false, - Optional<unsigned> NumExpanded = std::nullopt); + std::optional<unsigned> NumExpanded = std::nullopt); static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, unsigned ID); static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, @@ -3433,7 +3434,7 @@ inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) { /// /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us /// is not a pack expansion, so returns an empty Optional. -inline Optional<unsigned> getExpandedPackSize(const NamedDecl *Param) { +inline std::optional<unsigned> getExpandedPackSize(const NamedDecl *Param) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { if (TTP->isExpandedParameterPack()) return TTP->getNumExpansionParameters(); diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h index 2a81b46..4852789 100644 --- a/clang/include/clang/AST/Expr.h +++ b/clang/include/clang/AST/Expr.h @@ -540,9 +540,9 @@ public: /// /// Note: This does not perform the implicit conversions required by C++11 /// [expr.const]p5. - Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx, - SourceLocation *Loc = nullptr, - bool isEvaluated = true) const; + std::optional<llvm::APSInt> + getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr, + bool isEvaluated = true) const; bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr) const; diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index 3851d74..a6532ef 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -2263,7 +2263,7 @@ private: CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, - SourceRange TypeIdParens, Optional<Expr *> ArraySize, + SourceRange TypeIdParens, std::optional<Expr *> ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange); @@ -2278,7 +2278,7 @@ public: Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, - SourceRange TypeIdParens, Optional<Expr *> ArraySize, + SourceRange TypeIdParens, std::optional<Expr *> ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange); @@ -2323,7 +2323,7 @@ public: /// This might return std::nullopt even if isArray() returns true, /// since there might not be an array size expression. /// If the result is not-None, it will never wrap a nullptr. - Optional<Expr *> getArraySize() { + std::optional<Expr *> getArraySize() { if (!isArray()) return std::nullopt; @@ -2337,7 +2337,7 @@ public: /// This might return std::nullopt even if isArray() returns true, /// since there might not be an array size expression. /// If the result is not-None, it will never wrap a nullptr. - Optional<const Expr *> getArraySize() const { + std::optional<const Expr *> getArraySize() const { if (!isArray()) return std::nullopt; @@ -4139,7 +4139,7 @@ class PackExpansionExpr : public Expr { public: PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) + std::optional<unsigned> NumExpansions) : Expr(PackExpansionExprClass, T, Pattern->getValueKind(), Pattern->getObjectKind()), EllipsisLoc(EllipsisLoc), @@ -4162,7 +4162,7 @@ public: /// Determine the number of expansions that will be produced when /// this pack expansion is instantiated, if already known. - Optional<unsigned> getNumExpansions() const { + std::optional<unsigned> getNumExpansions() const { if (NumExpansions) return NumExpansions - 1; @@ -4233,7 +4233,7 @@ class SizeOfPackExpr final /// the given parameter pack. SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack, SourceLocation PackLoc, SourceLocation RParenLoc, - Optional<unsigned> Length, + std::optional<unsigned> Length, ArrayRef<TemplateArgument> PartialArgs) : Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary), OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc), @@ -4254,7 +4254,7 @@ public: static SizeOfPackExpr * Create(ASTContext &Context, SourceLocation OperatorLoc, NamedDecl *Pack, SourceLocation PackLoc, SourceLocation RParenLoc, - Optional<unsigned> Length = std::nullopt, + std::optional<unsigned> Length = std::nullopt, ArrayRef<TemplateArgument> PartialArgs = std::nullopt); static SizeOfPackExpr *CreateDeserialized(ASTContext &Context, unsigned NumPartialArgs); @@ -4338,7 +4338,7 @@ public: SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind, SourceLocation Loc, Expr *Replacement, Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex, bool RefParam) + std::optional<unsigned> PackIndex, bool RefParam) : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary), Replacement(Replacement), AssociatedDeclAndRef(AssociatedDecl, RefParam), Index(Index), @@ -4364,7 +4364,7 @@ public: /// This should match the result of `getParameter()->getIndex()`. unsigned getIndex() const { return Index; } - Optional<unsigned> getPackIndex() const { + std::optional<unsigned> getPackIndex() const { if (PackIndex == 0) return std::nullopt; return PackIndex - 1; @@ -4691,7 +4691,7 @@ public: CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, - Optional<unsigned> NumExpansions) + std::optional<unsigned> NumExpansions) : Expr(CXXFoldExprClass, T, VK_PRValue, OK_Ordinary), LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc), NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) { @@ -4728,7 +4728,7 @@ public: SourceLocation getEllipsisLoc() const { return EllipsisLoc; } BinaryOperatorKind getOperator() const { return Opcode; } - Optional<unsigned> getNumExpansions() const { + std::optional<unsigned> getNumExpansions() const { if (NumExpansions) return NumExpansions - 1; return std::nullopt; diff --git a/clang/include/clang/AST/ExprObjC.h b/clang/include/clang/AST/ExprObjC.h index f1d2160..4a6c588 100644 --- a/clang/include/clang/AST/ExprObjC.h +++ b/clang/include/clang/AST/ExprObjC.h @@ -272,7 +272,7 @@ struct ObjCDictionaryElement { /// The number of elements this pack expansion will expand to, if /// this is a pack expansion and is known. - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; /// Determines whether this dictionary element is a pack expansion. bool isPackExpansion() const { return EllipsisLoc.isValid(); } diff --git a/clang/include/clang/AST/ExternalASTSource.h b/clang/include/clang/AST/ExternalASTSource.h index 18f9816..8d0ed35 100644 --- a/clang/include/clang/AST/ExternalASTSource.h +++ b/clang/include/clang/AST/ExternalASTSource.h @@ -161,7 +161,7 @@ public: virtual Module *getModule(unsigned ID) { return nullptr; } /// Return a descriptor for the corresponding module, if one exists. - virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID); + virtual std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID); enum ExtKind { EK_Always, EK_Never, EK_ReplyHazy }; diff --git a/clang/include/clang/AST/FormatString.h b/clang/include/clang/AST/FormatString.h index e1f8a2d..5c4ad9b 100644 --- a/clang/include/clang/AST/FormatString.h +++ b/clang/include/clang/AST/FormatString.h @@ -242,7 +242,7 @@ public: bool isPrintfKind() const { return IsPrintf; } - Optional<ConversionSpecifier> getStandardSpecifier() const; + std::optional<ConversionSpecifier> getStandardSpecifier() const; protected: bool IsPrintf; @@ -467,7 +467,7 @@ public: bool hasStandardLengthModifier() const; - Optional<LengthModifier> getCorrectedLengthModifier() const; + std::optional<LengthModifier> getCorrectedLengthModifier() const; bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const; diff --git a/clang/include/clang/AST/Mangle.h b/clang/include/clang/AST/Mangle.h index 2ed2d76..9662a33 100644 --- a/clang/include/clang/AST/Mangle.h +++ b/clang/include/clang/AST/Mangle.h @@ -185,7 +185,7 @@ public: class ItaniumMangleContext : public MangleContext { public: using DiscriminatorOverrideTy = - llvm::Optional<unsigned> (*)(ASTContext &, const NamedDecl *); + std::optional<unsigned> (*)(ASTContext &, const NamedDecl *); explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D, bool IsAux = false) : MangleContext(C, D, MK_Itanium, IsAux) {} diff --git a/clang/include/clang/AST/NSAPI.h b/clang/include/clang/AST/NSAPI.h index 7692502..f348164 100644 --- a/clang/include/clang/AST/NSAPI.h +++ b/clang/include/clang/AST/NSAPI.h @@ -90,7 +90,7 @@ public: Selector getNSArraySelector(NSArrayMethodKind MK) const; /// Return NSArrayMethodKind if \p Sel is such a selector. - Optional<NSArrayMethodKind> getNSArrayMethodKind(Selector Sel); + std::optional<NSArrayMethodKind> getNSArrayMethodKind(Selector Sel); /// Enumerates the NSDictionary/NSMutableDictionary methods used /// to generate literals and to apply some checks. @@ -115,7 +115,7 @@ public: Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const; /// Return NSDictionaryMethodKind if \p Sel is such a selector. - Optional<NSDictionaryMethodKind> getNSDictionaryMethodKind(Selector Sel); + std::optional<NSDictionaryMethodKind> getNSDictionaryMethodKind(Selector Sel); /// Enumerates the NSMutableSet/NSOrderedSet methods used /// to apply some checks. @@ -132,7 +132,7 @@ public: Selector getNSSetSelector(NSSetMethodKind MK) const; /// Return NSSetMethodKind if \p Sel is such a selector. - Optional<NSSetMethodKind> getNSSetMethodKind(Selector Sel); + std::optional<NSSetMethodKind> getNSSetMethodKind(Selector Sel); /// Returns selector for "objectForKeyedSubscript:". Selector getObjectForKeyedSubscriptSelector() const { @@ -204,13 +204,13 @@ public: } /// Return NSNumberLiteralMethodKind if \p Sel is such a selector. - Optional<NSNumberLiteralMethodKind> - getNSNumberLiteralMethodKind(Selector Sel) const; + std::optional<NSNumberLiteralMethodKind> + getNSNumberLiteralMethodKind(Selector Sel) const; /// Determine the appropriate NSNumber factory method kind for a /// literal of the given type. - Optional<NSNumberLiteralMethodKind> - getNSNumberFactoryMethodKind(QualType T) const; + std::optional<NSNumberLiteralMethodKind> + getNSNumberFactoryMethodKind(QualType T) const; /// Returns true if \param T is a typedef of "BOOL" in objective-c. bool isObjCBOOLType(QualType T) const; diff --git a/clang/include/clang/AST/PropertiesBase.td b/clang/include/clang/AST/PropertiesBase.td index d713b86..c2823c6 100644 --- a/clang/include/clang/AST/PropertiesBase.td +++ b/clang/include/clang/AST/PropertiesBase.td @@ -41,7 +41,7 @@ class RefPropertyType<string className> : PropertyType<className # "*"> { let PackOptional = "value ? *value : nullptr"; let UnpackOptional = - "value ? llvm::Optional<" # CXXName # ">(value) : std::nullopt"; + "value ? std::optional<" # CXXName # ">(value) : std::nullopt"; } /// Property types that correspond to a specific subclass of another type. @@ -58,7 +58,7 @@ class DefaultValuePropertyType<string typeName = ""> : PropertyType<typeName> { let PackOptional = "value ? *value : " # CXXName # "()"; let UnpackOptional = - "value.isNull() ? std::nullopt : llvm::Optional<" # CXXName # ">(value)"; + "value.isNull() ? std::nullopt : std::optional<" # CXXName # ">(value)"; } /// Property types that correspond to integer types and support optional @@ -67,7 +67,7 @@ class CountPropertyType<string typeName = ""> : PropertyType<typeName> { let PackOptional = "value ? *value + 1 : 0"; let UnpackOptional = - "value ? llvm::Optional<" # CXXName # ">(value - 1) : std::nullopt"; + "value ? std::optional<" # CXXName # ">(value - 1) : std::nullopt"; } def APInt : PropertyType<"llvm::APInt"> { let PassByReference = 1; } @@ -155,7 +155,7 @@ class Array<PropertyType element> : PropertyType { let BufferElementTypes = [ element ]; } -/// llvm::Optional<T>. The corresponding C++ type is generally just the +/// std::optional<T>. The corresponding C++ type is generally just the /// corresponding C++ type of the element. /// /// Optional<Unsigned> may restrict the range of the operand for some diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h index 1f7b095..b70cf3a 100644 --- a/clang/include/clang/AST/Stmt.h +++ b/clang/include/clang/AST/Stmt.h @@ -2149,8 +2149,8 @@ public: /// If this is an 'if constexpr', determine which substatement will be taken. /// Otherwise, or if the condition is value-dependent, returns std::nullopt. - Optional<const Stmt*> getNondiscardedCase(const ASTContext &Ctx) const; - Optional<Stmt *> getNondiscardedCase(const ASTContext &Ctx); + std::optional<const Stmt *> getNondiscardedCase(const ASTContext &Ctx) const; + std::optional<Stmt *> getNondiscardedCase(const ASTContext &Ctx); bool isObjCAvailabilityCheck() const; diff --git a/clang/include/clang/AST/TemplateBase.h b/clang/include/clang/AST/TemplateBase.h index d4bf4e3..1bb0674 100644 --- a/clang/include/clang/AST/TemplateBase.h +++ b/clang/include/clang/AST/TemplateBase.h @@ -202,7 +202,7 @@ public: /// /// \param NumExpansions The number of expansions that will be generated by /// instantiating - TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) { + TemplateArgument(TemplateName Name, std::optional<unsigned> NumExpansions) { TemplateArg.Kind = TemplateExpansion; TemplateArg.Name = Name.getAsVoidPointer(); if (NumExpansions) @@ -307,7 +307,7 @@ public: /// Retrieve the number of expansions that a template template argument /// expansion will produce, if known. - Optional<unsigned> getNumTemplateExpansions() const; + std::optional<unsigned> getNumTemplateExpansions() const; /// Retrieve the template argument as an integral value. // FIXME: Provide a way to read the integral data without copying the value. diff --git a/clang/include/clang/AST/TemplateName.h b/clang/include/clang/AST/TemplateName.h index c7489f6..2f108ea 100644 --- a/clang/include/clang/AST/TemplateName.h +++ b/clang/include/clang/AST/TemplateName.h @@ -380,7 +380,7 @@ class SubstTemplateTemplateParmStorage SubstTemplateTemplateParmStorage(TemplateName Replacement, Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) + std::optional<unsigned> PackIndex) : UncommonTemplateNameStorage(SubstTemplateTemplateParm, Index, PackIndex ? *PackIndex + 1 : 0), Replacement(Replacement), AssociatedDecl(AssociatedDecl) { @@ -396,7 +396,7 @@ public: /// This should match the result of `getParameter()->getIndex()`. unsigned getIndex() const { return Bits.Index; } - Optional<unsigned> getPackIndex() const { + std::optional<unsigned> getPackIndex() const { if (Bits.Data == 0) return std::nullopt; return Bits.Data - 1; @@ -409,7 +409,7 @@ public: static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Replacement, Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex); + std::optional<unsigned> PackIndex); }; inline TemplateName TemplateName::getUnderlying() const { diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index 21843c3c..b1acd64 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -2553,7 +2553,7 @@ public: /// Note that nullability is only captured as sugar within the type /// system, not as part of the canonical type, so nullability will /// be lost by canonicalization and desugaring. - Optional<NullabilityKind> getNullability() const; + std::optional<NullabilityKind> getNullability() const; /// Determine whether the given type can have a nullability /// specifier applied to it, i.e., if it is any kind of pointer type. @@ -2577,7 +2577,7 @@ public: /// the type parameters of the given declaration context in any type described /// within that context, or an empty optional to indicate that no /// substitution is required. - Optional<ArrayRef<QualType>> + std::optional<ArrayRef<QualType>> getObjCSubstitutions(const DeclContext *dc) const; /// Determines if this is an ObjC interface type that may accept type @@ -4923,7 +4923,7 @@ public: bool isCallingConv() const; - llvm::Optional<NullabilityKind> getImmediateNullability() const; + std::optional<NullabilityKind> getImmediateNullability() const; /// Retrieve the attribute kind corresponding to the given /// nullability kind. @@ -4953,7 +4953,7 @@ public: /// to the underlying modified type. /// /// \returns the top-level nullability, if present. - static Optional<NullabilityKind> stripOuterNullability(QualType &T); + static std::optional<NullabilityKind> stripOuterNullability(QualType &T); void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getAttrKind(), ModifiedType, EquivalentType); @@ -5094,7 +5094,7 @@ class SubstTemplateTypeParmType final Decl *AssociatedDecl; SubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, - unsigned Index, Optional<unsigned> PackIndex); + unsigned Index, std::optional<unsigned> PackIndex); public: /// Gets the type that was substituted for the template @@ -5117,7 +5117,7 @@ public: /// This should match the result of `getReplacedParameter()->getIndex()`. unsigned getIndex() const { return SubstTemplateTypeParmTypeBits.Index; } - Optional<unsigned> getPackIndex() const { + std::optional<unsigned> getPackIndex() const { if (SubstTemplateTypeParmTypeBits.PackIndex == 0) return std::nullopt; return SubstTemplateTypeParmTypeBits.PackIndex - 1; @@ -5133,7 +5133,7 @@ public: static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement, const Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) { + std::optional<unsigned> PackIndex) { Replacement.Profile(ID); ID.AddPointer(AssociatedDecl); ID.AddInteger(Index); @@ -5847,7 +5847,7 @@ class PackExpansionType : public Type, public llvm::FoldingSetNode { QualType Pattern; PackExpansionType(QualType Pattern, QualType Canon, - Optional<unsigned> NumExpansions) + std::optional<unsigned> NumExpansions) : Type(PackExpansion, Canon, (Pattern->getDependence() | TypeDependence::Dependent | TypeDependence::Instantiation) & @@ -5865,7 +5865,7 @@ public: /// Retrieve the number of expansions that this pack expansion will /// generate, if known. - Optional<unsigned> getNumExpansions() const { + std::optional<unsigned> getNumExpansions() const { if (PackExpansionTypeBits.NumExpansions) return PackExpansionTypeBits.NumExpansions - 1; return std::nullopt; @@ -5879,7 +5879,7 @@ public: } static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { ID.AddPointer(Pattern.getAsOpaquePtr()); ID.AddBoolean(NumExpansions.has_value()); if (NumExpansions) diff --git a/clang/include/clang/AST/TypeProperties.td b/clang/include/clang/AST/TypeProperties.td index 84cf787..aca445f 100644 --- a/clang/include/clang/AST/TypeProperties.td +++ b/clang/include/clang/AST/TypeProperties.td @@ -666,10 +666,10 @@ let Class = TemplateSpecializationType in { def : Property<"underlyingType", Optional<QualType>> { let Read = [{ node->isTypeAlias() - ? llvm::Optional<QualType>(node->getAliasedType()) + ? std::optional<QualType>(node->getAliasedType()) : node->isCanonicalUnqualified() ? std::nullopt - : llvm::Optional<QualType>(node->getCanonicalTypeInternal()) + : std::optional<QualType>(node->getCanonicalTypeInternal()) }]; } @@ -835,7 +835,7 @@ let Class = DependentNameType in { let Read = [{ node->isCanonicalUnqualified() ? std::nullopt - : llvm::Optional<QualType>(node->getCanonicalTypeInternal()) + : std::optional<QualType>(node->getCanonicalTypeInternal()) }]; } diff --git a/clang/include/clang/ASTMatchers/ASTMatchFinder.h b/clang/include/clang/ASTMatchers/ASTMatchFinder.h index 9ff3012..a387d90 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchFinder.h +++ b/clang/include/clang/ASTMatchers/ASTMatchFinder.h @@ -138,7 +138,7 @@ public: /// Enables per-check timers. /// /// It prints a report after match. - llvm::Optional<Profiling> CheckProfiling; + std::optional<Profiling> CheckProfiling; }; MatchFinder(MatchFinderOptions Options = MatchFinderOptions()); diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h b/clang/include/clang/ASTMatchers/ASTMatchers.h index 7dda0806..baedc89 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchers.h +++ b/clang/include/clang/ASTMatchers/ASTMatchers.h @@ -318,10 +318,10 @@ AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro, // Verifies that the statement' beginning and ending are both expanded from // the same instance of the given macro. auto& Context = Finder->getASTContext(); - llvm::Optional<SourceLocation> B = + std::optional<SourceLocation> B = internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context); if (!B) return false; - llvm::Optional<SourceLocation> E = + std::optional<SourceLocation> E = internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context); if (!E) return false; return *B == *E; @@ -5629,7 +5629,7 @@ AST_POLYMORPHIC_MATCHER_P( AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, UnaryOperator), std::string, Name) { - if (Optional<StringRef> OpName = internal::getOpName(Node)) + if (std::optional<StringRef> OpName = internal::getOpName(Node)) return *OpName == Name; return false; } diff --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h index 8252982..67379ac0 100644 --- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h +++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h @@ -483,8 +483,8 @@ public: /// Bind the specified \p ID to the matcher. /// \return A new matcher with the \p ID bound to it if this matcher supports - /// binding. Otherwise, returns an empty \c Optional<>. - llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const; + /// binding. Otherwise, returns an empty \c std::optional<>. + std::optional<DynTypedMatcher> tryBind(StringRef ID) const; /// Returns a unique \p ID for the matcher. /// @@ -1974,13 +1974,13 @@ struct GetBodyMatcher< }; template <typename NodeType> -inline Optional<BinaryOperatorKind> +inline std::optional<BinaryOperatorKind> equivalentBinaryOperator(const NodeType &Node) { return Node.getOpcode(); } template <> -inline Optional<BinaryOperatorKind> +inline std::optional<BinaryOperatorKind> equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { if (Node.getNumArgs() != 2) return std::nullopt; @@ -2055,13 +2055,13 @@ equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { } template <typename NodeType> -inline Optional<UnaryOperatorKind> +inline std::optional<UnaryOperatorKind> equivalentUnaryOperator(const NodeType &Node) { return Node.getOpcode(); } template <> -inline Optional<UnaryOperatorKind> +inline std::optional<UnaryOperatorKind> equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus && Node.getOperator() != OO_MinusMinus) @@ -2173,20 +2173,20 @@ CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) { /// location (in the chain of expansions) at which \p MacroName was /// expanded. Since the macro may have been expanded inside a series of /// expansions, that location may itself be a MacroID. -llvm::Optional<SourceLocation> -getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc, - const ASTContext &Context); +std::optional<SourceLocation> getExpansionLocOfMacro(StringRef MacroName, + SourceLocation Loc, + const ASTContext &Context); -inline Optional<StringRef> getOpName(const UnaryOperator &Node) { +inline std::optional<StringRef> getOpName(const UnaryOperator &Node) { return Node.getOpcodeStr(Node.getOpcode()); } -inline Optional<StringRef> getOpName(const BinaryOperator &Node) { +inline std::optional<StringRef> getOpName(const BinaryOperator &Node) { return Node.getOpcodeStr(); } inline StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { return Node.getOpcodeStr(); } -inline Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { +inline std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { auto optBinaryOpcode = equivalentBinaryOperator(Node); if (!optBinaryOpcode) { auto optUnaryOpcode = equivalentUnaryOperator(Node); @@ -2217,21 +2217,21 @@ public: : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {} bool matchesNode(const T &Node) const override { - Optional<StringRef> OptOpName = getOpName(Node); + std::optional<StringRef> OptOpName = getOpName(Node); return OptOpName && llvm::is_contained(Names, *OptOpName); } private: - static Optional<StringRef> getOpName(const UnaryOperator &Node) { + static std::optional<StringRef> getOpName(const UnaryOperator &Node) { return Node.getOpcodeStr(Node.getOpcode()); } - static Optional<StringRef> getOpName(const BinaryOperator &Node) { + static std::optional<StringRef> getOpName(const BinaryOperator &Node) { return Node.getOpcodeStr(); } static StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { return Node.getOpcodeStr(); } - static Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { + static std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { auto optBinaryOpcode = equivalentBinaryOperator(Node); if (!optBinaryOpcode) { auto optUnaryOpcode = equivalentUnaryOperator(Node); diff --git a/clang/include/clang/ASTMatchers/Dynamic/Parser.h b/clang/include/clang/ASTMatchers/Dynamic/Parser.h index ebe8597..26361de 100644 --- a/clang/include/clang/ASTMatchers/Dynamic/Parser.h +++ b/clang/include/clang/ASTMatchers/Dynamic/Parser.h @@ -96,9 +96,9 @@ public: /// /// \param MatcherName The matcher name found by the parser. /// - /// \return The matcher constructor, or Optional<MatcherCtor>() if not + /// \return The matcher constructor, or std::optional<MatcherCtor>() if not /// found. - virtual llvm::Optional<MatcherCtor> + virtual std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) = 0; virtual bool isBuilderMatcher(MatcherCtor) const = 0; @@ -139,7 +139,7 @@ public: public: ~RegistrySema() override; - llvm::Optional<MatcherCtor> + std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) override; VariantMatcher actOnMatcherExpression(MatcherCtor Ctor, @@ -181,14 +181,14 @@ public: /// Optional if an error occurred. In that case, \c Error will contain a /// description of the error. /// The caller takes ownership of the DynTypedMatcher object returned. - static llvm::Optional<DynTypedMatcher> + static std::optional<DynTypedMatcher> parseMatcherExpression(StringRef &MatcherCode, Sema *S, const NamedValueMap *NamedValues, Diagnostics *Error); - static llvm::Optional<DynTypedMatcher> + static std::optional<DynTypedMatcher> parseMatcherExpression(StringRef &MatcherCode, Sema *S, Diagnostics *Error) { return parseMatcherExpression(MatcherCode, S, nullptr, Error); } - static llvm::Optional<DynTypedMatcher> + static std::optional<DynTypedMatcher> parseMatcherExpression(StringRef &MatcherCode, Diagnostics *Error) { return parseMatcherExpression(MatcherCode, nullptr, Error); } @@ -255,7 +255,7 @@ private: const TokenInfo &OpenToken, VariantValue *Value); bool parseMatcherExpressionImpl(const TokenInfo &NameToken, const TokenInfo &OpenToken, - llvm::Optional<MatcherCtor> Ctor, + std::optional<MatcherCtor> Ctor, VariantValue *Value); bool parseIdentifierPrefixImpl(VariantValue *Value); diff --git a/clang/include/clang/ASTMatchers/Dynamic/Registry.h b/clang/include/clang/ASTMatchers/Dynamic/Registry.h index e33e0c7..6159150 100644 --- a/clang/include/clang/ASTMatchers/Dynamic/Registry.h +++ b/clang/include/clang/ASTMatchers/Dynamic/Registry.h @@ -95,8 +95,8 @@ public: /// Look up a matcher in the registry by name, /// /// \return An opaque value which may be used to refer to the matcher - /// constructor, or Optional<MatcherCtor>() if not found. - static llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName); + /// constructor, or std::optional<MatcherCtor>() if not found. + static std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName); /// Compute the list of completion types for \p Context. /// diff --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h index d67d5c3..a506f9e 100644 --- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h +++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h @@ -119,7 +119,7 @@ class VariantMatcher { /// Constructs a variadic typed matcher from \p InnerMatchers. /// Will try to convert each inner matcher to the destination type and /// return std::nullopt if it fails to do so. - llvm::Optional<DynTypedMatcher> + std::optional<DynTypedMatcher> constructVariadicOperator(DynTypedMatcher::VariadicOperator Op, ArrayRef<VariantMatcher> InnerMatchers) const; @@ -133,9 +133,9 @@ class VariantMatcher { class Payload { public: virtual ~Payload(); - virtual llvm::Optional<DynTypedMatcher> getSingleMatcher() const = 0; + virtual std::optional<DynTypedMatcher> getSingleMatcher() const = 0; virtual std::string getTypeAsString() const = 0; - virtual llvm::Optional<DynTypedMatcher> + virtual std::optional<DynTypedMatcher> getTypedMatcher(const MatcherOps &Ops) const = 0; virtual bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity) const = 0; @@ -172,7 +172,7 @@ public: /// \returns the matcher, if there is only one matcher. An empty Optional, if /// the underlying matcher is a polymorphic matcher with more than one /// representation. - llvm::Optional<DynTypedMatcher> getSingleMatcher() const; + std::optional<DynTypedMatcher> getSingleMatcher() const; /// Determines if the contained matcher can be converted to /// \c Matcher<T>. diff --git a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h index 9c34f33..4a25fbb 100644 --- a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h +++ b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h @@ -958,7 +958,7 @@ public: private: SExpr* Rec; - mutable llvm::Optional<std::string> SlotName; + mutable std::optional<std::string> SlotName; const ValueDecl *Cvdecl; }; diff --git a/clang/include/clang/Analysis/AnyCall.h b/clang/include/clang/Analysis/AnyCall.h index 801105b..48abce0 100644 --- a/clang/include/clang/Analysis/AnyCall.h +++ b/clang/include/clang/Analysis/AnyCall.h @@ -110,7 +110,7 @@ public: /// If @c E is a generic call (to ObjC method /function/block/etc), /// return a constructed @c AnyCall object. Return std::nullopt otherwise. - static Optional<AnyCall> forExpr(const Expr *E) { + static std::optional<AnyCall> forExpr(const Expr *E) { if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { return AnyCall(ME); } else if (const auto *CE = dyn_cast<CallExpr>(E)) { @@ -131,7 +131,7 @@ public: /// If @c D is a callable (Objective-C method or a function), return /// a constructed @c AnyCall object. Return std::nullopt otherwise. // FIXME: block support. - static Optional<AnyCall> forDecl(const Decl *D) { + static std::optional<AnyCall> forDecl(const Decl *D) { if (const auto *FD = dyn_cast<FunctionDecl>(D)) { return AnyCall(FD); } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { diff --git a/clang/include/clang/Analysis/BodyFarm.h b/clang/include/clang/Analysis/BodyFarm.h index f6ed9d6..75de26e 100644 --- a/clang/include/clang/Analysis/BodyFarm.h +++ b/clang/include/clang/Analysis/BodyFarm.h @@ -42,7 +42,7 @@ public: BodyFarm(const BodyFarm &other) = delete; private: - typedef llvm::DenseMap<const Decl *, Optional<Stmt *>> BodyMap; + typedef llvm::DenseMap<const Decl *, std::optional<Stmt *>> BodyMap; ASTContext &C; BodyMap Bodies; diff --git a/clang/include/clang/Analysis/CFG.h b/clang/include/clang/Analysis/CFG.h index f2cf9f9..dc0471b 100644 --- a/clang/include/clang/Analysis/CFG.h +++ b/clang/include/clang/Analysis/CFG.h @@ -105,8 +105,7 @@ public: /// Convert to the specified CFGElement type, returning std::nullopt if this /// CFGElement is not of the desired type. - template<typename T> - Optional<T> getAs() const { + template <typename T> std::optional<T> getAs() const { if (!T::isKind(*this)) return std::nullopt; T t; @@ -1400,7 +1399,7 @@ public: for (const_iterator I = begin(), E = end(); I != E; ++I) for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) { - if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>()) + if (std::optional<CFGStmt> stmt = BI->getAs<CFGStmt>()) O(const_cast<Stmt *>(stmt->getStmt())); } } diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h index 03d48ca..f69544b 100644 --- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h +++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h @@ -190,7 +190,7 @@ template <typename LatticeT> struct DataflowAnalysisState { /// program point. template <typename AnalysisT> llvm::Expected<std::vector< - llvm::Optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>> + std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>> runDataflowAnalysis( const ControlFlowContext &CFCtx, AnalysisT &Analysis, const Environment &InitEnv, @@ -216,8 +216,7 @@ runDataflowAnalysis( if (!TypeErasedBlockStates) return TypeErasedBlockStates.takeError(); - std::vector< - llvm::Optional<DataflowAnalysisState<typename AnalysisT::Lattice>>> + std::vector<std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>> BlockStates; BlockStates.reserve(TypeErasedBlockStates->size()); diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h index 4ab1e9c..74748c8 100644 --- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h +++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h @@ -66,7 +66,7 @@ public: /// unit, or empty to disable context-sensitive analysis. Note that this is /// fundamentally limited: some constructs, such as recursion, are /// explicitly unsupported. - llvm::Optional<ContextSensitiveOptions> ContextSensitiveOpts; + std::optional<ContextSensitiveOptions> ContextSensitiveOpts; }; /// Constructs a dataflow analysis context. diff --git a/clang/include/clang/Analysis/FlowSensitive/Solver.h b/clang/include/clang/Analysis/FlowSensitive/Solver.h index d0f954d..8b8c9e1 100644 --- a/clang/include/clang/Analysis/FlowSensitive/Solver.h +++ b/clang/include/clang/Analysis/FlowSensitive/Solver.h @@ -65,7 +65,7 @@ public: /// Returns a truth assignment to boolean values that satisfies the queried /// boolean formula if available. Otherwise, an empty optional is returned. - llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> + std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> getSolution() const { return Solution; } @@ -73,11 +73,11 @@ public: private: Result( enum Status SATCheckStatus, - llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution) + std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution) : SATCheckStatus(SATCheckStatus), Solution(std::move(Solution)) {} Status SATCheckStatus; - llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution; + std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution; }; virtual ~Solver() = default; diff --git a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h index ab04a70..770564f 100644 --- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h +++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h @@ -140,7 +140,7 @@ struct TypeErasedDataflowAnalysisState { /// `std::nullopt` represent basic blocks that are not evaluated yet. TypeErasedDataflowAnalysisState transferBlock( const ControlFlowContext &CFCtx, - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates, + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockStates, const CFGBlock &Block, const Environment &InitEnv, TypeErasedDataflowAnalysis &Analysis, std::function<void(const CFGElement &, @@ -153,7 +153,7 @@ TypeErasedDataflowAnalysisState transferBlock( /// dataflow analysis cannot be performed successfully. Otherwise, calls /// `PostVisitCFG` on each CFG element with the final analysis results at that /// program point. -llvm::Expected<std::vector<llvm::Optional<TypeErasedDataflowAnalysisState>>> +llvm::Expected<std::vector<std::optional<TypeErasedDataflowAnalysisState>>> runTypeErasedDataflowAnalysis( const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis, const Environment &InitEnv, diff --git a/clang/include/clang/Analysis/MacroExpansionContext.h b/clang/include/clang/Analysis/MacroExpansionContext.h index bfa529f..f09c57d 100644 --- a/clang/include/clang/Analysis/MacroExpansionContext.h +++ b/clang/include/clang/Analysis/MacroExpansionContext.h @@ -87,13 +87,15 @@ public: /// \return The textual representation of the token sequence which was /// substituted in place of the macro after the preprocessing. /// If no macro was expanded at that location, returns std::nullopt. - Optional<StringRef> getExpandedText(SourceLocation MacroExpansionLoc) const; + std::optional<StringRef> + getExpandedText(SourceLocation MacroExpansionLoc) const; /// \param MacroExpansionLoc Must be the expansion location of a macro. /// \return The text from the original source code which were substituted by /// the macro expansion chain from the given location. /// If no macro was expanded at that location, returns std::nullopt. - Optional<StringRef> getOriginalText(SourceLocation MacroExpansionLoc) const; + std::optional<StringRef> + getOriginalText(SourceLocation MacroExpansionLoc) const; LLVM_DUMP_METHOD void dumpExpansionRangesToStream(raw_ostream &OS) const; LLVM_DUMP_METHOD void dumpExpandedTextsToStream(raw_ostream &OS) const; diff --git a/clang/include/clang/Analysis/PathDiagnostic.h b/clang/include/clang/Analysis/PathDiagnostic.h index e6c7173d6..bf4ec09 100644 --- a/clang/include/clang/Analysis/PathDiagnostic.h +++ b/clang/include/clang/Analysis/PathDiagnostic.h @@ -533,7 +533,7 @@ public: }; class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece { - Optional<bool> IsPrunable; + std::optional<bool> IsPrunable; public: PathDiagnosticEventPiece(const PathDiagnosticLocation &pos, diff --git a/clang/include/clang/Analysis/ProgramPoint.h b/clang/include/clang/Analysis/ProgramPoint.h index 2478137..c47c355 100644 --- a/clang/include/clang/Analysis/ProgramPoint.h +++ b/clang/include/clang/Analysis/ProgramPoint.h @@ -147,8 +147,7 @@ public: /// Convert to the specified ProgramPoint type, returning std::nullopt if this /// ProgramPoint is not of the desired type. - template<typename T> - Optional<T> getAs() const { + template <typename T> std::optional<T> getAs() const { if (!T::isKind(*this)) return std::nullopt; T t; @@ -234,9 +233,9 @@ public: return reinterpret_cast<const CFGBlock*>(getData1()); } - Optional<CFGElement> getFirstElement() const { + std::optional<CFGElement> getFirstElement() const { const CFGBlock *B = getBlock(); - return B->empty() ? Optional<CFGElement>() : B->front(); + return B->empty() ? std::optional<CFGElement>() : B->front(); } private: diff --git a/clang/include/clang/Analysis/RetainSummaryManager.h b/clang/include/clang/Analysis/RetainSummaryManager.h index 58129df..86865b9 100644 --- a/clang/include/clang/Analysis/RetainSummaryManager.h +++ b/clang/include/clang/Analysis/RetainSummaryManager.h @@ -649,8 +649,9 @@ public: IdentityOrZero }; - Optional<BehaviorSummary> canEval(const CallExpr *CE, const FunctionDecl *FD, - bool &hasTrustedImplementationAnnotation); + std::optional<BehaviorSummary> + canEval(const CallExpr *CE, const FunctionDecl *FD, + bool &hasTrustedImplementationAnnotation); /// \return Whether the type corresponds to a known smart pointer /// implementation (that is, everything about it is inlineable). @@ -687,8 +688,8 @@ private: Selector S, QualType RetTy); /// Determine if there is a special return effect for this function or method. - Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy, - const Decl *D); + std::optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy, + const Decl *D); void updateSummaryFromAnnotations(const RetainSummary *&Summ, const ObjCMethodDecl *MD); @@ -724,10 +725,10 @@ private: /// std::nullopt, if none of the specified attributes are present. /// Crashes if passed an attribute which is not explicitly handled. template <class T> - Optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); + std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); template <class T1, class T2, class... Others> - Optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); + std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); friend class RetainSummaryTemplate; }; diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index 65b6242..d449a2f 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -3786,11 +3786,11 @@ def OMPDeclareTargetDecl : InheritableAttr { ]; let AdditionalMembers = [{ void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const; - static llvm::Optional<MapTypeTy> + static std::optional<MapTypeTy> isDeclareTargetDeclaration(const ValueDecl *VD); - static llvm::Optional<OMPDeclareTargetDeclAttr*> getActiveAttr(const ValueDecl *VD); - static llvm::Optional<DevTypeTy> getDeviceType(const ValueDecl *VD); - static llvm::Optional<SourceLocation> getLocation(const ValueDecl *VD); + static std::optional<OMPDeclareTargetDeclAttr*> getActiveAttr(const ValueDecl *VD); + static std::optional<DevTypeTy> getDeviceType(const ValueDecl *VD); + static std::optional<SourceLocation> getLocation(const ValueDecl *VD); }]; } diff --git a/clang/include/clang/Basic/CustomizableOptional.h b/clang/include/clang/Basic/CustomizableOptional.h index 7323a81..84d4002 100644 --- a/clang/include/clang/Basic/CustomizableOptional.h +++ b/clang/include/clang/Basic/CustomizableOptional.h @@ -45,7 +45,7 @@ public: constexpr CustomizableOptional(std::in_place_t, ArgTypes &&...Args) : Storage(std::in_place, std::forward<ArgTypes>(Args)...) {} - // Allow conversion from Optional<T>. + // Allow conversion from std::optional<T>. constexpr CustomizableOptional(const std::optional<T> &y) : CustomizableOptional(y ? *y : CustomizableOptional()) {} constexpr CustomizableOptional(std::optional<T> &&y) @@ -98,7 +98,7 @@ public: return has_value() ? std::move(operator*()) : std::forward<U>(alt); } - // Allow conversion to Optional<T>. + // Allow conversion to std::optional<T>. explicit operator std::optional<T> &() const & { return *this ? **this : std::optional<T>(); } diff --git a/clang/include/clang/Basic/DarwinSDKInfo.h b/clang/include/clang/Basic/DarwinSDKInfo.h index 7a44187..62e2368 100644 --- a/clang/include/clang/Basic/DarwinSDKInfo.h +++ b/clang/include/clang/Basic/DarwinSDKInfo.h @@ -105,7 +105,7 @@ public: map(const VersionTuple &Key, const VersionTuple &MinimumValue, std::optional<VersionTuple> MaximumValue) const; - static Optional<RelatedTargetVersionMapping> + static std::optional<RelatedTargetVersionMapping> parseJSON(const llvm::json::Object &Obj, VersionTuple MaximumDeploymentTarget); @@ -117,12 +117,13 @@ public: llvm::DenseMap<VersionTuple, VersionTuple> Mapping; }; - DarwinSDKInfo(VersionTuple Version, VersionTuple MaximumDeploymentTarget, - llvm::DenseMap<OSEnvPair::StorageType, - Optional<RelatedTargetVersionMapping>> - VersionMappings = - llvm::DenseMap<OSEnvPair::StorageType, - Optional<RelatedTargetVersionMapping>>()) + DarwinSDKInfo( + VersionTuple Version, VersionTuple MaximumDeploymentTarget, + llvm::DenseMap<OSEnvPair::StorageType, + std::optional<RelatedTargetVersionMapping>> + VersionMappings = + llvm::DenseMap<OSEnvPair::StorageType, + std::optional<RelatedTargetVersionMapping>>()) : Version(Version), MaximumDeploymentTarget(MaximumDeploymentTarget), VersionMappings(std::move(VersionMappings)) {} @@ -155,7 +156,8 @@ private: // Need to wrap the value in an optional here as the value has to be default // constructible, and std::unique_ptr doesn't like DarwinSDKInfo being // Optional as Optional is trying to copy it in emplace. - llvm::DenseMap<OSEnvPair::StorageType, Optional<RelatedTargetVersionMapping>> + llvm::DenseMap<OSEnvPair::StorageType, + std::optional<RelatedTargetVersionMapping>> VersionMappings; }; diff --git a/clang/include/clang/Basic/Diagnostic.h b/clang/include/clang/Basic/Diagnostic.h index 9b5272e..68eb48d 100644 --- a/clang/include/clang/Basic/Diagnostic.h +++ b/clang/include/clang/Basic/Diagnostic.h @@ -1512,7 +1512,7 @@ inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, inline const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, - const llvm::Optional<SourceRange> &Opt) { + const std::optional<SourceRange> &Opt) { if (Opt) DB << *Opt; return DB; @@ -1520,15 +1520,14 @@ operator<<(const StreamingDiagnostic &DB, inline const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, - const llvm::Optional<CharSourceRange> &Opt) { + const std::optional<CharSourceRange> &Opt) { if (Opt) DB << *Opt; return DB; } inline const StreamingDiagnostic & -operator<<(const StreamingDiagnostic &DB, - const llvm::Optional<FixItHint> &Opt) { +operator<<(const StreamingDiagnostic &DB, const std::optional<FixItHint> &Opt) { if (Opt) DB << *Opt; return DB; diff --git a/clang/include/clang/Basic/DiagnosticError.h b/clang/include/clang/Basic/DiagnosticError.h index a42329b..3660bd1 100644 --- a/clang/include/clang/Basic/DiagnosticError.h +++ b/clang/include/clang/Basic/DiagnosticError.h @@ -37,8 +37,8 @@ public: /// Extracts and returns the diagnostic payload from the given \c Error if /// the error is a \c DiagnosticError. Returns none if the given error is not /// a \c DiagnosticError. - static Optional<PartialDiagnosticAt> take(llvm::Error &Err) { - Optional<PartialDiagnosticAt> Result; + static std::optional<PartialDiagnosticAt> take(llvm::Error &Err) { + std::optional<PartialDiagnosticAt> Result; Err = llvm::handleErrors(std::move(Err), [&](DiagnosticError &E) { Result = std::move(E.getDiagnostic()); }); diff --git a/clang/include/clang/Basic/DiagnosticIDs.h b/clang/include/clang/Basic/DiagnosticIDs.h index 3211dba..6dd78bf 100644 --- a/clang/include/clang/Basic/DiagnosticIDs.h +++ b/clang/include/clang/Basic/DiagnosticIDs.h @@ -238,10 +238,10 @@ public: /// Given a group ID, returns the flag that toggles the group. /// For example, for "deprecated-declarations", returns /// Group::DeprecatedDeclarations. - static llvm::Optional<diag::Group> getGroupForWarningOption(StringRef); + static std::optional<diag::Group> getGroupForWarningOption(StringRef); /// Return the lowest-level group that contains the specified diagnostic. - static llvm::Optional<diag::Group> getGroupForDiag(unsigned DiagID); + static std::optional<diag::Group> getGroupForDiag(unsigned DiagID); /// Return the lowest-level warning option that enables the specified /// diagnostic. diff --git a/clang/include/clang/Basic/FileSystemStatCache.h b/clang/include/clang/Basic/FileSystemStatCache.h index e9f9fa3..5a003a7 100644 --- a/clang/include/clang/Basic/FileSystemStatCache.h +++ b/clang/include/clang/Basic/FileSystemStatCache.h @@ -55,7 +55,7 @@ public: protected: // FIXME: The pointer here is a non-owning/optional reference to the - // unique_ptr. Optional<unique_ptr<vfs::File>&> might be nicer, but + // unique_ptr. std::optional<unique_ptr<vfs::File>&> might be nicer, but // Optional needs some work to support references so this isn't possible yet. virtual std::error_code getStat(StringRef Path, llvm::vfs::Status &Status, bool isFile, diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index 47d04f3..38261c4 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -467,7 +467,7 @@ public: /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=. /// This overrides the default ABI used by the target. - llvm::Optional<TargetCXXABI::Kind> CXXABI; + std::optional<TargetCXXABI::Kind> CXXABI; /// Indicates whether the front-end is explicitly told that the /// input is a header file (i.e. -x c-header). diff --git a/clang/include/clang/Basic/Module.h b/clang/include/clang/Basic/Module.h index cb430d5..fc6d29a 100644 --- a/clang/include/clang/Basic/Module.h +++ b/clang/include/clang/Basic/Module.h @@ -241,8 +241,8 @@ public: std::string FileName; bool IsUmbrella = false; bool HasBuiltinHeader = false; - Optional<off_t> Size; - Optional<time_t> ModTime; + std::optional<off_t> Size; + std::optional<time_t> ModTime; }; /// Headers that are mentioned in the module map file but that we have not diff --git a/clang/include/clang/Basic/ProfileList.h b/clang/include/clang/Basic/ProfileList.h index 23829bd..c4faf06 100644 --- a/clang/include/clang/Basic/ProfileList.h +++ b/clang/include/clang/Basic/ProfileList.h @@ -42,8 +42,8 @@ private: std::unique_ptr<ProfileSpecialCaseList> SCL; const bool Empty; SourceManager &SM; - llvm::Optional<ExclusionType> inSection(StringRef Section, StringRef Prefix, - StringRef Query) const; + std::optional<ExclusionType> inSection(StringRef Section, StringRef Prefix, + StringRef Query) const; public: ProfileList(ArrayRef<std::string> Paths, SourceManager &SM); @@ -52,13 +52,13 @@ public: bool isEmpty() const { return Empty; } ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const; - llvm::Optional<ExclusionType> + std::optional<ExclusionType> isFunctionExcluded(StringRef FunctionName, CodeGenOptions::ProfileInstrKind Kind) const; - llvm::Optional<ExclusionType> + std::optional<ExclusionType> isLocationExcluded(SourceLocation Loc, CodeGenOptions::ProfileInstrKind Kind) const; - llvm::Optional<ExclusionType> + std::optional<ExclusionType> isFileExcluded(StringRef FileName, CodeGenOptions::ProfileInstrKind Kind) const; }; diff --git a/clang/include/clang/Basic/Sarif.h b/clang/include/clang/Basic/Sarif.h index 9fbe70e..aec1c63 100644 --- a/clang/include/clang/Basic/Sarif.h +++ b/clang/include/clang/Basic/Sarif.h @@ -73,7 +73,7 @@ class SarifArtifactLocation { private: friend class clang::SarifDocumentWriter; - llvm::Optional<uint32_t> Index; + std::optional<uint32_t> Index; std::string URI; SarifArtifactLocation() = delete; @@ -106,8 +106,8 @@ class SarifArtifact { private: friend class clang::SarifDocumentWriter; - llvm::Optional<uint32_t> Offset; - llvm::Optional<size_t> Length; + std::optional<uint32_t> Offset; + std::optional<size_t> Length; std::string MimeType; SarifArtifactLocation Location; llvm::SmallVector<std::string, 4> Roles; @@ -325,7 +325,7 @@ class SarifResult { std::string DiagnosticMessage; llvm::SmallVector<CharSourceRange, 8> Locations; llvm::SmallVector<ThreadFlow, 8> ThreadFlows; - llvm::Optional<SarifResultLevel> LevelOverride; + std::optional<SarifResultLevel> LevelOverride; SarifResult() = delete; explicit SarifResult(uint32_t RuleIdx) : RuleIdx(RuleIdx) {} diff --git a/clang/include/clang/Basic/SourceManager.h b/clang/include/clang/Basic/SourceManager.h index 27c8fe8..a877308 100644 --- a/clang/include/clang/Basic/SourceManager.h +++ b/clang/include/clang/Basic/SourceManager.h @@ -212,7 +212,7 @@ public: /// /// \param Loc If specified, is the location that invalid file diagnostics /// will be emitted at. - llvm::Optional<llvm::MemoryBufferRef> + std::optional<llvm::MemoryBufferRef> getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc = SourceLocation()) const; @@ -235,7 +235,7 @@ public: llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const; /// Return the buffer, only if it has been loaded. - llvm::Optional<llvm::MemoryBufferRef> getBufferIfLoaded() const { + std::optional<llvm::MemoryBufferRef> getBufferIfLoaded() const { if (Buffer) return Buffer->getMemBufferRef(); return std::nullopt; @@ -243,7 +243,7 @@ public: /// Return a StringRef to the source buffer data, only if it has already /// been loaded. - llvm::Optional<StringRef> getBufferDataIfLoaded() const { + std::optional<StringRef> getBufferDataIfLoaded() const { if (Buffer) return Buffer->getBuffer(); return std::nullopt; @@ -258,7 +258,7 @@ public: /// Set the buffer to one that's not owned (or to nullptr). /// /// \pre Buffer cannot already be set. - void setUnownedBuffer(llvm::Optional<llvm::MemoryBufferRef> B) { + void setUnownedBuffer(std::optional<llvm::MemoryBufferRef> B) { assert(!Buffer && "Expected to be called right after construction"); if (B) setBuffer(llvm::MemoryBuffer::getMemBuffer(*B)); @@ -941,7 +941,7 @@ public: /// Retrieve the memory buffer associated with the given file. /// /// Returns std::nullopt if the buffer is not valid. - llvm::Optional<llvm::MemoryBufferRef> + std::optional<llvm::MemoryBufferRef> getMemoryBufferForFileOrNone(const FileEntry *File); /// Retrieve the memory buffer associated with the given file. @@ -1023,7 +1023,7 @@ public: /// /// If there is an error opening this buffer the first time, return /// std::nullopt. - llvm::Optional<llvm::MemoryBufferRef> + std::optional<llvm::MemoryBufferRef> getBufferOrNone(FileID FID, SourceLocation Loc = SourceLocation()) const { if (auto *Entry = getSLocEntryForFile(FID)) return Entry->getFile().getContentCache().getBufferOrNone( @@ -1060,7 +1060,7 @@ public: /// buffer that's not represented by a filename. /// /// Returns std::nullopt for non-files and built-in files. - Optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const; + std::optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const; /// Returns the FileEntry record for the provided SLocEntry. const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const @@ -1079,13 +1079,13 @@ public: /// specified FileID, returning std::nullopt if invalid. /// /// \param FID The file ID whose contents will be returned. - llvm::Optional<StringRef> getBufferDataOrNone(FileID FID) const; + std::optional<StringRef> getBufferDataOrNone(FileID FID) const; /// Return a StringRef to the source buffer data for the /// specified FileID, returning std::nullopt if it's not yet loaded. /// /// \param FID The file ID whose contents will be returned. - llvm::Optional<StringRef> getBufferDataIfLoaded(FileID FID) const; + std::optional<StringRef> getBufferDataIfLoaded(FileID FID) const; /// Get the number of FileIDs (files and macros) that were created /// during preprocessing of \p FID, including it. @@ -1696,7 +1696,7 @@ public: // Produce notes describing the current source location address space usage. void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag, - Optional<unsigned> MaxNotes = 32) const; + std::optional<unsigned> MaxNotes = 32) const; /// Get the number of local SLocEntries we have. unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); } diff --git a/clang/include/clang/Basic/TargetInfo.h b/clang/include/clang/Basic/TargetInfo.h index a5aea33..8a3151d 100644 --- a/clang/include/clang/Basic/TargetInfo.h +++ b/clang/include/clang/Basic/TargetInfo.h @@ -255,9 +255,9 @@ protected: unsigned MaxOpenCLWorkGroupSize; - Optional<unsigned> MaxBitIntWidth; + std::optional<unsigned> MaxBitIntWidth; - Optional<llvm::Triple> DarwinTargetVariantTriple; + std::optional<llvm::Triple> DarwinTargetVariantTriple; // TargetInfo Constructor. Default initializes all fields. TargetInfo(const llvm::Triple &T); @@ -953,7 +953,7 @@ public: virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0; /// Returns target-specific min and max values VScale_Range. - virtual Optional<std::pair<unsigned, unsigned>> + virtual std::optional<std::pair<unsigned, unsigned>> getVScaleRange(const LangOptions &LangOpts) const { return std::nullopt; } @@ -1179,7 +1179,7 @@ public: /// Replace some escaped characters with another string based on /// target-specific rules - virtual llvm::Optional<std::string> handleAsmEscapedChar(char C) const { + virtual std::optional<std::string> handleAsmEscapedChar(char C) const { return std::nullopt; } @@ -1198,7 +1198,7 @@ public: } /// Returns the target ID if supported. - virtual llvm::Optional<std::string> getTargetID() const { + virtual std::optional<std::string> getTargetID() const { return std::nullopt; } @@ -1448,7 +1448,7 @@ public: // Get the cache line size of a given cpu. This method switches over // the given cpu and returns "std::nullopt" if the CPU is not found. - virtual Optional<unsigned> getCPUCacheLineSize() const { + virtual std::optional<unsigned> getCPUCacheLineSize() const { return std::nullopt; } @@ -1525,7 +1525,7 @@ public: /// for constant global memory. It must be possible to convert pointers into /// this address space to LangAS::Default. If no such address space exists, /// this may return std::nullopt, and such optimizations will be disabled. - virtual llvm::Optional<LangAS> getConstantAddressSpace() const { + virtual std::optional<LangAS> getConstantAddressSpace() const { return LangAS::Default; } @@ -1700,10 +1700,10 @@ public: /// Returns the version of the darwin target variant SDK which was used during /// the compilation if one was specified, or an empty version otherwise. - const Optional<VersionTuple> getDarwinTargetVariantSDKVersion() const { + const std::optional<VersionTuple> getDarwinTargetVariantSDKVersion() const { return !getTargetOpts().DarwinTargetVariantSDKVersion.empty() ? getTargetOpts().DarwinTargetVariantSDKVersion - : Optional<VersionTuple>(); + : std::optional<VersionTuple>(); } protected: diff --git a/clang/include/clang/CrossTU/CrossTranslationUnit.h b/clang/include/clang/CrossTU/CrossTranslationUnit.h index 5002c1c..0abb4e5 100644 --- a/clang/include/clang/CrossTU/CrossTranslationUnit.h +++ b/clang/include/clang/CrossTU/CrossTranslationUnit.h @@ -182,7 +182,7 @@ public: ASTUnit *Unit); /// Get a name to identify a named decl. - static llvm::Optional<std::string> getLookupName(const NamedDecl *ND); + static std::optional<std::string> getLookupName(const NamedDecl *ND); /// Emit diagnostics for the user for potential configuration errors. void emitCrossTUDiagnostics(const IndexError &IE); @@ -194,7 +194,7 @@ public: /// source-location, empty is returned. /// \note Macro expansion tracking for imported TUs is not implemented yet. /// It returns empty unconditionally. - llvm::Optional<clang::MacroExpansionContext> + std::optional<clang::MacroExpansionContext> getMacroExpansionContextForSourceLocation( const clang::SourceLocation &ToLoc) const; @@ -264,7 +264,7 @@ private: StringRef InvocationListFilePath; /// In case of on-demand parsing, the invocations for parsing the source /// files is stored. - llvm::Optional<InvocationListTy> InvocationList; + std::optional<InvocationListTy> InvocationList; index_error_code PreviousParsingResult = index_error_code::success; }; diff --git a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h index e6c1866..55c7bb3 100644 --- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h +++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h @@ -68,8 +68,8 @@ public: /// \returns an optional JSON Object representing the payload that libclang /// expects for providing symbol information for a single symbol. If this is /// not a known symbol returns \c None. - static Optional<Object> serializeSingleSymbolSGF(StringRef USR, - const APISet &API); + static std::optional<Object> serializeSingleSymbolSGF(StringRef USR, + const APISet &API); /// The kind of a relationship between two symbols. enum RelationshipKind { @@ -121,7 +121,7 @@ private: /// \returns \c std::nullopt if this \p Record should be skipped, or a JSON /// object containing common symbol information of \p Record. template <typename RecordTy> - Optional<Object> serializeAPIRecord(const RecordTy &Record) const; + std::optional<Object> serializeAPIRecord(const RecordTy &Record) const; /// Helper method to serialize second-level member records of \p Record and /// the member-of relationships. diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index c5bfbfe..02d48de 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -4267,7 +4267,7 @@ struct FormatStyle { WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros; } - llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const; + std::optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const; // Stores per-language styles. A FormatStyle instance inside has an empty // StyleSet. A FormatStyle instance returned by the Get method has its @@ -4279,7 +4279,7 @@ struct FormatStyle { struct FormatStyleSet { typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType; - llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const; + std::optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const; // Adds \p Style to this FormatStyleSet. Style must not have an associated // FormatStyleSet. diff --git a/clang/include/clang/Frontend/ASTUnit.h b/clang/include/clang/Frontend/ASTUnit.h index 62c0190..78dc4ba 100644 --- a/clang/include/clang/Frontend/ASTUnit.h +++ b/clang/include/clang/Frontend/ASTUnit.h @@ -222,7 +222,7 @@ private: llvm::StringMap<SourceLocation> PreambleSrcLocCache; /// The contents of the preamble. - llvm::Optional<PrecompiledPreamble> Preamble; + std::optional<PrecompiledPreamble> Preamble; /// When non-NULL, this is the buffer used to store the contents of /// the main file when it has been padded for use with the precompiled @@ -835,7 +835,7 @@ public: bool SingleFileParse = false, bool UserFilesAreVolatile = false, bool ForSerialization = false, bool RetainExcludedConditionalBlocks = false, - llvm::Optional<StringRef> ModuleFormat = std::nullopt, + std::optional<StringRef> ModuleFormat = std::nullopt, std::unique_ptr<ASTUnit> *ErrAST = nullptr, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); diff --git a/clang/include/clang/Frontend/CommandLineSourceLoc.h b/clang/include/clang/Frontend/CommandLineSourceLoc.h index 4637a1c..074800a 100644 --- a/clang/include/clang/Frontend/CommandLineSourceLoc.h +++ b/clang/include/clang/Frontend/CommandLineSourceLoc.h @@ -77,7 +77,7 @@ struct ParsedSourceRange { /// /// If the end line and column are omitted, the starting line and columns /// are used as the end values. - static Optional<ParsedSourceRange> fromString(StringRef Str) { + static std::optional<ParsedSourceRange> fromString(StringRef Str) { std::pair<StringRef, StringRef> RangeSplit = Str.rsplit('-'); unsigned EndLine, EndColumn; bool HasEndLoc = false; diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h index 04d32c2..f132c96 100644 --- a/clang/include/clang/Frontend/CompilerInstance.h +++ b/clang/include/clang/Frontend/CompilerInstance.h @@ -165,9 +165,10 @@ class CompilerInstance : public ModuleLoader { /// failed. struct OutputFile { std::string Filename; - Optional<llvm::sys::fs::TempFile> File; + std::optional<llvm::sys::fs::TempFile> File; - OutputFile(std::string filename, Optional<llvm::sys::fs::TempFile> file) + OutputFile(std::string filename, + std::optional<llvm::sys::fs::TempFile> file) : Filename(std::move(filename)), File(std::move(file)) {} }; diff --git a/clang/include/clang/Frontend/FrontendOptions.h b/clang/include/clang/Frontend/FrontendOptions.h index a757749..6efe3cd 100644 --- a/clang/include/clang/Frontend/FrontendOptions.h +++ b/clang/include/clang/Frontend/FrontendOptions.h @@ -223,7 +223,7 @@ class FrontendInputFile { /// The input, if it comes from a buffer rather than a file. This object /// does not own the buffer, and the caller is responsible for ensuring /// that it outlives any users. - llvm::Optional<llvm::MemoryBufferRef> Buffer; + std::optional<llvm::MemoryBufferRef> Buffer; /// The kind of input, e.g., C source, AST file, LLVM IR. InputKind Kind; @@ -493,10 +493,10 @@ public: std::string AuxTriple; /// Auxiliary target CPU for CUDA/HIP compilation. - Optional<std::string> AuxTargetCPU; + std::optional<std::string> AuxTargetCPU; /// Auxiliary target features for CUDA/HIP compilation. - Optional<std::vector<std::string>> AuxTargetFeatures; + std::optional<std::vector<std::string>> AuxTargetFeatures; /// Filename to write statistics to. std::string StatsFile; diff --git a/clang/include/clang/Lex/HeaderMap.h b/clang/include/clang/Lex/HeaderMap.h index 9836765..efaf481 100644 --- a/clang/include/clang/Lex/HeaderMap.h +++ b/clang/include/clang/Lex/HeaderMap.h @@ -49,7 +49,7 @@ public: for (unsigned Bucket = 0; Bucket < NumBuckets; ++Bucket) { HMapBucket B = getBucket(Bucket); if (B.Key != HMAP_EmptyBucketKey) - if (Optional<StringRef> Key = getString(B.Key)) + if (std::optional<StringRef> Key = getString(B.Key)) Callback(*Key); } } @@ -75,7 +75,7 @@ private: /// Look up the specified string in the string table. If the string index is /// not valid, return std::nullopt. - Optional<StringRef> getString(unsigned StrTabIdx) const; + std::optional<StringRef> getString(unsigned StrTabIdx) const; }; /// This class represents an Apple concept known as a 'header map'. To the diff --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h index 3e21987..c383544 100644 --- a/clang/include/clang/Lex/Lexer.h +++ b/clang/include/clang/Lex/Lexer.h @@ -553,9 +553,9 @@ public: /// Finds the token that comes right after the given location. /// /// Returns the next token, or none if the location is inside a macro. - static Optional<Token> findNextToken(SourceLocation Loc, - const SourceManager &SM, - const LangOptions &LangOpts); + static std::optional<Token> findNextToken(SourceLocation Loc, + const SourceManager &SM, + const LangOptions &LangOpts); /// Checks that the given token is the first token that occurs after /// the given location (this excludes comments and whitespace). Returns the @@ -770,10 +770,10 @@ private: void codeCompleteIncludedFile(const char *PathStart, const char *CompletionPoint, bool IsAngled); - llvm::Optional<uint32_t> + std::optional<uint32_t> tryReadNumericUCN(const char *&StartPtr, const char *SlashLoc, Token *Result); - llvm::Optional<uint32_t> tryReadNamedUCN(const char *&StartPtr, - const char *SlashLoc, Token *Result); + std::optional<uint32_t> tryReadNamedUCN(const char *&StartPtr, + const char *SlashLoc, Token *Result); /// Read a universal character name. /// diff --git a/clang/include/clang/Lex/ModuleMap.h b/clang/include/clang/Lex/ModuleMap.h index 2ce5961..77a1bda 100644 --- a/clang/include/clang/Lex/ModuleMap.h +++ b/clang/include/clang/Lex/ModuleMap.h @@ -467,7 +467,7 @@ public: /// provided, only headers with same size and modtime are resolved. If File /// is not set, all headers are resolved. void resolveHeaderDirectives(Module *Mod, - llvm::Optional<const FileEntry *> File) const; + std::optional<const FileEntry *> File) const; /// Reports errors if a module must not include a specific file. /// @@ -733,7 +733,7 @@ public: } /// Return a cached module load. - llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) { + std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) { auto I = CachedModuleLoads.find(&II); if (I == CachedModuleLoads.end()) return std::nullopt; diff --git a/clang/include/clang/Lex/PreprocessingRecord.h b/clang/include/clang/Lex/PreprocessingRecord.h index fd269fd..197c979 100644 --- a/clang/include/clang/Lex/PreprocessingRecord.h +++ b/clang/include/clang/Lex/PreprocessingRecord.h @@ -291,8 +291,8 @@ class Token; /// Optionally returns true or false if the preallocated preprocessed /// entity with index \p Index came from file \p FID. - virtual Optional<bool> isPreprocessedEntityInFileID(unsigned Index, - FileID FID) { + virtual std::optional<bool> isPreprocessedEntityInFileID(unsigned Index, + FileID FID) { return std::nullopt; } diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h index afef702..0cad3737 100644 --- a/clang/include/clang/Lex/Preprocessor.h +++ b/clang/include/clang/Lex/Preprocessor.h @@ -581,7 +581,7 @@ private: void clearSkipInfo() { SkipInfo.reset(); } - llvm::Optional<PreambleSkipInfo> SkipInfo; + std::optional<PreambleSkipInfo> SkipInfo; private: SmallVector<PPConditionalInfo, 4> ConditionalStack; @@ -897,9 +897,9 @@ private: }; struct MacroAnnotations { - llvm::Optional<MacroAnnotationInfo> DeprecationInfo; - llvm::Optional<MacroAnnotationInfo> RestrictExpansionInfo; - llvm::Optional<SourceLocation> FinalAnnotationLoc; + std::optional<MacroAnnotationInfo> DeprecationInfo; + std::optional<MacroAnnotationInfo> RestrictExpansionInfo; + std::optional<SourceLocation> FinalAnnotationLoc; static MacroAnnotations makeDeprecation(SourceLocation Loc, std::string Msg) { @@ -2581,14 +2581,14 @@ public: PreambleConditionalStack.setStack(s); } - void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s, - llvm::Optional<PreambleSkipInfo> SkipInfo) { + void setReplayablePreambleConditionalStack( + ArrayRef<PPConditionalInfo> s, std::optional<PreambleSkipInfo> SkipInfo) { PreambleConditionalStack.startReplaying(); PreambleConditionalStack.setStack(s); PreambleConditionalStack.SkipInfo = SkipInfo; } - llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const { + std::optional<PreambleSkipInfo> getPreambleSkipInfo() const { return PreambleConditionalStack.SkipInfo; } diff --git a/clang/include/clang/Lex/PreprocessorOptions.h b/clang/include/clang/Lex/PreprocessorOptions.h index 8ad2cc2..432f5df 100644 --- a/clang/include/clang/Lex/PreprocessorOptions.h +++ b/clang/include/clang/Lex/PreprocessorOptions.h @@ -211,7 +211,7 @@ public: /// Enables a client to cache the directives for a file and provide them /// across multiple compiler invocations. /// FIXME: Allow returning an error. - std::function<Optional<ArrayRef<dependency_directives_scan::Directive>>( + std::function<std::optional<ArrayRef<dependency_directives_scan::Directive>>( FileEntryRef)> DependencyDirectivesForFile; @@ -222,7 +222,7 @@ public: bool DisablePragmaDebugCrash = false; /// If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH. - Optional<uint64_t> SourceDateEpoch; + std::optional<uint64_t> SourceDateEpoch; public: PreprocessorOptions() : PrecompiledPreambleBytes(0, false) {} diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index 4f87d55..6f9581b 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -2949,7 +2949,7 @@ private: SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); - Optional<AvailabilitySpec> ParseAvailabilitySpec(); + std::optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, @@ -3070,7 +3070,7 @@ private: void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, - Optional<llvm::function_ref<void()>> CodeCompletionHandler = + std::optional<llvm::function_ref<void()>> CodeCompletionHandler = std::nullopt); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); @@ -3080,7 +3080,7 @@ private: bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, - llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); + std::optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); diff --git a/clang/include/clang/Sema/CodeCompleteConsumer.h b/clang/include/clang/Sema/CodeCompleteConsumer.h index 063c960..33a10c3 100644 --- a/clang/include/clang/Sema/CodeCompleteConsumer.h +++ b/clang/include/clang/Sema/CodeCompleteConsumer.h @@ -359,7 +359,7 @@ private: /// The scope specifier that comes before the completion token e.g. /// "a::b::" - llvm::Optional<CXXScopeSpec> ScopeSpecifier; + std::optional<CXXScopeSpec> ScopeSpecifier; /// A set of declaration contexts visited by Sema when doing lookup for /// code completion. @@ -422,7 +422,7 @@ public: return VisitedContexts; } - llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() { + std::optional<const CXXScopeSpec *> getCXXScopeSpecifier() { if (ScopeSpecifier) return &*ScopeSpecifier; return std::nullopt; diff --git a/clang/include/clang/Sema/Lookup.h b/clang/include/clang/Sema/Lookup.h index 34a8756..70f900b 100644 --- a/clang/include/clang/Sema/Lookup.h +++ b/clang/include/clang/Sema/Lookup.h @@ -508,7 +508,7 @@ public: Paths = nullptr; } } else { - llvm::Optional<AmbiguityKind> SavedAK; + std::optional<AmbiguityKind> SavedAK; bool WasAmbiguous = false; if (ResultKind == Ambiguous) { SavedAK = Ambiguity; diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h index 7290879..be5cdb6 100644 --- a/clang/include/clang/Sema/Scope.h +++ b/clang/include/clang/Sema/Scope.h @@ -222,7 +222,7 @@ private: /// (e.g. return a function parameter). /// 3) std::nullopt value means that there is no NRVO candidate in this scope /// (i.e. there are no return statements in this scope). - Optional<VarDecl *> NRVO; + std::optional<VarDecl *> NRVO; /// Represents return slots for NRVO candidates in the current scope. /// If a variable is present in this set, it means that a return slot is diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 33d8ed6..dce97c6 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -1348,7 +1348,7 @@ public: ValueDecl *Decl = nullptr; DeclContext *Context = nullptr; }; - llvm::Optional<InitializationContext> DelayedDefaultInitializationContext; + std::optional<InitializationContext> DelayedDefaultInitializationContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, @@ -1626,7 +1626,7 @@ public: private: std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager; - Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; + std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; bool WarnedDarwinSDKInfoMissing = false; @@ -1860,8 +1860,8 @@ public: // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. - llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; - llvm::Optional<unsigned> PartialDiagId; + std::optional<ImmediateDiagBuilder> ImmediateDiag; + std::optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined @@ -6610,7 +6610,7 @@ public: BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, - Optional<unsigned> NumExpansions); + std::optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); @@ -6717,16 +6717,12 @@ public: SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); - ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, - SourceLocation PlacementLParen, - MultiExprArg PlacementArgs, - SourceLocation PlacementRParen, - SourceRange TypeIdParens, - QualType AllocType, - TypeSourceInfo *AllocTypeInfo, - Optional<Expr *> ArraySize, - SourceRange DirectInitRange, - Expr *Initializer); + ExprResult + BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, + MultiExprArg PlacementArgs, SourceLocation PlacementRParen, + SourceRange TypeIdParens, QualType AllocType, + TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize, + SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. @@ -7099,7 +7095,7 @@ public: /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, - Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = + std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = std::nullopt); /// Endow the lambda scope info with the relevant properties. @@ -7124,8 +7120,8 @@ public: } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, - Expr *&Init); + std::optional<unsigned> NumExpansions, IdentifierInfo *Id, + bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. @@ -7266,15 +7262,15 @@ private: /// the case of lambdas) set up the LocalInstantiationScope of the current /// function. bool SetupConstraintScope( - FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, + FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope); /// Used during constraint checking, sets up the constraint template argument /// lists, and calls SetupConstraintScope to set up the /// LocalInstantiationScope to have the proper set of ParVarDecls configured. - llvm::Optional<MultiLevelTemplateArgumentList> + std::optional<MultiLevelTemplateArgumentList> SetupConstraintCheckingTemplateArgumentsAndScope( - FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, + FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, LocalInstantiationScope &Scope); private: @@ -7988,7 +7984,7 @@ public: explicit operator bool() const { return isRequired(); } private: - llvm::Optional<SourceLocation> TemplateKW; + std::optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { @@ -8802,14 +8798,13 @@ public: /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions); + std::optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. - QualType CheckPackExpansion(QualType Pattern, - SourceRange PatternRange, + QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions); + std::optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. @@ -8828,7 +8823,7 @@ public: /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions); + std::optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly @@ -8864,13 +8859,11 @@ public: /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. - bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, - SourceRange PatternRange, - ArrayRef<UnexpandedParameterPack> Unexpanded, - const MultiLevelTemplateArgumentList &TemplateArgs, - bool &ShouldExpand, - bool &RetainExpansion, - Optional<unsigned> &NumExpansions); + bool CheckParameterPacksForExpansion( + SourceLocation EllipsisLoc, SourceRange PatternRange, + ArrayRef<UnexpandedParameterPack> Unexpanded, + const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, + bool &RetainExpansion, std::optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. @@ -8879,8 +8872,8 @@ public: /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. - Optional<unsigned> getNumArgumentsInExpansion(QualType T, - const MultiLevelTemplateArgumentList &TemplateArgs); + std::optional<unsigned> getNumArgumentsInExpansion( + QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. @@ -8908,9 +8901,8 @@ public: /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( - TemplateArgumentLoc OrigLoc, - SourceLocation &Ellipsis, - Optional<unsigned> &NumExpansions) const; + TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, + std::optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of @@ -8918,7 +8910,7 @@ public: /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. - Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); + std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) @@ -9653,7 +9645,7 @@ public: /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. - Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; + std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. @@ -9684,7 +9676,7 @@ public: Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer; } - llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> + std::optional<ExpressionEvaluationContextRecord::InitializationContext> InnermostDeclarationWithDelayedImmediateInvocations() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); @@ -9699,12 +9691,11 @@ public: return std::nullopt; } - llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> + std::optional<ExpressionEvaluationContextRecord::InitializationContext> OutermostDeclarationWithDelayedImmediateInvocations() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); - llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> - Res; + std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res; for (auto &Ctx : llvm::reverse(ExprEvalContexts)) { if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && !Ctx.DelayedDefaultInitializationContext && Res) @@ -9949,7 +9940,7 @@ public: ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, - int indexAdjustment, Optional<unsigned> NumExpansions, + int indexAdjustment, std::optional<unsigned> NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints = true); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, @@ -10929,7 +10920,7 @@ private: OpenMPDirectiveKind Kind; /// The directive with indirect clause. - Optional<Expr *> Indirect; + std::optional<Expr *> Indirect; /// The directive location. SourceLocation Loc; @@ -11684,7 +11675,7 @@ public: /// \returns std::nullopt, if the function/variant function are not compatible /// with the pragma, pair of original function/variant ref expression /// otherwise. - Optional<std::pair<FunctionDecl *, Expr *>> + std::optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR); @@ -12798,7 +12789,7 @@ public: return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } - llvm::Optional<bool> getKnownValue() const { + std::optional<bool> getKnownValue() const { if (!HasKnownValue) return std::nullopt; return KnownValue; @@ -13349,7 +13340,8 @@ public: void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); - void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, + void CodeCompleteObjCMethodDecl(Scope *S, + std::optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, diff --git a/clang/include/clang/Sema/SemaConcept.h b/clang/include/clang/Sema/SemaConcept.h index 1cbe18f..74210bc2 100644 --- a/clang/include/clang/Sema/SemaConcept.h +++ b/clang/include/clang/Sema/SemaConcept.h @@ -29,7 +29,7 @@ class Sema; struct AtomicConstraint { const Expr *ConstraintExpr; - Optional<ArrayRef<TemplateArgumentLoc>> ParameterMapping; + std::optional<ArrayRef<TemplateArgumentLoc>> ParameterMapping; AtomicConstraint(Sema &S, const Expr *ConstraintExpr) : ConstraintExpr(ConstraintExpr) { }; @@ -145,9 +145,9 @@ struct NormalizedConstraint { } private: - static Optional<NormalizedConstraint> + static std::optional<NormalizedConstraint> fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef<const Expr *> E); - static Optional<NormalizedConstraint> + static std::optional<NormalizedConstraint> fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E); }; diff --git a/clang/include/clang/Sema/SemaLambda.h b/clang/include/clang/Sema/SemaLambda.h index fcc4ebe..3c9d22d 100644 --- a/clang/include/clang/Sema/SemaLambda.h +++ b/clang/include/clang/Sema/SemaLambda.h @@ -31,7 +31,7 @@ class Sema; /// of the capture-capable lambda's LambdaScopeInfo. /// See Implementation for more detailed comments. -Optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda( +std::optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda( ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, ValueDecl *VarToCapture, Sema &S); diff --git a/clang/include/clang/Sema/Template.h b/clang/include/clang/Sema/Template.h index 52fff8e..9083894 100644 --- a/clang/include/clang/Sema/Template.h +++ b/clang/include/clang/Sema/Template.h @@ -601,7 +601,7 @@ enum class TemplateSubstitutionKind : char { // A few supplemental visitor functions. Decl *VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, - Optional<const ASTTemplateArgumentListInfo *> + std::optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs = std::nullopt, RewriteKind RK = RewriteKind::None); Decl *VisitFunctionDecl(FunctionDecl *D, diff --git a/clang/include/clang/Sema/TemplateDeduction.h b/clang/include/clang/Sema/TemplateDeduction.h index e8d235c..a3cf790 100644 --- a/clang/include/clang/Sema/TemplateDeduction.h +++ b/clang/include/clang/Sema/TemplateDeduction.h @@ -285,7 +285,7 @@ struct DeductionFailureInfo { /// Return the index of the call argument that this deduction /// failure refers to, if any. - llvm::Optional<unsigned> getCallArgIndex(); + std::optional<unsigned> getCallArgIndex(); /// Free any memory associated with this deduction failure. void Destroy(); diff --git a/clang/include/clang/Serialization/ASTReader.h b/clang/include/clang/Serialization/ASTReader.h index f2a7f26..e5ced39 100644 --- a/clang/include/clang/Serialization/ASTReader.h +++ b/clang/include/clang/Serialization/ASTReader.h @@ -463,7 +463,7 @@ private: SourceLocation CurrentImportLoc; /// The module kind that is currently deserializing. - Optional<ModuleKind> CurrentDeserializingModuleKind; + std::optional<ModuleKind> CurrentDeserializingModuleKind; /// The global module index, if loaded. std::unique_ptr<GlobalModuleIndex> GlobalIndex; @@ -883,7 +883,7 @@ private: SourceLocation PointersToMembersPragmaLocation; /// The pragma float_control state. - Optional<FPOptionsOverride> FpPragmaCurrentValue; + std::optional<FPOptionsOverride> FpPragmaCurrentValue; SourceLocation FpPragmaCurrentLocation; struct FpPragmaStackEntry { FPOptionsOverride Value; @@ -895,7 +895,7 @@ private: llvm::SmallVector<std::string, 2> FpPragmaStrings; /// The pragma align/pack state. - Optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue; + std::optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue; SourceLocation PragmaAlignPackCurrentLocation; struct PragmaAlignPackStackEntry { Sema::AlignPackInfo Value; @@ -1778,8 +1778,8 @@ public: /// Optionally returns true or false if the preallocated preprocessed /// entity with index \p Index came from file \p FID. - Optional<bool> isPreprocessedEntityInFileID(unsigned Index, - FileID FID) override; + std::optional<bool> isPreprocessedEntityInFileID(unsigned Index, + FileID FID) override; /// Read a preallocated skipped range from the external source. SourceRange ReadSkippedRange(unsigned Index) override; @@ -2142,7 +2142,7 @@ public: unsigned getModuleFileID(ModuleFile *M); /// Return a descriptor for the corresponding module. - llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override; + std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override; ExtKind hasExternalDefinitions(const Decl *D) override; diff --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h index d89eaf50..e5ebb04 100644 --- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h +++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h @@ -453,13 +453,13 @@ public: bool isInteresting(SVal V) const; bool isInteresting(const LocationContext *LC) const; - Optional<bugreporter::TrackingKind> + std::optional<bugreporter::TrackingKind> getInterestingnessKind(SymbolRef sym) const; - Optional<bugreporter::TrackingKind> + std::optional<bugreporter::TrackingKind> getInterestingnessKind(const MemRegion *R) const; - Optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const; + std::optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const; /// Returns whether or not this report should be considered valid. /// @@ -779,8 +779,8 @@ public: return T->getTagKind() == &Kind; } - Optional<std::string> generateMessage(BugReporterContext &BRC, - PathSensitiveBugReport &R) const { + std::optional<std::string> generateMessage(BugReporterContext &BRC, + PathSensitiveBugReport &R) const { std::string Msg = Cb(BRC, R); if (Msg.empty()) return std::nullopt; diff --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h index 6ccae6f..c479dae 100644 --- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h +++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h @@ -503,13 +503,9 @@ public: bool printValue(const Expr *CondVarExpr, raw_ostream &Out, const ExplodedNode *N, bool TookTrue, bool IsAssuming); - bool patternMatch(const Expr *Ex, - const Expr *ParentEx, - raw_ostream &Out, - BugReporterContext &BRC, - PathSensitiveBugReport &R, - const ExplodedNode *N, - Optional<bool> &prunable, + bool patternMatch(const Expr *Ex, const Expr *ParentEx, raw_ostream &Out, + BugReporterContext &BRC, PathSensitiveBugReport &R, + const ExplodedNode *N, std::optional<bool> &prunable, bool IsSameFieldName); static bool isPieceMessageGeneric(const PathDiagnosticPiece *Piece); diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h index 360f81e..5244f9e 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h @@ -43,9 +43,9 @@ enum CallDescriptionFlags : unsigned { /// arguments and the name of the function. class CallDescription { friend class CallEvent; - using MaybeCount = Optional<unsigned>; + using MaybeCount = std::optional<unsigned>; - mutable Optional<const IdentifierInfo *> II; + mutable std::optional<const IdentifierInfo *> II; // The list of the qualified names used to identify the specified CallEvent, // e.g. "{a, b}" represent the qualified names, like "a::b". std::vector<std::string> QualifiedName; diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h index 6ac768c..710bc8c 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -154,7 +154,7 @@ private: ProgramStateRef State; const LocationContext *LCtx; llvm::PointerUnion<const Expr *, const Decl *> Origin; - mutable Optional<bool> Foreign; // Set by CTU analysis. + mutable std::optional<bool> Foreign; // Set by CTU analysis. protected: // This is user data for subclasses. @@ -423,7 +423,7 @@ public: /// This function converts an argument index to the corresponding /// parameter index. Returns std::nullopt is the argument doesn't correspond /// to any parameter variable. - virtual Optional<unsigned> + virtual std::optional<unsigned> getAdjustedParameterIndex(unsigned ASTArgumentIndex) const { return ASTArgumentIndex; } @@ -442,7 +442,7 @@ public: /// If the call returns a C++ record type then the region of its return value /// can be retrieved from its construction context. - Optional<SVal> getReturnValueUnderConstruction() const; + std::optional<SVal> getReturnValueUnderConstruction() const; // Iterator access to formal parameters and their types. private: @@ -771,12 +771,13 @@ public: return CA->getKind() == CE_CXXMemberOperator; } - Optional<unsigned> + std::optional<unsigned> getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override { // For member operator calls argument 0 on the expression corresponds // to implicit this-parameter on the declaration. - return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1) - : std::nullopt; + return (ASTArgumentIndex > 0) + ? std::optional<unsigned>(ASTArgumentIndex - 1) + : std::nullopt; } unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override { @@ -1035,7 +1036,7 @@ public: bool isArray() const { return getOriginExpr()->isArray(); } - Optional<const clang::Expr *> getArraySizeExpr() const { + std::optional<const clang::Expr *> getArraySizeExpr() const { return getOriginExpr()->getArraySize(); } diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h index ce1407e..9bd5a80 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h @@ -140,7 +140,7 @@ public: /// example, for finding variables that the given symbol was assigned to. static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) { ProgramPoint L = N->getLocation(); - if (Optional<PostStore> PSL = L.getAs<PostStore>()) + if (std::optional<PostStore> PSL = L.getAs<PostStore>()) return reinterpret_cast<const MemRegion*>(PSL->getLocationValue()); return nullptr; } diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h index 2ad5e1f8..4993e79 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h @@ -70,7 +70,7 @@ Nullability getNullabilityAnnotation(QualType Type); /// simple expressions that consist of an optional minus sign token and then a /// token for an integer. If we cannot parse the value then std::nullopt is /// returned. -llvm::Optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP); +std::optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP); class OperatorKind { union { @@ -89,7 +89,7 @@ public: return Op.Bin; } - Optional<BinaryOperatorKind> GetBinaryOp() const { + std::optional<BinaryOperatorKind> GetBinaryOp() const { if (IsBinary) return Op.Bin; return {}; @@ -101,7 +101,7 @@ public: return Op.Un; } - Optional<UnaryOperatorKind> GetUnaryOp() const { + std::optional<UnaryOperatorKind> GetUnaryOp() const { if (!IsBinary) return Op.Un; return {}; diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h index eb84506..c9e6805 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h @@ -37,7 +37,7 @@ class ExprEngine; class SymbolReaper; class ConditionTruthVal { - Optional<bool> Val; + std::optional<bool> Val; public: /// Construct a ConditionTruthVal indicating the constraint is constrained diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h index 5b7e337..69c75a0 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h @@ -168,7 +168,7 @@ public: const ProgramStateRef &getState() const { return State; } - template <typename T> Optional<T> getLocationAs() const & { + template <typename T> std::optional<T> getLocationAs() const & { return Location.getAs<T>(); } diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h index a5e075c..d736615 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h @@ -619,24 +619,24 @@ public: } /// Retreives which element is being constructed in a non-POD type array. - static Optional<unsigned> + static std::optional<unsigned> getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx); /// Retreives which element is being destructed in a non-POD type array. - static Optional<unsigned> + static std::optional<unsigned> getPendingArrayDestruction(ProgramStateRef State, const LocationContext *LCtx); /// Retreives the size of the array in the pending ArrayInitLoopExpr. - static Optional<unsigned> getPendingInitLoop(ProgramStateRef State, - const CXXConstructExpr *E, - const LocationContext *LCtx); + static std::optional<unsigned> + getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, + const LocationContext *LCtx); /// By looking at a certain item that may be potentially part of an object's /// ConstructionContext, retrieve such object's location. A particular /// statement can be transparently passed as \p Item in most cases. - static Optional<SVal> + static std::optional<SVal> getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC); diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h index effe9e4..45e01c6 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h @@ -86,7 +86,7 @@ public: markShouldNotInline(D); } - Optional<bool> mayInline(const Decl *D) { + std::optional<bool> mayInline(const Decl *D) { MapTy::const_iterator I = Map.find(D); if (I != Map.end() && I->second.InlineChecked) return I->second.MayInline; diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h index 74551122..d99240c 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -103,7 +103,7 @@ public: private: const Kind kind; - mutable Optional<RegionOffset> cachedOffset; + mutable std::optional<RegionOffset> cachedOffset; protected: MemRegion(Kind k) : kind(k) {} diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h index 0e37182..ca75c2a 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h @@ -747,7 +747,7 @@ ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val, } inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const { - if (Optional<Loc> L = LV.getAs<Loc>()) + if (std::optional<Loc> L = LV.getAs<Loc>()) return bindLoc(*L, V, LCtx); return this; } @@ -797,7 +797,7 @@ inline SVal ProgramState::getLValue(const IndirectFieldDecl *D, } inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{ - if (Optional<NonLoc> N = Idx.getAs<NonLoc>()) + if (std::optional<NonLoc> N = Idx.getAs<NonLoc>()) return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base); return UnknownVal(); } diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h index d00432d..d5c2dc6 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h @@ -247,7 +247,7 @@ public: bool canReasonAbout(SVal X) const override { const TargetInfo &TI = getBasicVals().getContext().getTargetInfo(); - Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); + std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); if (!SymVal) return true; diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h index 298435f..23bcf4a 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h @@ -237,7 +237,7 @@ public: /// manner. /// /// If \p E is not a constant or cannot be modeled, returns \c std::nullopt. - Optional<SVal> getConstantVal(const Expr *E); + std::optional<SVal> getConstantVal(const Expr *E); NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) { return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals)); @@ -371,8 +371,8 @@ public: } /// Return MemRegionVal on success cast, otherwise return std::nullopt. - Optional<loc::MemRegionVal> getCastedMemRegionVal(const MemRegion *region, - QualType type); + std::optional<loc::MemRegionVal> + getCastedMemRegionVal(const MemRegion *region, QualType type); /// Make an SVal that represents the given symbol. This follows the convention /// of representing Loc-type symbols (symbolic pointers and references) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h index 2e4afb2..4e10d7e 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h @@ -101,7 +101,7 @@ public: /// Convert to the specified SVal type, returning std::nullopt if this SVal is /// not of the desired type. - template <typename T> Optional<T> getAs() const { + template <typename T> std::optional<T> getAs() const { return llvm::dyn_cast<T>(*this); } @@ -568,11 +568,11 @@ struct CastInfo< static bool isPossible(const From &V) { return To::classof(*static_cast<const ::clang::ento::SVal *>(&V)); } - static Optional<To> castFailed() { return Optional<To>{}; } + static std::optional<To> castFailed() { return std::optional<To>{}; } static To doCast(const From &f) { return *static_cast<const To *>(cast<::clang::ento::SVal>(&f)); } - static Optional<To> doCastIfPossible(const From &f) { + static std::optional<To> doCastIfPossible(const From &f) { if (!Self::isPossible(f)) return Self::castFailed(); return doCast(f); diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index bf2dfd1..468ada37 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -84,7 +84,8 @@ public: /// \param[in] R The region to find the default binding for. /// \return The default value bound to the region in the store, if a default /// binding exists. - virtual Optional<SVal> getDefaultBinding(Store store, const MemRegion *R) = 0; + virtual std::optional<SVal> getDefaultBinding(Store store, + const MemRegion *R) = 0; /// Return the default value bound to a LazyCompoundVal. The default binding /// is used to represent the value of any fields or elements within the @@ -94,7 +95,7 @@ public: /// \param[in] lcv The lazy compound value. /// \return The default value bound to the LazyCompoundVal \c lcv, if a /// default binding exists. - Optional<SVal> getDefaultBinding(nonloc::LazyCompoundVal lcv) { + std::optional<SVal> getDefaultBinding(nonloc::LazyCompoundVal lcv) { return getDefaultBinding(lcv.getStore(), lcv.getRegion()); } @@ -175,15 +176,15 @@ public: /// enough info to determine if the cast will succeed at run time). /// The function returns an optional with SVal representing the derived class /// in case of a successful cast and `std::nullopt` otherwise. - Optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType); + std::optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType); const ElementRegion *GetElementZeroRegion(const SubRegion *R, QualType T); /// castRegion - Used by ExprEngine::VisitCast to handle casts from /// a MemRegion* to a specific location type. 'R' is the region being /// casted and 'CastToTy' the result type of the cast. - Optional<const MemRegion *> castRegion(const MemRegion *region, - QualType CastToTy); + std::optional<const MemRegion *> castRegion(const MemRegion *region, + QualType CastToTy); virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper &SymReaper) = 0; diff --git a/clang/include/clang/Tooling/ASTDiff/ASTDiff.h b/clang/include/clang/Tooling/ASTDiff/ASTDiff.h index a84444a..6b351e2 100644 --- a/clang/include/clang/Tooling/ASTDiff/ASTDiff.h +++ b/clang/include/clang/Tooling/ASTDiff/ASTDiff.h @@ -45,8 +45,8 @@ struct Node { ASTNodeKind getType() const; StringRef getTypeLabel() const; bool isLeaf() const { return Children.empty(); } - llvm::Optional<StringRef> getIdentifier() const; - llvm::Optional<std::string> getQualifiedIdentifier() const; + std::optional<StringRef> getIdentifier() const; + std::optional<std::string> getQualifiedIdentifier() const; }; /// SyntaxTree objects represent subtrees of the AST. diff --git a/clang/include/clang/Tooling/AllTUsExecution.h b/clang/include/clang/Tooling/AllTUsExecution.h index fcc952f..03cfc9c 100644 --- a/clang/include/clang/Tooling/AllTUsExecution.h +++ b/clang/include/clang/Tooling/AllTUsExecution.h @@ -62,7 +62,7 @@ public: private: // Used to store the parser when the executor is initialized with parser. - llvm::Optional<CommonOptionsParser> OptionsParser; + std::optional<CommonOptionsParser> OptionsParser; const CompilationDatabase &Compilations; std::unique_ptr<ToolResults> Results; ExecutionContext Context; diff --git a/clang/include/clang/Tooling/Core/Replacement.h b/clang/include/clang/Tooling/Core/Replacement.h index 929d6197..b32ee68 100644 --- a/clang/include/clang/Tooling/Core/Replacement.h +++ b/clang/include/clang/Tooling/Core/Replacement.h @@ -174,11 +174,11 @@ public: static char ID; - const llvm::Optional<Replacement> &getNewReplacement() const { + const std::optional<Replacement> &getNewReplacement() const { return NewReplacement; } - const llvm::Optional<Replacement> &getExistingReplacement() const { + const std::optional<Replacement> &getExistingReplacement() const { return ExistingReplacement; } @@ -192,10 +192,10 @@ private: // A new replacement, which is to expected be added into a set of // replacements, that is causing problem. - llvm::Optional<Replacement> NewReplacement; + std::optional<Replacement> NewReplacement; // An existing replacement in a replacements set that is causing problem. - llvm::Optional<Replacement> ExistingReplacement; + std::optional<Replacement> ExistingReplacement; }; /// Less-than operator between two Replacements. diff --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h index 510c41f..4b4e3c7 100644 --- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h +++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h @@ -40,7 +40,7 @@ struct CachedFileContents { SmallVector<dependency_directives_scan::Token, 10> DepDirectiveTokens; /// Accessor to the directive tokens that's atomic to avoid data races. /// \p CachedFileContents has ownership of the pointer. - std::atomic<const Optional<DependencyDirectivesTy> *> DepDirectives; + std::atomic<const std::optional<DependencyDirectivesTy> *> DepDirectives; ~CachedFileContents() { delete DepDirectives.load(); } }; @@ -89,7 +89,7 @@ public: /// \returns The scanned preprocessor directive tokens of the file that are /// used to speed up preprocessing, if available. - Optional<ArrayRef<dependency_directives_scan::Directive>> + std::optional<ArrayRef<dependency_directives_scan::Directive>> getDirectiveTokens() const { assert(!isError() && "error"); assert(!isDirectory() && "not a file"); @@ -263,7 +263,7 @@ public: StringRef getContents() const { return Entry.getOriginalContents(); } - Optional<ArrayRef<dependency_directives_scan::Directive>> + std::optional<ArrayRef<dependency_directives_scan::Directive>> getDirectiveTokens() const { return Entry.getDirectiveTokens(); } diff --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h index 7262ac8..6af878d 100644 --- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h +++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h @@ -85,7 +85,7 @@ public: /// occurred, dependency file contents otherwise. llvm::Expected<std::string> getDependencyFile(const std::vector<std::string> &CommandLine, StringRef CWD, - llvm::Optional<StringRef> ModuleName = std::nullopt); + std::optional<StringRef> ModuleName = std::nullopt); /// Collect the full module dependency graph for the input, ignoring any /// modules which have already been seen. If \p ModuleName isn't empty, this @@ -106,13 +106,13 @@ public: getFullDependencies(const std::vector<std::string> &CommandLine, StringRef CWD, const llvm::StringSet<> &AlreadySeen, LookupModuleOutputCallback LookupModuleOutput, - llvm::Optional<StringRef> ModuleName = std::nullopt); + std::optional<StringRef> ModuleName = std::nullopt); llvm::Expected<FullDependenciesResult> getFullDependenciesLegacyDriverCommand( const std::vector<std::string> &CommandLine, StringRef CWD, const llvm::StringSet<> &AlreadySeen, LookupModuleOutputCallback LookupModuleOutput, - llvm::Optional<StringRef> ModuleName = std::nullopt); + std::optional<StringRef> ModuleName = std::nullopt); private: DependencyScanningWorker Worker; diff --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h index 7163893..458c4d9 100644 --- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h +++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h @@ -80,14 +80,14 @@ public: const std::vector<std::string> &CommandLine, DependencyConsumer &DepConsumer, DiagnosticConsumer &DiagConsumer, - llvm::Optional<StringRef> ModuleName = std::nullopt); + std::optional<StringRef> ModuleName = std::nullopt); /// \returns A \c StringError with the diagnostic output if clang errors /// occurred, success otherwise. llvm::Error computeDependencies(StringRef WorkingDirectory, const std::vector<std::string> &CommandLine, DependencyConsumer &Consumer, - llvm::Optional<StringRef> ModuleName = std::nullopt); + std::optional<StringRef> ModuleName = std::nullopt); bool shouldEagerLoadModules() const { return EagerLoadModules; } diff --git a/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h b/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h index e7cc1ee..9e08046 100644 --- a/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h +++ b/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h @@ -73,9 +73,9 @@ public: /// same category in the code that should be sorted after \p IncludeName. If /// \p IncludeName already exists (with exactly the same spelling), this /// returns std::nullopt. - llvm::Optional<tooling::Replacement> insert(llvm::StringRef Header, - bool IsAngled, - IncludeDirective Directive) const; + std::optional<tooling::Replacement> insert(llvm::StringRef Header, + bool IsAngled, + IncludeDirective Directive) const; /// Removes all existing #includes and #imports of \p Header quoted with <> if /// \p IsAngled is true or "" if \p IsAngled is false. diff --git a/clang/include/clang/Tooling/Refactoring/ASTSelection.h b/clang/include/clang/Tooling/Refactoring/ASTSelection.h index d9e7c1b..009437f 100644 --- a/clang/include/clang/Tooling/Refactoring/ASTSelection.h +++ b/clang/include/clang/Tooling/Refactoring/ASTSelection.h @@ -68,8 +68,8 @@ struct SelectedASTNode { /// /// \returns std::nullopt if no nodes are selected in the AST, or a selected AST /// node that corresponds to the TranslationUnitDecl otherwise. -Optional<SelectedASTNode> findSelectedASTNodes(const ASTContext &Context, - SourceRange SelectionRange); +std::optional<SelectedASTNode> findSelectedASTNodes(const ASTContext &Context, + SourceRange SelectionRange); /// An AST selection value that corresponds to a selection of a set of /// statements that belong to one body of code (like one function). @@ -131,7 +131,7 @@ public: /// declaration doesn't exist. const Decl *getFunctionLikeNearestParent() const; - static Optional<CodeRangeASTSelection> + static std::optional<CodeRangeASTSelection> create(SourceRange SelectionRange, const SelectedASTNode &ASTSelection); private: diff --git a/clang/include/clang/Tooling/Refactoring/Extract/Extract.h b/clang/include/clang/Tooling/Refactoring/Extract/Extract.h index f72d619..695ca38 100644 --- a/clang/include/clang/Tooling/Refactoring/Extract/Extract.h +++ b/clang/include/clang/Tooling/Refactoring/Extract/Extract.h @@ -25,14 +25,15 @@ public: /// \param Code The selected set of statements. /// \param DeclName The name of the extract function. If None, /// "extracted" is used. - static Expected<ExtractFunction> initiate(RefactoringRuleContext &Context, - CodeRangeASTSelection Code, - Optional<std::string> DeclName); + static Expected<ExtractFunction> + initiate(RefactoringRuleContext &Context, CodeRangeASTSelection Code, + std::optional<std::string> DeclName); static const RefactoringDescriptor &describe(); private: - ExtractFunction(CodeRangeASTSelection Code, Optional<std::string> DeclName) + ExtractFunction(CodeRangeASTSelection Code, + std::optional<std::string> DeclName) : Code(std::move(Code)), DeclName(DeclName ? std::move(*DeclName) : "extracted") {} diff --git a/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h b/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h index 327f470..3234b09 100644 --- a/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h +++ b/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h @@ -28,7 +28,7 @@ public: virtual ~RefactoringOptionVisitor() {} virtual void visit(const RefactoringOption &Opt, - Optional<std::string> &Value) = 0; + std::optional<std::string> &Value) = 0; }; namespace traits { @@ -39,7 +39,8 @@ private: template <typename ClassT> static auto check(ClassT *) -> typename std::is_same< decltype(std::declval<RefactoringOptionVisitor>().visit( - std::declval<RefactoringOption>(), *std::declval<Optional<T> *>())), + std::declval<RefactoringOption>(), + *std::declval<std::optional<T> *>())), void>::type; template <typename> static std::false_type check(...); diff --git a/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h b/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h index 963eb2d..62c01e7 100644 --- a/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h +++ b/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h @@ -31,12 +31,12 @@ public: bool isRequired() const override { return false; } - using ValueType = Optional<T>; + using ValueType = std::optional<T>; const ValueType &getValue() const { return Value; } protected: - Optional<T> Value; + std::optional<T> Value; }; /// A required refactoring option that stores a value of type \c T. diff --git a/clang/include/clang/Tooling/StandaloneExecution.h b/clang/include/clang/Tooling/StandaloneExecution.h index 359324f..cdbe65a 100644 --- a/clang/include/clang/Tooling/StandaloneExecution.h +++ b/clang/include/clang/Tooling/StandaloneExecution.h @@ -84,7 +84,7 @@ public: private: // Used to store the parser when the executor is initialized with parser. - llvm::Optional<CommonOptionsParser> OptionsParser; + std::optional<CommonOptionsParser> OptionsParser; // FIXME: The standalone executor is currently just a wrapper of `ClangTool`. // Merge `ClangTool` implementation into the this. ClangTool Tool; diff --git a/clang/lib/ARCMigrate/Internals.h b/clang/lib/ARCMigrate/Internals.h index 2c7b8bc..0b8bab0 100644 --- a/clang/lib/ARCMigrate/Internals.h +++ b/clang/lib/ARCMigrate/Internals.h @@ -153,7 +153,7 @@ public: TransformActions &TA; const CapturedDiagList &CapturedDiags; std::vector<SourceLocation> &ARCMTMacroLocs; - Optional<bool> EnableCFBridgeFns; + std::optional<bool> EnableCFBridgeFns; MigrationPass(ASTContext &Ctx, LangOptions::GCMode OrigGCMode, Sema &sema, TransformActions &TA, const CapturedDiagList &capturedDiags, diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp index 15a4380..cb9eb1a 100644 --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -802,7 +802,7 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( TTP->getDepth(), TTP->getIndex(), nullptr, false, TTP->isParameterPack(), TTP->hasTypeConstraint(), TTP->isExpandedParameterPack() - ? llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) + ? std::optional<unsigned>(TTP->getNumExpansionParameters()) : std::nullopt); if (const auto *TC = TTP->getTypeConstraint()) { QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); @@ -2693,11 +2693,11 @@ static int64_t getSubobjectOffset(const CXXRecordDecl *RD, return Context.toBits(Layout.getBaseClassOffset(RD)); } -static llvm::Optional<int64_t> +static std::optional<int64_t> structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD); -static llvm::Optional<int64_t> +static std::optional<int64_t> getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { if (Field->getType()->isRecordType()) { const RecordDecl *RD = Field->getType()->getAsRecordDecl(); @@ -2731,17 +2731,17 @@ getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { return FieldSizeInBits; } -static llvm::Optional<int64_t> +static std::optional<int64_t> getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { return structHasUniqueObjectRepresentations(Context, RD); } template <typename RangeT> -static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( +static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout) { for (const auto *Subobject : Subobjects) { - llvm::Optional<int64_t> SizeInBits = + std::optional<int64_t> SizeInBits = getSubobjectSizeInBits(Subobject, Context); if (!SizeInBits) return std::nullopt; @@ -2755,7 +2755,7 @@ static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( return CurOffsetInBits; } -static llvm::Optional<int64_t> +static std::optional<int64_t> structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD) { assert(!RD->isUnion() && "Must be struct/class type"); @@ -2777,7 +2777,7 @@ structHasUniqueObjectRepresentations(const ASTContext &Context, return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); }); - llvm::Optional<int64_t> OffsetAfterBases = + std::optional<int64_t> OffsetAfterBases = structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, Context, Layout); if (!OffsetAfterBases) @@ -2785,7 +2785,7 @@ structHasUniqueObjectRepresentations(const ASTContext &Context, CurOffsetInBits = *OffsetAfterBases; } - llvm::Optional<int64_t> OffsetAfterFields = + std::optional<int64_t> OffsetAfterFields = structSubobjectsHaveUniqueObjectRepresentations( RD->fields(), CurOffsetInBits, Context, Layout); if (!OffsetAfterFields) @@ -2850,7 +2850,7 @@ bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { if (Record->isUnion()) return unionHasUniqueObjectRepresentations(*this, Record); - Optional<int64_t> StructSize = + std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(*this, Record); return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty)); @@ -4806,10 +4806,9 @@ QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, } /// Retrieve a substitution-result type. -QualType -ASTContext::getSubstTemplateTypeParmType(QualType Replacement, - Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) const { +QualType ASTContext::getSubstTemplateTypeParmType( + QualType Replacement, Decl *AssociatedDecl, unsigned Index, + std::optional<unsigned> PackIndex) const { llvm::FoldingSetNodeID ID; SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index, PackIndex); @@ -5208,7 +5207,7 @@ TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { } else { auto *TTP = cast<TemplateTemplateParmDecl>(Param); if (TTP->isParameterPack()) - Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); + Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>()); else Arg = TemplateArgument(TemplateName(TTP)); } @@ -5229,7 +5228,7 @@ ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, } QualType ASTContext::getPackExpansionType(QualType Pattern, - Optional<unsigned> NumExpansions, + std::optional<unsigned> NumExpansions, bool ExpectPackInType) { assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && "Pack expansions must expand one or more parameter packs"); @@ -9268,10 +9267,9 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, return TemplateName(QTN); } -TemplateName -ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement, - Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) const { +TemplateName ASTContext::getSubstTemplateTemplateParm( + TemplateName Replacement, Decl *AssociatedDecl, unsigned Index, + std::optional<unsigned> PackIndex) const { llvm::FoldingSetNodeID ID; SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl, Index, PackIndex); @@ -10650,7 +10648,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, const ConstantArrayType* CAT) -> std::pair<bool,llvm::APInt> { if (VAT) { - Optional<llvm::APSInt> TheInt; + std::optional<llvm::APSInt> TheInt; Expr *E = VAT->getSizeExpr(); if (E && (TheInt = E->getIntegerConstantExpr(*this))) return std::make_pair(true, *TheInt); @@ -11922,7 +11920,7 @@ MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { case TargetCXXABI::XL: return ItaniumMangleContext::create( *this, getDiagnostics(), - [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { + [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> { if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) return RD->getDeviceLambdaManglingNumber(); return std::nullopt; diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp index 60cafbc..d4e70f4 100644 --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -219,9 +219,9 @@ namespace clang { return Importer.Import(From); } - // Import an Optional<T> by importing the contained T, if any. - template<typename T> - Expected<Optional<T>> import(Optional<T> From) { + // Import an std::optional<T> by importing the contained T, if any. + template <typename T> + Expected<std::optional<T>> import(std::optional<T> From) { if (!From) return std::nullopt; return import(*From); @@ -3272,7 +3272,7 @@ namespace { /// solution no visit function is needed if the type has only a desugared type /// as data. class IsTypeDeclaredInsideVisitor - : public TypeVisitor<IsTypeDeclaredInsideVisitor, Optional<bool>> { + : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> { public: IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC) : ParentDC(ParentDC) {} @@ -3281,12 +3281,12 @@ public: // Check the chain of "sugar" types. // The "sugar" types are typedef or similar types that have the same // canonical type. - if (Optional<bool> Res = Visit(T.getTypePtr())) + if (std::optional<bool> Res = Visit(T.getTypePtr())) return *Res; QualType DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext()); while (DsT != T) { - if (Optional<bool> Res = Visit(DsT.getTypePtr())) + if (std::optional<bool> Res = Visit(DsT.getTypePtr())) return *Res; T = DsT; DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext()); @@ -3294,7 +3294,7 @@ public: return false; } - Optional<bool> VisitTagType(const TagType *T) { + std::optional<bool> VisitTagType(const TagType *T) { if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) for (const auto &Arg : Spec->getTemplateArgs().asArray()) if (checkTemplateArgument(Arg)) @@ -3302,21 +3302,21 @@ public: return isAncestorDeclContextOf(ParentDC, T->getDecl()); } - Optional<bool> VisitPointerType(const PointerType *T) { + std::optional<bool> VisitPointerType(const PointerType *T) { return CheckType(T->getPointeeType()); } - Optional<bool> VisitReferenceType(const ReferenceType *T) { + std::optional<bool> VisitReferenceType(const ReferenceType *T) { return CheckType(T->getPointeeTypeAsWritten()); } - Optional<bool> VisitTypedefType(const TypedefType *T) { + std::optional<bool> VisitTypedefType(const TypedefType *T) { const TypedefNameDecl *TD = T->getDecl(); assert(TD); return isAncestorDeclContextOf(ParentDC, TD); } - Optional<bool> VisitUsingType(const UsingType *T) { + std::optional<bool> VisitUsingType(const UsingType *T) { if (T->getFoundDecl() && isAncestorDeclContextOf(ParentDC, T->getFoundDecl())) return true; @@ -3324,7 +3324,7 @@ public: return {}; } - Optional<bool> + std::optional<bool> VisitTemplateSpecializationType(const TemplateSpecializationType *T) { for (const auto &Arg : T->template_arguments()) if (checkTemplateArgument(Arg)) @@ -3333,24 +3333,24 @@ public: return {}; } - Optional<bool> VisitConstantArrayType(const ConstantArrayType *T) { + std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) { if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr())) return true; return CheckType(T->getElementType()); } - Optional<bool> VisitVariableArrayType(const VariableArrayType *T) { + std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) { llvm_unreachable( "Variable array should not occur in deduced return type of a function"); } - Optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) { + std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) { llvm_unreachable("Incomplete array should not occur in deduced return type " "of a function"); } - Optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) { + std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) { llvm_unreachable("Dependent array should not occur in deduced return type " "of a function"); } @@ -7681,7 +7681,8 @@ ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { // see VisitParmVarDecl). ParmVarDecl *ToParam = *ToParamOrErr; if (!ToParam->getDefaultArg()) { - Optional<ParmVarDecl *> FromParam = Importer.getImportedFromDecl(ToParam); + std::optional<ParmVarDecl *> FromParam = + Importer.getImportedFromDecl(ToParam); assert(FromParam && "ParmVarDecl was not imported?"); if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam)) @@ -7814,7 +7815,7 @@ ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { if (Err) return std::move(Err); - Optional<unsigned> Length; + std::optional<unsigned> Length; if (!E->isValueDependent()) Length = E->getPackLength(); @@ -8553,7 +8554,7 @@ ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTImporter::~ASTImporter() = default; -Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { +std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && "Try to get field index for non-field."); @@ -9564,7 +9565,7 @@ Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) { if (ToID.isInvalid() || IsBuiltin) { // FIXME: We want to re-use the existing MemoryBuffer! - llvm::Optional<llvm::MemoryBufferRef> FromBuf = + std::optional<llvm::MemoryBufferRef> FromBuf = Cache->getBufferOrNone(FromContext.getDiagnostics(), FromSM.getFileManager(), SourceLocation{}); if (!FromBuf) @@ -10033,7 +10034,7 @@ Decl *ASTImporter::MapImported(Decl *From, Decl *To) { return To; } -llvm::Optional<ASTImportError> +std::optional<ASTImportError> ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const { auto Pos = ImportDeclErrors.find(FromD); if (Pos != ImportDeclErrors.end()) diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp b/clang/lib/AST/ASTStructuralEquivalence.cpp index 46321f5..01dce8d 100644 --- a/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -1482,9 +1482,9 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (!D1->getDeclName() && !D2->getDeclName()) { // If both anonymous structs/unions are in a record context, make sure // they occur in the same location in the context records. - if (Optional<unsigned> Index1 = + if (std::optional<unsigned> Index1 = StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) { - if (Optional<unsigned> Index2 = + if (std::optional<unsigned> Index2 = StructuralEquivalenceContext::findUntaggedStructOrUnionIndex( D2)) { if (*Index1 != *Index2) @@ -2156,7 +2156,7 @@ DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc, return ToCtx.getDiagnostics().Report(Loc, DiagID); } -Optional<unsigned> +std::optional<unsigned> StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) { ASTContext &Context = Anon->getASTContext(); QualType AnonTy = Context.getRecordType(Anon); diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp index e4e25e2..0adcca7 100644 --- a/clang/lib/AST/AttrImpl.cpp +++ b/clang/lib/AST/AttrImpl.cpp @@ -149,7 +149,7 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma( } } -llvm::Optional<OMPDeclareTargetDeclAttr *> +std::optional<OMPDeclareTargetDeclAttr *> OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) { if (!VD->hasAttrs()) return std::nullopt; @@ -166,25 +166,25 @@ OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) { return std::nullopt; } -llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> +std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(const ValueDecl *VD) { - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); if (ActiveAttr) return (*ActiveAttr)->getMapType(); return std::nullopt; } -llvm::Optional<OMPDeclareTargetDeclAttr::DevTypeTy> +std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> OMPDeclareTargetDeclAttr::getDeviceType(const ValueDecl *VD) { - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); if (ActiveAttr) return (*ActiveAttr)->getDevType(); return std::nullopt; } -llvm::Optional<SourceLocation> +std::optional<SourceLocation> OMPDeclareTargetDeclAttr::getLocation(const ValueDecl *VD) { - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); if (ActiveAttr) return (*ActiveAttr)->getRange().getBegin(); return std::nullopt; diff --git a/clang/lib/AST/ComparisonCategories.cpp b/clang/lib/AST/ComparisonCategories.cpp index 2259741..5841120 100644 --- a/clang/lib/AST/ComparisonCategories.cpp +++ b/clang/lib/AST/ComparisonCategories.cpp @@ -21,7 +21,7 @@ using namespace clang; -Optional<ComparisonCategoryType> +std::optional<ComparisonCategoryType> clang::getComparisonCategoryForBuiltinCmp(QualType T) { using CCT = ComparisonCategoryType; diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index c0e1290..b921ce2 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -170,8 +170,8 @@ withExplicitVisibilityAlready(LVComputationKind Kind) { return Kind; } -static Optional<Visibility> getExplicitVisibility(const NamedDecl *D, - LVComputationKind kind) { +static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D, + LVComputationKind kind) { assert(!kind.IgnoreExplicitVisibility && "asking for explicit visibility when we shouldn't be"); return D->getExplicitVisibility(kind.getExplicitVisibilityKind()); @@ -220,8 +220,8 @@ static Visibility getVisibilityFromAttr(const T *attr) { } /// Return the explicit visibility of the given declaration. -static Optional<Visibility> getVisibilityOf(const NamedDecl *D, - NamedDecl::ExplicitVisibilityKind kind) { +static std::optional<Visibility> +getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) { // If we're ultimately computing the visibility of a type, look for // a 'type_visibility' attribute before looking for 'visibility'. if (kind == NamedDecl::VisibilityForType) { @@ -729,7 +729,7 @@ LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, LinkageInfo LV = getExternalLinkageFor(D); if (!hasExplicitVisibilityAlready(computation)) { - if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) { + if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) { LV.mergeVisibility(*Vis, true); } else { // If we're declared in a namespace with a visibility attribute, @@ -739,7 +739,8 @@ LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, DC = DC->getParent()) { const auto *ND = dyn_cast<NamespaceDecl>(DC); if (!ND) continue; - if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) { + if (std::optional<Visibility> Vis = + getExplicitVisibility(ND, computation)) { LV.mergeVisibility(*Vis, true); break; } @@ -965,7 +966,7 @@ LinkageComputer::getLVForClassMember(const NamedDecl *D, // If we have an explicit visibility attribute, merge that in. if (!hasExplicitVisibilityAlready(computation)) { - if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) + if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) LV.mergeVisibility(*Vis, true); // If we're paying attention to global visibility, apply // -finline-visibility-hidden if this is an inline method. @@ -1177,14 +1178,14 @@ LinkageInfo NamedDecl::getLinkageAndVisibility() const { return LinkageComputer{}.getDeclLinkageAndVisibility(this); } -static Optional<Visibility> +static std::optional<Visibility> getExplicitVisibilityAux(const NamedDecl *ND, NamedDecl::ExplicitVisibilityKind kind, bool IsMostRecent) { assert(!IsMostRecent || ND == ND->getMostRecentDecl()); // Check the declaration itself first. - if (Optional<Visibility> V = getVisibilityOf(ND, kind)) + if (std::optional<Visibility> V = getVisibilityOf(ND, kind)) return V; // If this is a member class of a specialization of a class template @@ -1256,7 +1257,7 @@ getExplicitVisibilityAux(const NamedDecl *ND, return std::nullopt; } -Optional<Visibility> +std::optional<Visibility> NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { return getExplicitVisibilityAux(this, kind, false); } @@ -1313,7 +1314,7 @@ LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, LinkageInfo LV; if (!hasExplicitVisibilityAlready(computation)) { - if (Optional<Visibility> Vis = + if (std::optional<Visibility> Vis = getExplicitVisibility(Function, computation)) LV.mergeVisibility(*Vis, true); } @@ -1334,7 +1335,8 @@ LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, if (Var->getStorageClass() == SC_PrivateExtern) LV.mergeVisibility(HiddenVisibility, true); else if (!hasExplicitVisibilityAlready(computation)) { - if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation)) + if (std::optional<Visibility> Vis = + getExplicitVisibility(Var, computation)) LV.mergeVisibility(*Vis, true); } @@ -1529,7 +1531,7 @@ LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, if (computation.IgnoreAllVisibility && D->hasCachedLinkage()) return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); - if (llvm::Optional<LinkageInfo> LI = lookup(D, computation)) + if (std::optional<LinkageInfo> LI = lookup(D, computation)) return *LI; LinkageInfo LV = computeLVForDecl(D, computation); @@ -3215,7 +3217,7 @@ bool FunctionDecl::isReservedGlobalPlacementOperator() const { } bool FunctionDecl::isReplaceableGlobalAllocationFunction( - Optional<unsigned> *AlignmentParam, bool *IsNothrow) const { + std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const { if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) return false; if (getDeclName().getCXXOverloadedOperator() != OO_New && diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp index c6f3ea2..531be70 100644 --- a/clang/lib/AST/DeclTemplate.cpp +++ b/clang/lib/AST/DeclTemplate.cpp @@ -131,7 +131,7 @@ unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned NumRequiredArgs = 0; for (const NamedDecl *P : asArray()) { if (P->isTemplateParameterPack()) { - if (Optional<unsigned> Expansions = getExpandedPackSize(P)) { + if (std::optional<unsigned> Expansions = getExpandedPackSize(P)) { NumRequiredArgs += *Expansions; continue; } @@ -637,13 +637,11 @@ ClassTemplateDecl::getInjectedClassNameSpecialization() { // TemplateTypeParm Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// -TemplateTypeParmDecl * -TemplateTypeParmDecl::Create(const ASTContext &C, DeclContext *DC, - SourceLocation KeyLoc, SourceLocation NameLoc, - unsigned D, unsigned P, IdentifierInfo *Id, - bool Typename, bool ParameterPack, - bool HasTypeConstraint, - Optional<unsigned> NumExpanded) { +TemplateTypeParmDecl *TemplateTypeParmDecl::Create( + const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, + SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, + bool Typename, bool ParameterPack, bool HasTypeConstraint, + std::optional<unsigned> NumExpanded) { auto *TTPDecl = new (C, DC, additionalSizeToAlloc<TypeConstraint>(HasTypeConstraint ? 1 : 0)) diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp index 9858fbf..67862a8 100644 --- a/clang/lib/AST/Expr.cpp +++ b/clang/lib/AST/Expr.cpp @@ -645,7 +645,7 @@ std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const { std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context, QualType Ty) { auto MangleCallback = [](ASTContext &Ctx, - const NamedDecl *ND) -> llvm::Optional<unsigned> { + const NamedDecl *ND) -> std::optional<unsigned> { if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) return RD->getDeviceLambdaManglingNumber(); return std::nullopt; diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp index 975287e..2a9e335 100644 --- a/clang/lib/AST/ExprCXX.cpp +++ b/clang/lib/AST/ExprCXX.cpp @@ -183,7 +183,7 @@ CXXNewExpr::CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens, - Optional<Expr *> ArraySize, + std::optional<Expr *> ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, @@ -245,7 +245,7 @@ CXXNewExpr::Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens, - Optional<Expr *> ArraySize, + std::optional<Expr *> ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange) { @@ -1621,12 +1621,12 @@ CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() { return Record; } -SizeOfPackExpr * -SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc, - NamedDecl *Pack, SourceLocation PackLoc, - SourceLocation RParenLoc, - Optional<unsigned> Length, - ArrayRef<TemplateArgument> PartialArgs) { +SizeOfPackExpr *SizeOfPackExpr::Create(ASTContext &Context, + SourceLocation OperatorLoc, + NamedDecl *Pack, SourceLocation PackLoc, + SourceLocation RParenLoc, + std::optional<unsigned> Length, + ArrayRef<TemplateArgument> PartialArgs) { void *Storage = Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size())); return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack, diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 7544671..c23b5a6 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -1046,8 +1046,8 @@ namespace { APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); - Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { - Optional<DynAlloc*> Result; + std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { + std::optional<DynAlloc *> Result; auto It = HeapAllocs.find(DA); if (It != HeapAllocs.end()) Result = &It->second; @@ -2105,7 +2105,7 @@ static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { // FIXME: Produce a note for dangling pointers too. - if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) + if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) Info.Note((*Alloc)->AllocExpr->getExprLoc(), diag::note_constexpr_dynamic_alloc_here); } @@ -4138,7 +4138,7 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) return CompleteObject(); } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { - Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); + std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); if (!Alloc) { Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; return CompleteObject(); @@ -5676,8 +5676,10 @@ static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, } /// Determine the dynamic type of an object. -static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, - LValue &This, AccessKinds AK) { +static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, + const Expr *E, + LValue &This, + AccessKinds AK) { // If we don't have an lvalue denoting an object of class type, there is no // meaningful dynamic type. (We consider objects of non-class type to have no // dynamic type.) @@ -5734,7 +5736,7 @@ static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, static const CXXMethodDecl *HandleVirtualDispatch( EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { - Optional<DynamicType> DynType = ComputeDynamicType( + std::optional<DynamicType> DynType = ComputeDynamicType( Info, E, This, isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); if (!DynType) @@ -5852,7 +5854,7 @@ static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, // For all the other cases, we need the pointer to point to an object within // its lifetime / period of construction / destruction, and we need to know // its dynamic type. - Optional<DynamicType> DynType = + std::optional<DynamicType> DynType = ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); if (!DynType) return false; @@ -6742,9 +6744,9 @@ static const FunctionDecl *getVirtualOperatorDelete(QualType T) { /// /// On success, returns the heap allocation to deallocate. On failure, produces /// a diagnostic and returns std::nullopt. -static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, - const LValue &Pointer, - DynAlloc::Kind DeallocKind) { +static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, + const LValue &Pointer, + DynAlloc::Kind DeallocKind) { auto PointerAsString = [&] { return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); }; @@ -6758,7 +6760,7 @@ static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, return std::nullopt; } - Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); + std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); if (!Alloc) { Info.FFDiag(E, diag::note_constexpr_double_delete); return std::nullopt; @@ -7025,8 +7027,8 @@ class APValueToBufferConverter { } public: - static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, - const CastExpr *BCE) { + static std::optional<BitCastBuffer> + convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) { CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); APValueToBufferConverter Converter(Info, DstSize, BCE); if (!Converter.visit(Src, BCE->getSubExpr()->getType())) @@ -7062,8 +7064,8 @@ class BufferToAPValueConverter { return std::nullopt; } - Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, - const EnumType *EnumSugar = nullptr) { + std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset, + const EnumType *EnumSugar = nullptr) { if (T->isNullPtrType()) { uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); return APValue((Expr *)nullptr, @@ -7131,7 +7133,7 @@ class BufferToAPValueConverter { return unsupportedType(QualType(T, 0)); } - Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { + std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { const RecordDecl *RD = RTy->getAsRecordDecl(); const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); @@ -7151,7 +7153,7 @@ class BufferToAPValueConverter { Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) continue; - Optional<APValue> SubObj = visitType( + std::optional<APValue> SubObj = visitType( BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); if (!SubObj) return std::nullopt; @@ -7177,7 +7179,7 @@ class BufferToAPValueConverter { CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + Offset; QualType FieldTy = FD->getType(); - Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); + std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset); if (!SubObj) return std::nullopt; ResultVal.getStructField(FieldIdx) = *SubObj; @@ -7187,7 +7189,7 @@ class BufferToAPValueConverter { return ResultVal; } - Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { + std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { QualType RepresentationType = Ty->getDecl()->getIntegerType(); assert(!RepresentationType.isNull() && "enum forward decl should be caught by Sema"); @@ -7198,13 +7200,13 @@ class BufferToAPValueConverter { return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); } - Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { + std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { size_t Size = Ty->getSize().getLimitedValue(); CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); APValue ArrayValue(APValue::UninitArray(), Size, Size); for (size_t I = 0; I != Size; ++I) { - Optional<APValue> ElementValue = + std::optional<APValue> ElementValue = visitType(Ty->getElementType(), Offset + I * ElementWidth); if (!ElementValue) return std::nullopt; @@ -7214,11 +7216,11 @@ class BufferToAPValueConverter { return ArrayValue; } - Optional<APValue> visit(const Type *Ty, CharUnits Offset) { + std::optional<APValue> visit(const Type *Ty, CharUnits Offset) { return unsupportedType(QualType(Ty, 0)); } - Optional<APValue> visitType(QualType Ty, CharUnits Offset) { + std::optional<APValue> visitType(QualType Ty, CharUnits Offset) { QualType Can = Ty.getCanonicalType(); switch (Can->getTypeClass()) { @@ -7243,8 +7245,8 @@ class BufferToAPValueConverter { public: // Pull out a full value of type DstType. - static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, - const CastExpr *BCE) { + static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, + const CastExpr *BCE) { BufferToAPValueConverter Converter(Info, Buffer, BCE); return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); } @@ -7333,13 +7335,13 @@ static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, return false; // Read out SourceValue into a char buffer. - Optional<BitCastBuffer> Buffer = + std::optional<BitCastBuffer> Buffer = APValueToBufferConverter::convert(Info, SourceRValue, BCE); if (!Buffer) return false; // Write out the buffer into a new APValue. - Optional<APValue> MaybeDestValue = + std::optional<APValue> MaybeDestValue = BufferToAPValueConverter::convert(Info, *Buffer, BCE); if (!MaybeDestValue) return false; @@ -8448,7 +8450,7 @@ bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { if (!Visit(E->getExprOperand())) return false; - Optional<DynamicType> DynType = + std::optional<DynamicType> DynType = ComputeDynamicType(Info, E, Result, AK_TypeId); if (!DynType) return false; @@ -9550,7 +9552,7 @@ bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { bool ValueInit = false; QualType AllocType = E->getAllocatedType(); - if (Optional<const Expr *> ArraySize = E->getArraySize()) { + if (std::optional<const Expr *> ArraySize = E->getArraySize()) { const Expr *Stripped = *ArraySize; for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); Stripped = ICE->getSubExpr()) @@ -10544,10 +10546,10 @@ bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { return Success(LHSValue, E); } -static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, - QualType ResultTy, - UnaryOperatorKind Op, - APValue Elt) { +static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, + QualType ResultTy, + UnaryOperatorKind Op, + APValue Elt) { switch (Op) { case UO_Plus: // Nothing to do here. @@ -10621,7 +10623,7 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { SmallVector<APValue, 4> ResultElements; for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { - llvm::Optional<APValue> Elt = handleVectorUnaryOperator( + std::optional<APValue> Elt = handleVectorUnaryOperator( Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); if (!Elt) return false; @@ -14919,7 +14921,7 @@ bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { return true; } - Optional<DynAlloc *> Alloc = CheckDeleteKind( + std::optional<DynAlloc *> Alloc = CheckDeleteKind( Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); if (!Alloc) return false; @@ -16013,9 +16015,9 @@ bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, return true; } -Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, - SourceLocation *Loc, - bool isEvaluated) const { +std::optional<llvm::APSInt> +Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc, + bool isEvaluated) const { if (isValueDependent()) { // Expression evaluator can't succeed on a dependent expression. return std::nullopt; diff --git a/clang/lib/AST/ExternalASTSource.cpp b/clang/lib/AST/ExternalASTSource.cpp index ac522c8..090ef02 100644 --- a/clang/lib/AST/ExternalASTSource.cpp +++ b/clang/lib/AST/ExternalASTSource.cpp @@ -30,7 +30,7 @@ char ExternalASTSource::ID; ExternalASTSource::~ExternalASTSource() = default; -llvm::Optional<ASTSourceDescriptor> +std::optional<ASTSourceDescriptor> ExternalASTSource::getSourceDescriptor(unsigned ID) { return std::nullopt; } diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp index 3e6d45b..c7dee2d 100644 --- a/clang/lib/AST/FormatString.cpp +++ b/clang/lib/AST/FormatString.cpp @@ -735,7 +735,7 @@ const char *ConversionSpecifier::toString() const { return nullptr; } -Optional<ConversionSpecifier> +std::optional<ConversionSpecifier> ConversionSpecifier::getStandardSpecifier() const { ConversionSpecifier::Kind NewKind; @@ -1032,7 +1032,8 @@ bool FormatSpecifier::hasStandardLengthConversionCombination() const { return true; } -Optional<LengthModifier> FormatSpecifier::getCorrectedLengthModifier() const { +std::optional<LengthModifier> +FormatSpecifier::getCorrectedLengthModifier() const { if (CS.isAnyIntArg() || CS.getKind() == ConversionSpecifier::nArg) { if (LM.getKind() == LengthModifier::AsLongDouble || LM.getKind() == LengthModifier::AsQuad) { diff --git a/clang/lib/AST/ItaniumCXXABI.cpp b/clang/lib/AST/ItaniumCXXABI.cpp index 10f33e4..c9aadce 100644 --- a/clang/lib/AST/ItaniumCXXABI.cpp +++ b/clang/lib/AST/ItaniumCXXABI.cpp @@ -85,8 +85,8 @@ template<typename T> bool isDenseMapKeyTombstone(T V) { V, llvm::DenseMapInfo<T>::getTombstoneKey()); } -template<typename T> -Optional<bool> areDenseMapKeysEqualSpecialValues(T LHS, T RHS) { +template <typename T> +std::optional<bool> areDenseMapKeysEqualSpecialValues(T LHS, T RHS) { bool LHSEmpty = isDenseMapKeyEmpty(LHS); bool RHSEmpty = isDenseMapKeyEmpty(RHS); if (LHSEmpty || RHSEmpty) @@ -114,8 +114,8 @@ struct DenseMapInfo<DecompositionDeclName> { return llvm::hash_combine_range(Key.begin(), Key.end()); } static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS) { - if (Optional<bool> Result = areDenseMapKeysEqualSpecialValues( - LHS.Bindings, RHS.Bindings)) + if (std::optional<bool> Result = + areDenseMapKeysEqualSpecialValues(LHS.Bindings, RHS.Bindings)) return *Result; return LHS.Bindings.size() == RHS.Bindings.size() && diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp index 50d6775..b23bc5f 100644 --- a/clang/lib/AST/ItaniumMangle.cpp +++ b/clang/lib/AST/ItaniumMangle.cpp @@ -1554,7 +1554,7 @@ void CXXNameMangler::mangleUnqualifiedName( // <lambda-sig> ::= <template-param-decl>* <parameter-type>+ // # Parameter types or 'v' for 'void'. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { - llvm::Optional<unsigned> DeviceNumber = + std::optional<unsigned> DeviceNumber = Context.getDiscriminatorOverride()(Context.getASTContext(), Record); // If we have a device-number via the discriminator, use that to mangle @@ -2003,7 +2003,7 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { // if the host-side CXX ABI has different numbering for lambda. In such case, // if the mangle context is that device-side one, use the device-side lambda // mangling number for this lambda. - llvm::Optional<unsigned> DeviceNumber = + std::optional<unsigned> DeviceNumber = Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda); unsigned Number = DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber(); @@ -6561,7 +6561,7 @@ ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, bool IsAux) { return new ItaniumMangleContextImpl( Context, Diags, - [](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> { + [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> { return std::nullopt; }, IsAux); diff --git a/clang/lib/AST/JSONNodeDumper.cpp b/clang/lib/AST/JSONNodeDumper.cpp index 9ca1d2b..83b097d 100644 --- a/clang/lib/AST/JSONNodeDumper.cpp +++ b/clang/lib/AST/JSONNodeDumper.cpp @@ -738,7 +738,7 @@ void JSONNodeDumper::VisitObjCInterfaceType(const ObjCInterfaceType *OIT) { } void JSONNodeDumper::VisitPackExpansionType(const PackExpansionType *PET) { - if (llvm::Optional<unsigned> N = PET->getNumExpansions()) + if (std::optional<unsigned> N = PET->getNumExpansions()) JOS.attribute("numExpansions", *N); } diff --git a/clang/lib/AST/Linkage.h b/clang/lib/AST/Linkage.h index e1c0f92..2d5b615 100644 --- a/clang/lib/AST/Linkage.h +++ b/clang/lib/AST/Linkage.h @@ -92,8 +92,8 @@ class LinkageComputer { return QueryType(ND, Kind.toBits()); } - llvm::Optional<LinkageInfo> lookup(const NamedDecl *ND, - LVComputationKind Kind) const { + std::optional<LinkageInfo> lookup(const NamedDecl *ND, + LVComputationKind Kind) const { auto Iter = CachedLinkageInfo.find(makeCacheKey(ND, Kind)); if (Iter == CachedLinkageInfo.end()) return std::nullopt; diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 2748fd6..cdd2c93 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -1509,7 +1509,7 @@ void MicrosoftCXXNameMangler::mangleIntegerLiteral( void MicrosoftCXXNameMangler::mangleExpression( const Expr *E, const NonTypeTemplateParmDecl *PD) { // See if this is a constant expression. - if (Optional<llvm::APSInt> Value = + if (std::optional<llvm::APSInt> Value = E->getIntegerConstantExpr(Context.getASTContext())) { mangleIntegerLiteral(*Value, PD, E->getType()); return; diff --git a/clang/lib/AST/NSAPI.cpp b/clang/lib/AST/NSAPI.cpp index 81c8f76..3621a2e 100644 --- a/clang/lib/AST/NSAPI.cpp +++ b/clang/lib/AST/NSAPI.cpp @@ -143,7 +143,8 @@ Selector NSAPI::getNSArraySelector(NSArrayMethodKind MK) const { return NSArraySelectors[MK]; } -Optional<NSAPI::NSArrayMethodKind> NSAPI::getNSArrayMethodKind(Selector Sel) { +std::optional<NSAPI::NSArrayMethodKind> +NSAPI::getNSArrayMethodKind(Selector Sel) { for (unsigned i = 0; i != NumNSArrayMethods; ++i) { NSArrayMethodKind MK = NSArrayMethodKind(i); if (Sel == getNSArraySelector(MK)) @@ -244,7 +245,7 @@ Selector NSAPI::getNSDictionarySelector( return NSDictionarySelectors[MK]; } -Optional<NSAPI::NSDictionaryMethodKind> +std::optional<NSAPI::NSDictionaryMethodKind> NSAPI::getNSDictionaryMethodKind(Selector Sel) { for (unsigned i = 0; i != NumNSDictionaryMethods; ++i) { NSDictionaryMethodKind MK = NSDictionaryMethodKind(i); @@ -301,8 +302,7 @@ Selector NSAPI::getNSSetSelector(NSSetMethodKind MK) const { return NSSetSelectors[MK]; } -Optional<NSAPI::NSSetMethodKind> -NSAPI::getNSSetMethodKind(Selector Sel) { +std::optional<NSAPI::NSSetMethodKind> NSAPI::getNSSetMethodKind(Selector Sel) { for (unsigned i = 0; i != NumNSSetMethods; ++i) { NSSetMethodKind MK = NSSetMethodKind(i); if (Sel == getNSSetSelector(MK)) @@ -364,7 +364,7 @@ Selector NSAPI::getNSNumberLiteralSelector(NSNumberLiteralMethodKind MK, return Sels[MK]; } -Optional<NSAPI::NSNumberLiteralMethodKind> +std::optional<NSAPI::NSNumberLiteralMethodKind> NSAPI::getNSNumberLiteralMethodKind(Selector Sel) const { for (unsigned i = 0; i != NumNSNumberLiteralMethods; ++i) { NSNumberLiteralMethodKind MK = NSNumberLiteralMethodKind(i); @@ -375,7 +375,7 @@ NSAPI::getNSNumberLiteralMethodKind(Selector Sel) const { return std::nullopt; } -Optional<NSAPI::NSNumberLiteralMethodKind> +std::optional<NSAPI::NSNumberLiteralMethodKind> NSAPI::getNSNumberFactoryMethodKind(QualType T) const { const BuiltinType *BT = T->getAs<BuiltinType>(); if (!BT) diff --git a/clang/lib/AST/OpenMPClause.cpp b/clang/lib/AST/OpenMPClause.cpp index d795b703..7d7158d 100644 --- a/clang/lib/AST/OpenMPClause.cpp +++ b/clang/lib/AST/OpenMPClause.cpp @@ -2455,7 +2455,7 @@ void OMPTraitInfo::getAsVariantMatchInfo(ASTContext &ASTCtx, TraitProperty::user_condition_unknown && "Ill-formed user condition, expected unknown trait property!"); - if (Optional<APSInt> CondVal = + if (std::optional<APSInt> CondVal = Selector.ScoreOrCondition->getIntegerConstantExpr(ASTCtx)) VMI.addTrait(CondVal->isZero() ? TraitProperty::user_condition_false : TraitProperty::user_condition_true, @@ -2465,7 +2465,7 @@ void OMPTraitInfo::getAsVariantMatchInfo(ASTContext &ASTCtx, continue; } - Optional<llvm::APSInt> Score; + std::optional<llvm::APSInt> Score; llvm::APInt *ScorePtr = nullptr; if (Selector.ScoreOrCondition) { if ((Score = Selector.ScoreOrCondition->getIntegerConstantExpr(ASTCtx))) diff --git a/clang/lib/AST/Stmt.cpp b/clang/lib/AST/Stmt.cpp index 3e65543..8744bba 100644 --- a/clang/lib/AST/Stmt.cpp +++ b/clang/lib/AST/Stmt.cpp @@ -1002,15 +1002,15 @@ bool IfStmt::isObjCAvailabilityCheck() const { return isa<ObjCAvailabilityCheckExpr>(getCond()); } -Optional<Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) { +std::optional<Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) { if (!isConstexpr() || getCond()->isValueDependent()) return std::nullopt; return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen(); } -Optional<const Stmt *> +std::optional<const Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) const { - if (Optional<Stmt *> Result = + if (std::optional<Stmt *> Result = const_cast<IfStmt *>(this)->getNondiscardedCase(Ctx)) return *Result; return std::nullopt; diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index d561685..0a879bb 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -2276,7 +2276,7 @@ void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) { if (E->isArray()) { llvm::raw_string_ostream s(TypeS); s << '['; - if (Optional<Expr *> Size = E->getArraySize()) + if (std::optional<Expr *> Size = E->getArraySize()) (*Size)->printPretty(s, Helper, Policy); s << ']'; } diff --git a/clang/lib/AST/TemplateBase.cpp b/clang/lib/AST/TemplateBase.cpp index c5a8895..ceff7a3 100644 --- a/clang/lib/AST/TemplateBase.cpp +++ b/clang/lib/AST/TemplateBase.cpp @@ -271,7 +271,7 @@ bool TemplateArgument::containsUnexpandedParameterPack() const { return getDependence() & TemplateArgumentDependence::UnexpandedPack; } -Optional<unsigned> TemplateArgument::getNumTemplateExpansions() const { +std::optional<unsigned> TemplateArgument::getNumTemplateExpansions() const { assert(getKind() == TemplateExpansion); if (TemplateArg.NumExpansions) return TemplateArg.NumExpansions - 1; diff --git a/clang/lib/AST/TemplateName.cpp b/clang/lib/AST/TemplateName.cpp index a16f835..a6dd0fa 100644 --- a/clang/lib/AST/TemplateName.cpp +++ b/clang/lib/AST/TemplateName.cpp @@ -57,11 +57,9 @@ void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Replacement, getAssociatedDecl(), getIndex(), getPackIndex()); } -void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID, - TemplateName Replacement, - Decl *AssociatedDecl, - unsigned Index, - Optional<unsigned> PackIndex) { +void SubstTemplateTemplateParmStorage::Profile( + llvm::FoldingSetNodeID &ID, TemplateName Replacement, Decl *AssociatedDecl, + unsigned Index, std::optional<unsigned> PackIndex) { Replacement.Profile(ID); ID.AddPointer(AssociatedDecl); ID.AddInteger(Index); diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp index cac10584..a713d6e 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -1534,8 +1534,8 @@ QualType QualType::getAtomicUnqualifiedType() const { return getUnqualifiedType(); } -Optional<ArrayRef<QualType>> Type::getObjCSubstitutions( - const DeclContext *dc) const { +std::optional<ArrayRef<QualType>> +Type::getObjCSubstitutions(const DeclContext *dc) const { // Look through method scopes. if (const auto method = dyn_cast<ObjCMethodDecl>(dc)) dc = method->getDeclContext(); @@ -3683,7 +3683,7 @@ static const TemplateTypeParmDecl *getReplacedParameter(Decl *D, SubstTemplateTypeParmType::SubstTemplateTypeParmType( QualType Replacement, Decl *AssociatedDecl, unsigned Index, - Optional<unsigned> PackIndex) + std::optional<unsigned> PackIndex) : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(), Replacement->getDependence()), AssociatedDecl(AssociatedDecl) { @@ -4179,7 +4179,7 @@ LinkageInfo Type::getLinkageAndVisibility() const { return LinkageComputer{}.getTypeLinkageAndVisibility(this); } -Optional<NullabilityKind> Type::getNullability() const { +std::optional<NullabilityKind> Type::getNullability() const { QualType Type(this, 0); while (const auto *AT = Type->getAs<AttributedType>()) { // Check whether this is an attributed type with nullability @@ -4320,8 +4320,7 @@ bool Type::canHaveNullability(bool ResultIfUnknown) const { llvm_unreachable("bad type kind!"); } -llvm::Optional<NullabilityKind> -AttributedType::getImmediateNullability() const { +std::optional<NullabilityKind> AttributedType::getImmediateNullability() const { if (getAttrKind() == attr::TypeNonNull) return NullabilityKind::NonNull; if (getAttrKind() == attr::TypeNullable) @@ -4333,7 +4332,8 @@ AttributedType::getImmediateNullability() const { return std::nullopt; } -Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { +std::optional<NullabilityKind> +AttributedType::stripOuterNullability(QualType &T) { QualType AttrTy = T; if (auto MacroTy = dyn_cast<MacroQualifiedType>(T)) AttrTy = MacroTy->getUnderlyingType(); diff --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp index 9e755fa..f1f73fc 100644 --- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp +++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp @@ -339,7 +339,7 @@ bool DynTypedMatcher::matchesNoKindCheck(const DynTypedNode &DynNode, return false; } -llvm::Optional<DynTypedMatcher> DynTypedMatcher::tryBind(StringRef ID) const { +std::optional<DynTypedMatcher> DynTypedMatcher::tryBind(StringRef ID) const { if (!AllowBind) return std::nullopt; auto Result = *this; @@ -686,7 +686,7 @@ static bool isTokenAtLoc(const SourceManager &SM, const LangOptions &LangOpts, return !Invalid && Text == TokenText; } -llvm::Optional<SourceLocation> +std::optional<SourceLocation> getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc, const ASTContext &Context) { auto &SM = Context.getSourceManager(); @@ -697,7 +697,7 @@ getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc, if (Expansion.isMacroArgExpansion()) // Check macro argument for an expansion of the given macro. For example, // `F(G(3))`, where `MacroName` is `G`. - if (llvm::Optional<SourceLocation> ArgLoc = getExpansionLocOfMacro( + if (std::optional<SourceLocation> ArgLoc = getExpansionLocOfMacro( MacroName, Expansion.getSpellingLoc(), Context)) return ArgLoc; Loc = Expansion.getExpansionLocStart(); diff --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp index 04e7d3c..16a7509 100644 --- a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp +++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp @@ -14,7 +14,7 @@ #include <optional> #include <string> -static llvm::Optional<std::string> +static std::optional<std::string> getBestGuess(llvm::StringRef Search, llvm::ArrayRef<llvm::StringRef> Allowed, llvm::StringRef DropPrefix = "", unsigned MaxEditDistance = 3) { if (MaxEditDistance != ~0U) @@ -60,7 +60,7 @@ getBestGuess(llvm::StringRef Search, llvm::ArrayRef<llvm::StringRef> Allowed, return std::nullopt; } -llvm::Optional<std::string> +std::optional<std::string> clang::ast_matchers::dynamic::internal::ArgTypeTraits< clang::attr::Kind>::getBestGuess(const VariantValue &Value) { static constexpr llvm::StringRef Allowed[] = { @@ -72,7 +72,7 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits< return std::nullopt; } -llvm::Optional<std::string> +std::optional<std::string> clang::ast_matchers::dynamic::internal::ArgTypeTraits< clang::CastKind>::getBestGuess(const VariantValue &Value) { static constexpr llvm::StringRef Allowed[] = { @@ -84,7 +84,7 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits< return std::nullopt; } -llvm::Optional<std::string> +std::optional<std::string> clang::ast_matchers::dynamic::internal::ArgTypeTraits< clang::OpenMPClauseKind>::getBestGuess(const VariantValue &Value) { static constexpr llvm::StringRef Allowed[] = { @@ -97,7 +97,7 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits< return std::nullopt; } -llvm::Optional<std::string> +std::optional<std::string> clang::ast_matchers::dynamic::internal::ArgTypeTraits< clang::UnaryExprOrTypeTrait>::getBestGuess(const VariantValue &Value) { static constexpr llvm::StringRef Allowed[] = { @@ -118,7 +118,7 @@ static constexpr std::pair<llvm::StringRef, llvm::Regex::RegexFlags> {"BasicRegex", llvm::Regex::RegexFlags::BasicRegex}, }; -static llvm::Optional<llvm::Regex::RegexFlags> +static std::optional<llvm::Regex::RegexFlags> getRegexFlag(llvm::StringRef Flag) { for (const auto &StringFlag : RegexMap) { if (Flag == StringFlag.first) @@ -127,8 +127,7 @@ getRegexFlag(llvm::StringRef Flag) { return std::nullopt; } -static llvm::Optional<llvm::StringRef> -getCloseRegexMatch(llvm::StringRef Flag) { +static std::optional<llvm::StringRef> getCloseRegexMatch(llvm::StringRef Flag) { for (const auto &StringFlag : RegexMap) { if (Flag.edit_distance(StringFlag.first) < 3) return StringFlag.first; @@ -136,14 +135,14 @@ getCloseRegexMatch(llvm::StringRef Flag) { return std::nullopt; } -llvm::Optional<llvm::Regex::RegexFlags> +std::optional<llvm::Regex::RegexFlags> clang::ast_matchers::dynamic::internal::ArgTypeTraits< llvm::Regex::RegexFlags>::getFlags(llvm::StringRef Flags) { - llvm::Optional<llvm::Regex::RegexFlags> Flag; + std::optional<llvm::Regex::RegexFlags> Flag; SmallVector<StringRef, 4> Split; Flags.split(Split, '|', -1, false); for (StringRef OrFlag : Split) { - if (llvm::Optional<llvm::Regex::RegexFlags> NextFlag = + if (std::optional<llvm::Regex::RegexFlags> NextFlag = getRegexFlag(OrFlag.trim())) Flag = Flag.value_or(llvm::Regex::NoFlags) | *NextFlag; else @@ -152,7 +151,7 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits< return Flag; } -llvm::Optional<std::string> +std::optional<std::string> clang::ast_matchers::dynamic::internal::ArgTypeTraits< llvm::Regex::RegexFlags>::getBestGuess(const VariantValue &Value) { if (!Value.isString()) @@ -160,7 +159,7 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits< SmallVector<StringRef, 4> Split; llvm::StringRef(Value.getString()).split(Split, '|', -1, false); for (llvm::StringRef &Flag : Split) { - if (llvm::Optional<llvm::StringRef> BestGuess = + if (std::optional<llvm::StringRef> BestGuess = getCloseRegexMatch(Flag.trim())) Flag = *BestGuess; else diff --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h b/clang/lib/ASTMatchers/Dynamic/Marshallers.h index c6bd6d5..5df5130 100644 --- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h +++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h @@ -71,7 +71,7 @@ template <> struct ArgTypeTraits<std::string> { return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &) { + static std::optional<std::string> getBestGuess(const VariantValue &) { return std::nullopt; } }; @@ -96,7 +96,7 @@ template <class T> struct ArgTypeTraits<ast_matchers::internal::Matcher<T>> { return ArgKind::MakeMatcherArg(ASTNodeKind::getFromNodeKind<T>()); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &) { + static std::optional<std::string> getBestGuess(const VariantValue &) { return std::nullopt; } }; @@ -115,7 +115,7 @@ template <> struct ArgTypeTraits<bool> { return ArgKind(ArgKind::AK_Boolean); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &) { + static std::optional<std::string> getBestGuess(const VariantValue &) { return std::nullopt; } }; @@ -134,7 +134,7 @@ template <> struct ArgTypeTraits<double> { return ArgKind(ArgKind::AK_Double); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &) { + static std::optional<std::string> getBestGuess(const VariantValue &) { return std::nullopt; } }; @@ -153,17 +153,17 @@ template <> struct ArgTypeTraits<unsigned> { return ArgKind(ArgKind::AK_Unsigned); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &) { + static std::optional<std::string> getBestGuess(const VariantValue &) { return std::nullopt; } }; template <> struct ArgTypeTraits<attr::Kind> { private: - static Optional<attr::Kind> getAttrKind(llvm::StringRef AttrKind) { + static std::optional<attr::Kind> getAttrKind(llvm::StringRef AttrKind) { if (!AttrKind.consume_front("attr::")) return std::nullopt; - return llvm::StringSwitch<Optional<attr::Kind>>(AttrKind) + return llvm::StringSwitch<std::optional<attr::Kind>>(AttrKind) #define ATTR(X) .Case(#X, attr::X) #include "clang/Basic/AttrList.inc" .Default(std::nullopt); @@ -185,15 +185,15 @@ public: return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &Value); + static std::optional<std::string> getBestGuess(const VariantValue &Value); }; template <> struct ArgTypeTraits<CastKind> { private: - static Optional<CastKind> getCastKind(llvm::StringRef AttrKind) { + static std::optional<CastKind> getCastKind(llvm::StringRef AttrKind) { if (!AttrKind.consume_front("CK_")) return std::nullopt; - return llvm::StringSwitch<Optional<CastKind>>(AttrKind) + return llvm::StringSwitch<std::optional<CastKind>>(AttrKind) #define CAST_OPERATION(Name) .Case(#Name, CK_##Name) #include "clang/AST/OperationKinds.def" .Default(std::nullopt); @@ -215,12 +215,12 @@ public: return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &Value); + static std::optional<std::string> getBestGuess(const VariantValue &Value); }; template <> struct ArgTypeTraits<llvm::Regex::RegexFlags> { private: - static Optional<llvm::Regex::RegexFlags> getFlags(llvm::StringRef Flags); + static std::optional<llvm::Regex::RegexFlags> getFlags(llvm::StringRef Flags); public: static bool hasCorrectType(const VariantValue &Value) { @@ -236,13 +236,14 @@ public: static ArgKind getKind() { return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &Value); + static std::optional<std::string> getBestGuess(const VariantValue &Value); }; template <> struct ArgTypeTraits<OpenMPClauseKind> { private: - static Optional<OpenMPClauseKind> getClauseKind(llvm::StringRef ClauseKind) { - return llvm::StringSwitch<Optional<OpenMPClauseKind>>(ClauseKind) + static std::optional<OpenMPClauseKind> + getClauseKind(llvm::StringRef ClauseKind) { + return llvm::StringSwitch<std::optional<OpenMPClauseKind>>(ClauseKind) #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) .Case(#Enum, llvm::omp::Clause::Enum) #include "llvm/Frontend/OpenMP/OMP.inc" @@ -263,16 +264,16 @@ public: static ArgKind getKind() { return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &Value); + static std::optional<std::string> getBestGuess(const VariantValue &Value); }; template <> struct ArgTypeTraits<UnaryExprOrTypeTrait> { private: - static Optional<UnaryExprOrTypeTrait> + static std::optional<UnaryExprOrTypeTrait> getUnaryOrTypeTraitKind(llvm::StringRef ClauseKind) { if (!ClauseKind.consume_front("UETT_")) return std::nullopt; - return llvm::StringSwitch<Optional<UnaryExprOrTypeTrait>>(ClauseKind) + return llvm::StringSwitch<std::optional<UnaryExprOrTypeTrait>>(ClauseKind) #define UNARY_EXPR_OR_TYPE_TRAIT(Spelling, Name, Key) .Case(#Name, UETT_##Name) #define CXX11_UNARY_EXPR_OR_TYPE_TRAIT(Spelling, Name, Key) \ .Case(#Name, UETT_##Name) @@ -294,7 +295,7 @@ public: static ArgKind getKind() { return ArgKind(ArgKind::AK_String); } - static llvm::Optional<std::string> getBestGuess(const VariantValue &Value); + static std::optional<std::string> getBestGuess(const VariantValue &Value); }; /// Matcher descriptor interface. @@ -508,7 +509,7 @@ variadicMatcherDescriptor(StringRef MatcherName, SourceRange NameRange, return {}; } if (!ArgTraits::hasCorrectValue(Value)) { - if (llvm::Optional<std::string> BestGuess = + if (std::optional<std::string> BestGuess = ArgTraits::getBestGuess(Value)) { Error->addError(Arg.Range, Error->ET_RegistryUnknownEnumWithReplace) << i + 1 << Value.getString() << *BestGuess; @@ -635,7 +636,7 @@ private: return VariantMatcher(); \ } \ if (!ArgTypeTraits<type>::hasCorrectValue(Args[index].Value)) { \ - if (llvm::Optional<std::string> BestGuess = \ + if (std::optional<std::string> BestGuess = \ ArgTypeTraits<type>::getBestGuess(Args[index].Value)) { \ Error->addError(Args[index].Range, \ Error->ET_RegistryUnknownEnumWithReplace) \ @@ -845,7 +846,7 @@ public: } if (!ArgTypeTraits<llvm::Regex::RegexFlags>::hasCorrectValue( Args[1].Value)) { - if (llvm::Optional<std::string> BestGuess = + if (std::optional<std::string> BestGuess = ArgTypeTraits<llvm::Regex::RegexFlags>::getBestGuess( Args[1].Value)) { Error->addError(Args[1].Range, Error->ET_RegistryUnknownEnumWithReplace) diff --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp b/clang/lib/ASTMatchers/Dynamic/Parser.cpp index ac6d643..6085897 100644 --- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp +++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp @@ -396,10 +396,10 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue *Value) { return false; assert(NamedValue.isMatcher()); - llvm::Optional<DynTypedMatcher> Result = + std::optional<DynTypedMatcher> Result = NamedValue.getMatcher().getSingleMatcher(); if (Result) { - llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); + std::optional<DynTypedMatcher> Bound = Result->tryBind(BindID); if (Bound) { *Value = VariantMatcher::SingleMatcher(*Bound); return true; @@ -439,7 +439,7 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue *Value) { return false; } - llvm::Optional<MatcherCtor> Ctor = S->lookupMatcherCtor(NameToken.Text); + std::optional<MatcherCtor> Ctor = S->lookupMatcherCtor(NameToken.Text); // Parse as a matcher expression. return parseMatcherExpressionImpl(NameToken, OpenToken, Ctor, Value); @@ -518,7 +518,7 @@ bool Parser::parseMatcherBuilder(MatcherCtor Ctor, const TokenInfo &NameToken, ArgValue.Text = NodeMatcherToken.Text; ArgValue.Range = NodeMatcherToken.Range; - llvm::Optional<MatcherCtor> MappedMatcher = + std::optional<MatcherCtor> MappedMatcher = S->lookupMatcherCtor(ArgValue.Text); if (!MappedMatcher) { @@ -629,7 +629,7 @@ bool Parser::parseMatcherBuilder(MatcherCtor Ctor, const TokenInfo &NameToken, /// returns \c false. bool Parser::parseMatcherExpressionImpl(const TokenInfo &NameToken, const TokenInfo &OpenToken, - llvm::Optional<MatcherCtor> Ctor, + std::optional<MatcherCtor> Ctor, VariantValue *Value) { if (!Ctor) { Error->addError(NameToken.Range, Error->ET_RegistryMatcherNotFound) @@ -829,7 +829,7 @@ Parser::Parser(CodeTokenizer *Tokenizer, Sema *S, Parser::RegistrySema::~RegistrySema() = default; -llvm::Optional<MatcherCtor> +std::optional<MatcherCtor> Parser::RegistrySema::lookupMatcherCtor(StringRef MatcherName) { return Registry::lookupMatcherCtor(MatcherName); } @@ -905,7 +905,7 @@ Parser::completeExpression(StringRef &Code, unsigned CompletionOffset, Sema *S, return P.Completions; } -llvm::Optional<DynTypedMatcher> +std::optional<DynTypedMatcher> Parser::parseMatcherExpression(StringRef &Code, Sema *S, const NamedValueMap *NamedValues, Diagnostics *Error) { @@ -916,8 +916,7 @@ Parser::parseMatcherExpression(StringRef &Code, Sema *S, Error->addError(SourceRange(), Error->ET_ParserNotAMatcher); return std::nullopt; } - llvm::Optional<DynTypedMatcher> Result = - Value.getMatcher().getSingleMatcher(); + std::optional<DynTypedMatcher> Result = Value.getMatcher().getSingleMatcher(); if (!Result) { Error->addError(SourceRange(), Error->ET_ParserOverloadedType) << Value.getTypeAsString(); diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp b/clang/lib/ASTMatchers/Dynamic/Registry.cpp index 2fb51c7..f822c9f 100644 --- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp +++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp @@ -622,11 +622,10 @@ Registry::buildMatcherCtor(MatcherCtor Ctor, SourceRange NameRange, } // static -llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) { +std::optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) { auto it = RegistryData->constructors().find(MatcherName); - return it == RegistryData->constructors().end() - ? llvm::Optional<MatcherCtor>() - : it->second.get(); + return it == RegistryData->constructors().end() ? std::optional<MatcherCtor>() + : it->second.get(); } static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, @@ -799,9 +798,9 @@ VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor, VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error); if (Out.isNull()) return Out; - llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher(); + std::optional<DynTypedMatcher> Result = Out.getSingleMatcher(); if (Result) { - llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); + std::optional<DynTypedMatcher> Bound = Result->tryBind(BindID); if (Bound) { return VariantMatcher::SingleMatcher(*Bound); } diff --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp index ee60042..4f6b021 100644 --- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp +++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp @@ -67,7 +67,7 @@ DynTypedMatcher VariantMatcher::MatcherOps::convertMatcher( return Matcher.dynCastTo(NodeKind); } -llvm::Optional<DynTypedMatcher> +std::optional<DynTypedMatcher> VariantMatcher::MatcherOps::constructVariadicOperator( DynTypedMatcher::VariadicOperator Op, ArrayRef<VariantMatcher> InnerMatchers) const { @@ -77,7 +77,7 @@ VariantMatcher::MatcherOps::constructVariadicOperator( // Matcher<T>. if (!InnerMatcher.Value) return std::nullopt; - llvm::Optional<DynTypedMatcher> Inner = + std::optional<DynTypedMatcher> Inner = InnerMatcher.Value->getTypedMatcher(*this); if (!Inner) return std::nullopt; @@ -92,7 +92,7 @@ class VariantMatcher::SinglePayload : public VariantMatcher::Payload { public: SinglePayload(const DynTypedMatcher &Matcher) : Matcher(Matcher) {} - llvm::Optional<DynTypedMatcher> getSingleMatcher() const override { + std::optional<DynTypedMatcher> getSingleMatcher() const override { return Matcher; } @@ -101,7 +101,7 @@ public: .str(); } - llvm::Optional<DynTypedMatcher> + std::optional<DynTypedMatcher> getTypedMatcher(const MatcherOps &Ops) const override { bool Ignore; if (Ops.canConstructFrom(Matcher, Ignore)) @@ -125,7 +125,7 @@ public: ~PolymorphicPayload() override {} - llvm::Optional<DynTypedMatcher> getSingleMatcher() const override { + std::optional<DynTypedMatcher> getSingleMatcher() const override { if (Matchers.size() != 1) return std::nullopt; return Matchers[0]; @@ -141,7 +141,7 @@ public: return (Twine("Matcher<") + Inner + ">").str(); } - llvm::Optional<DynTypedMatcher> + std::optional<DynTypedMatcher> getTypedMatcher(const MatcherOps &Ops) const override { bool FoundIsExact = false; const DynTypedMatcher *Found = nullptr; @@ -190,7 +190,7 @@ public: std::vector<VariantMatcher> Args) : Op(Op), Args(std::move(Args)) {} - llvm::Optional<DynTypedMatcher> getSingleMatcher() const override { + std::optional<DynTypedMatcher> getSingleMatcher() const override { return std::nullopt; } @@ -204,7 +204,7 @@ public: return Inner; } - llvm::Optional<DynTypedMatcher> + std::optional<DynTypedMatcher> getTypedMatcher(const MatcherOps &Ops) const override { return Ops.constructVariadicOperator(Op, Args); } @@ -241,8 +241,8 @@ VariantMatcher VariantMatcher::VariadicOperatorMatcher( std::make_shared<VariadicOpPayload>(Op, std::move(Args))); } -llvm::Optional<DynTypedMatcher> VariantMatcher::getSingleMatcher() const { - return Value ? Value->getSingleMatcher() : llvm::Optional<DynTypedMatcher>(); +std::optional<DynTypedMatcher> VariantMatcher::getSingleMatcher() const { + return Value ? Value->getSingleMatcher() : std::optional<DynTypedMatcher>(); } void VariantMatcher::reset() { Value.reset(); } diff --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp index e5fa481..c055348 100644 --- a/clang/lib/Analysis/BodyFarm.cpp +++ b/clang/lib/Analysis/BodyFarm.cpp @@ -698,7 +698,7 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) } Stmt *BodyFarm::getBody(const FunctionDecl *D) { - Optional<Stmt *> &Val = Bodies[D]; + std::optional<Stmt *> &Val = Bodies[D]; if (Val) return *Val; @@ -873,7 +873,7 @@ Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) { if (!D->isImplicit()) return nullptr; - Optional<Stmt *> &Val = Bodies[D]; + std::optional<Stmt *> &Val = Bodies[D]; if (Val) return *Val; Val = nullptr; diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index dd1de75..27ee1c2 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -969,7 +969,7 @@ private: const Expr *LHSExpr = B->getLHS()->IgnoreParens(); const Expr *RHSExpr = B->getRHS()->IgnoreParens(); - Optional<llvm::APInt> IntLiteral1 = + std::optional<llvm::APInt> IntLiteral1 = getIntegerLiteralSubexpressionValue(LHSExpr); const Expr *BoolExpr = RHSExpr; @@ -987,7 +987,7 @@ private: const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens(); const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens(); - Optional<llvm::APInt> IntLiteral2 = + std::optional<llvm::APInt> IntLiteral2 = getIntegerLiteralSubexpressionValue(LHSExpr2); if (!IntLiteral2) @@ -1021,7 +1021,8 @@ private: // FIXME: it would be good to unify this function with // IsIntegerLiteralConstantExpr at some point given the similarity between the // functions. - Optional<llvm::APInt> getIntegerLiteralSubexpressionValue(const Expr *E) { + std::optional<llvm::APInt> + getIntegerLiteralSubexpressionValue(const Expr *E) { // If unary. if (const auto *UnOp = dyn_cast<UnaryOperator>(E->IgnoreParens())) { @@ -5423,7 +5424,7 @@ public: unsigned j = 1; for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; BI != BEnd; ++BI, ++j ) { - if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { + if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { const Stmt *stmt= SE->getStmt(); std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); StmtMap[stmt] = P; @@ -5797,7 +5798,7 @@ static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, OS << " (BindTemporary)"; } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { OS << " (CXXConstructExpr"; - if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) { + if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) { print_construction_context(OS, Helper, CE->getConstructionContext()); } OS << ", " << CCE->getType() << ")"; @@ -6172,7 +6173,7 @@ static bool isImmediateSinkBlock(const CFGBlock *Blk) { // we'd need to carefully handle the case when the throw is being // immediately caught. if (llvm::any_of(*Blk, [](const CFGElement &Elm) { - if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>()) + if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>()) if (isa<CXXThrowExpr>(StmtElm->getStmt())) return true; return false; diff --git a/clang/lib/Analysis/CFGStmtMap.cpp b/clang/lib/Analysis/CFGStmtMap.cpp index 82f151c..c3a4581 100644 --- a/clang/lib/Analysis/CFGStmtMap.cpp +++ b/clang/lib/Analysis/CFGStmtMap.cpp @@ -50,7 +50,7 @@ static void Accumulate(SMap &SM, CFGBlock *B) { // First walk the block-level expressions. for (CFGBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) { const CFGElement &CE = *I; - Optional<CFGStmt> CS = CE.getAs<CFGStmt>(); + std::optional<CFGStmt> CS = CE.getAs<CFGStmt>(); if (!CS) continue; diff --git a/clang/lib/Analysis/CalledOnceCheck.cpp b/clang/lib/Analysis/CalledOnceCheck.cpp index d68182d..ca1e621 100644 --- a/clang/lib/Analysis/CalledOnceCheck.cpp +++ b/clang/lib/Analysis/CalledOnceCheck.cpp @@ -495,7 +495,7 @@ struct Clarification { /// of basic blocks. class NotCalledClarifier : public ConstStmtVisitor<NotCalledClarifier, - llvm::Optional<Clarification>> { + std::optional<Clarification>> { public: /// The main entrypoint for the class, the function that tries to find the /// clarification of how to explain which sub-path starts with a CFG edge @@ -509,24 +509,24 @@ public: /// results only for such cases. For this very reason, the parent basic /// block, Conditional, is named that way, so it is clear what kind of /// block is expected. - static llvm::Optional<Clarification> - clarify(const CFGBlock *Conditional, const CFGBlock *SuccWithoutCall) { + static std::optional<Clarification> clarify(const CFGBlock *Conditional, + const CFGBlock *SuccWithoutCall) { if (const Stmt *Terminator = Conditional->getTerminatorStmt()) { return NotCalledClarifier{Conditional, SuccWithoutCall}.Visit(Terminator); } return std::nullopt; } - llvm::Optional<Clarification> VisitIfStmt(const IfStmt *If) { + std::optional<Clarification> VisitIfStmt(const IfStmt *If) { return VisitBranchingBlock(If, NeverCalledReason::IfThen); } - llvm::Optional<Clarification> + std::optional<Clarification> VisitAbstractConditionalOperator(const AbstractConditionalOperator *Ternary) { return VisitBranchingBlock(Ternary, NeverCalledReason::IfThen); } - llvm::Optional<Clarification> VisitSwitchStmt(const SwitchStmt *Switch) { + std::optional<Clarification> VisitSwitchStmt(const SwitchStmt *Switch) { const Stmt *CaseToBlame = SuccInQuestion->getLabel(); if (!CaseToBlame) { // If interesting basic block is not labeled, it means that this @@ -544,15 +544,15 @@ public: llvm_unreachable("Found unexpected switch structure"); } - llvm::Optional<Clarification> VisitForStmt(const ForStmt *For) { + std::optional<Clarification> VisitForStmt(const ForStmt *For) { return VisitBranchingBlock(For, NeverCalledReason::LoopEntered); } - llvm::Optional<Clarification> VisitWhileStmt(const WhileStmt *While) { + std::optional<Clarification> VisitWhileStmt(const WhileStmt *While) { return VisitBranchingBlock(While, NeverCalledReason::LoopEntered); } - llvm::Optional<Clarification> + std::optional<Clarification> VisitBranchingBlock(const Stmt *Terminator, NeverCalledReason DefaultReason) { assert(Parent->succ_size() == 2 && "Branching block should have exactly two successors"); @@ -562,12 +562,12 @@ public: return Clarification{ActualReason, Terminator}; } - llvm::Optional<Clarification> VisitBinaryOperator(const BinaryOperator *) { + std::optional<Clarification> VisitBinaryOperator(const BinaryOperator *) { // We don't want to report on short-curcuit logical operations. return std::nullopt; } - llvm::Optional<Clarification> VisitStmt(const Stmt *Terminator) { + std::optional<Clarification> VisitStmt(const Stmt *Terminator) { // If we got here, we didn't have a visit function for more derived // classes of statement that this terminator actually belongs to. // @@ -754,7 +754,7 @@ private: // We use a backward dataflow propagation and for this reason we // should traverse basic blocks bottom-up. for (const CFGElement &Element : llvm::reverse(*BB)) { - if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> S = Element.getAs<CFGStmt>()) { check(S->getStmt()); } } @@ -1000,8 +1000,8 @@ private: /// parameter is conventionally called once. /// Return std::nullopt if the given declaration doesn't have 'swift_async' /// attribute. - static llvm::Optional<bool> isConventionalSwiftAsync(const Decl *D, - unsigned ParamIndex) { + static std::optional<bool> isConventionalSwiftAsync(const Decl *D, + unsigned ParamIndex) { if (const SwiftAsyncAttr *A = D->getAttr<SwiftAsyncAttr>()) { if (A->getKind() == SwiftAsyncAttr::None) { return false; @@ -1266,7 +1266,7 @@ private: llvm::reverse(*BB), // we should start with return statements, if we // have any, i.e. from the bottom of the block [&ReturnChildren](const CFGElement &Element) { - if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> S = Element.getAs<CFGStmt>()) { const Stmt *SuspiciousStmt = S->getStmt(); if (isa<ReturnStmt>(SuspiciousStmt)) { @@ -1636,11 +1636,11 @@ public: private: unsigned size() const { return TrackedParams.size(); } - llvm::Optional<unsigned> getIndexOfCallee(const CallExpr *Call) const { + std::optional<unsigned> getIndexOfCallee(const CallExpr *Call) const { return getIndexOfExpression(Call->getCallee()); } - llvm::Optional<unsigned> getIndexOfExpression(const Expr *E) const { + std::optional<unsigned> getIndexOfExpression(const Expr *E) const { if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(E)) { return getIndex(*Parameter); } @@ -1648,7 +1648,7 @@ private: return std::nullopt; } - llvm::Optional<unsigned> getIndex(const ParmVarDecl &Parameter) const { + std::optional<unsigned> getIndex(const ParmVarDecl &Parameter) const { // Expected number of parameters that we actually track is 1. // // Also, the maximum number of declared parameters could not be on a scale diff --git a/clang/lib/Analysis/Consumed.cpp b/clang/lib/Analysis/Consumed.cpp index 287dfbb0..fb7fe99 100644 --- a/clang/lib/Analysis/Consumed.cpp +++ b/clang/lib/Analysis/Consumed.cpp @@ -63,7 +63,7 @@ static SourceLocation getFirstStmtLoc(const CFGBlock *Block) { // Find the source location of the first statement in the block, if the block // is not empty. for (const auto &B : *Block) - if (Optional<CFGStmt> CS = B.getAs<CFGStmt>()) + if (std::optional<CFGStmt> CS = B.getAs<CFGStmt>()) return CS->getStmt()->getBeginLoc(); // Block is empty. @@ -82,7 +82,7 @@ static SourceLocation getLastStmtLoc(const CFGBlock *Block) { } else { for (CFGBlock::const_reverse_iterator BI = Block->rbegin(), BE = Block->rend(); BI != BE; ++BI) { - if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) + if (std::optional<CFGStmt> CS = BI->getAs<CFGStmt>()) return CS->getStmt()->getBeginLoc(); } } diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp index c0eb256..308dc25d 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp @@ -59,7 +59,7 @@ auto hasOptionalType() { return hasType(optionalOrAliasType()); } auto isOptionalMemberCallWithName( llvm::StringRef MemberName, - const llvm::Optional<StatementMatcher> &Ignorable = std::nullopt) { + const std::optional<StatementMatcher> &Ignorable = std::nullopt) { auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr())) : cxxThisExpr()); return cxxMemberCallExpr( @@ -69,7 +69,7 @@ auto isOptionalMemberCallWithName( auto isOptionalOperatorCallWithName( llvm::StringRef operator_name, - const llvm::Optional<StatementMatcher> &Ignorable = std::nullopt) { + const std::optional<StatementMatcher> &Ignorable = std::nullopt) { return cxxOperatorCallExpr( hasOverloadedOperatorName(operator_name), callee(cxxMethodDecl(ofClass(optionalClass()))), @@ -615,7 +615,7 @@ void transferOptionalAndValueCmp(const clang::CXXOperatorCallExpr *CmpExpr, } } -llvm::Optional<StatementMatcher> +std::optional<StatementMatcher> ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) { if (Options.IgnoreSmartPointerDereference) { auto SmartPtrUse = expr(ignoringParenImpCasts(cxxOperatorCallExpr( @@ -628,12 +628,12 @@ ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) { } StatementMatcher -valueCall(const llvm::Optional<StatementMatcher> &IgnorableOptional) { +valueCall(const std::optional<StatementMatcher> &IgnorableOptional) { return isOptionalMemberCallWithName("value", IgnorableOptional); } StatementMatcher -valueOperatorCall(const llvm::Optional<StatementMatcher> &IgnorableOptional) { +valueOperatorCall(const std::optional<StatementMatcher> &IgnorableOptional) { return expr(anyOf(isOptionalOperatorCallWithName("*", IgnorableOptional), isOptionalOperatorCallWithName("->", IgnorableOptional))); } diff --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp index 44523a2..ce9ceb1 100644 --- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp +++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp @@ -43,7 +43,7 @@ class StmtToEnvMapImpl : public StmtToEnvMap { public: StmtToEnvMapImpl( const ControlFlowContext &CFCtx, - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockToState) : CFCtx(CFCtx), BlockToState(BlockToState) {} @@ -57,7 +57,7 @@ public: private: const ControlFlowContext &CFCtx; - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockToState; + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockToState; }; /// Returns the index of `Block` in the successors of `Pred`. @@ -182,11 +182,11 @@ private: /// Holds data structures required for running dataflow analysis. struct AnalysisContext { - AnalysisContext( - const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis, - const Environment &InitEnv, - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> - BlockStates) + AnalysisContext(const ControlFlowContext &CFCtx, + TypeErasedDataflowAnalysis &Analysis, + const Environment &InitEnv, + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> + BlockStates) : CFCtx(CFCtx), Analysis(Analysis), InitEnv(InitEnv), BlockStates(BlockStates) {} @@ -198,7 +198,7 @@ struct AnalysisContext { const Environment &InitEnv; /// Stores the state of a CFG block if it has been evaluated by the analysis. /// The indices correspond to the block IDs. - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates; + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockStates; }; /// Computes the input state for a given basic block by joining the output @@ -244,7 +244,7 @@ computeBlockInputState(const CFGBlock &Block, AnalysisContext &AC) { } } - llvm::Optional<TypeErasedDataflowAnalysisState> MaybeState; + std::optional<TypeErasedDataflowAnalysisState> MaybeState; auto &Analysis = AC.Analysis; for (const CFGBlock *Pred : Preds) { @@ -254,7 +254,7 @@ computeBlockInputState(const CFGBlock &Block, AnalysisContext &AC) { // Skip if `Pred` was not evaluated yet. This could happen if `Pred` has a // loop back edge to `Block`. - const llvm::Optional<TypeErasedDataflowAnalysisState> &MaybePredState = + const std::optional<TypeErasedDataflowAnalysisState> &MaybePredState = AC.BlockStates[Pred->getBlockID()]; if (!MaybePredState) continue; @@ -385,7 +385,7 @@ transferCFGBlock(const CFGBlock &Block, AnalysisContext &AC, TypeErasedDataflowAnalysisState transferBlock( const ControlFlowContext &CFCtx, - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates, + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockStates, const CFGBlock &Block, const Environment &InitEnv, TypeErasedDataflowAnalysis &Analysis, std::function<void(const CFGElement &, @@ -395,7 +395,7 @@ TypeErasedDataflowAnalysisState transferBlock( return transferCFGBlock(Block, AC, PostVisitCFG); } -llvm::Expected<std::vector<llvm::Optional<TypeErasedDataflowAnalysisState>>> +llvm::Expected<std::vector<std::optional<TypeErasedDataflowAnalysisState>>> runTypeErasedDataflowAnalysis( const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis, const Environment &InitEnv, @@ -405,7 +405,7 @@ runTypeErasedDataflowAnalysis( PostOrderCFGView POV(&CFCtx.getCFG()); ForwardDataflowWorklist Worklist(CFCtx.getCFG(), &POV); - std::vector<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates( + std::vector<std::optional<TypeErasedDataflowAnalysisState>> BlockStates( CFCtx.getCFG().size(), std::nullopt); // The entry basic block doesn't contain statements so it can be skipped. @@ -437,7 +437,7 @@ runTypeErasedDataflowAnalysis( "maximum number of iterations reached"); } - const llvm::Optional<TypeErasedDataflowAnalysisState> &OldBlockState = + const std::optional<TypeErasedDataflowAnalysisState> &OldBlockState = BlockStates[Block->getBlockID()]; TypeErasedDataflowAnalysisState NewBlockState = transferCFGBlock(*Block, AC); diff --git a/clang/lib/Analysis/IssueHash.cpp b/clang/lib/Analysis/IssueHash.cpp index 3e712fc..4d56e77 100644 --- a/clang/lib/Analysis/IssueHash.cpp +++ b/clang/lib/Analysis/IssueHash.cpp @@ -122,7 +122,7 @@ static std::string GetEnclosingDeclContextSignature(const Decl *D) { return ""; } -static StringRef GetNthLineOfFile(llvm::Optional<llvm::MemoryBufferRef> Buffer, +static StringRef GetNthLineOfFile(std::optional<llvm::MemoryBufferRef> Buffer, int Line) { if (!Buffer) return ""; @@ -147,7 +147,7 @@ static std::string NormalizeLine(const SourceManager &SM, const FullSourceLoc &L col++; SourceLocation StartOfLine = SM.translateLineCol(SM.getFileID(L), L.getExpansionLineNumber(), col); - Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = SM.getBufferOrNone(SM.getFileID(StartOfLine), StartOfLine); if (!Buffer) return {}; diff --git a/clang/lib/Analysis/LiveVariables.cpp b/clang/lib/Analysis/LiveVariables.cpp index d9194dd..6d03dd0 100644 --- a/clang/lib/Analysis/LiveVariables.cpp +++ b/clang/lib/Analysis/LiveVariables.cpp @@ -491,7 +491,7 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, ei = block->rend(); it != ei; ++it) { const CFGElement &elem = *it; - if (Optional<CFGAutomaticObjDtor> Dtor = + if (std::optional<CFGAutomaticObjDtor> Dtor = elem.getAs<CFGAutomaticObjDtor>()) { val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl()); continue; diff --git a/clang/lib/Analysis/MacroExpansionContext.cpp b/clang/lib/Analysis/MacroExpansionContext.cpp index 3d98be7..564e359 100644 --- a/clang/lib/Analysis/MacroExpansionContext.cpp +++ b/clang/lib/Analysis/MacroExpansionContext.cpp @@ -97,7 +97,7 @@ void MacroExpansionContext::registerForPreprocessor(Preprocessor &NewPP) { PP->setTokenWatcher([this](const Token &Tok) { onTokenLexed(Tok); }); } -Optional<StringRef> +std::optional<StringRef> MacroExpansionContext::getExpandedText(SourceLocation MacroExpansionLoc) const { if (MacroExpansionLoc.isMacroID()) return std::nullopt; @@ -115,7 +115,7 @@ MacroExpansionContext::getExpandedText(SourceLocation MacroExpansionLoc) const { return It->getSecond().str(); } -Optional<StringRef> +std::optional<StringRef> MacroExpansionContext::getOriginalText(SourceLocation MacroExpansionLoc) const { if (MacroExpansionLoc.isMacroID()) return std::nullopt; diff --git a/clang/lib/Analysis/PathDiagnostic.cpp b/clang/lib/Analysis/PathDiagnostic.cpp index 42fa401..ce6ad42 100644 --- a/clang/lib/Analysis/PathDiagnostic.cpp +++ b/clang/lib/Analysis/PathDiagnostic.cpp @@ -226,9 +226,10 @@ void PathDiagnosticConsumer::HandlePathDiagnostic( Diags.InsertNode(D.release()); } -static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y); +static std::optional<bool> comparePath(const PathPieces &X, + const PathPieces &Y); -static Optional<bool> +static std::optional<bool> compareControlFlow(const PathDiagnosticControlFlowPiece &X, const PathDiagnosticControlFlowPiece &Y) { FullSourceLoc XSL = X.getStartLocation().asLocation(); @@ -242,13 +243,13 @@ compareControlFlow(const PathDiagnosticControlFlowPiece &X, return std::nullopt; } -static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X, - const PathDiagnosticMacroPiece &Y) { +static std::optional<bool> compareMacro(const PathDiagnosticMacroPiece &X, + const PathDiagnosticMacroPiece &Y) { return comparePath(X.subPieces, Y.subPieces); } -static Optional<bool> compareCall(const PathDiagnosticCallPiece &X, - const PathDiagnosticCallPiece &Y) { +static std::optional<bool> compareCall(const PathDiagnosticCallPiece &X, + const PathDiagnosticCallPiece &Y) { FullSourceLoc X_CEL = X.callEnter.asLocation(); FullSourceLoc Y_CEL = Y.callEnter.asLocation(); if (X_CEL != Y_CEL) @@ -264,8 +265,8 @@ static Optional<bool> compareCall(const PathDiagnosticCallPiece &X, return comparePath(X.path, Y.path); } -static Optional<bool> comparePiece(const PathDiagnosticPiece &X, - const PathDiagnosticPiece &Y) { +static std::optional<bool> comparePiece(const PathDiagnosticPiece &X, + const PathDiagnosticPiece &Y) { if (X.getKind() != Y.getKind()) return X.getKind() < Y.getKind(); @@ -310,7 +311,8 @@ static Optional<bool> comparePiece(const PathDiagnosticPiece &X, llvm_unreachable("all cases handled"); } -static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) { +static std::optional<bool> comparePath(const PathPieces &X, + const PathPieces &Y) { if (X.size() != Y.size()) return X.size() < Y.size(); @@ -318,7 +320,7 @@ static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) { PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end(); for (; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) - if (Optional<bool> b = comparePiece(**X_I, **Y_I)) + if (std::optional<bool> b = comparePiece(**X_I, **Y_I)) return *b; return std::nullopt; @@ -363,7 +365,8 @@ static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) { return X.getVerboseDescription() < Y.getVerboseDescription(); if (X.getShortDescription() != Y.getShortDescription()) return X.getShortDescription() < Y.getShortDescription(); - auto CompareDecls = [&XL](const Decl *D1, const Decl *D2) -> Optional<bool> { + auto CompareDecls = [&XL](const Decl *D1, + const Decl *D2) -> std::optional<bool> { if (D1 == D2) return std::nullopt; if (!D1) @@ -661,7 +664,7 @@ PathDiagnosticLocation PathDiagnosticLocation::create(const ProgramPoint& P, const SourceManager &SMng) { const Stmt* S = nullptr; - if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { + if (std::optional<BlockEdge> BE = P.getAs<BlockEdge>()) { const CFGBlock *BSrc = BE->getSrc(); if (BSrc->getTerminator().isVirtualBaseBranch()) { // TODO: VirtualBaseBranches should also appear for destructors. @@ -681,22 +684,23 @@ PathDiagnosticLocation::create(const ProgramPoint& P, P.getLocationContext()->getDecl(), SMng); } } - } else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) { + } else if (std::optional<StmtPoint> SP = P.getAs<StmtPoint>()) { S = SP->getStmt(); if (P.getAs<PostStmtPurgeDeadSymbols>()) return PathDiagnosticLocation::createEnd(S, SMng, P.getLocationContext()); - } else if (Optional<PostInitializer> PIP = P.getAs<PostInitializer>()) { + } else if (std::optional<PostInitializer> PIP = P.getAs<PostInitializer>()) { return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(), SMng); - } else if (Optional<PreImplicitCall> PIC = P.getAs<PreImplicitCall>()) { + } else if (std::optional<PreImplicitCall> PIC = P.getAs<PreImplicitCall>()) { return PathDiagnosticLocation(PIC->getLocation(), SMng); - } else if (Optional<PostImplicitCall> PIE = P.getAs<PostImplicitCall>()) { + } else if (std::optional<PostImplicitCall> PIE = + P.getAs<PostImplicitCall>()) { return PathDiagnosticLocation(PIE->getLocation(), SMng); - } else if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { + } else if (std::optional<CallEnter> CE = P.getAs<CallEnter>()) { return getLocationForCaller(CE->getCalleeContext(), CE->getLocationContext(), SMng); - } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) { + } else if (std::optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) { return getLocationForCaller(CEE->getCalleeContext(), CEE->getLocationContext(), SMng); @@ -706,8 +710,8 @@ PathDiagnosticLocation::create(const ProgramPoint& P, CEB->getLocationContext()); return PathDiagnosticLocation( CEB->getLocationContext()->getDecl()->getSourceRange().getEnd(), SMng); - } else if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { - if (Optional<CFGElement> BlockFront = BE->getFirstElement()) { + } else if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { + if (std::optional<CFGElement> BlockFront = BE->getFirstElement()) { if (auto StmtElt = BlockFront->getAs<CFGStmt>()) { return PathDiagnosticLocation(StmtElt->getStmt()->getBeginLoc(), SMng); } else if (auto NewAllocElt = BlockFront->getAs<CFGNewAllocator>()) { @@ -719,7 +723,8 @@ PathDiagnosticLocation::create(const ProgramPoint& P, return PathDiagnosticLocation( BE->getBlock()->getTerminatorStmt()->getBeginLoc(), SMng); - } else if (Optional<FunctionExitPoint> FE = P.getAs<FunctionExitPoint>()) { + } else if (std::optional<FunctionExitPoint> FE = + P.getAs<FunctionExitPoint>()) { return PathDiagnosticLocation(FE->getStmt(), SMng, FE->getLocationContext()); } else { diff --git a/clang/lib/Analysis/ReachableCode.cpp b/clang/lib/Analysis/ReachableCode.cpp index a375521..5cc63bb 100644 --- a/clang/lib/Analysis/ReachableCode.cpp +++ b/clang/lib/Analysis/ReachableCode.cpp @@ -74,7 +74,7 @@ static bool isBuiltinAssumeFalse(const CFGBlock *B, const Stmt *S, // (e.g. a CFGBlock containing only a goto). return false; } - if (Optional<CFGStmt> CS = B->back().getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = B->back().getAs<CFGStmt>()) { if (const auto *CE = dyn_cast<CallExpr>(CS->getStmt())) { return CE->getCallee()->IgnoreCasts() == S && CE->isBuiltinAssumeFalse(C); } @@ -89,7 +89,7 @@ static bool isDeadReturn(const CFGBlock *B, const Stmt *S) { const CFGBlock *Current = B; while (true) { for (const CFGElement &CE : llvm::reverse(*Current)) { - if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) { if (RS == S) return true; @@ -340,7 +340,7 @@ static unsigned scanFromBlock(const CFGBlock *Start, // This allows us to potentially uncover some "always unreachable" code // within the "sometimes unreachable" code. // Look at the successors and mark then reachable. - Optional<bool> TreatAllSuccessorsAsReachable; + std::optional<bool> TreatAllSuccessorsAsReachable; if (!IncludeSometimesUnreachableEdges) TreatAllSuccessorsAsReachable = false; @@ -462,7 +462,7 @@ static bool isValidDeadStmt(const Stmt *S) { const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) { for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I) - if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = I->getAs<CFGStmt>()) { const Stmt *S = CS->getStmt(); if (isValidDeadStmt(S)) return S; diff --git a/clang/lib/Analysis/RetainSummaryManager.cpp b/clang/lib/Analysis/RetainSummaryManager.cpp index 30b37cc..468e94b2 100644 --- a/clang/lib/Analysis/RetainSummaryManager.cpp +++ b/clang/lib/Analysis/RetainSummaryManager.cpp @@ -66,8 +66,8 @@ struct GeneralizedConsumedAttr { } template <class T> -Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, - QualType QT) { +std::optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, + QualType QT) { ObjKind K; if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr, CFReturnsNotRetainedAttr>()) { @@ -107,8 +107,8 @@ Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, } template <class T1, class T2, class... Others> -Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, - QualType QT) { +std::optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, + QualType QT) { if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT)) return Out; return hasAnyEnabledAttrOf<T2, Others...>(D, QT); @@ -719,7 +719,7 @@ bool RetainSummaryManager::isTrustedReferenceCountImplementation( return hasRCAnnotation(FD, "rc_ownership_trusted_implementation"); } -Optional<RetainSummaryManager::BehaviorSummary> +std::optional<RetainSummaryManager::BehaviorSummary> RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD, bool &hasTrustedImplementationAnnotation) { @@ -865,7 +865,7 @@ RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { // Summary creation for Selectors. //===----------------------------------------------------------------------===// -Optional<RetEffect> +std::optional<RetEffect> RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy, const Decl *D) { if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy)) @@ -991,7 +991,7 @@ RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, applyParamAnnotationEffect(*pi, parm_idx, FD, Template); QualType RetTy = FD->getReturnType(); - if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD)) + if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD)) Template->setRetEffect(*RetE); if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy)) @@ -1018,7 +1018,7 @@ RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, applyParamAnnotationEffect(*pi, parm_idx, MD, Template); QualType RetTy = MD->getReturnType(); - if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD)) + if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD)) Template->setRetEffect(*RetE); } diff --git a/clang/lib/Analysis/ThreadSafety.cpp b/clang/lib/Analysis/ThreadSafety.cpp index feaca52..5333379 100644 --- a/clang/lib/Analysis/ThreadSafety.cpp +++ b/clang/lib/Analysis/ThreadSafety.cpp @@ -821,7 +821,7 @@ static void findBlockLocations(CFG *CFGraph, for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(), BE = CurrBlock->rend(); BI != BE; ++BI) { // FIXME: Handle other CFGElement kinds. - if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc(); break; } @@ -833,7 +833,7 @@ static void findBlockLocations(CFG *CFGraph, // of the first statement in the block. for (const auto &BI : *CurrBlock) { // FIXME: Handle other CFGElement kinds. - if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = BI.getAs<CFGStmt>()) { CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc(); break; } @@ -2217,7 +2217,7 @@ static bool neverReturns(const CFGBlock *B) { return false; CFGElement Last = B->back(); - if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> S = Last.getAs<CFGStmt>()) { if (isa<CXXThrowExpr>(S->getStmt())) return true; } diff --git a/clang/lib/Analysis/UninitializedValues.cpp b/clang/lib/Analysis/UninitializedValues.cpp index ae5c3541..3306904 100644 --- a/clang/lib/Analysis/UninitializedValues.cpp +++ b/clang/lib/Analysis/UninitializedValues.cpp @@ -71,7 +71,7 @@ public: unsigned size() const { return map.size(); } /// Returns the bit vector index for a given declaration. - Optional<unsigned> getValueIndex(const VarDecl *d) const; + std::optional<unsigned> getValueIndex(const VarDecl *d) const; }; } // namespace @@ -87,7 +87,7 @@ void DeclToIndex::computeMap(const DeclContext &dc) { } } -Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const { +std::optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const { llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d); if (I == map.end()) return std::nullopt; @@ -148,7 +148,7 @@ public: Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, const VarDecl *vd) { - Optional<unsigned> idx = declToIndex.getValueIndex(vd); + std::optional<unsigned> idx = declToIndex.getValueIndex(vd); return getValueVector(block)[*idx]; } }; @@ -859,7 +859,7 @@ static bool runOnBlock(const CFGBlock *block, const CFG &cfg, // Apply the transfer function. TransferFunctions tf(vals, cfg, block, ac, classification, handler); for (const auto &I : *block) { - if (Optional<CFGStmt> cs = I.getAs<CFGStmt>()) + if (std::optional<CFGStmt> cs = I.getAs<CFGStmt>()) tf.Visit(const_cast<Stmt *>(cs->getStmt())); } CFGTerminator terminator = block->getTerminator(); diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp index 43713b4..97f8136 100644 --- a/clang/lib/Analysis/UnsafeBufferUsage.cpp +++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp @@ -197,10 +197,9 @@ public: /// Returns a fixit that would fix the current gadget according to /// the current strategy. Returns None if the fix cannot be produced; /// returns an empty list if no fixes are necessary. - virtual Optional<FixItList> getFixits(const Strategy &) const { + virtual std::optional<FixItList> getFixits(const Strategy &) const { return std::nullopt; } - }; using FixableGadgetList = std::vector<std::unique_ptr<FixableGadget>>; diff --git a/clang/lib/Basic/DarwinSDKInfo.cpp b/clang/lib/Basic/DarwinSDKInfo.cpp index 4fb3409..00aa5f9 100644 --- a/clang/lib/Basic/DarwinSDKInfo.cpp +++ b/clang/lib/Basic/DarwinSDKInfo.cpp @@ -34,7 +34,7 @@ std::optional<VersionTuple> DarwinSDKInfo::RelatedTargetVersionMapping::map( return std::nullopt; } -Optional<DarwinSDKInfo::RelatedTargetVersionMapping> +std::optional<DarwinSDKInfo::RelatedTargetVersionMapping> DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON( const llvm::json::Object &Obj, VersionTuple MaximumDeploymentTarget) { VersionTuple Min = VersionTuple(std::numeric_limits<unsigned>::max()); @@ -82,7 +82,8 @@ DarwinSDKInfo::parseDarwinSDKSettingsJSON(const llvm::json::Object *Obj) { getVersionKey(*Obj, "MaximumDeploymentTarget"); if (!MaximumDeploymentVersion) return std::nullopt; - llvm::DenseMap<OSEnvPair::StorageType, Optional<RelatedTargetVersionMapping>> + llvm::DenseMap<OSEnvPair::StorageType, + std::optional<RelatedTargetVersionMapping>> VersionMappings; if (const auto *VM = Obj->getObject("VersionMap")) { // FIXME: Generalize this out beyond iOS-deriving targets. diff --git a/clang/lib/Basic/DiagnosticIDs.cpp b/clang/lib/Basic/DiagnosticIDs.cpp index 0b06a29..ac08e98 100644 --- a/clang/lib/Basic/DiagnosticIDs.cpp +++ b/clang/lib/Basic/DiagnosticIDs.cpp @@ -635,7 +635,7 @@ StringRef DiagnosticIDs::getWarningOptionForGroup(diag::Group Group) { return OptionTable[static_cast<int>(Group)].getName(); } -llvm::Optional<diag::Group> +std::optional<diag::Group> DiagnosticIDs::getGroupForWarningOption(StringRef Name) { const auto *Found = llvm::partition_point( OptionTable, [=](const WarningOption &O) { return O.getName() < Name; }); @@ -644,7 +644,7 @@ DiagnosticIDs::getGroupForWarningOption(StringRef Name) { return static_cast<diag::Group>(Found - OptionTable); } -llvm::Optional<diag::Group> DiagnosticIDs::getGroupForDiag(unsigned DiagID) { +std::optional<diag::Group> DiagnosticIDs::getGroupForDiag(unsigned DiagID) { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return static_cast<diag::Group>(Info->getOptionGroupIndex()); return std::nullopt; @@ -704,7 +704,7 @@ static bool getDiagnosticsInGroup(diag::Flavor Flavor, bool DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group, SmallVectorImpl<diag::kind> &Diags) const { - if (llvm::Optional<diag::Group> G = getGroupForWarningOption(Group)) + if (std::optional<diag::Group> G = getGroupForWarningOption(Group)) return ::getDiagnosticsInGroup( Flavor, &OptionTable[static_cast<unsigned>(*G)], Diags); return true; diff --git a/clang/lib/Basic/ProfileList.cpp b/clang/lib/Basic/ProfileList.cpp index 136924f..eea1b1e 100644 --- a/clang/lib/Basic/ProfileList.cpp +++ b/clang/lib/Basic/ProfileList.cpp @@ -101,7 +101,7 @@ ProfileList::getDefault(CodeGenOptions::ProfileInstrKind Kind) const { return Allow; } -llvm::Optional<ProfileList::ExclusionType> +std::optional<ProfileList::ExclusionType> ProfileList::inSection(StringRef Section, StringRef Prefix, StringRef Query) const { if (SCL->inSection(Section, Prefix, Query, "allow")) @@ -115,7 +115,7 @@ ProfileList::inSection(StringRef Section, StringRef Prefix, return std::nullopt; } -llvm::Optional<ProfileList::ExclusionType> +std::optional<ProfileList::ExclusionType> ProfileList::isFunctionExcluded(StringRef FunctionName, CodeGenOptions::ProfileInstrKind Kind) const { StringRef Section = getSectionName(Kind); @@ -129,13 +129,13 @@ ProfileList::isFunctionExcluded(StringRef FunctionName, return std::nullopt; } -llvm::Optional<ProfileList::ExclusionType> +std::optional<ProfileList::ExclusionType> ProfileList::isLocationExcluded(SourceLocation Loc, CodeGenOptions::ProfileInstrKind Kind) const { return isFileExcluded(SM.getFilename(SM.getFileLoc(Loc)), Kind); } -llvm::Optional<ProfileList::ExclusionType> +std::optional<ProfileList::ExclusionType> ProfileList::isFileExcluded(StringRef FileName, CodeGenOptions::ProfileInstrKind Kind) const { StringRef Section = getSectionName(Kind); diff --git a/clang/lib/Basic/Sarif.cpp b/clang/lib/Basic/Sarif.cpp index 52f22f2..c4a1ea4 100644 --- a/clang/lib/Basic/Sarif.cpp +++ b/clang/lib/Basic/Sarif.cpp @@ -120,7 +120,7 @@ static unsigned int adjustColumnPos(FullSourceLoc Loc, assert(!Loc.isInvalid() && "invalid Loc when adjusting column position"); std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedExpansionLoc(); - Optional<MemoryBufferRef> Buf = + std::optional<MemoryBufferRef> Buf = Loc.getManager().getBufferOrNone(LocInfo.first); assert(Buf && "got an invalid buffer for the location's file"); assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) && diff --git a/clang/lib/Basic/SourceManager.cpp b/clang/lib/Basic/SourceManager.cpp index 6fbeb38..6d88122 100644 --- a/clang/lib/Basic/SourceManager.cpp +++ b/clang/lib/Basic/SourceManager.cpp @@ -99,7 +99,7 @@ const char *ContentCache::getInvalidBOM(StringRef BufStr) { return InvalidBOM; } -llvm::Optional<llvm::MemoryBufferRef> +std::optional<llvm::MemoryBufferRef> ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc) const { // Lazily create the Buffer for ContentCaches that wrap files. If we already @@ -682,7 +682,7 @@ SourceManager::createExpansionLocImpl(const ExpansionInfo &Info, return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1)); } -llvm::Optional<llvm::MemoryBufferRef> +std::optional<llvm::MemoryBufferRef> SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) { SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef()); return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation()); @@ -730,7 +730,7 @@ void SourceManager::setFileIsTransient(const FileEntry *File) { getOrCreateContentCache(File->getLastRef()).IsTransient = true; } -Optional<StringRef> +std::optional<StringRef> SourceManager::getNonBuiltinFilenameForID(FileID FID) const { if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) if (Entry->getFile().getContentCache().OrigEntry) @@ -745,14 +745,14 @@ StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>"; } -llvm::Optional<StringRef> +std::optional<StringRef> SourceManager::getBufferDataIfLoaded(FileID FID) const { if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) return Entry->getFile().getContentCache().getBufferDataIfLoaded(); return std::nullopt; } -llvm::Optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const { +std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const { if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) if (auto B = Entry->getFile().getContentCache().getBufferOrNone( Diag, getFileManager(), SourceLocation())) @@ -1172,7 +1172,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL, return "<<<<INVALID BUFFER>>>>"; } - llvm::Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(), SourceLocation()); if (Invalid) @@ -1185,7 +1185,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL, /// this is significantly cheaper to compute than the line number. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid) const { - llvm::Optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID); + std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID); if (Invalid) *Invalid = !MemBuf; @@ -1375,7 +1375,7 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (!Content->SourceLineCache) { - llvm::Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(Diag, getFileManager(), SourceLocation()); if (Invalid) *Invalid = !Buffer; @@ -1725,7 +1725,7 @@ SourceLocation SourceManager::translateLineCol(FileID FID, // If this is the first use of line information for this buffer, compute the // SourceLineCache for it on demand. - llvm::Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(Diag, getFileManager()); if (!Buffer) return SourceLocation(); @@ -2183,7 +2183,7 @@ LLVM_DUMP_METHOD void SourceManager::dump() const { llvm::raw_ostream &out = llvm::errs(); auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry, - llvm::Optional<SourceLocation::UIntTy> NextStart) { + std::optional<SourceLocation::UIntTy> NextStart) { out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion") << " <SourceLocation " << Entry.getOffset() << ":"; if (NextStart) @@ -2223,7 +2223,7 @@ LLVM_DUMP_METHOD void SourceManager::dump() const { : LocalSLocEntryTable[ID + 1].getOffset()); } // Dump loaded SLocEntries. - llvm::Optional<SourceLocation::UIntTy> NextStart; + std::optional<SourceLocation::UIntTy> NextStart; for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) { int ID = -(int)Index - 2; if (SLocEntryLoaded[Index]) { @@ -2236,7 +2236,7 @@ LLVM_DUMP_METHOD void SourceManager::dump() const { } void SourceManager::noteSLocAddressSpaceUsage( - DiagnosticsEngine &Diag, Optional<unsigned> MaxNotes) const { + DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const { struct Info { // A location where this file was entered. SourceLocation Loc; diff --git a/clang/lib/Basic/Targets/AArch64.cpp b/clang/lib/Basic/Targets/AArch64.cpp index 4097796..3a6e8f15 100644 --- a/clang/lib/Basic/Targets/AArch64.cpp +++ b/clang/lib/Basic/Targets/AArch64.cpp @@ -581,7 +581,7 @@ ArrayRef<Builtin::Info> AArch64TargetInfo::getTargetBuiltins() const { Builtin::FirstTSBuiltin); } -Optional<std::pair<unsigned, unsigned>> +std::optional<std::pair<unsigned, unsigned>> AArch64TargetInfo::getVScaleRange(const LangOptions &LangOpts) const { if (LangOpts.VScaleMin || LangOpts.VScaleMax) return std::pair<unsigned, unsigned>( diff --git a/clang/lib/Basic/Targets/AArch64.h b/clang/lib/Basic/Targets/AArch64.h index 33d5d11..34df886 100644 --- a/clang/lib/Basic/Targets/AArch64.h +++ b/clang/lib/Basic/Targets/AArch64.h @@ -141,7 +141,7 @@ public: ArrayRef<Builtin::Info> getTargetBuiltins() const override; - Optional<std::pair<unsigned, unsigned>> + std::optional<std::pair<unsigned, unsigned>> getVScaleRange(const LangOptions &LangOpts) const override; bool getFeatureDepOptions(StringRef Feature, diff --git a/clang/lib/Basic/Targets/AMDGPU.h b/clang/lib/Basic/Targets/AMDGPU.h index 5b1e2688..576bcf9 100644 --- a/clang/lib/Basic/Targets/AMDGPU.h +++ b/clang/lib/Basic/Targets/AMDGPU.h @@ -370,7 +370,7 @@ public: } } - llvm::Optional<LangAS> getConstantAddressSpace() const override { + std::optional<LangAS> getConstantAddressSpace() const override { return getLangASFromTargetAS(Constant); } @@ -453,7 +453,7 @@ public: return true; } - Optional<std::string> getTargetID() const override { + std::optional<std::string> getTargetID() const override { if (!isAMDGCN(getTriple())) return std::nullopt; // When -target-cpu is not set, we assume generic code that it is valid diff --git a/clang/lib/Basic/Targets/M68k.cpp b/clang/lib/Basic/Targets/M68k.cpp index be3ab89..6c2d774 100644 --- a/clang/lib/Basic/Targets/M68k.cpp +++ b/clang/lib/Basic/Targets/M68k.cpp @@ -198,7 +198,7 @@ bool M68kTargetInfo::validateAsmConstraint( return false; } -llvm::Optional<std::string> +std::optional<std::string> M68kTargetInfo::handleAsmEscapedChar(char EscChar) const { char C; switch (EscChar) { diff --git a/clang/lib/Basic/Targets/M68k.h b/clang/lib/Basic/Targets/M68k.h index b68baeb..16b3224 100644 --- a/clang/lib/Basic/Targets/M68k.h +++ b/clang/lib/Basic/Targets/M68k.h @@ -48,7 +48,7 @@ public: std::string convertConstraint(const char *&Constraint) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override; - llvm::Optional<std::string> handleAsmEscapedChar(char EscChar) const override; + std::optional<std::string> handleAsmEscapedChar(char EscChar) const override; const char *getClobbers() const override; BuiltinVaListKind getBuiltinVaListKind() const override; bool setCPU(const std::string &Name) override; diff --git a/clang/lib/Basic/Targets/RISCV.cpp b/clang/lib/Basic/Targets/RISCV.cpp index a9adafd..a1d1ddc 100644 --- a/clang/lib/Basic/Targets/RISCV.cpp +++ b/clang/lib/Basic/Targets/RISCV.cpp @@ -254,7 +254,7 @@ bool RISCVTargetInfo::initFeatureMap( return TargetInfo::initFeatureMap(Features, Diags, CPU, ImpliedFeatures); } -Optional<std::pair<unsigned, unsigned>> +std::optional<std::pair<unsigned, unsigned>> RISCVTargetInfo::getVScaleRange(const LangOptions &LangOpts) const { if (LangOpts.VScaleMin || LangOpts.VScaleMax) return std::pair<unsigned, unsigned>( diff --git a/clang/lib/Basic/Targets/RISCV.h b/clang/lib/Basic/Targets/RISCV.h index 30988ae..adff1da 100644 --- a/clang/lib/Basic/Targets/RISCV.h +++ b/clang/lib/Basic/Targets/RISCV.h @@ -90,7 +90,7 @@ public: StringRef CPU, const std::vector<std::string> &FeaturesVec) const override; - Optional<std::pair<unsigned, unsigned>> + std::optional<std::pair<unsigned, unsigned>> getVScaleRange(const LangOptions &LangOpts) const override; bool hasFeature(StringRef Feature) const override; diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp index affe203..6b33f46 100644 --- a/clang/lib/Basic/Targets/X86.cpp +++ b/clang/lib/Basic/Targets/X86.cpp @@ -1358,7 +1358,7 @@ bool X86TargetInfo::validateAsmConstraint( // | Knights Landing | 64 | https://software.intel.com/en-us/articles/intel-xeon-phi-processor-7200-family-memory-management-optimizations "The Intel® Xeon Phi™ Processor Architecture" | // | Knights Mill | 64 | https://software.intel.com/sites/default/files/managed/9e/bc/64-ia-32-architectures-optimization-manual.pdf?countrylabel=Colombia "2.5.5.2 L1 DCache " | // +------------------------------------+-------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+ -Optional<unsigned> X86TargetInfo::getCPUCacheLineSize() const { +std::optional<unsigned> X86TargetInfo::getCPUCacheLineSize() const { using namespace llvm::X86; switch (CPU) { // i386 diff --git a/clang/lib/Basic/Targets/X86.h b/clang/lib/Basic/Targets/X86.h index ef38c77..5fcc97e 100644 --- a/clang/lib/Basic/Targets/X86.h +++ b/clang/lib/Basic/Targets/X86.h @@ -216,7 +216,7 @@ public: StringRef getCPUSpecificTuneName(StringRef Name) const override; - Optional<unsigned> getCPUCacheLineSize() const override; + std::optional<unsigned> getCPUCacheLineSize() const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override; diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 16b48c6..937a8dc 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -510,8 +510,8 @@ static bool initTargetOptions(DiagnosticsEngine &Diags, return true; } -static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts, - const LangOptions &LangOpts) { +static std::optional<GCOVOptions> +getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) { if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) return std::nullopt; // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if @@ -527,7 +527,7 @@ static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts, return Options; } -static Optional<InstrProfOptions> +static std::optional<InstrProfOptions> getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) { if (!CodeGenOpts.hasProfileClangInstr()) @@ -980,12 +980,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline( addKCFIPass(TargetTriple, LangOpts, PB); } - if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) + if (std::optional<GCOVOptions> Options = + getGCOVOptions(CodeGenOpts, LangOpts)) PB.registerPipelineStartEPCallback( [Options](ModulePassManager &MPM, OptimizationLevel Level) { MPM.addPass(GCOVProfilerPass(*Options)); }); - if (Optional<InstrProfOptions> Options = + if (std::optional<InstrProfOptions> Options = getInstrProfOptions(CodeGenOpts, LangOpts)) PB.registerPipelineStartEPCallback( [Options](ModulePassManager &MPM, OptimizationLevel Level) { diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 3bbcb1e..aa330fd 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -1179,7 +1179,7 @@ enum class CodeGenFunction::MSVCIntrin { __fastfail, }; -static Optional<CodeGenFunction::MSVCIntrin> +static std::optional<CodeGenFunction::MSVCIntrin> translateArmToMsvcIntrin(unsigned BuiltinID) { using MSVCIntrin = CodeGenFunction::MSVCIntrin; switch (BuiltinID) { @@ -1325,7 +1325,7 @@ translateArmToMsvcIntrin(unsigned BuiltinID) { llvm_unreachable("must return from switch"); } -static Optional<CodeGenFunction::MSVCIntrin> +static std::optional<CodeGenFunction::MSVCIntrin> translateAarch64ToMsvcIntrin(unsigned BuiltinID) { using MSVCIntrin = CodeGenFunction::MSVCIntrin; switch (BuiltinID) { @@ -1479,7 +1479,7 @@ translateAarch64ToMsvcIntrin(unsigned BuiltinID) { llvm_unreachable("must return from switch"); } -static Optional<CodeGenFunction::MSVCIntrin> +static std::optional<CodeGenFunction::MSVCIntrin> translateX86ToMsvcIntrin(unsigned BuiltinID) { using MSVCIntrin = CodeGenFunction::MSVCIntrin; switch (BuiltinID) { @@ -6801,7 +6801,7 @@ Value *CodeGenFunction::EmitCommonNeonBuiltinExpr( llvm::Triple::ArchType Arch) { // Get the last argument, which specifies the vector type. const Expr *Arg = E->getArg(E->getNumArgs() - 1); - Optional<llvm::APSInt> NeonTypeConst = + std::optional<llvm::APSInt> NeonTypeConst = Arg->getIntegerConstantExpr(getContext()); if (!NeonTypeConst) return nullptr; @@ -8063,7 +8063,7 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID, // Handle MSVC intrinsics before argument evaluation to prevent double // evaluation. - if (Optional<MSVCIntrin> MsvcIntId = translateArmToMsvcIntrin(BuiltinID)) + if (std::optional<MSVCIntrin> MsvcIntId = translateArmToMsvcIntrin(BuiltinID)) return EmitMSVCBuiltinExpr(*MsvcIntId, E); // Deal with MVE builtins @@ -8239,7 +8239,8 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID, // Get the last argument, which specifies the vector type. assert(HasExtraArg); const Expr *Arg = E->getArg(E->getNumArgs()-1); - Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(getContext()); + std::optional<llvm::APSInt> Result = + Arg->getIntegerConstantExpr(getContext()); if (!Result) return nullptr; @@ -8677,7 +8678,8 @@ static Value *EmitAArch64TblBuiltinExpr(CodeGenFunction &CGF, unsigned BuiltinID // Get the last argument, which specifies the vector type. const Expr *Arg = E->getArg(E->getNumArgs() - 1); - Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(CGF.getContext()); + std::optional<llvm::APSInt> Result = + Arg->getIntegerConstantExpr(CGF.getContext()); if (!Result) return nullptr; @@ -9399,7 +9401,7 @@ Value *CodeGenFunction::EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, else { // If this is required to be a constant, constant fold it so that we know // that the generated intrinsic gets a ConstantInt. - Optional<llvm::APSInt> Result = + std::optional<llvm::APSInt> Result = E->getArg(i)->getIntegerConstantExpr(getContext()); assert(Result && "Expected argument to be a constant"); @@ -10316,7 +10318,8 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID, // Handle MSVC intrinsics before argument evaluation to prevent double // evaluation. - if (Optional<MSVCIntrin> MsvcIntId = translateAarch64ToMsvcIntrin(BuiltinID)) + if (std::optional<MSVCIntrin> MsvcIntId = + translateAarch64ToMsvcIntrin(BuiltinID)) return EmitMSVCBuiltinExpr(*MsvcIntId, E); // Some intrinsics are equivalent - if they are use the base intrinsic ID. @@ -10379,7 +10382,8 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID, const Expr *Arg = E->getArg(E->getNumArgs()-1); NeonTypeFlags Type(0); - if (Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(getContext())) + if (std::optional<llvm::APSInt> Result = + Arg->getIntegerConstantExpr(getContext())) // Determine the type of this overloaded NEON intrinsic. Type = NeonTypeFlags(Result->getZExtValue()); @@ -13093,7 +13097,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, // Handle MSVC intrinsics before argument evaluation to prevent double // evaluation. - if (Optional<MSVCIntrin> MsvcIntId = translateX86ToMsvcIntrin(BuiltinID)) + if (std::optional<MSVCIntrin> MsvcIntId = translateX86ToMsvcIntrin(BuiltinID)) return EmitMSVCBuiltinExpr(*MsvcIntId, E); SmallVector<Value*, 4> Ops; @@ -18373,7 +18377,7 @@ CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { Address Dst = EmitPointerWithAlignment(E->getArg(0)); Value *Src = EmitScalarExpr(E->getArg(1)); Value *Ldm = EmitScalarExpr(E->getArg(2)); - Optional<llvm::APSInt> isColMajorArg = + std::optional<llvm::APSInt> isColMajorArg = E->getArg(3)->getIntegerConstantExpr(getContext()); if (!isColMajorArg) return nullptr; @@ -18420,7 +18424,7 @@ CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { Value *Dst = EmitScalarExpr(E->getArg(0)); Address Src = EmitPointerWithAlignment(E->getArg(1)); Value *Ldm = EmitScalarExpr(E->getArg(2)); - Optional<llvm::APSInt> isColMajorArg = + std::optional<llvm::APSInt> isColMajorArg = E->getArg(3)->getIntegerConstantExpr(getContext()); if (!isColMajorArg) return nullptr; @@ -18479,7 +18483,7 @@ CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { Address SrcA = EmitPointerWithAlignment(E->getArg(1)); Address SrcB = EmitPointerWithAlignment(E->getArg(2)); Address SrcC = EmitPointerWithAlignment(E->getArg(3)); - Optional<llvm::APSInt> LayoutArg = + std::optional<llvm::APSInt> LayoutArg = E->getArg(4)->getIntegerConstantExpr(getContext()); if (!LayoutArg) return nullptr; @@ -18490,7 +18494,7 @@ CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { if (BuiltinID == NVPTX::BI__bmma_m8n8k128_mma_xor_popc_b1 || BuiltinID == NVPTX::BI__bmma_m8n8k128_mma_and_popc_b1) SatfArg = 0; // .b1 does not have satf argument. - else if (Optional<llvm::APSInt> OptSatfArg = + else if (std::optional<llvm::APSInt> OptSatfArg = E->getArg(5)->getIntegerConstantExpr(getContext())) SatfArg = *OptSatfArg; else @@ -19053,7 +19057,7 @@ Value *CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, Ops[OpIdx++] = EmitScalarExpr(E->getArg(0)); Ops[OpIdx++] = EmitScalarExpr(E->getArg(1)); while (OpIdx < 18) { - Optional<llvm::APSInt> LaneConst = + std::optional<llvm::APSInt> LaneConst = E->getArg(OpIdx)->getIntegerConstantExpr(getContext()); assert(LaneConst && "Constant arg isn't actually constant?"); Ops[OpIdx++] = llvm::ConstantInt::get(getLLVMContext(), *LaneConst); diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp index ec09c74..0795ea598 100644 --- a/clang/lib/CodeGen/CGClass.cpp +++ b/clang/lib/CodeGen/CGClass.cpp @@ -1653,7 +1653,7 @@ namespace { class DeclAsInlineDebugLocation { CGDebugInfo *DI; llvm::MDNode *InlinedAt; - llvm::Optional<ApplyDebugLocation> Location; + std::optional<ApplyDebugLocation> Location; public: DeclAsInlineDebugLocation(CodeGenFunction &CGF, const NamedDecl &Decl) @@ -1675,7 +1675,7 @@ namespace { static void EmitSanitizerDtorCallback( CodeGenFunction &CGF, StringRef Name, llvm::Value *Ptr, - llvm::Optional<CharUnits::QuantityType> PoisonSize = {}) { + std::optional<CharUnits::QuantityType> PoisonSize = {}) { CodeGenFunction::SanitizerScope SanScope(&CGF); // Pass in void pointer and size of region as arguments to runtime // function @@ -1809,7 +1809,7 @@ namespace { ASTContext &Context; EHScopeStack &EHStack; const CXXDestructorDecl *DD; - llvm::Optional<unsigned> StartIndex; + std::optional<unsigned> StartIndex; public: SanitizeDtorCleanupBuilder(ASTContext &Context, EHScopeStack &EHStack, diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 6096c92..f53a9d0 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -355,7 +355,7 @@ CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const { return std::nullopt; SourceManager &SM = CGM.getContext().getSourceManager(); - Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID); + std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID); if (!MemBuffer) return std::nullopt; @@ -1989,7 +1989,7 @@ void CGDebugInfo::CollectCXXBasesAux( } llvm::DINodeArray -CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs, +CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs, llvm::DIFile *Unit) { if (!OArgs) return llvm::DINodeArray(); @@ -2120,7 +2120,7 @@ CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs, return DBuilder.getOrCreateArray(TemplateParams); } -Optional<CGDebugInfo::TemplateArgs> +std::optional<CGDebugInfo::TemplateArgs> CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const { if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization) { @@ -2131,7 +2131,7 @@ CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const { } return std::nullopt; } -Optional<CGDebugInfo::TemplateArgs> +std::optional<CGDebugInfo::TemplateArgs> CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const { // Always get the full list of parameters, not just the ones from the // specialization. A partial specialization may have fewer parameters than @@ -2144,7 +2144,7 @@ CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const { auto TA = TS->getTemplateArgs().asArray(); return {{TList, TA}}; } -Optional<CGDebugInfo::TemplateArgs> +std::optional<CGDebugInfo::TemplateArgs> CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const { if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { // Always get the full list of parameters, not just the ones from the @@ -4435,7 +4435,7 @@ CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage, - llvm::Optional<unsigned> ArgNo, + std::optional<unsigned> ArgNo, CGBuilderTy &Builder, const bool UsePointerValue) { assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); @@ -4615,7 +4615,7 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD, llvm::Value *Storage, - llvm::Optional<unsigned> ArgNo, + std::optional<unsigned> ArgNo, CGBuilderTy &Builder, const bool UsePointerValue) { assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); @@ -5161,7 +5161,7 @@ std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const { if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) TemplateNamesKind = codegenoptions::DebugTemplateNamesKind::Full; - Optional<TemplateArgs> Args; + std::optional<TemplateArgs> Args; bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND); if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) { diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h index 9d54832f..ff9fb75 100644 --- a/clang/lib/CodeGen/CGDebugInfo.h +++ b/clang/lib/CodeGen/CGDebugInfo.h @@ -280,7 +280,7 @@ class CGDebugInfo { llvm::ArrayRef<TemplateArgument> Args; }; /// A helper function to collect template parameters. - llvm::DINodeArray CollectTemplateParams(Optional<TemplateArgs> Args, + llvm::DINodeArray CollectTemplateParams(std::optional<TemplateArgs> Args, llvm::DIFile *Unit); /// A helper function to collect debug info for function template /// parameters. @@ -292,9 +292,9 @@ class CGDebugInfo { llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD, llvm::DIFile *Unit); - Optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const; - Optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const; - Optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const; + std::optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const; + std::optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const; + std::optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const; /// A helper function to collect debug info for template /// parameters. @@ -587,7 +587,7 @@ private: /// Returns a pointer to the DILocalVariable associated with the /// llvm.dbg.declare, or nullptr otherwise. llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI, - llvm::Optional<unsigned> ArgNo, + std::optional<unsigned> ArgNo, CGBuilderTy &Builder, const bool UsePointerValue = false); @@ -595,7 +595,7 @@ private: /// Returns a pointer to the DILocalVariable associated with the /// llvm.dbg.declare, or nullptr otherwise. llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI, - llvm::Optional<unsigned> ArgNo, + std::optional<unsigned> ArgNo, CGBuilderTy &Builder, const bool UsePointerValue = false); diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp index 764afed..ceaddc4 100644 --- a/clang/lib/CodeGen/CGDecl.cpp +++ b/clang/lib/CodeGen/CGDecl.cpp @@ -2699,7 +2699,7 @@ void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) { } } -llvm::Optional<CharUnits> +std::optional<CharUnits> CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) { if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) { if (Expr *Alignment = AA->getAlignment()) { diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 213f6b7..c26dd1b 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -2494,7 +2494,7 @@ static LValue EmitThreadPrivateVarDeclLValue( static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T) { - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); // Return an invalid address if variable is MT_To (or MT_Enter starting with // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link @@ -3216,7 +3216,7 @@ static void emitCheckHandlerCall(CodeGenFunction &CGF, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB) { assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); - Optional<ApplyDebugLocation> DL; + std::optional<ApplyDebugLocation> DL; if (!CGF.Builder.getCurrentDebugLocation()) { // Ensure that the call has at least an artificial debug location. DL.emplace(CGF, SourceLocation()); @@ -4013,14 +4013,15 @@ LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, llvm::APSInt ConstLength; if (Length) { // Idx = LowerBound + Length - 1; - if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) { + if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) { ConstLength = CL->zextOrTrunc(PointerWidthInBits); Length = nullptr; } auto *LowerBound = E->getLowerBound(); llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); if (LowerBound) { - if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) { + if (std::optional<llvm::APSInt> LB = + LowerBound->getIntegerConstantExpr(C)) { ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits); LowerBound = nullptr; } @@ -4060,7 +4061,7 @@ LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, : BaseTy; if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { Length = VAT->getSizeExpr(); - if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) { + if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) { ConstLength = *L; Length = nullptr; } @@ -4571,8 +4572,8 @@ LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { /// Emit the operand of a glvalue conditional operator. This is either a glvalue /// or a (possibly-parenthesized) throw-expression. If this is a throw, no /// LValue is returned and the current block has been terminated. -static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, - const Expr *Operand) { +static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, + const Expr *Operand) { if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); return std::nullopt; @@ -4584,7 +4585,7 @@ static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, namespace { // Handle the case where the condition is a constant evaluatable simple integer, // which means we don't have to separately handle the true/false blocks. -llvm::Optional<LValue> HandleConditionalOperatorLValueSimpleCase( +std::optional<LValue> HandleConditionalOperatorLValueSimpleCase( CodeGenFunction &CGF, const AbstractConditionalOperator *E) { const Expr *condExpr = E->getCond(); bool CondExprBool; @@ -4614,7 +4615,7 @@ llvm::Optional<LValue> HandleConditionalOperatorLValueSimpleCase( } struct ConditionalInfo { llvm::BasicBlock *lhsBlock, *rhsBlock; - Optional<LValue> LHS, RHS; + std::optional<LValue> LHS, RHS; }; // Create and generate the 3 blocks for a conditional operator. @@ -4683,7 +4684,7 @@ LValue CodeGenFunction::EmitConditionalOperatorLValue( } OpaqueValueMapping binding(*this, expr); - if (llvm::Optional<LValue> Res = + if (std::optional<LValue> Res = HandleConditionalOperatorLValueSimpleCase(*this, expr)) return *Res; diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index 28c4a82..c38feaa 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -95,7 +95,7 @@ class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils { bool NaturalLayout = true; bool split(size_t Index, CharUnits Hint); - Optional<size_t> splitAt(CharUnits Pos); + std::optional<size_t> splitAt(CharUnits Pos); static llvm::Constant *buildFrom(CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems, @@ -159,12 +159,12 @@ bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset, } // Uncommon case: constant overlaps what we've already created. - llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset); + std::optional<size_t> FirstElemToReplace = splitAt(Offset); if (!FirstElemToReplace) return false; CharUnits CSize = getSize(C); - llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize); + std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize); if (!LastElemToReplace) return false; @@ -223,10 +223,10 @@ bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits, // Partial byte: update the existing integer if there is one. If we // can't split out a 1-CharUnit range to update, then we can't add // these bits and fail the entire constant emission. - llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars); + std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars); if (!FirstElemToUpdate) return false; - llvm::Optional<size_t> LastElemToUpdate = + std::optional<size_t> LastElemToUpdate = splitAt(OffsetInChars + CharUnits::One()); if (!LastElemToUpdate) return false; @@ -285,7 +285,7 @@ bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits, /// before the returned index end before Pos and all elements at or after /// the returned index begin at or after Pos. Splits elements as necessary /// to ensure this. Returns std::nullopt if we find something we can't split. -Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) { +std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) { if (Pos >= Size) return Offsets.size(); @@ -518,12 +518,12 @@ void ConstantAggregateBuilder::condense(CharUnits Offset, llvm::Type *DesiredTy) { CharUnits Size = getSize(DesiredTy); - llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset); + std::optional<size_t> FirstElemToReplace = splitAt(Offset); if (!FirstElemToReplace) return; size_t First = *FirstElemToReplace; - llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size); + std::optional<size_t> LastElemToReplace = splitAt(Offset + Size); if (!LastElemToReplace) return; size_t Last = *LastElemToReplace; diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 992edc0..24b6048 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -153,8 +153,8 @@ static bool MustVisitNullValue(const Expr *E) { } /// If \p E is a widened promoted integer, get its base (unpromoted) type. -static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, - const Expr *E) { +static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, + const Expr *E) { const Expr *Base = E->IgnoreImpCasts(); if (E == Base) return std::nullopt; diff --git a/clang/lib/CodeGen/CGHLSLRuntime.h b/clang/lib/CodeGen/CGHLSLRuntime.h index 29a849c..74b08d0 100644 --- a/clang/lib/CodeGen/CGHLSLRuntime.h +++ b/clang/lib/CodeGen/CGHLSLRuntime.h @@ -51,7 +51,7 @@ class CGHLSLRuntime { public: struct BufferResBinding { // The ID like 2 in register(b2, space1). - llvm::Optional<unsigned> Reg; + std::optional<unsigned> Reg; // The Space like 1 is register(b2, space1). // Default value is 0. unsigned Space; diff --git a/clang/lib/CodeGen/CGLoopInfo.cpp b/clang/lib/CodeGen/CGLoopInfo.cpp index d6036fd..e5d9db2 100644 --- a/clang/lib/CodeGen/CGLoopInfo.cpp +++ b/clang/lib/CodeGen/CGLoopInfo.cpp @@ -38,7 +38,7 @@ MDNode *LoopInfo::createPipeliningMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.PipelineDisabled) Enabled = false; else if (Attrs.PipelineInitiationInterval != 0) @@ -83,7 +83,7 @@ LoopInfo::createPartialUnrollMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.UnrollEnable == LoopAttributes::Disable) Enabled = false; else if (Attrs.UnrollEnable == LoopAttributes::Full) @@ -145,7 +145,7 @@ LoopInfo::createUnrollAndJamMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.UnrollAndJamEnable == LoopAttributes::Disable) Enabled = false; else if (Attrs.UnrollAndJamEnable == LoopAttributes::Enable || @@ -213,7 +213,7 @@ LoopInfo::createLoopVectorizeMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.VectorizeEnable == LoopAttributes::Disable) Enabled = false; else if (Attrs.VectorizeEnable != LoopAttributes::Unspecified || @@ -331,7 +331,7 @@ LoopInfo::createLoopDistributeMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.DistributeEnable == LoopAttributes::Disable) Enabled = false; if (Attrs.DistributeEnable == LoopAttributes::Enable) @@ -381,7 +381,7 @@ MDNode *LoopInfo::createFullUnrollMetadata(const LoopAttributes &Attrs, bool &HasUserTransforms) { LLVMContext &Ctx = Header->getContext(); - Optional<bool> Enabled; + std::optional<bool> Enabled; if (Attrs.UnrollEnable == LoopAttributes::Disable) Enabled = false; else if (Attrs.UnrollEnable == LoopAttributes::Full) diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp index 200396b..7df2088 100644 --- a/clang/lib/CodeGen/CGObjC.cpp +++ b/clang/lib/CodeGen/CGObjC.cpp @@ -374,12 +374,10 @@ static const Expr *findWeakLValue(const Expr *E) { /// If the runtime does support a required entrypoint, then this method will /// generate a call and return the resulting value. Otherwise it will return /// std::nullopt and the caller can generate a msgSend instead. -static Optional<llvm::Value *> -tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType, - llvm::Value *Receiver, - const CallArgList& Args, Selector Sel, - const ObjCMethodDecl *method, - bool isClassMessage) { +static std::optional<llvm::Value *> tryGenerateSpecializedMessageSend( + CodeGenFunction &CGF, QualType ResultType, llvm::Value *Receiver, + const CallArgList &Args, Selector Sel, const ObjCMethodDecl *method, + bool isClassMessage) { auto &CGM = CGF.CGM; if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls) return std::nullopt; @@ -442,7 +440,7 @@ CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend( Selector Sel, llvm::Value *Receiver, const CallArgList &Args, const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method, bool isClassMessage) { - if (Optional<llvm::Value *> SpecializedResult = + if (std::optional<llvm::Value *> SpecializedResult = tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args, Sel, Method, isClassMessage)) { return RValue::get(*SpecializedResult); @@ -523,7 +521,7 @@ CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin, /// Instead of '[[MyClass alloc] init]', try to generate /// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the /// caller side, as well as the optimized objc_alloc. -static Optional<llvm::Value *> +static std::optional<llvm::Value *> tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) { auto &Runtime = CGF.getLangOpts().ObjCRuntime; if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit()) @@ -593,7 +591,7 @@ RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, } } - if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E)) + if (std::optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E)) return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val)); // We don't retain the receiver in delegate init calls, and this is diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index d766263..a291466 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -1621,7 +1621,7 @@ getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc, Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) { if (CGM.getLangOpts().OpenMPSimd) return Address::invalid(); - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link || ((*Res == OMPDeclareTargetDeclAttr::MT_To || @@ -1835,7 +1835,7 @@ bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD, if (CGM.getLangOpts().OMPTargetTriples.empty() && !CGM.getLangOpts().OpenMPIsDevice) return false; - Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link || ((*Res == OMPDeclareTargetDeclAttr::MT_To || @@ -7364,7 +7364,7 @@ private: BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress(CGF); if (const auto *VD = dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) { - if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { if ((*Res == OMPDeclareTargetDeclAttr::MT_Link) || ((*Res == OMPDeclareTargetDeclAttr::MT_To || @@ -10245,7 +10245,7 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S, } static bool isAssumedToBeNotEmitted(const ValueDecl *VD, bool IsDevice) { - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD); if (!DevTy) return false; @@ -10310,7 +10310,7 @@ bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) { } // Do not to emit variable if it is not marked as declare target. - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( cast<VarDecl>(GD.getDecl())); if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link || @@ -10330,12 +10330,12 @@ void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD, return; // If we have host/nohost variables, they do not need to be registered. - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD); if (DevTy && *DevTy != OMPDeclareTargetDeclAttr::DT_Any) return; - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (!Res) { if (CGM.getLangOpts().OpenMPIsDevice) { @@ -10418,7 +10418,7 @@ bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) { void CGOpenMPRuntime::emitDeferredTargetDecls() const { for (const VarDecl *VD : DeferredGlobalVariables) { - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (!Res) continue; @@ -11731,7 +11731,7 @@ static llvm::Value *getAllocatorVal(CodeGenFunction &CGF, /// Return the alignment from an allocate directive if present. static llvm::Value *getAlignmentValue(CodeGenModule &CGM, const VarDecl *VD) { - llvm::Optional<CharUnits> AllocateAlignment = CGM.getOMPAllocateAlignment(VD); + std::optional<CharUnits> AllocateAlignment = CGM.getOMPAllocateAlignment(VD); if (!AllocateAlignment) return nullptr; diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp index ce7ab9e..248ffb5 100644 --- a/clang/lib/CodeGen/CGStmt.cpp +++ b/clang/lib/CodeGen/CGStmt.cpp @@ -1869,7 +1869,7 @@ static bool FindCaseStatementsForValue(const SwitchStmt &S, FoundCase; } -static Optional<SmallVector<uint64_t, 16>> +static std::optional<SmallVector<uint64_t, 16>> getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) { // Are there enough branches to weight them? if (Likelihoods.size() <= 1) @@ -2076,7 +2076,7 @@ void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { } else if (SwitchLikelihood) { assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() && "switch likelihoods do not match switch cases"); - Optional<SmallVector<uint64_t, 16>> LHW = + std::optional<SmallVector<uint64_t, 16>> LHW = getLikelihoodWeights(*SwitchLikelihood); if (LHW) { llvm::MDBuilder MDHelper(CGM.getLLVMContext()); diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index 27f44f1..87bab57 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -75,7 +75,7 @@ class OMPLexicalScope : public CodeGenFunction::LexicalScope { public: OMPLexicalScope( CodeGenFunction &CGF, const OMPExecutableDirective &S, - const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = std::nullopt, + const std::optional<OpenMPDirectiveKind> CapturedRegion = std::nullopt, const bool EmitPreInitStmt = true) : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), InlinedShareds(CGF) { diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp index 083d6b6..2b21926 100644 --- a/clang/lib/CodeGen/CodeGenAction.cpp +++ b/clang/lib/CodeGen/CodeGenAction.cpp @@ -423,7 +423,8 @@ namespace clang { bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const; - Optional<FullSourceLoc> getFunctionSourceLocation(const Function &F) const; + std::optional<FullSourceLoc> + getFunctionSourceLocation(const Function &F) const; void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); /// Specialized handler for InlineAsm diagnostic. @@ -692,7 +693,7 @@ const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc( return Loc; } -Optional<FullSourceLoc> +std::optional<FullSourceLoc> BackendConsumer::getFunctionSourceLocation(const Function &F) const { auto Hash = llvm::hash_value(F.getName()); for (const auto &Pair : ManglingFullSourceLocs) { @@ -1183,7 +1184,7 @@ void CodeGenAction::ExecuteAction() { SourceManager &SM = CI.getSourceManager(); FileID FID = SM.getMainFileID(); - Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); + std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); if (!MainFile) return; diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp index 6dafd4a..55464e1 100644 --- a/clang/lib/CodeGen/CodeGenFunction.cpp +++ b/clang/lib/CodeGen/CodeGenFunction.cpp @@ -364,7 +364,7 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { if (HasCleanups) { // Make sure the line table doesn't jump back into the body for // the ret after it's been at EndLoc. - Optional<ApplyDebugLocation> AL; + std::optional<ApplyDebugLocation> AL; if (CGDebugInfo *DI = getDebugInfo()) { if (OnlySimpleReturnStmts) DI->EmitLocation(Builder, EndLoc); @@ -505,7 +505,7 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { llvm::utostr(LargestVectorWidth)); // Add vscale_range attribute if appropriate. - Optional<std::pair<unsigned, unsigned>> VScaleRange = + std::optional<std::pair<unsigned, unsigned>> VScaleRange = getContext().getTargetInfo().getVScaleRange(getLangOpts()); if (VScaleRange) { CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs( diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h index 10b9271..a535aa7 100644 --- a/clang/lib/CodeGen/CodeGenFunction.h +++ b/clang/lib/CodeGen/CodeGenFunction.h @@ -724,7 +724,7 @@ public: FPOptions OldFPFeatures; llvm::fp::ExceptionBehavior OldExcept; llvm::RoundingMode OldRounding; - Optional<CGBuilderTy::FastMathFlagGuard> FMFGuard; + std::optional<CGBuilderTy::FastMathFlagGuard> FMFGuard; }; FPOptions CurFPFeatures; diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 446874f..12d602f 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -3085,7 +3085,7 @@ bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { // we have if the level of the declare target attribute is -1. Note that we // check somewhere else if we should emit this at all. if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(Global); if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) return false; @@ -3349,7 +3349,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) { !Context.isMSStaticDataMemberInlineDefinition(VD)) { if (LangOpts.OpenMP) { // Emit declaration of the must-be-emitted declare target variable. - if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { bool UnifiedMemoryEnabled = getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); @@ -4843,7 +4843,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, const VarDecl *InitDecl; const Expr *InitExpr = D->getAnyInitializer(InitDecl); - Optional<ConstantEmitter> emitter; + std::optional<ConstantEmitter> emitter; // CUDA E.2.4.1 "__shared__ variables cannot have an initialization // as part of their declaration." Sema has already checked for @@ -5003,7 +5003,7 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, CharUnits AlignVal = getContext().getDeclAlign(D); // Check for alignment specifed in an 'omp allocate' directive. - if (llvm::Optional<CharUnits> AlignValFromAllocate = + if (std::optional<CharUnits> AlignValFromAllocate = getOMPAllocateAlignment(D)) AlignVal = *AlignValFromAllocate; GV->setAlignment(AlignVal.getAsAlign()); @@ -6057,7 +6057,7 @@ ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( LangAS AddrSpace = VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); - Optional<ConstantEmitter> emitter; + std::optional<ConstantEmitter> emitter; llvm::Constant *InitialValue = nullptr; bool Constant = false; llvm::Type *Type; diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h index 689d554..b335465 100644 --- a/clang/lib/CodeGen/CodeGenModule.h +++ b/clang/lib/CodeGen/CodeGenModule.h @@ -1422,7 +1422,7 @@ public: void EmitOMPAllocateDecl(const OMPAllocateDecl *D); /// Return the alignment specified in an allocate directive, if present. - llvm::Optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD); + std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD); /// Returns whether the given record has hidden LTO visibility and therefore /// may participate in (single-module) CFI and whole-program vtable diff --git a/clang/lib/CodeGen/CodeGenPGO.cpp b/clang/lib/CodeGen/CodeGenPGO.cpp index c581af2..15a3d74 100644 --- a/clang/lib/CodeGen/CodeGenPGO.cpp +++ b/clang/lib/CodeGen/CodeGenPGO.cpp @@ -1117,7 +1117,7 @@ CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond, uint64_t LoopCount) const { if (!PGO.haveRegionCounts()) return nullptr; - Optional<uint64_t> CondCount = PGO.getStmtCount(Cond); + std::optional<uint64_t> CondCount = PGO.getStmtCount(Cond); if (!CondCount || *CondCount == 0) return nullptr; return createProfileWeights(LoopCount, diff --git a/clang/lib/CodeGen/CodeGenPGO.h b/clang/lib/CodeGen/CodeGenPGO.h index 048251f..66c93cb 100644 --- a/clang/lib/CodeGen/CodeGenPGO.h +++ b/clang/lib/CodeGen/CodeGenPGO.h @@ -60,7 +60,7 @@ public: /// Check if an execution count is known for a given statement. If so, return /// true and put the value in Count; else return false. - Optional<uint64_t> getStmtCount(const Stmt *S) const { + std::optional<uint64_t> getStmtCount(const Stmt *S) const { if (!StmtCountMap) return std::nullopt; auto I = StmtCountMap->find(S); diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp b/clang/lib/CodeGen/CoverageMappingGen.cpp index 3fd7f10..bd39dbd 100644 --- a/clang/lib/CodeGen/CoverageMappingGen.cpp +++ b/clang/lib/CodeGen/CoverageMappingGen.cpp @@ -98,27 +98,29 @@ class SourceMappingRegion { Counter Count; /// Secondary Counter used for Branch Regions for "False" branches. - Optional<Counter> FalseCount; + std::optional<Counter> FalseCount; /// The region's starting location. - Optional<SourceLocation> LocStart; + std::optional<SourceLocation> LocStart; /// The region's ending location. - Optional<SourceLocation> LocEnd; + std::optional<SourceLocation> LocEnd; /// Whether this region is a gap region. The count from a gap region is set /// as the line execution count if there are no other regions on the line. bool GapRegion; public: - SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, - Optional<SourceLocation> LocEnd, bool GapRegion = false) + SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart, + std::optional<SourceLocation> LocEnd, + bool GapRegion = false) : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) { } - SourceMappingRegion(Counter Count, Optional<Counter> FalseCount, - Optional<SourceLocation> LocStart, - Optional<SourceLocation> LocEnd, bool GapRegion = false) + SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount, + std::optional<SourceLocation> LocStart, + std::optional<SourceLocation> LocEnd, + bool GapRegion = false) : Count(Count), FalseCount(FalseCount), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {} @@ -327,7 +329,7 @@ public: /// Get the coverage mapping file ID for \c Loc. /// /// If such file id doesn't exist, return std::nullopt. - Optional<unsigned> getCoverageFileID(SourceLocation Loc) { + std::optional<unsigned> getCoverageFileID(SourceLocation Loc) { auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); if (Mapping != FileIDMapping.end()) return Mapping->second.first; @@ -339,11 +341,11 @@ public: /// this returns std::nullopt. /// Note this function can potentially be expensive because /// getSpellingLineNumber uses getLineNumber, which is expensive. - Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM, - SourceLocation LocStart, - SourceLocation LocEnd, - SourceLocation PrevTokLoc, - SourceLocation NextTokLoc) { + std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM, + SourceLocation LocStart, + SourceLocation LocEnd, + SourceLocation PrevTokLoc, + SourceLocation NextTokLoc) { SpellingRegion SR{SM, LocStart, LocEnd}; SR.ColumnStart = 1; if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) && @@ -386,7 +388,7 @@ public: auto CovFileID = getCoverageFileID(LocStart); if (!CovFileID) continue; - Optional<SpellingRegion> SR; + std::optional<SpellingRegion> SR; if (I.isComment()) SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc); @@ -585,9 +587,9 @@ struct CounterCoverageMappingBuilder /// Returns the index on the stack where the region was pushed. This can be /// used with popRegions to exit a "scope", ending the region that was pushed. size_t pushRegion(Counter Count, - Optional<SourceLocation> StartLoc = std::nullopt, - Optional<SourceLocation> EndLoc = std::nullopt, - Optional<Counter> FalseCount = std::nullopt) { + std::optional<SourceLocation> StartLoc = std::nullopt, + std::optional<SourceLocation> EndLoc = std::nullopt, + std::optional<Counter> FalseCount = std::nullopt) { if (StartLoc && !FalseCount) { MostRecentLocation = *StartLoc; @@ -812,7 +814,7 @@ struct CounterCoverageMappingBuilder } llvm::SmallSet<SourceLocation, 8> StartLocs; - Optional<Counter> ParentCounter; + std::optional<Counter> ParentCounter; for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { if (!I.hasStartLoc()) continue; @@ -880,8 +882,8 @@ struct CounterCoverageMappingBuilder } /// Find a valid gap range between \p AfterLoc and \p BeforeLoc. - Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc, - SourceLocation BeforeLoc) { + std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc, + SourceLocation BeforeLoc) { // If AfterLoc is in function-like macro, use the right parenthesis // location. if (AfterLoc.isMacroID()) { @@ -1391,7 +1393,7 @@ struct CounterCoverageMappingBuilder propagateCounts(ParentCount, S->getCond()); // The 'then' count applies to the area immediately after the condition. - Optional<SourceRange> Gap = + std::optional<SourceRange> Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen())); if (Gap) fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount); @@ -1405,7 +1407,7 @@ struct CounterCoverageMappingBuilder bool ThenHasTerminateStmt = HasTerminateStmt; HasTerminateStmt = false; // The 'else' count applies to the area immediately after the 'then'. - Optional<SourceRange> Gap = + std::optional<SourceRange> Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else)); if (Gap) fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount); diff --git a/clang/lib/CodeGen/SwiftCallingConv.cpp b/clang/lib/CodeGen/SwiftCallingConv.cpp index 982067c4..6b868fe 100644 --- a/clang/lib/CodeGen/SwiftCallingConv.cpp +++ b/clang/lib/CodeGen/SwiftCallingConv.cpp @@ -440,7 +440,7 @@ static bool isMergeableEntryType(llvm::Type *type) { // merge pointers, but (1) it doesn't currently matter in practice because // the chunk size is never greater than the size of a pointer and (2) // Swift IRGen uses integer types for a lot of things that are "really" - // just storing pointers (like Optional<SomePointer>). If we ever have a + // just storing pointers (like std::optional<SomePointer>). If we ever have a // target that would otherwise combine pointers, we should put some effort // into fixing those cases in Swift IRGen and then call out pointer types // here. diff --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp b/clang/lib/CrossTU/CrossTranslationUnit.cpp index a871eee..4ba03b2 100644 --- a/clang/lib/CrossTU/CrossTranslationUnit.cpp +++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp @@ -242,7 +242,7 @@ CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI) CrossTranslationUnitContext::~CrossTranslationUnitContext() {} -llvm::Optional<std::string> +std::optional<std::string> CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) { SmallString<128> DeclUSR; bool Ret = index::generateUSRForDecl(ND, DeclUSR); @@ -268,7 +268,7 @@ CrossTranslationUnitContext::findDefInDeclContext(const DeclContext *DC, const T *ResultDecl; if (!ND || !hasBodyOrInit(ND, ResultDecl)) continue; - llvm::Optional<std::string> ResultLookupName = getLookupName(ResultDecl); + std::optional<std::string> ResultLookupName = getLookupName(ResultDecl); if (!ResultLookupName || *ResultLookupName != LookupName) continue; return ResultDecl; @@ -284,7 +284,7 @@ llvm::Expected<const T *> CrossTranslationUnitContext::getCrossTUDefinitionImpl( assert(!hasBodyOrInit(D) && "D has a body or init in current translation unit!"); ++NumGetCTUCalled; - const llvm::Optional<std::string> LookupName = getLookupName(D); + const std::optional<std::string> LookupName = getLookupName(D); if (!LookupName) return llvm::make_error<IndexError>( index_error_code::failed_to_generate_usr); @@ -794,7 +794,7 @@ CrossTranslationUnitContext::getOrCreateASTImporter(ASTUnit *Unit) { return *NewImporter; } -llvm::Optional<clang::MacroExpansionContext> +std::optional<clang::MacroExpansionContext> CrossTranslationUnitContext::getMacroExpansionContextForSourceLocation( const clang::SourceLocation &ToLoc) const { // FIXME: Implement: Record such a context for every imported ASTUnit; lookup. diff --git a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp index 89dbc96..736e450 100644 --- a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp +++ b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp @@ -692,7 +692,7 @@ static bool getLiteralInfo(SourceRange literalRange, if (text.empty()) return false; - Optional<bool> UpperU, UpperL; + std::optional<bool> UpperU, UpperL; bool UpperF = false; struct Suff { @@ -776,8 +776,8 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, ASTContext &Ctx = NS.getASTContext(); Selector Sel = Msg->getSelector(); - Optional<NSAPI::NSNumberLiteralMethodKind> - MKOpt = NS.getNSNumberLiteralMethodKind(Sel); + std::optional<NSAPI::NSNumberLiteralMethodKind> MKOpt = + NS.getNSNumberLiteralMethodKind(Sel); if (!MKOpt) return false; NSAPI::NSNumberLiteralMethodKind MK = *MKOpt; @@ -984,8 +984,8 @@ static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg, ASTContext &Ctx = NS.getASTContext(); Selector Sel = Msg->getSelector(); - Optional<NSAPI::NSNumberLiteralMethodKind> - MKOpt = NS.getNSNumberLiteralMethodKind(Sel); + std::optional<NSAPI::NSNumberLiteralMethodKind> MKOpt = + NS.getNSNumberLiteralMethodKind(Sel); if (!MKOpt) return false; NSAPI::NSNumberLiteralMethodKind MK = *MKOpt; diff --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp index a274585..644845e 100644 --- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp +++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp @@ -48,9 +48,9 @@ using namespace extractapi; namespace { -Optional<std::string> getRelativeIncludeName(const CompilerInstance &CI, - StringRef File, - bool *IsQuoted = nullptr) { +std::optional<std::string> getRelativeIncludeName(const CompilerInstance &CI, + StringRef File, + bool *IsQuoted = nullptr) { assert(CI.hasFileManager() && "CompilerInstance does not have a FileNamager!"); diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp index 91b86bd..01e9b37 100644 --- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp +++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp @@ -38,14 +38,14 @@ namespace { /// Helper function to inject a JSON object \p Obj into another object \p Paren /// at position \p Key. -void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) { +void serializeObject(Object &Paren, StringRef Key, std::optional<Object> Obj) { if (Obj) Paren[Key] = std::move(*Obj); } /// Helper function to inject a JSON array \p Array into object \p Paren at /// position \p Key. -void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) { +void serializeArray(Object &Paren, StringRef Key, std::optional<Array> Array) { if (Array) Paren[Key] = std::move(*Array); } @@ -66,7 +66,7 @@ void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) { /// /// \returns \c std::nullopt if the version \p V is empty, or an \c Object /// containing the semantic version representation of \p V. -Optional<Object> serializeSemanticVersion(const VersionTuple &V) { +std::optional<Object> serializeSemanticVersion(const VersionTuple &V) { if (V.empty()) return std::nullopt; @@ -152,7 +152,8 @@ Object serializeSourceRange(const PresumedLoc &BeginLoc, /// /// \returns \c std::nullopt if the symbol has default availability attributes, /// or an \c Array containing the formatted availability information. -Optional<Array> serializeAvailability(const AvailabilitySet &Availabilities) { +std::optional<Array> +serializeAvailability(const AvailabilitySet &Availabilities) { if (Availabilities.isDefault()) return std::nullopt; @@ -238,7 +239,7 @@ Object serializeIdentifier(const APIRecord &Record, Language Lang) { /// /// \returns \c std::nullopt if \p Comment is empty, or an \c Object containing /// the formatted lines. -Optional<Object> serializeDocComment(const DocComment &Comment) { +std::optional<Object> serializeDocComment(const DocComment &Comment) { if (Comment.empty()) return std::nullopt; @@ -290,7 +291,8 @@ Optional<Object> serializeDocComment(const DocComment &Comment) { /// /// \returns \c std::nullopt if \p DF is empty, or an \c Array containing the /// formatted declaration fragments array. -Optional<Array> serializeDeclarationFragments(const DeclarationFragments &DF) { +std::optional<Array> +serializeDeclarationFragments(const DeclarationFragments &DF) { if (DF.getFragments().empty()) return std::nullopt; @@ -421,8 +423,8 @@ Object serializeSymbolKind(const APIRecord &Record, Language Lang) { } template <typename RecordTy> -Optional<Object> serializeFunctionSignatureMixinImpl(const RecordTy &Record, - std::true_type) { +std::optional<Object> +serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::true_type) { const auto &FS = Record.Signature; if (FS.empty()) return std::nullopt; @@ -447,8 +449,8 @@ Optional<Object> serializeFunctionSignatureMixinImpl(const RecordTy &Record, } template <typename RecordTy> -Optional<Object> serializeFunctionSignatureMixinImpl(const RecordTy &Record, - std::false_type) { +std::optional<Object> +serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::false_type) { return std::nullopt; } @@ -583,7 +585,7 @@ bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const { } template <typename RecordTy> -Optional<Object> +std::optional<Object> SymbolGraphSerializer::serializeAPIRecord(const RecordTy &Record) const { if (shouldSkip(Record)) return std::nullopt; @@ -856,7 +858,7 @@ void SymbolGraphSerializer::serialize(raw_ostream &os) { os << formatv("{0:2}", Value(std::move(root))) << "\n"; } -Optional<Object> +std::optional<Object> SymbolGraphSerializer::serializeSingleSymbolSGF(StringRef USR, const APISet &API) { APIRecord *Record = API.findRecordForUSR(USR); diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index d3e192f..412c57b 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -187,7 +187,7 @@ getCanonicalRawStringDelimiter(const FormatStyle &Style, RawStringFormatStyleManager::RawStringFormatStyleManager( const FormatStyle &CodeStyle) { for (const auto &RawStringFormat : CodeStyle.RawStringFormats) { - llvm::Optional<FormatStyle> LanguageStyle = + std::optional<FormatStyle> LanguageStyle = CodeStyle.GetLanguageStyle(RawStringFormat.Language); if (!LanguageStyle) { FormatStyle PredefinedStyle; @@ -206,7 +206,7 @@ RawStringFormatStyleManager::RawStringFormatStyleManager( } } -llvm::Optional<FormatStyle> +std::optional<FormatStyle> RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const { auto It = DelimiterStyle.find(Delimiter); if (It == DelimiterStyle.end()) @@ -214,7 +214,7 @@ RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const { return It->second; } -llvm::Optional<FormatStyle> +std::optional<FormatStyle> RawStringFormatStyleManager::getEnclosingFunctionStyle( StringRef EnclosingFunction) const { auto It = EnclosingFunctionStyle.find(EnclosingFunction); @@ -2080,7 +2080,7 @@ static StringRef getEnclosingFunctionName(const FormatToken &Current) { return Tok->TokenText; } -llvm::Optional<FormatStyle> +std::optional<FormatStyle> ContinuationIndenter::getRawStringStyle(const FormatToken &Current, const LineState &State) { if (!Current.isStringLiteral()) diff --git a/clang/lib/Format/ContinuationIndenter.h b/clang/lib/Format/ContinuationIndenter.h index 6b4d5b6..2a1b968 100644 --- a/clang/lib/Format/ContinuationIndenter.h +++ b/clang/lib/Format/ContinuationIndenter.h @@ -42,9 +42,9 @@ struct RawStringFormatStyleManager { RawStringFormatStyleManager(const FormatStyle &CodeStyle); - llvm::Optional<FormatStyle> getDelimiterStyle(StringRef Delimiter) const; + std::optional<FormatStyle> getDelimiterStyle(StringRef Delimiter) const; - llvm::Optional<FormatStyle> + std::optional<FormatStyle> getEnclosingFunctionStyle(StringRef EnclosingFunction) const; }; @@ -121,8 +121,8 @@ private: /// If \p Current is a raw string that is configured to be reformatted, /// return the style to be used. - llvm::Optional<FormatStyle> getRawStringStyle(const FormatToken &Current, - const LineState &State); + std::optional<FormatStyle> getRawStringStyle(const FormatToken &Current, + const LineState &State); /// If the current token sticks out over the end of the line, break /// it if possible. diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index b09d057..2e8f130 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1915,7 +1915,7 @@ std::string configurationAsText(const FormatStyle &Style) { return Stream.str(); } -llvm::Optional<FormatStyle> +std::optional<FormatStyle> FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const { if (!Styles) return std::nullopt; @@ -1940,7 +1940,7 @@ void FormatStyle::FormatStyleSet::Add(FormatStyle Style) { void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); } -llvm::Optional<FormatStyle> +std::optional<FormatStyle> FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const { return StyleSet.Get(Language); } diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 61a395e..9d055ef 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -521,7 +521,7 @@ public: // Contains all attributes related to how this token takes part // in a configured macro expansion. - llvm::Optional<MacroExpansion> MacroCtx; + std::optional<MacroExpansion> MacroCtx; /// When macro expansion introduces nodes with children, those are marked as /// \c MacroParent. diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index fcfc18e..463f7ad 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -1744,8 +1744,8 @@ ASTUnit *ASTUnit::LoadFromCommandLine( bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies, bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization, - bool RetainExcludedConditionalBlocks, - llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST, + bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat, + std::unique_ptr<ASTUnit> *ErrAST, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { assert(Diags.get() && "no DiagnosticsEngine was provided"); diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index a124566..ecc1c4c 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -879,7 +879,7 @@ CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary, } } - Optional<llvm::sys::fs::TempFile> Temp; + std::optional<llvm::sys::fs::TempFile> Temp; if (UseTemporary) { // Create a temporary file. // Insert -%%%%%%%% before the extension (if any), and because some tools diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index 1cabf28..032940a 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -2507,7 +2507,8 @@ static const auto &getFrontendActionTable() { } /// Maps command line option to frontend action. -static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) { +static std::optional<frontend::ActionKind> +getFrontendAction(OptSpecifier &Opt) { for (const auto &ActionOpt : getFrontendActionTable()) if (ActionOpt.second == Opt.getID()) return ActionOpt.first; @@ -2516,7 +2517,7 @@ static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) { } /// Maps frontend action to command line option. -static Optional<OptSpecifier> +static std::optional<OptSpecifier> getProgramActionOpt(frontend::ActionKind ProgramAction) { for (const auto &ActionOpt : getFrontendActionTable()) if (ActionOpt.first == ProgramAction) @@ -2541,7 +2542,7 @@ static void GenerateFrontendArgs(const FrontendOptions &Opts, #include "clang/Driver/Options.inc" #undef FRONTEND_OPTION_WITH_MARSHALLING - Optional<OptSpecifier> ProgramActionOpt = + std::optional<OptSpecifier> ProgramActionOpt = getProgramActionOpt(Opts.ProgramAction); // Generating a simple flag covers most frontend actions. @@ -2720,7 +2721,7 @@ static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.ProgramAction = frontend::ParseSyntaxOnly; if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { OptSpecifier Opt = OptSpecifier(A->getOption().getID()); - Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt); + std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt); assert(ProgramAction && "Option specifier not in Action_Group."); if (ProgramAction == frontend::ASTDump && diff --git a/clang/lib/Frontend/DependencyFile.cpp b/clang/lib/Frontend/DependencyFile.cpp index 1c175c7..fe4218b 100644 --- a/clang/lib/Frontend/DependencyFile.cpp +++ b/clang/lib/Frontend/DependencyFile.cpp @@ -44,7 +44,7 @@ struct DepCollectorPPCallbacks : public PPCallbacks { // Dependency generation really does want to go all the way to the // file entry for a source location to find out what is depended on. // We do not want #line markers to affect dependency generation! - if (Optional<StringRef> Filename = + if (std::optional<StringRef> Filename = PP.getSourceManager().getNonBuiltinFilenameForID(FID)) DepCollector.maybeAddDependency( llvm::sys::path::remove_leading_dotslash(*Filename), diff --git a/clang/lib/Frontend/FrontendActions.cpp b/clang/lib/Frontend/FrontendActions.cpp index fa9ec46..2d81178 100644 --- a/clang/lib/Frontend/FrontendActions.cpp +++ b/clang/lib/Frontend/FrontendActions.cpp @@ -971,7 +971,7 @@ void PrintPreprocessedAction::ExecuteAction() { if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) { BinaryMode = true; const SourceManager &SM = CI.getSourceManager(); - if (llvm::Optional<llvm::MemoryBufferRef> Buffer = + if (std::optional<llvm::MemoryBufferRef> Buffer = SM.getBufferOrNone(SM.getMainFileID())) { const char *cur = Buffer->getBufferStart(); const char *end = Buffer->getBufferEnd(); diff --git a/clang/lib/Lex/DependencyDirectivesScanner.cpp b/clang/lib/Lex/DependencyDirectivesScanner.cpp index c932c0d..0adbaa3 100644 --- a/clang/lib/Lex/DependencyDirectivesScanner.cpp +++ b/clang/lib/Lex/DependencyDirectivesScanner.cpp @@ -96,7 +96,7 @@ private: /// /// In any case (whatever the token kind) \p First and the \p Lexer will /// advance beyond the token. - [[nodiscard]] Optional<StringRef> + [[nodiscard]] std::optional<StringRef> tryLexIdentifierOrSkipLine(const char *&First, const char *const End); /// Used when it is certain that next token is an identifier. @@ -525,7 +525,7 @@ void Scanner::lexPPDirectiveBody(const char *&First, const char *const End) { } } -[[nodiscard]] Optional<StringRef> +[[nodiscard]] std::optional<StringRef> Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) { const dependency_directives_scan::Token &Tok = lexToken(First, End); if (Tok.isNot(tok::raw_identifier)) { @@ -556,14 +556,15 @@ Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) { } StringRef Scanner::lexIdentifier(const char *&First, const char *const End) { - Optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End); + std::optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End); assert(Id && "expected identifier token"); return *Id; } bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First, const char *const End) { - if (Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End)) { + if (std::optional<StringRef> FoundId = + tryLexIdentifierOrSkipLine(First, End)) { if (*FoundId == Id) return true; skipLine(First, End); @@ -589,7 +590,7 @@ bool Scanner::lexModule(const char *&First, const char *const End) { bool Export = false; if (Id == "export") { Export = true; - Optional<StringRef> NextId = tryLexIdentifierOrSkipLine(First, End); + std::optional<StringRef> NextId = tryLexIdentifierOrSkipLine(First, End); if (!NextId) return false; Id = *NextId; @@ -629,7 +630,7 @@ bool Scanner::lexModule(const char *&First, const char *const End) { } bool Scanner::lexPragma(const char *&First, const char *const End) { - Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End); + std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End); if (!FoundId) return false; @@ -754,7 +755,7 @@ bool Scanner::lexPPLine(const char *&First, const char *const End) { assert(HashTok.is(tok::hash)); (void)HashTok; - Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End); + std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End); if (!FoundId) return false; @@ -874,7 +875,7 @@ void clang::printDependencyDirectivesAsSource( for (const dependency_directives_scan::Directive &Directive : Directives) { if (Directive.Kind == tokens_present_before_eof) OS << "<TokBeforeEOF>"; - Optional<tok::TokenKind> PrevTokenKind; + std::optional<tok::TokenKind> PrevTokenKind; for (const dependency_directives_scan::Token &Tok : Directive.Tokens) { if (PrevTokenKind && needsSpaceSeparator(*PrevTokenKind, Tok)) OS << ' '; diff --git a/clang/lib/Lex/HeaderMap.cpp b/clang/lib/Lex/HeaderMap.cpp index 2a444b5..bb50a4e 100644 --- a/clang/lib/Lex/HeaderMap.cpp +++ b/clang/lib/Lex/HeaderMap.cpp @@ -146,7 +146,7 @@ HMapBucket HeaderMapImpl::getBucket(unsigned BucketNo) const { return Result; } -Optional<StringRef> HeaderMapImpl::getString(unsigned StrTabIdx) const { +std::optional<StringRef> HeaderMapImpl::getString(unsigned StrTabIdx) const { // Add the start of the string table to the idx. StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset); @@ -178,7 +178,7 @@ LLVM_DUMP_METHOD void HeaderMapImpl::dump() const { << ", " << getEndianAdjustedWord(Hdr.NumEntries) << "\n"; auto getStringOrInvalid = [this](unsigned Id) -> StringRef { - if (Optional<StringRef> S = getString(Id)) + if (std::optional<StringRef> S = getString(Id)) return *S; return "<invalid>"; }; @@ -209,7 +209,7 @@ StringRef HeaderMapImpl::lookupFilename(StringRef Filename, if (B.Key == HMAP_EmptyBucketKey) return StringRef(); // Hash miss. // See if the key matches. If not, probe on. - Optional<StringRef> Key = getString(B.Key); + std::optional<StringRef> Key = getString(B.Key); if (LLVM_UNLIKELY(!Key)) continue; if (!Filename.equals_insensitive(*Key)) @@ -217,8 +217,8 @@ StringRef HeaderMapImpl::lookupFilename(StringRef Filename, // If so, we have a match in the hash table. Construct the destination // path. - Optional<StringRef> Prefix = getString(B.Prefix); - Optional<StringRef> Suffix = getString(B.Suffix); + std::optional<StringRef> Prefix = getString(B.Prefix); + std::optional<StringRef> Suffix = getString(B.Suffix); DestPath.clear(); if (LLVM_LIKELY(Prefix && Suffix)) { @@ -241,9 +241,9 @@ StringRef HeaderMapImpl::reverseLookupFilename(StringRef DestPath) const { if (B.Key == HMAP_EmptyBucketKey) continue; - Optional<StringRef> Key = getString(B.Key); - Optional<StringRef> Prefix = getString(B.Prefix); - Optional<StringRef> Suffix = getString(B.Suffix); + std::optional<StringRef> Key = getString(B.Key); + std::optional<StringRef> Prefix = getString(B.Prefix); + std::optional<StringRef> Suffix = getString(B.Suffix); if (LLVM_LIKELY(Key && Prefix && Suffix)) { SmallVector<char, 1024> Buf; Buf.append(Prefix->begin(), Prefix->end()); diff --git a/clang/lib/Lex/InitHeaderSearch.cpp b/clang/lib/Lex/InitHeaderSearch.cpp index 4b527ac..d4465565 100644 --- a/clang/lib/Lex/InitHeaderSearch.cpp +++ b/clang/lib/Lex/InitHeaderSearch.cpp @@ -36,10 +36,10 @@ namespace { struct DirectoryLookupInfo { IncludeDirGroup Group; DirectoryLookup Lookup; - Optional<unsigned> UserEntryIdx; + std::optional<unsigned> UserEntryIdx; DirectoryLookupInfo(IncludeDirGroup Group, DirectoryLookup Lookup, - Optional<unsigned> UserEntryIdx) + std::optional<unsigned> UserEntryIdx) : Group(Group), Lookup(Lookup), UserEntryIdx(UserEntryIdx) {} }; @@ -63,14 +63,14 @@ public: /// if used. /// Returns true if the path exists, false if it was ignored. bool AddPath(const Twine &Path, IncludeDirGroup Group, bool isFramework, - Optional<unsigned> UserEntryIdx = std::nullopt); + std::optional<unsigned> UserEntryIdx = std::nullopt); /// Add the specified path to the specified group list, without performing any /// sysroot remapping. /// Returns true if the path exists, false if it was ignored. bool AddUnmappedPath(const Twine &Path, IncludeDirGroup Group, bool isFramework, - Optional<unsigned> UserEntryIdx = std::nullopt); + std::optional<unsigned> UserEntryIdx = std::nullopt); /// Add the specified prefix to the system header prefix list. void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) { @@ -122,7 +122,7 @@ static bool CanPrefixSysroot(StringRef Path) { bool InitHeaderSearch::AddPath(const Twine &Path, IncludeDirGroup Group, bool isFramework, - Optional<unsigned> UserEntryIdx) { + std::optional<unsigned> UserEntryIdx) { // Add the path with sysroot prepended, if desired and this is a system header // group. if (HasSysroot) { @@ -139,7 +139,7 @@ bool InitHeaderSearch::AddPath(const Twine &Path, IncludeDirGroup Group, bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group, bool isFramework, - Optional<unsigned> UserEntryIdx) { + std::optional<unsigned> UserEntryIdx) { assert(!Path.isTriviallyEmpty() && "can't handle empty path here"); FileManager &FM = Headers.getFileMgr(); diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index 9965acb..872d56a 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -1259,9 +1259,9 @@ const char *Lexer::SkipEscapedNewLines(const char *P) { } } -Optional<Token> Lexer::findNextToken(SourceLocation Loc, - const SourceManager &SM, - const LangOptions &LangOpts) { +std::optional<Token> Lexer::findNextToken(SourceLocation Loc, + const SourceManager &SM, + const LangOptions &LangOpts) { if (Loc.isMacroID()) { if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) return std::nullopt; @@ -1295,7 +1295,7 @@ Optional<Token> Lexer::findNextToken(SourceLocation Loc, SourceLocation Lexer::findLocationAfterToken( SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) { - Optional<Token> Tok = findNextToken(Loc, SM, LangOpts); + std::optional<Token> Tok = findNextToken(Loc, SM, LangOpts); if (!Tok || Tok->isNot(TKind)) return {}; SourceLocation TokenLoc = Tok->getLocation(); @@ -3257,9 +3257,9 @@ bool Lexer::isCodeCompletionPoint(const char *CurPtr) const { return false; } -llvm::Optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr, - const char *SlashLoc, - Token *Result) { +std::optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr, + const char *SlashLoc, + Token *Result) { unsigned CharSize; char Kind = getCharAndSize(StartPtr, CharSize); assert((Kind == 'u' || Kind == 'U') && "expected a UCN"); @@ -3371,9 +3371,9 @@ llvm::Optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr, return CodePoint; } -llvm::Optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr, - const char *SlashLoc, - Token *Result) { +std::optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr, + const char *SlashLoc, + Token *Result) { unsigned CharSize; bool Diagnose = Result && !isLexingRawMode(); @@ -3462,14 +3462,14 @@ llvm::Optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr, } else { StartPtr = CurPtr; } - return Match ? llvm::Optional<uint32_t>(*Match) : std::nullopt; + return Match ? std::optional<uint32_t>(*Match) : std::nullopt; } uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc, Token *Result) { unsigned CharSize; - llvm::Optional<uint32_t> CodePointOpt; + std::optional<uint32_t> CodePointOpt; char Kind = getCharAndSize(StartPtr, CharSize); if (Kind == 'u' || Kind == 'U') CodePointOpt = tryReadNumericUCN(StartPtr, SlashLoc, Result); diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp index 819bb72..b2c70e5 100644 --- a/clang/lib/Lex/MacroInfo.cpp +++ b/clang/lib/Lex/MacroInfo.cpp @@ -199,7 +199,7 @@ LLVM_DUMP_METHOD void MacroInfo::dump() const { MacroDirective::DefInfo MacroDirective::getDefinition() { MacroDirective *MD = this; SourceLocation UndefLoc; - Optional<bool> isPublic; + std::optional<bool> isPublic; for (; MD; MD = MD->getPrevious()) { if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) return DefInfo(DefMD, UndefLoc, !isPublic || *isPublic); diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp index 7292f16..106e9c3 100644 --- a/clang/lib/Lex/ModuleMap.cpp +++ b/clang/lib/Lex/ModuleMap.cpp @@ -1213,7 +1213,7 @@ void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const { } void ModuleMap::resolveHeaderDirectives( - Module *Mod, llvm::Optional<const FileEntry *> File) const { + Module *Mod, std::optional<const FileEntry *> File) const { bool NeedsFramework = false; SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders; const auto Size = File ? (*File)->getSize() : 0; @@ -3067,7 +3067,7 @@ bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem, } assert(Target && "Missing target information"); - llvm::Optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID); + std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID); if (!Buffer) return ParsedModuleMap[File] = true; assert((!Offset || *Offset <= Buffer->getBufferSize()) && diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp index 3064c8c..41b38b6 100644 --- a/clang/lib/Lex/PPDirectives.cpp +++ b/clang/lib/Lex/PPDirectives.cpp @@ -275,8 +275,8 @@ static bool warnByDefaultOnWrongCase(StringRef Include) { /// /// \returns a similar string if exists. If no similar string exists, /// returns std::nullopt. -static Optional<StringRef> findSimilarStr( - StringRef LHS, const std::vector<StringRef> &Candidates) { +static std::optional<StringRef> +findSimilarStr(StringRef LHS, const std::vector<StringRef> &Candidates) { // We need to check if `Candidates` has the exact case-insensitive string // because the Levenshtein distance match does not care about it. for (StringRef C : Candidates) { @@ -291,7 +291,7 @@ static Optional<StringRef> findSimilarStr( size_t Length = LHS.size(); size_t MaxDist = Length < 3 ? Length - 1 : Length / 3; - Optional<std::pair<StringRef, size_t>> SimilarStr; + std::optional<std::pair<StringRef, size_t>> SimilarStr; for (StringRef C : Candidates) { size_t CurDist = LHS.edit_distance(C, true); if (CurDist <= MaxDist) { @@ -456,7 +456,7 @@ void Preprocessor::SuggestTypoedDirective(const Token &Tok, if (LangOpts.C2x || LangOpts.CPlusPlus2b) Candidates.insert(Candidates.end(), {"elifdef", "elifndef"}); - if (Optional<StringRef> Sugg = findSimilarStr(Directive, Candidates)) { + if (std::optional<StringRef> Sugg = findSimilarStr(Directive, Candidates)) { // Directive cannot be coming from macro. assert(Tok.getLocation().isFileID()); CharSourceRange DirectiveRange = CharSourceRange::getCharRange( diff --git a/clang/lib/Lex/PPLexerChange.cpp b/clang/lib/Lex/PPLexerChange.cpp index c997bc3..6616846 100644 --- a/clang/lib/Lex/PPLexerChange.cpp +++ b/clang/lib/Lex/PPLexerChange.cpp @@ -76,7 +76,7 @@ bool Preprocessor::EnterSourceFile(FileID FID, ConstSearchDirIterator CurDir, MaxIncludeStackDepth = IncludeMacroStack.size(); // Get the MemoryBuffer for this FID, if it fails, we fail. - llvm::Optional<llvm::MemoryBufferRef> InputFile = + std::optional<llvm::MemoryBufferRef> InputFile = getSourceManager().getBufferOrNone(FID, Loc); if (!InputFile) { SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); @@ -96,7 +96,7 @@ bool Preprocessor::EnterSourceFile(FileID FID, ConstSearchDirIterator CurDir, if (getPreprocessorOpts().DependencyDirectivesForFile && FID != PredefinesFileID) { if (OptionalFileEntryRef File = SourceMgr.getFileEntryRefForID(FID)) { - if (Optional<ArrayRef<dependency_directives_scan::Directive>> + if (std::optional<ArrayRef<dependency_directives_scan::Directive>> DepDirectives = getPreprocessorOpts().DependencyDirectivesForFile(*File)) { TheLexer->DepDirectives = *DepDirectives; diff --git a/clang/lib/Lex/PPMacroExpansion.cpp b/clang/lib/Lex/PPMacroExpansion.cpp index cd60452..fcf1f27 100644 --- a/clang/lib/Lex/PPMacroExpansion.cpp +++ b/clang/lib/Lex/PPMacroExpansion.cpp @@ -1302,7 +1302,7 @@ static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS, unsigned ParenDepth = 1; SourceLocation LParenLoc = Tok.getLocation(); - llvm::Optional<int> Result; + std::optional<int> Result; Token ResultTok; bool SuppressDiagnostic = false; diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp index ab61c72..4da9d16 100644 --- a/clang/lib/Lex/Pragma.cpp +++ b/clang/lib/Lex/Pragma.cpp @@ -1185,7 +1185,7 @@ struct PragmaDebugHandler : public PragmaHandler { } else if (II->isStr("sloc_usage")) { // An optional integer literal argument specifies the number of files to // specifically report information about. - Optional<unsigned> MaxNotes; + std::optional<unsigned> MaxNotes; Token ArgToken; PP.Lex(ArgToken); uint64_t Value; diff --git a/clang/lib/Lex/PreprocessingRecord.cpp b/clang/lib/Lex/PreprocessingRecord.cpp index e187fb6..d015411 100644 --- a/clang/lib/Lex/PreprocessingRecord.cpp +++ b/clang/lib/Lex/PreprocessingRecord.cpp @@ -113,7 +113,7 @@ bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) { // See if the external source can see if the entity is in the file without // deserializing it. - if (Optional<bool> IsInFile = + if (std::optional<bool> IsInFile = ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID)) return *IsInFile; diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp index 87655c7..fe9adb5 100644 --- a/clang/lib/Lex/Preprocessor.cpp +++ b/clang/lib/Lex/Preprocessor.cpp @@ -400,7 +400,7 @@ bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, assert(!CodeCompletionFile && "Already set"); // Load the actual file's contents. - Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getMemoryBufferForFileOrNone(File); if (!Buffer) return true; diff --git a/clang/lib/Lex/TokenLexer.cpp b/clang/lib/Lex/TokenLexer.cpp index 6f801db..c6968b9 100644 --- a/clang/lib/Lex/TokenLexer.cpp +++ b/clang/lib/Lex/TokenLexer.cpp @@ -249,7 +249,7 @@ void TokenLexer::ExpandFunctionArguments() { // we install the newly expanded sequence as the new 'Tokens' list. bool MadeChange = false; - Optional<bool> CalledWithVariadicArguments; + std::optional<bool> CalledWithVariadicArguments; VAOptExpansionContext VCtx(PP); diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index eec12a1..7b1dd53 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -535,7 +535,7 @@ void Parser::ParseGNUAttributeArgs( // These may refer to the function arguments, but need to be parsed early to // participate in determining whether it's a redeclaration. - llvm::Optional<ParseScope> PrototypeScope; + std::optional<ParseScope> PrototypeScope; if (normalizeAttrName(AttrName->getName()) == "enable_if" && D && D->isFunctionDeclarator()) { DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo(); @@ -1690,7 +1690,7 @@ void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned DiagID, Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts); if (FirstLSquare.is(tok::l_square)) { - llvm::Optional<Token> SecondLSquare = + std::optional<Token> SecondLSquare = Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts); if (SecondLSquare && SecondLSquare->is(tok::l_square)) { @@ -5798,7 +5798,7 @@ bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide, void Parser::ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed, bool IdentifierRequired, - Optional<llvm::function_ref<void()>> CodeCompletionHandler) { + std::optional<llvm::function_ref<void()>> CodeCompletionHandler) { if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) && isCXX11AttributeSpecifier()) { ParsedAttributes Attrs(AttrFactory); @@ -6765,7 +6765,7 @@ void Parser::ParseParenDeclarator(Declarator &D) { void Parser::InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, - llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) { + std::optional<Sema::CXXThisScopeRAII> &ThisScope) { // C++11 [expr.prim.general]p3: // If a declaration declares a member function or member function // template of a class X, the expression this is a prvalue of type @@ -6917,7 +6917,7 @@ void Parser::ParseFunctionDeclarator(Declarator &D, if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) EndLoc = RefQualifierLoc; - llvm::Optional<Sema::CXXThisScopeRAII> ThisScope; + std::optional<Sema::CXXThisScopeRAII> ThisScope; InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope); // Parse exception-specification[opt]. diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp index 1dadb76..227c1df 100644 --- a/clang/lib/Parse/ParseDeclCXX.cpp +++ b/clang/lib/Parse/ParseDeclCXX.cpp @@ -4072,7 +4072,7 @@ void Parser::ParseTrailingRequiresClause(Declarator &D) { Actions.ActOnStartTrailingRequiresClause(getCurScope(), D); - llvm::Optional<Sema::CXXThisScopeRAII> ThisScope; + std::optional<Sema::CXXThisScopeRAII> ThisScope; InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope); TrailingRequiresClause = diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index ab3b77d..e8bdf5f 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -3706,7 +3706,7 @@ static bool CheckAvailabilitySpecList(Parser &P, /// availability-spec: /// '*' /// identifier version-tuple -Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() { +std::optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() { if (Tok.is(tok::star)) { return AvailabilitySpec(ConsumeToken()); } else { @@ -3758,7 +3758,7 @@ ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) { SmallVector<AvailabilitySpec, 4> AvailSpecs; bool HasError = false; while (true) { - Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec(); + std::optional<AvailabilitySpec> Spec = ParseAvailabilitySpec(); if (!Spec) HasError = true; else diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index b5e6d01..23afdbd 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -1484,7 +1484,7 @@ void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr, ConsumeToken(); } - Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = + std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = Actions.checkOpenMPDeclareVariantFunction( Ptr, AssociatedFunction.get(), TI, AppendArgs.size(), SourceRange(Loc, Tok.getLocation())); @@ -1782,7 +1782,7 @@ struct SimpleClauseData { }; } // anonymous namespace -static Optional<SimpleClauseData> +static std::optional<SimpleClauseData> parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) { const Token &Tok = P.getCurToken(); SourceLocation Loc = Tok.getLocation(); @@ -1877,7 +1877,7 @@ void Parser::ParseOMPDeclareTargetClauses( } // Parse 'device_type' clause and go to next clause if any. if (IsDeviceTypeClause) { - Optional<SimpleClauseData> DevTypeData = + std::optional<SimpleClauseData> DevTypeData = parseOpenMPSimpleClause(*this, OMPC_device_type); if (DevTypeData) { if (DeviceTypeLoc.isValid()) { @@ -3694,7 +3694,7 @@ OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind, /// OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly) { - llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind); + std::optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind); if (!Val || ParseOnly) return nullptr; if (getLangOpts().OpenMP < 51 && Kind == OMPC_default && diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index 445ad64..658853d 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -1582,8 +1582,8 @@ bool Parser::ParsePragmaAttributeSubjectMatchRuleSet( Diag(Tok, diag::err_pragma_attribute_expected_subject_identifier); return true; } - std::pair<Optional<attr::SubjectMatchRule>, - Optional<attr::SubjectMatchRule> (*)(StringRef, bool)> + std::pair<std::optional<attr::SubjectMatchRule>, + std::optional<attr::SubjectMatchRule> (*)(StringRef, bool)> Rule = isAttributeSubjectMatchRule(Name); if (!Rule.first) { Diag(Tok, diag::err_pragma_attribute_unknown_subject_rule) << Name; @@ -3173,10 +3173,10 @@ struct TokFPAnnotValue { enum FlagKinds { Contract, Reassociate, Exceptions, EvalMethod }; enum FlagValues { On, Off, Fast }; - llvm::Optional<LangOptions::FPModeKind> ContractValue; - llvm::Optional<LangOptions::FPModeKind> ReassociateValue; - llvm::Optional<LangOptions::FPExceptionModeKind> ExceptionsValue; - llvm::Optional<LangOptions::FPEvalMethodKind> EvalMethodValue; + std::optional<LangOptions::FPModeKind> ContractValue; + std::optional<LangOptions::FPModeKind> ReassociateValue; + std::optional<LangOptions::FPExceptionModeKind> ExceptionsValue; + std::optional<LangOptions::FPEvalMethodKind> EvalMethodValue; }; } // end anonymous namespace @@ -3198,7 +3198,7 @@ void PragmaFPHandler::HandlePragma(Preprocessor &PP, IdentifierInfo *OptionInfo = Tok.getIdentifierInfo(); auto FlagKind = - llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagKinds>>( + llvm::StringSwitch<std::optional<TokFPAnnotValue::FlagKinds>>( OptionInfo->getName()) .Case("contract", TokFPAnnotValue::Contract) .Case("reassociate", TokFPAnnotValue::Reassociate) @@ -3232,7 +3232,7 @@ void PragmaFPHandler::HandlePragma(Preprocessor &PP, if (FlagKind == TokFPAnnotValue::Contract) { AnnotValue->ContractValue = - llvm::StringSwitch<llvm::Optional<LangOptions::FPModeKind>>( + llvm::StringSwitch<std::optional<LangOptions::FPModeKind>>( II->getName()) .Case("on", LangOptions::FPModeKind::FPM_On) .Case("off", LangOptions::FPModeKind::FPM_Off) @@ -3245,7 +3245,7 @@ void PragmaFPHandler::HandlePragma(Preprocessor &PP, } } else if (FlagKind == TokFPAnnotValue::Reassociate) { AnnotValue->ReassociateValue = - llvm::StringSwitch<llvm::Optional<LangOptions::FPModeKind>>( + llvm::StringSwitch<std::optional<LangOptions::FPModeKind>>( II->getName()) .Case("on", LangOptions::FPModeKind::FPM_On) .Case("off", LangOptions::FPModeKind::FPM_Off) @@ -3257,7 +3257,7 @@ void PragmaFPHandler::HandlePragma(Preprocessor &PP, } } else if (FlagKind == TokFPAnnotValue::Exceptions) { AnnotValue->ExceptionsValue = - llvm::StringSwitch<llvm::Optional<LangOptions::FPExceptionModeKind>>( + llvm::StringSwitch<std::optional<LangOptions::FPExceptionModeKind>>( II->getName()) .Case("ignore", LangOptions::FPE_Ignore) .Case("maytrap", LangOptions::FPE_MayTrap) @@ -3270,7 +3270,7 @@ void PragmaFPHandler::HandlePragma(Preprocessor &PP, } } else if (FlagKind == TokFPAnnotValue::EvalMethod) { AnnotValue->EvalMethodValue = - llvm::StringSwitch<llvm::Optional<LangOptions::FPEvalMethodKind>>( + llvm::StringSwitch<std::optional<LangOptions::FPEvalMethodKind>>( II->getName()) .Case("source", LangOptions::FPEvalMethodKind::FEM_Source) .Case("double", LangOptions::FPEvalMethodKind::FEM_Double) diff --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp index 9f3a4cb..1c8441f 100644 --- a/clang/lib/Parse/ParseStmt.cpp +++ b/clang/lib/Parse/ParseStmt.cpp @@ -1489,7 +1489,7 @@ StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) { Sema::ConditionResult Cond; SourceLocation LParen; SourceLocation RParen; - llvm::Optional<bool> ConstexprCondition; + std::optional<bool> ConstexprCondition; if (!IsConsteval) { if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc, diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp index 13960fd..3a0f566 100644 --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -328,7 +328,7 @@ static void visitReachableThrows( if (!Reachable[B->getBlockID()]) continue; for (CFGElement &E : *B) { - Optional<CFGStmt> S = E.getAs<CFGStmt>(); + std::optional<CFGStmt> S = E.getAs<CFGStmt>(); if (!S) continue; if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt())) @@ -1115,19 +1115,19 @@ namespace { if (!ReachableBlocks.count(P)) { for (const CFGElement &Elem : llvm::reverse(*P)) { - if (Optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) { - if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) { - // Don't issue a warning for an unreachable fallthrough - // attribute in template instantiations as it may not be - // unreachable in all instantiations of the template. - if (!IsTemplateInstantiation) - S.Diag(AS->getBeginLoc(), - diag::warn_unreachable_fallthrough_attr); - markFallthroughVisited(AS); - ++AnnotatedCnt; - break; - } - // Don't care about other unreachable statements. + if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) { + if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) { + // Don't issue a warning for an unreachable fallthrough + // attribute in template instantiations as it may not be + // unreachable in all instantiations of the template. + if (!IsTemplateInstantiation) + S.Diag(AS->getBeginLoc(), + diag::warn_unreachable_fallthrough_attr); + markFallthroughVisited(AS); + ++AnnotatedCnt; + break; + } + // Don't care about other unreachable statements. } } // If there are no unreachable statements, this may be a special @@ -1200,7 +1200,7 @@ namespace { if (const Stmt *Term = B.getTerminatorStmt()) return Term; for (const CFGElement &Elem : llvm::reverse(B)) - if (Optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) + if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) return CS->getStmt(); // Workaround to detect a statement thrown out by CFGBuilder: // case X: {} case Y: @@ -2298,7 +2298,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings( } // Install the logical handler. - llvm::Optional<LogicalErrorHandler> LEH; + std::optional<LogicalErrorHandler> LEH; if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) { LEH.emplace(S); AC.getCFGBuildOptions().Observer = &*LEH; diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp index 19c75c7..0f03054 100644 --- a/clang/lib/Sema/Sema.cpp +++ b/clang/lib/Sema/Sema.cpp @@ -565,12 +565,12 @@ void Sema::PrintStats() const { void Sema::diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc) { - Optional<NullabilityKind> ExprNullability = SrcType->getNullability(); + std::optional<NullabilityKind> ExprNullability = SrcType->getNullability(); if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable && *ExprNullability != NullabilityKind::NullableResult)) return; - Optional<NullabilityKind> TypeNullability = DstType->getNullability(); + std::optional<NullabilityKind> TypeNullability = DstType->getNullability(); if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) return; @@ -1498,7 +1498,7 @@ void Sema::EmitCurrentDiagnostic(unsigned DiagID) { // eliminated. If it truly cannot be (for example, there is some reentrancy // issue I am not seeing yet), then there should at least be a clarifying // comment somewhere. - if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { + if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) { switch (DiagnosticIDs::getDiagnosticSFINAEResponse( Diags.getCurrentDiagID())) { case DiagnosticIDs::SFINAE_Report: diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp index 572eb16..42f5827 100644 --- a/clang/lib/Sema/SemaAttr.cpp +++ b/clang/lib/Sema/SemaAttr.cpp @@ -338,7 +338,7 @@ void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, AlignPackInfo::Mode ModeVal = CurVal.getAlignMode(); if (Alignment) { - Optional<llvm::APSInt> Val; + std::optional<llvm::APSInt> Val; Val = Alignment->getIntegerConstantExpr(Context); // pack(0) is like pack(), which just works out since that is what @@ -886,7 +886,7 @@ void Sema::AddCFAuditedAttribute(Decl *D) { namespace { -Optional<attr::SubjectMatchRule> +std::optional<attr::SubjectMatchRule> getParentAttrMatcherRule(attr::SubjectMatchRule Rule) { using namespace attr; switch (Rule) { @@ -961,7 +961,7 @@ void Sema::ActOnPragmaAttributeAttribute( RulesToFirstSpecifiedNegatedSubRule; for (const auto &Rule : Rules) { attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first); - Optional<attr::SubjectMatchRule> ParentRule = + std::optional<attr::SubjectMatchRule> ParentRule = getParentAttrMatcherRule(MatchRule); if (!ParentRule) continue; @@ -985,7 +985,7 @@ void Sema::ActOnPragmaAttributeAttribute( bool IgnoreNegatedSubRules = false; for (const auto &Rule : Rules) { attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first); - Optional<attr::SubjectMatchRule> ParentRule = + std::optional<attr::SubjectMatchRule> ParentRule = getParentAttrMatcherRule(MatchRule); if (!ParentRule) continue; diff --git a/clang/lib/Sema/SemaAvailability.cpp b/clang/lib/Sema/SemaAvailability.cpp index e5aeaad..05ad427 100644 --- a/clang/lib/Sema/SemaAvailability.cpp +++ b/clang/lib/Sema/SemaAvailability.cpp @@ -247,7 +247,7 @@ struct AttributeInsertion { /// of unsuccessful parsing can contain invalid data. /// \returns A number of method parameters if parsing was successful, /// std::nullopt otherwise. -static Optional<unsigned> +static std::optional<unsigned> tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames, const LangOptions &LangOpts) { // Accept replacements starting with - or + as valid ObjC method names. @@ -280,7 +280,7 @@ tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames, /// Returns a source location in which it's appropriate to insert a new /// attribute for the given declaration \D. -static Optional<AttributeInsertion> +static std::optional<AttributeInsertion> createAttributeInsertion(const NamedDecl *D, const SourceManager &SM, const LangOptions &LangOpts) { if (isa<ObjCPropertyDecl>(D)) @@ -401,7 +401,7 @@ static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, return; if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE")) return; - Optional<AttributeInsertion> Insertion = createAttributeInsertion( + std::optional<AttributeInsertion> Insertion = createAttributeInsertion( Enclosing, S.getSourceManager(), S.getLangOpts()); if (!Insertion) return; @@ -503,7 +503,7 @@ static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) { Selector Sel = MethodDecl->getSelector(); SmallVector<StringRef, 12> SelectorSlotNames; - Optional<unsigned> NumParams = tryParseObjCMethodName( + std::optional<unsigned> NumParams = tryParseObjCMethodName( Replacement, SelectorSlotNames, S.getLangOpts()); if (NumParams && *NumParams == Sel.getNumArgs()) { assert(SelectorSlotNames.size() == Locs.size()); diff --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp index 58063df..b5e3704 100644 --- a/clang/lib/Sema/SemaCUDA.cpp +++ b/clang/lib/Sema/SemaCUDA.cpp @@ -339,7 +339,7 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, if (!InClass || HasExplicitAttr) return false; - llvm::Optional<CUDAFunctionTarget> InferredTarget; + std::optional<CUDAFunctionTarget> InferredTarget; // We're going to invoke special member lookup; mark that these special // members are called from this one, and not from its caller. diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 5bd1072..07054cf 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -796,7 +796,7 @@ class ScanfDiagnosticFormatHandler // Accepts the argument index (relative to the first destination index) of the // argument whose size we want. using ComputeSizeFunction = - llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; + llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>; // Accepts the argument index (relative to the first destination index), the // destination size, and the source size). @@ -836,7 +836,8 @@ public: unsigned SourceSize = FW.getConstantAmount() + NulByte; - Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); + std::optional<llvm::APSInt> DestSizeAPS = + ComputeSizeArgument(FS.getArgIndex()); if (!DestSizeAPS) return true; @@ -1054,7 +1055,7 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, const TargetInfo &TI = getASTContext().getTargetInfo(); unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); - auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { + auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> { // If we refer to a diagnose_as_builtin attribute, we need to change the // argument index to refer to the arguments of the called function. Unless // the index is out of bounds, which presumably means it's a variadic @@ -1071,8 +1072,8 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, }; auto ComputeExplicitObjectSizeArgument = - [&](unsigned Index) -> Optional<llvm::APSInt> { - Optional<unsigned> IndexOptional = TranslateIndex(Index); + [&](unsigned Index) -> std::optional<llvm::APSInt> { + std::optional<unsigned> IndexOptional = TranslateIndex(Index); if (!IndexOptional) return std::nullopt; unsigned NewIndex = *IndexOptional; @@ -1085,7 +1086,8 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, return Integer; }; - auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { + auto ComputeSizeArgument = + [&](unsigned Index) -> std::optional<llvm::APSInt> { // If the parameter has a pass_object_size attribute, then we should use its // (potentially) more strict checking mode. Otherwise, conservatively assume // type 0. @@ -1097,7 +1099,7 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, BOSType = POS->getType(); } - Optional<unsigned> IndexOptional = TranslateIndex(Index); + std::optional<unsigned> IndexOptional = TranslateIndex(Index); if (!IndexOptional) return std::nullopt; unsigned NewIndex = *IndexOptional; @@ -1114,8 +1116,9 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); }; - auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { - Optional<unsigned> IndexOptional = TranslateIndex(Index); + auto ComputeStrLenArgument = + [&](unsigned Index) -> std::optional<llvm::APSInt> { + std::optional<unsigned> IndexOptional = TranslateIndex(Index); if (!IndexOptional) return std::nullopt; unsigned NewIndex = *IndexOptional; @@ -1128,8 +1131,8 @@ void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); }; - Optional<llvm::APSInt> SourceSize; - Optional<llvm::APSInt> DestinationSize; + std::optional<llvm::APSInt> SourceSize; + std::optional<llvm::APSInt> DestinationSize; unsigned DiagID = 0; bool IsChkVariant = false; @@ -1908,14 +1911,14 @@ static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { TheCall->setType(ParamTy); - auto DiagSelect = [&]() -> llvm::Optional<unsigned> { + auto DiagSelect = [&]() -> std::optional<unsigned> { if (!ParamTy->isPointerType()) return 0; if (ParamTy->isFunctionPointerType()) return 1; if (ParamTy->isVoidPointerType()) return 2; - return llvm::Optional<unsigned>{}; + return std::optional<unsigned>{}; }(); if (DiagSelect) { S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) @@ -3439,7 +3442,7 @@ bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, // The second argument needs to be a constant int Expr *Arg = TheCall->getArg(1); - Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); + std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); diag::kind kind; if (!Value) { if (BuiltinID == BPF::BI__builtin_preserve_field_info) @@ -4638,7 +4641,8 @@ bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { if (BuiltinID == SystemZ::BI__builtin_tabort) { Expr *Arg = TheCall->getArg(0); - if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) + if (std::optional<llvm::APSInt> AbortCode = + Arg->getIntegerConstantExpr(Context)) if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) << Arg->getSourceRange(); @@ -6655,7 +6659,7 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, } if (SubExprs.size() >= 2 && Form != Init) { - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = SubExprs[1]->getIntegerConstantExpr(Context)) if (!isValidOrderingForOp(Result->getSExtValue(), Op)) Diag(SubExprs[1]->getBeginLoc(), @@ -6665,7 +6669,7 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { auto *Scope = Args[Args.size() - 1]; - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = Scope->getIntegerConstantExpr(Context)) { if (!ScopeModel->isValid(Result->getZExtValue())) Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) @@ -7335,7 +7339,7 @@ bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { // check. bool SecondArgIsLastNamedArgument = false; const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); - if (Optional<llvm::APSInt> Val = + if (std::optional<llvm::APSInt> Val = TheCall->getArg(1)->getIntegerConstantExpr(Context); Val && LangOpts.C2x && *Val == 0) return false; @@ -7690,7 +7694,7 @@ ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { TheCall->getArg(i)->isValueDependent()) continue; - Optional<llvm::APSInt> Result; + std::optional<llvm::APSInt> Result; if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) return ExprError(Diag(TheCall->getBeginLoc(), diag::err_shufflevector_nonconstant_argument) @@ -7976,7 +7980,7 @@ bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; - Optional<llvm::APSInt> R; + std::optional<llvm::APSInt> R; if (!(R = Arg->getIntegerConstantExpr(Context))) return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) << FDecl->getDeclName() << Arg->getSourceRange(); @@ -9318,7 +9322,7 @@ void CheckFormatHandler::HandleInvalidLengthModifier( CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); // See if we know how to fix this length modifier. - Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); + std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); if (FixedLM) { EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), getLocationOfByte(LM.getStart()), @@ -9351,7 +9355,7 @@ void CheckFormatHandler::HandleNonStandardLengthModifier( CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); // See if we know how to fix this length modifier. - Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); + std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); if (FixedLM) { EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString() << 0, @@ -9378,7 +9382,7 @@ void CheckFormatHandler::HandleNonStandardConversionSpecifier( using namespace analyze_format_string; // See if we know how to fix this conversion specifier. - Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); + std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); if (FixedCS) { EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() << /*conversion specifier*/1, @@ -12574,7 +12578,7 @@ static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, // If the shift amount is a positive constant, drop the width by // that much. - if (Optional<llvm::APSInt> shift = + if (std::optional<llvm::APSInt> shift = BO->getRHS()->getIntegerConstantExpr(C)) { if (shift->isNonNegative()) { unsigned zext = shift->getZExtValue(); @@ -12619,7 +12623,7 @@ static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, Approximate); // If the divisor is constant, use that. - if (Optional<llvm::APSInt> divisor = + if (std::optional<llvm::APSInt> divisor = BO->getRHS()->getIntegerConstantExpr(C)) { unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) if (log2 >= L.Width) @@ -12849,7 +12853,7 @@ struct PromotedRange { llvm_unreachable("impossible compare result"); } - static llvm::Optional<StringRef> + static std::optional<StringRef> constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { if (Op == BO_Cmp) { ComparisonResult LTFlag = LT, GTFlag = GT; @@ -13093,8 +13097,10 @@ static void AnalyzeComparison(Sema &S, BinaryOperator *E) { Expr *RHS = E->getRHS(); if (T->isIntegralType(S.Context)) { - Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); - Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); + std::optional<llvm::APSInt> RHSValue = + RHS->getIntegerConstantExpr(S.Context); + std::optional<llvm::APSInt> LHSValue = + LHS->getIntegerConstantExpr(S.Context); // We don't care about expressions whose result is a constant. if (RHSValue && LHSValue) @@ -14103,7 +14109,7 @@ static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, if (SourcePrecision > 0 && TargetPrecision > 0 && SourcePrecision > TargetPrecision) { - if (Optional<llvm::APSInt> SourceInt = + if (std::optional<llvm::APSInt> SourceInt = E->getIntegerConstantExpr(S.Context)) { // If the source integer is a constant, convert it to the target // floating point type. Issue a warning if the value changes @@ -15829,8 +15835,11 @@ bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, return HasInvalidParm; } -Optional<std::pair<CharUnits, CharUnits>> -static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); +std::optional<std::pair< + CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr + *E, + ASTContext + &Ctx); /// Compute the alignment and offset of the base class object given the /// derived-to-base cast expression and the alignment and offset of the derived @@ -15864,7 +15873,7 @@ getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, } /// Compute the alignment and offset of a binary additive operator. -static Optional<std::pair<CharUnits, CharUnits>> +static std::optional<std::pair<CharUnits, CharUnits>> getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx) { QualType PointeeType = PtrE->getType()->getPointeeType(); @@ -15878,7 +15887,7 @@ getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, return std::nullopt; CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); - if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { + if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { CharUnits Offset = EltSize * IdxRes->getExtValue(); if (IsSub) Offset = -Offset; @@ -15895,8 +15904,10 @@ getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, /// This helper function takes an lvalue expression and returns the alignment of /// a VarDecl and a constant offset from the VarDecl. -Optional<std::pair<CharUnits, CharUnits>> -static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { +std::optional<std::pair< + CharUnits, + CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E, + ASTContext &Ctx) { E = E->IgnoreParens(); switch (E->getStmtClass()) { default: @@ -15944,7 +15955,7 @@ static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { if (!FD || FD->getType()->isReferenceType() || FD->getParent()->isInvalidDecl()) break; - Optional<std::pair<CharUnits, CharUnits>> P; + std::optional<std::pair<CharUnits, CharUnits>> P; if (ME->isArrow()) P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); else @@ -15983,8 +15994,11 @@ static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { /// This helper function takes a pointer expression and returns the alignment of /// a VarDecl and a constant offset from the VarDecl. -Optional<std::pair<CharUnits, CharUnits>> -static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { +std::optional<std::pair< + CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr + *E, + ASTContext + &Ctx) { E = E->IgnoreParens(); switch (E->getStmtClass()) { default: @@ -16048,7 +16062,7 @@ static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { // See if we can compute the alignment of a VarDecl and an offset from it. - Optional<std::pair<CharUnits, CharUnits>> P = + std::optional<std::pair<CharUnits, CharUnits>> P = getBaseAlignmentAndOffsetFromPtr(E, S.Context); if (P) @@ -16151,7 +16165,7 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, EffectiveType->getCanonicalTypeInternal().getAddressSpace()); if (index.getBitWidth() < AddrBits) index = index.zext(AddrBits); - Optional<CharUnits> ElemCharUnits = + std::optional<CharUnits> ElemCharUnits = ASTC.getTypeSizeInCharsIfKnown(EffectiveType); // PR50741 - If EffectiveType has unknown size (e.g., if it's a void // pointer) bounds-checking isn't meaningful. @@ -16523,7 +16537,7 @@ namespace { return; if (Expr *RHS = BinOp->getRHS()) { RHS = RHS->IgnoreParenCasts(); - Optional<llvm::APSInt> Value; + std::optional<llvm::APSInt> Value; VarWillBeReased = (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && *Value == 0); @@ -16604,8 +16618,8 @@ static bool isSetterLikeSelector(Selector sel) { return !isLowercase(str.front()); } -static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, - ObjCMessageExpr *Message) { +static std::optional<int> +GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message) { bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( Message->getReceiverInterface(), NSAPI::ClassId_NSMutableArray); @@ -16615,8 +16629,8 @@ static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, Selector Sel = Message->getSelector(); - Optional<NSAPI::NSArrayMethodKind> MKOpt = - S.NSAPIObj->getNSArrayMethodKind(Sel); + std::optional<NSAPI::NSArrayMethodKind> MKOpt = + S.NSAPIObj->getNSArrayMethodKind(Sel); if (!MKOpt) { return std::nullopt; } @@ -16638,9 +16652,8 @@ static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, return std::nullopt; } -static -Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, - ObjCMessageExpr *Message) { +static std::optional<int> +GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message) { bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( Message->getReceiverInterface(), NSAPI::ClassId_NSMutableDictionary); @@ -16650,8 +16663,8 @@ Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, Selector Sel = Message->getSelector(); - Optional<NSAPI::NSDictionaryMethodKind> MKOpt = - S.NSAPIObj->getNSDictionaryMethodKind(Sel); + std::optional<NSAPI::NSDictionaryMethodKind> MKOpt = + S.NSAPIObj->getNSDictionaryMethodKind(Sel); if (!MKOpt) { return std::nullopt; } @@ -16671,7 +16684,8 @@ Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, return std::nullopt; } -static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { +static std::optional<int> GetNSSetArgumentIndex(Sema &S, + ObjCMessageExpr *Message) { bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( Message->getReceiverInterface(), NSAPI::ClassId_NSMutableSet); @@ -16685,7 +16699,8 @@ static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { Selector Sel = Message->getSelector(); - Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); + std::optional<NSAPI::NSSetMethodKind> MKOpt = + S.NSAPIObj->getNSSetMethodKind(Sel); if (!MKOpt) { return std::nullopt; } @@ -16710,7 +16725,7 @@ void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { return; } - Optional<int> ArgOpt; + std::optional<int> ArgOpt; if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && @@ -17816,10 +17831,10 @@ ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, } // Get and verify the matrix dimensions. -static llvm::Optional<unsigned> +static std::optional<unsigned> getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { SourceLocation ErrorPos; - Optional<llvm::APSInt> Value = + std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context, &ErrorPos); if (!Value) { S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) @@ -17916,11 +17931,11 @@ ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, } // Check row and column dimensions. - llvm::Optional<unsigned> MaybeRows; + std::optional<unsigned> MaybeRows; if (RowsExpr) MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); - llvm::Optional<unsigned> MaybeColumns; + std::optional<unsigned> MaybeColumns; if (ColumnsExpr) MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); @@ -17932,7 +17947,7 @@ ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, TheCall->setArg(3, StrideExpr); if (MaybeRows) { - if (Optional<llvm::APSInt> Value = + if (std::optional<llvm::APSInt> Value = StrideExpr->getIntegerConstantExpr(Context)) { uint64_t Stride = Value->getZExtValue(); if (Stride < *MaybeRows) { @@ -18032,7 +18047,7 @@ ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, // Check stride argument. if (MatrixTy) { - if (Optional<llvm::APSInt> Value = + if (std::optional<llvm::APSInt> Value = StrideExpr->getIntegerConstantExpr(Context)) { uint64_t Stride = Value->getZExtValue(); if (Stride < MatrixTy->getNumRows()) { diff --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp index 0bc264c..144bbe1 100644 --- a/clang/lib/Sema/SemaCodeComplete.cpp +++ b/clang/lib/Sema/SemaCodeComplete.cpp @@ -2851,17 +2851,16 @@ static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, } } -static std::string -formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, - FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, - bool SuppressBlockName = false, - bool SuppressBlock = false, - Optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt); +static std::string formatBlockPlaceholder( + const PrintingPolicy &Policy, const NamedDecl *BlockDecl, + FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, + bool SuppressBlockName = false, bool SuppressBlock = false, + std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt); static std::string FormatFunctionParameter( const PrintingPolicy &Policy, const DeclaratorDecl *Param, bool SuppressName = false, bool SuppressBlock = false, - Optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) { + std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) { // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid. // It would be better to pass in the param Type, which is usually available. // But this case is rare, so just pretend we fell back to int as elsewhere. @@ -2956,7 +2955,7 @@ static std::string formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, bool SuppressBlockName, bool SuppressBlock, - Optional<ArrayRef<QualType>> ObjCSubsts) { + std::optional<ArrayRef<QualType>> ObjCSubsts) { std::string Result; QualType ResultType = Block.getTypePtr()->getReturnType(); if (ObjCSubsts) @@ -3625,7 +3624,7 @@ CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl( std::string Arg; QualType ParamType = (*P)->getType(); - Optional<ArrayRef<QualType>> ObjCSubsts; + std::optional<ArrayRef<QualType>> ObjCSubsts; if (!CCContext.getBaseType().isNull()) ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); @@ -5082,9 +5081,11 @@ AddObjCProperties(const CodeCompletionContext &CCContext, } } -static void AddRecordMembersCompletionResults( - Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType, - ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) { +static void +AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, + Scope *S, QualType BaseType, + ExprValueKind BaseKind, RecordDecl *RD, + std::optional<FixItHint> AccessOpFixIt) { // Indicate that we are performing a member access, and the cv-qualifiers // for the base object type. Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind); @@ -5183,7 +5184,7 @@ public: // We don't have the declared parameter types, only the actual types of // arguments we've seen. These are still valuable, as it's hard to render // a useful function completion with neither parameter types nor names! - llvm::Optional<SmallVector<QualType, 1>> ArgTypes; + std::optional<SmallVector<QualType, 1>> ArgTypes; // Whether this is accessed as T.member, T->member, or T::member. enum AccessOperator { Colons, @@ -5650,7 +5651,7 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, &ResultBuilder::IsMember); auto DoCompletion = [&](Expr *Base, bool IsArrow, - Optional<FixItHint> AccessOpFixIt) -> bool { + std::optional<FixItHint> AccessOpFixIt) -> bool { if (!Base) return false; @@ -6208,7 +6209,7 @@ QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, // Returns an out-of-range index. // - we saw no designators, just positional arguments. // Returns std::nullopt. -static llvm::Optional<unsigned> +static std::optional<unsigned> getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, ArrayRef<Expr *> Args) { static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max(); @@ -8722,7 +8723,7 @@ typedef llvm::DenseMap<Selector, /// indexed by selector so they can be easily found. static void FindImplementableMethods(ASTContext &Context, ObjCContainerDecl *Container, - Optional<bool> WantInstanceMethods, + std::optional<bool> WantInstanceMethods, QualType ReturnType, KnownMethodsMap &KnownMethods, bool InOriginalClass = true) { @@ -9446,7 +9447,8 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, } } -void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, +void Sema::CodeCompleteObjCMethodDecl(Scope *S, + std::optional<bool> IsInstanceMethod, ParsedType ReturnTy) { // Determine the return type of the method we're declaring, if // provided. diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp index 6b3bb0d..fa5509f 100644 --- a/clang/lib/Sema/SemaConcept.cpp +++ b/clang/lib/Sema/SemaConcept.cpp @@ -501,7 +501,7 @@ bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr, } bool Sema::SetupConstraintScope( - FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, + FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) { if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) { FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate(); @@ -564,9 +564,9 @@ bool Sema::SetupConstraintScope( // This function collects all of the template arguments for the purposes of // constraint-instantiation and checking. -llvm::Optional<MultiLevelTemplateArgumentList> +std::optional<MultiLevelTemplateArgumentList> Sema::SetupConstraintCheckingTemplateArgumentsAndScope( - FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, + FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, LocalInstantiationScope &Scope) { MultiLevelTemplateArgumentList MLTAL; @@ -611,7 +611,7 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD, ContextRAII SavedContext{*this, CtxToSave}; LocalInstantiationScope Scope(*this, !ForOverloadResolution || isLambdaCallOperator(FD)); - llvm::Optional<MultiLevelTemplateArgumentList> MLTAL = + std::optional<MultiLevelTemplateArgumentList> MLTAL = SetupConstraintCheckingTemplateArgumentsAndScope( const_cast<FunctionDecl *>(FD), {}, Scope); @@ -786,7 +786,7 @@ bool Sema::CheckInstantiatedFunctionTemplateConstraints( Sema::ContextRAII savedContext(*this, Decl); LocalInstantiationScope Scope(*this); - Optional<MultiLevelTemplateArgumentList> MLTAL = + std::optional<MultiLevelTemplateArgumentList> MLTAL = SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs, Scope); @@ -1150,7 +1150,7 @@ static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N, CSE->getTemplateArgsAsWritten()); } -Optional<NormalizedConstraint> +std::optional<NormalizedConstraint> NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef<const Expr *> E) { assert(E.size() != 0); @@ -1167,7 +1167,7 @@ NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D, return Conjunction; } -llvm::Optional<NormalizedConstraint> +std::optional<NormalizedConstraint> NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) { assert(E != nullptr); @@ -1215,7 +1215,7 @@ NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) { return std::nullopt; } - Optional<NormalizedConstraint> New; + std::optional<NormalizedConstraint> New; New.emplace(S.Context, *SubNF); if (substituteParameterMappings(S, *New, CSE)) diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 44657a1..072bc9b 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -2221,7 +2221,7 @@ void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { /// and sort the diagnostics before emitting them, after we visited all decls. struct LocAndDiag { SourceLocation Loc; - Optional<SourceLocation> PreviousDeclLoc; + std::optional<SourceLocation> PreviousDeclLoc; PartialDiagnostic PD; }; SmallVector<LocAndDiag, 16> DeclDiags; @@ -13954,7 +13954,7 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { } // Cache the result of checking for constant initialization. - Optional<bool> CacheHasConstInit; + std::optional<bool> CacheHasConstInit; const Expr *CacheCulprit = nullptr; auto checkConstInit = [&]() mutable { if (!CacheHasConstInit) @@ -14379,7 +14379,7 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) { if (!MagicValueExpr) { continue; } - Optional<llvm::APSInt> MagicValueInt; + std::optional<llvm::APSInt> MagicValueInt; if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { Diag(I->getRange().getBegin(), diag::err_type_tag_for_datatype_not_ice) @@ -15986,7 +15986,7 @@ void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) return; - Optional<unsigned> AlignmentParam; + std::optional<unsigned> AlignmentParam; bool IsNothrow = false; if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) return; @@ -19850,7 +19850,7 @@ Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, if (LangOpts.OpenMPIsDevice) { // In OpenMP device mode we will not emit host only functions, or functions // we don't need due to their linkage. - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); // DevTy may be changed later by // #pragma omp declare target to(*) device_type(*). @@ -19872,7 +19872,7 @@ Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, // In OpenMP host compilation prior to 5.0 everything was an emitted host // function. In 5.0, no_host was introduced which might cause a function to // be ommitted. - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); if (DevTy) if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 9032205..ce028d5 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -218,7 +218,7 @@ template <typename AttrInfo> static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx = UINT_MAX, bool StrictlyUnsigned = false) { - Optional<llvm::APSInt> I = llvm::APSInt(32); + std::optional<llvm::APSInt> I = llvm::APSInt(32); if (Expr->isTypeDependent() || !(I = Expr->getIntegerConstantExpr(S.Context))) { if (Idx != UINT_MAX) @@ -310,7 +310,7 @@ static bool checkFunctionOrMethodParameterIndex( unsigned NumParams = (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; - Optional<llvm::APSInt> IdxInt; + std::optional<llvm::APSInt> IdxInt; if (IdxExpr->isTypeDependent() || !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) { S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) @@ -1691,7 +1691,7 @@ void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, } if (!E->isValueDependent()) { - Optional<llvm::APSInt> I = llvm::APSInt(64); + std::optional<llvm::APSInt> I = llvm::APSInt(64); if (!(I = E->getIntegerConstantExpr(Context))) { if (OE) Diag(AttrLoc, diag::err_attribute_argument_n_type) @@ -3038,7 +3038,7 @@ static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; if (AL.getNumArgs() > 0) { Expr *E = AL.getArgAsExpr(0); - Optional<llvm::APSInt> Idx = llvm::APSInt(32); + std::optional<llvm::APSInt> Idx = llvm::APSInt(32); if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); @@ -3057,7 +3057,7 @@ static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; if (AL.getNumArgs() > 1) { Expr *E = AL.getArgAsExpr(1); - Optional<llvm::APSInt> Idx = llvm::APSInt(32); + std::optional<llvm::APSInt> Idx = llvm::APSInt(32); if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); @@ -5506,7 +5506,7 @@ static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, if (E->isValueDependent()) return E; - Optional<llvm::APSInt> I = llvm::APSInt(64); + std::optional<llvm::APSInt> I = llvm::APSInt(64); if (!(I = E->getIntegerConstantExpr(S.Context))) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); @@ -6552,9 +6552,9 @@ validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc, } StringRef CurrentParam; - llvm::Optional<unsigned> SelfLocation; + std::optional<unsigned> SelfLocation; unsigned NewValueCount = 0; - llvm::Optional<unsigned> NewValueLocation; + std::optional<unsigned> NewValueLocation; do { std::tie(CurrentParam, Parameters) = Parameters.split(':'); @@ -7290,7 +7290,7 @@ static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { } Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); - Optional<llvm::APSInt> NumParams = llvm::APSInt(32); + std::optional<llvm::APSInt> NumParams = llvm::APSInt(32); if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIntegerConstant diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index 0c8cb7b..ea52b70 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -8056,7 +8056,7 @@ private: "invalid builtin comparison"); if (NeedsDeducing) { - Optional<ComparisonCategoryType> Cat = + std::optional<ComparisonCategoryType> Cat = getComparisonCategoryForBuiltinCmp(T); assert(Cat && "no category for builtin comparison?"); R.Category = *Cat; diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp b/clang/lib/Sema/SemaExceptionSpec.cpp index 6fe0575..a5a57c3 100644 --- a/clang/lib/Sema/SemaExceptionSpec.cpp +++ b/clang/lib/Sema/SemaExceptionSpec.cpp @@ -1548,7 +1548,7 @@ CanThrowResult Sema::canThrow(const Stmt *S) { // For 'if constexpr', consider only the non-discarded case. // FIXME: We should add a DiscardedStmt marker to the AST. - if (Optional<const Stmt *> Case = IS->getNondiscardedCase(Context)) + if (std::optional<const Stmt *> Case = IS->getNondiscardedCase(Context)) return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT; CanThrowResult Then = canThrow(IS->getThen()); diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 710befe..d90c284 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -5015,7 +5015,7 @@ ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, return nullptr; } - if (Optional<llvm::APSInt> Idx = + if (std::optional<llvm::APSInt> Idx = IndexExpr->getIntegerConstantExpr(Context)) { if ((*Idx < 0 || *Idx >= Dim)) { Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) @@ -5438,7 +5438,8 @@ ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, IsCorrect = false; continue; } - Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); + std::optional<llvm::APSInt> Result = + Step->getIntegerConstantExpr(Context); // OpenMP 5.0, 2.1.6 Iterators, Restrictions // If the step expression of a range-specification equals zero, the // behavior is unspecified. @@ -5984,7 +5985,7 @@ ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); - llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> + std::optional<ExpressionEvaluationContextRecord::InitializationContext> InitializationContext = OutermostDeclarationWithDelayedImmediateInvocations(); if (!InitializationContext.has_value()) @@ -6042,7 +6043,7 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { auto *ParentRD = cast<CXXRecordDecl>(Field->getParent()); - llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> + std::optional<ExpressionEvaluationContextRecord::InitializationContext> InitializationContext = OutermostDeclarationWithDelayedImmediateInvocations(); if (!InitializationContext.has_value()) @@ -6520,9 +6521,10 @@ Sema::CheckStaticArrayArgument(SourceLocation CallLoc, return; } - Optional<CharUnits> ArgSize = + std::optional<CharUnits> ArgSize = getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); - Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); + std::optional<CharUnits> ParmSize = + getASTContext().getTypeSizeInCharsIfKnown(CAT); if (ArgSize && ParmSize && *ArgSize < *ParmSize) { Diag(CallLoc, diag::warn_static_array_too_small) << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() @@ -9301,7 +9303,7 @@ static QualType computeConditionalNullability(QualType ResTy, bool IsBin, return ResTy; auto GetNullability = [](QualType Ty) { - Optional<NullabilityKind> Kind = Ty->getNullability(); + std::optional<NullabilityKind> Kind = Ty->getNullability(); if (Kind) { // For our purposes, treat _Nullable_result as _Nullable. if (*Kind == NullabilityKind::NullableResult) @@ -12539,7 +12541,7 @@ static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, if (Type.isNull()) return S.InvalidOperands(Loc, LHS, RHS); - Optional<ComparisonCategoryType> CCT = + std::optional<ComparisonCategoryType> CCT = getComparisonCategoryForBuiltinCmp(Type); if (!CCT) return S.InvalidOperands(Loc, LHS, RHS); @@ -12683,7 +12685,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, QualType CompositeTy = LHS.get()->getType(); assert(!CompositeTy->isReferenceType()); - Optional<ComparisonCategoryType> CCT = + std::optional<ComparisonCategoryType> CCT = getComparisonCategoryForBuiltinCmp(CompositeTy); if (!CCT) return InvalidOperands(Loc, LHS, RHS); @@ -21125,7 +21127,8 @@ Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { ExprResult Sema::ActOnObjCAvailabilityCheckExpr( llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen) { - auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { + auto FindSpecVersion = + [&](StringRef Platform) -> std::optional<VersionTuple> { auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { return Spec.getPlatform() == Platform; }); diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 08dd6f7..4e9541a 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -1850,7 +1850,7 @@ Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer) { - Optional<Expr *> ArraySize; + std::optional<Expr *> ArraySize; // If the specified type is an array, unwrap it and save the expression. if (D.getNumTypeObjects() > 0 && D.getTypeObject(0).Kind == DeclaratorChunk::Array) { @@ -1942,7 +1942,7 @@ Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { return false; if (FD.isDefined()) return false; - Optional<unsigned> AlignmentParam; + std::optional<unsigned> AlignmentParam; if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && AlignmentParam) return true; @@ -1968,17 +1968,14 @@ void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, } } -ExprResult -Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, - SourceLocation PlacementLParen, - MultiExprArg PlacementArgs, - SourceLocation PlacementRParen, - SourceRange TypeIdParens, - QualType AllocType, - TypeSourceInfo *AllocTypeInfo, - Optional<Expr *> ArraySize, - SourceRange DirectInitRange, - Expr *Initializer) { +ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, + SourceLocation PlacementLParen, + MultiExprArg PlacementArgs, + SourceLocation PlacementRParen, + SourceRange TypeIdParens, QualType AllocType, + TypeSourceInfo *AllocTypeInfo, + std::optional<Expr *> ArraySize, + SourceRange DirectInitRange, Expr *Initializer) { SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); SourceLocation StartLoc = Range.getBegin(); @@ -2121,7 +2118,7 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, // conversion function to integral or unscoped enumeration type exists. // C++1y [expr.new]p6: The expression [...] is implicitly converted to // std::size_t. - llvm::Optional<uint64_t> KnownArraySize; + std::optional<uint64_t> KnownArraySize; if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { ExprResult ConvertedSize; if (getLangOpts().CPlusPlus14) { @@ -2215,7 +2212,7 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, // FIXME: Per CWG1464, we are required to check the value prior to // converting to size_t. This will never find a negative array size in // C++14 onwards, because Value is always unsigned here! - if (Optional<llvm::APSInt> Value = + if (std::optional<llvm::APSInt> Value = (*ArraySize)->getIntegerConstantExpr(Context)) { if (Value->isSigned() && Value->isNegative()) { return ExprError(Diag((*ArraySize)->getBeginLoc(), @@ -2302,7 +2299,7 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); // How many bytes do we want to allocate here? - llvm::Optional<llvm::APInt> AllocationSize; + std::optional<llvm::APInt> AllocationSize; if (!ArraySize && !AllocType->isDependentType()) { // For non-array operator new, we only want to allocate one element. AllocationSize = SingleEltSize; @@ -8306,7 +8303,7 @@ static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( // If we have a capture-capable lambda for the variable, go ahead and // capture the variable in that lambda (and all its enclosing lambdas). - if (const Optional<unsigned> Index = + if (const std::optional<unsigned> Index = getStackIndexOfNearestEnclosingCaptureCapableLambda( S.FunctionScopes, Var, S)) S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index); @@ -8339,7 +8336,7 @@ static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( if (CurrentLSI->hasPotentialThisCapture()) { // If we have a capture-capable lambda for 'this', go ahead and capture // 'this' in that lambda (and all its enclosing lambdas). - if (const Optional<unsigned> Index = + if (const std::optional<unsigned> Index = getStackIndexOfNearestEnclosingCaptureCapableLambda( S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { const unsigned FunctionScopeIndexOfCapturableLambda = *Index; diff --git a/clang/lib/Sema/SemaExprObjC.cpp b/clang/lib/Sema/SemaExprObjC.cpp index abd104b..a437234 100644 --- a/clang/lib/Sema/SemaExprObjC.cpp +++ b/clang/lib/Sema/SemaExprObjC.cpp @@ -244,7 +244,7 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, QualType NumberType, bool isLiteral = false, SourceRange R = SourceRange()) { - Optional<NSAPI::NSNumberLiteralMethodKind> Kind = + std::optional<NSAPI::NSNumberLiteralMethodKind> Kind = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); if (!Kind) { @@ -592,7 +592,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { BoxingMethod = StringWithUTF8StringMethod; BoxedType = NSStringPointer; // Transfer the nullability from method's return type. - Optional<NullabilityKind> Nullability = + std::optional<NullabilityKind> Nullability = BoxingMethod->getReturnType()->getNullability(); if (Nullability) BoxedType = Context.getAttributedType( @@ -1561,14 +1561,16 @@ QualType Sema::getMessageSendResultType(const Expr *Receiver, // Map the nullability of the result into a table index. unsigned receiverNullabilityIdx = 0; - if (Optional<NullabilityKind> nullability = ReceiverType->getNullability()) { + if (std::optional<NullabilityKind> nullability = + ReceiverType->getNullability()) { if (*nullability == NullabilityKind::NullableResult) nullability = NullabilityKind::Nullable; receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability); } unsigned resultNullabilityIdx = 0; - if (Optional<NullabilityKind> nullability = resultType->getNullability()) { + if (std::optional<NullabilityKind> nullability = + resultType->getNullability()) { if (*nullability == NullabilityKind::NullableResult) nullability = NullabilityKind::Nullable; resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability); @@ -1804,8 +1806,8 @@ bool Sema::CheckMessageArgumentTypes( // Compute the set of type arguments to be substituted into each parameter // type. - Optional<ArrayRef<QualType>> typeArgs - = ReceiverType->getObjCSubstitutions(Method->getDeclContext()); + std::optional<ArrayRef<QualType>> typeArgs = + ReceiverType->getObjCSubstitutions(Method->getDeclContext()); bool IsError = false; for (unsigned i = 0; i < NumNamedArgs; i++) { // We can't do any type-checking on a type-dependent argument. diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp index 1e4b638..00ab6ba 100644 --- a/clang/lib/Sema/SemaLambda.cpp +++ b/clang/lib/Sema/SemaLambda.cpp @@ -55,17 +55,17 @@ using namespace sema; /// is at the top of the stack and has the highest index. /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. /// -/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains -/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda -/// which is capture-ready. If the return value evaluates to 'false' then -/// no lambda is capture-ready for \p VarToCapture. +/// \returns An std::optional<unsigned> Index that if evaluates to 'true' +/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost +/// lambda which is capture-ready. If the return value evaluates to 'false' +/// then no lambda is capture-ready for \p VarToCapture. -static inline Optional<unsigned> +static inline std::optional<unsigned> getStackIndexOfNearestEnclosingCaptureReadyLambda( ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, ValueDecl *VarToCapture) { // Label failure to capture. - const Optional<unsigned> NoLambdaIsCaptureReady; + const std::optional<unsigned> NoLambdaIsCaptureReady; // Ignore all inner captured regions. unsigned CurScopeIndex = FunctionScopes.size() - 1; @@ -166,18 +166,19 @@ getStackIndexOfNearestEnclosingCaptureReadyLambda( /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. /// /// -/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains -/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda -/// which is capture-capable. If the return value evaluates to 'false' then -/// no lambda is capture-capable for \p VarToCapture. +/// \returns An std::optional<unsigned> Index that if evaluates to 'true' +/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost +/// lambda which is capture-capable. If the return value evaluates to 'false' +/// then no lambda is capture-capable for \p VarToCapture. -Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( +std::optional<unsigned> +clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, ValueDecl *VarToCapture, Sema &S) { - const Optional<unsigned> NoLambdaIsCaptureCapable; + const std::optional<unsigned> NoLambdaIsCaptureCapable; - const Optional<unsigned> OptionalStackIndex = + const std::optional<unsigned> OptionalStackIndex = getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, VarToCapture); if (!OptionalStackIndex) @@ -434,7 +435,7 @@ CXXMethodDecl *Sema::startLambdaDefinition( void Sema::handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, - Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) { + std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) { if (Mangling) { bool HasKnownInternalLinkage; unsigned ManglingNumber, DeviceManglingNumber; @@ -796,8 +797,8 @@ void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { QualType Sema::buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit, - Expr *&Init) { + std::optional<unsigned> NumExpansions, IdentifierInfo *Id, + bool IsDirectInit, Expr *&Init) { // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to // deduce against. QualType DeductType = Context.getAutoDeductType(); diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp index cea8b42..b2e94369 100644 --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -527,7 +527,7 @@ void LookupResult::resolveKind() { continue; } - llvm::Optional<unsigned> ExistingI; + std::optional<unsigned> ExistingI; // Redeclarations of types via typedef can occur both within a scope // and, through using declarations and directives, across scopes. There is diff --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp index 60b4a86..64dce281 100644 --- a/clang/lib/Sema/SemaModule.cpp +++ b/clang/lib/Sema/SemaModule.cpp @@ -827,7 +827,7 @@ enum class UnnamedDeclKind { }; } -static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) { +static std::optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) { if (isa<EmptyDecl>(D)) return UnnamedDeclKind::Empty; if (isa<StaticAssertDecl>(D)) diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index 09c21a4..2ab6cba 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -173,7 +173,7 @@ private: /// First argument (Expr *) contains optional argument of the /// 'ordered' clause, the second one is true if the regions has 'ordered' /// clause, false otherwise. - llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; + std::optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; bool RegionHasOrderConcurrent = false; unsigned AssociatedLoops = 1; bool HasMutipleLoops = false; @@ -1127,15 +1127,16 @@ public: } /// Checks if specified decl is used in uses allocator clause as the /// allocator. - Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, - const Decl *D) const { + std::optional<UsesAllocatorsDeclKind> + isUsesAllocatorsDecl(unsigned Level, const Decl *D) const { const SharingMapTy &StackElem = getTopOfStack(); auto I = StackElem.UsesAllocatorsDecls.find(D); if (I == StackElem.UsesAllocatorsDecls.end()) return std::nullopt; return I->getSecond(); } - Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { + std::optional<UsesAllocatorsDeclKind> + isUsesAllocatorsDecl(const Decl *D) const { const SharingMapTy &StackElem = getTopOfStack(); auto I = StackElem.UsesAllocatorsDecls.find(D); if (I == StackElem.UsesAllocatorsDecls.end()) @@ -2678,7 +2679,7 @@ void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc) { assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); // Ignore host functions during device analyzis. if (LangOpts.OpenMPIsDevice && @@ -2710,7 +2711,7 @@ void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, Callee->specific_attrs<OMPDeclareVariantAttr>()) { auto *DeclRefVariant = cast<DeclRefExpr>(A->getVariantFuncRef()); auto *VariantFD = cast<FunctionDecl>(DeclRefVariant->getDecl()); - Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = + std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = OMPDeclareTargetDeclAttr::getDeviceType( VariantFD->getMostRecentDecl()); if (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host) @@ -3730,7 +3731,7 @@ public: return; // Skip internally declared static variables. - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || @@ -7333,7 +7334,7 @@ ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); } -Optional<std::pair<FunctionDecl *, Expr *>> +std::optional<std::pair<FunctionDecl *, Expr *>> Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, @@ -7813,7 +7814,7 @@ class OpenMPIterationSpaceChecker { /// UB > Var /// UB >= Var /// This will have no value when the condition is != - llvm::Optional<bool> TestIsLessOp; + std::optional<bool> TestIsLessOp; /// This flag is true when condition is strict ( < or > ). bool TestIsStrictOp = false; /// This flag is true when step is subtracted on each iteration. @@ -7822,12 +7823,13 @@ class OpenMPIterationSpaceChecker { const ValueDecl *DepDecl = nullptr; /// Contains number of loop (starts from 1) on which loop counter init /// expression of this loop depends on. - Optional<unsigned> InitDependOnLC; + std::optional<unsigned> InitDependOnLC; /// Contains number of loop (starts from 1) on which loop counter condition /// expression of this loop depends on. - Optional<unsigned> CondDependOnLC; + std::optional<unsigned> CondDependOnLC; /// Checks if the provide statement depends on the loop counter. - Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); + std::optional<unsigned> doesDependOnLoopCounter(const Stmt *S, + bool IsInitializer); /// Original condition required for checking of the exit condition for /// non-rectangular loop. Expr *Condition = nullptr; @@ -7910,7 +7912,7 @@ private: bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, bool EmitDiags); /// Helper to set upper bound. - bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, + bool setUB(Expr *NewUB, std::optional<bool> LessOp, bool StrictOp, SourceRange SR, SourceLocation SL); /// Helper to set loop increment. bool setStep(Expr *NewStep, bool Subtract); @@ -7948,8 +7950,7 @@ bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, return false; } -bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, - llvm::Optional<bool> LessOp, +bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, std::optional<bool> LessOp, bool StrictOp, SourceRange SR, SourceLocation SL) { // State consistency checking to ensure correct usage. @@ -7992,7 +7993,7 @@ bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { // loop. If test-expr is of form b relational-op var and relational-op is // > or >= then incr-expr must cause var to increase on each iteration of // the loop. - Optional<llvm::APSInt> Result = + std::optional<llvm::APSInt> Result = NewStep->getIntegerConstantExpr(SemaRef.Context); bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); bool IsConstNeg = @@ -8126,7 +8127,7 @@ public: }; } // namespace -Optional<unsigned> +std::optional<unsigned> OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, bool IsInitializer) { // Check for the non-rectangular loops. @@ -8262,10 +8263,10 @@ bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { Condition = S; S = getExprAsWritten(S); SourceLocation CondLoc = S->getBeginLoc(); - auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( - BinaryOperatorKind Opcode, const Expr *LHS, - const Expr *RHS, SourceRange SR, - SourceLocation OpLoc) -> llvm::Optional<bool> { + auto &&CheckAndSetCond = + [this, IneqCondIsCanonical](BinaryOperatorKind Opcode, const Expr *LHS, + const Expr *RHS, SourceRange SR, + SourceLocation OpLoc) -> std::optional<bool> { if (BinaryOperator::isRelationalOp(Opcode)) { if (getInitLCDecl(LHS) == LCDecl) return setUB(const_cast<Expr *>(RHS), @@ -8282,7 +8283,7 @@ bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { } return std::nullopt; }; - llvm::Optional<bool> Res; + std::optional<bool> Res; if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), @@ -8445,12 +8446,12 @@ calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, return nullptr; llvm::APSInt LRes, SRes; bool IsLowerConst = false, IsStepConst = false; - if (Optional<llvm::APSInt> Res = + if (std::optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) { LRes = *Res; IsLowerConst = true; } - if (Optional<llvm::APSInt> Res = + if (std::optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) { SRes = *Res; IsStepConst = true; @@ -8489,7 +8490,7 @@ calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, } llvm::APSInt URes; bool IsUpperConst = false; - if (Optional<llvm::APSInt> Res = + if (std::optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) { URes = *Res; IsUpperConst = true; @@ -9445,7 +9446,7 @@ static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { if (E == nullptr) return false; - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = E->getIntegerConstantExpr(SemaRef.Context)) return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); return false; @@ -16321,7 +16322,7 @@ isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, ValExpr = Value.get(); // The expression must evaluate to a non-negative integer value. - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = ValExpr->getIntegerConstantExpr(SemaRef.Context)) { if (Result->isSigned() && !((!StrictlyPositive && Result->isNonNegative()) || @@ -17157,7 +17158,7 @@ OMPClause *Sema::ActOnOpenMPScheduleClause( // OpenMP [2.7.1, Restrictions] // chunk_size must be a loop invariant integer expression with a positive // value. - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = ValExpr->getIntegerConstantExpr(Context)) { if (Result->isSigned() && !Result->isStrictlyPositive()) { Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) @@ -19970,7 +19971,7 @@ OMPClause *Sema::ActOnOpenMPLinearClause( // Warn about zero linear step (it would be probably better specified as // making corresponding variables 'const'). - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = StepExpr->getIntegerConstantExpr(Context)) { if (!Result->isNegative() && !Result->isStrictlyPositive()) Diag(StepLoc, diag::warn_omp_linear_step_zero) @@ -22638,7 +22639,7 @@ OMPClause *Sema::ActOnOpenMPDistScheduleClause( // OpenMP [2.7.1, Restrictions] // chunk_size must be a loop invariant integer expression with a positive // value. - if (Optional<llvm::APSInt> Result = + if (std::optional<llvm::APSInt> Result = ValExpr->getIntegerConstantExpr(Context)) { if (Result->isSigned() && !Result->isStrictlyPositive()) { Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) @@ -22837,7 +22838,7 @@ void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, const unsigned Level = -1; auto *VD = cast<ValueDecl>(ND); - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); if (ActiveAttr && (*ActiveAttr)->getDevType() != DTCI.DT && (*ActiveAttr)->getLevel() == Level) { @@ -22877,7 +22878,7 @@ static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, if (!D || !isa<VarDecl>(D)) return; auto *VD = cast<VarDecl>(D); - Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); if (SemaRef.LangOpts.OpenMP >= 50 && (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || @@ -22933,7 +22934,7 @@ void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) D = FTD->getTemplatedDecl(); if (auto *FD = dyn_cast<FunctionDecl>(D)) { - llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = + std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { Diag(IdLoc, diag::err_omp_function_in_link_clause); @@ -22951,7 +22952,7 @@ void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, // Checking declaration inside declare target region. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { - llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = + std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); unsigned Level = DeclareTargetNesting.size(); if (ActiveAttr && (*ActiveAttr)->getLevel() >= Level) diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp index 08c66d3..c6c3525 100644 --- a/clang/lib/Sema/SemaOverload.cpp +++ b/clang/lib/Sema/SemaOverload.cpp @@ -359,7 +359,7 @@ NarrowingKind StandardConversionSequence::getNarrowingKind( if (Initializer->isValueDependent()) return NK_Dependent_Narrowing; - if (Optional<llvm::APSInt> IntConstantValue = + if (std::optional<llvm::APSInt> IntConstantValue = Initializer->getIntegerConstantExpr(Ctx)) { // Convert the integer to the floating type. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); @@ -442,7 +442,7 @@ NarrowingKind StandardConversionSequence::getNarrowingKind( if (Initializer->isValueDependent()) return NK_Dependent_Narrowing; - Optional<llvm::APSInt> OptInitializerValue; + std::optional<llvm::APSInt> OptInitializerValue; if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { // Such conversions on variables are always narrowing. return NK_Variable_Narrowing; @@ -884,7 +884,7 @@ const TemplateArgument *DeductionFailureInfo::getSecondArg() { return nullptr; } -llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { +std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { switch (static_cast<Sema::TemplateDeductionResult>(Result)) { case Sema::TDK_DeducedMismatch: case Sema::TDK_DeducedMismatchNested: @@ -2294,7 +2294,7 @@ bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { // compatibility. if (From) { if (FieldDecl *MemberDecl = From->getSourceBitField()) { - Optional<llvm::APSInt> BitWidth; + std::optional<llvm::APSInt> BitWidth; if (FromType->isIntegralType(Context) && (BitWidth = MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { @@ -9745,8 +9745,8 @@ isBetterMultiversionCandidate(const OverloadCandidate &Cand1, /// Compute the type of the implicit object parameter for the given function, /// if any. Returns std::nullopt if there is no implicit object parameter, and a /// null QualType if there is a 'matches anything' implicit object parameter. -static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, - const FunctionDecl *F) { +static std::optional<QualType> +getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) return std::nullopt; @@ -9768,7 +9768,7 @@ static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { if (First) { - if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) + if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) return *T; } assert(I < F->getNumParams()); @@ -12650,7 +12650,7 @@ Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { SmallVector<FunctionDecl *, 2> AmbiguousDecls; auto CheckMoreConstrained = [&](FunctionDecl *FD1, - FunctionDecl *FD2) -> Optional<bool> { + FunctionDecl *FD2) -> std::optional<bool> { if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) FD1 = MF; if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) @@ -12682,8 +12682,8 @@ Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { // We have more than one result - see if it is more constrained than the // previous one. if (Result) { - Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, - Result); + std::optional<bool> MoreConstrainedThanPrevious = + CheckMoreConstrained(FD, Result); if (!MoreConstrainedThanPrevious) { IsResultAmbiguous = true; AmbiguousDecls.push_back(FD); @@ -13341,7 +13341,7 @@ bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, // Guess at what the return type for an unresolvable overload should be. static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best) { - llvm::Optional<QualType> Result; + std::optional<QualType> Result; // Adjust Type after seeing a candidate. auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { if (!Candidate.Function) diff --git a/clang/lib/Sema/SemaRISCVVectorLookup.cpp b/clang/lib/Sema/SemaRISCVVectorLookup.cpp index 13f9aeb..b85d247 100644 --- a/clang/lib/Sema/SemaRISCVVectorLookup.cpp +++ b/clang/lib/Sema/SemaRISCVVectorLookup.cpp @@ -251,7 +251,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { if (!(Record.Log2LMULMask & (1 << (Log2LMUL + 3)))) continue; - Optional<RVVTypes> Types = + std::optional<RVVTypes> Types = TypeCache.computeTypes(BaseType, Log2LMUL, Record.NF, ProtoSeq); // Ignored to create new intrinsic if there are any illegal types. @@ -276,7 +276,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { BasicProtoSeq, /*IsMasked=*/false, /*HasMaskedOffOperand=*/false, Record.HasVL, Record.NF, Record.IsPrototypeDefaultTU, UnMaskedPolicyScheme, P); - Optional<RVVTypes> PolicyTypes = TypeCache.computeTypes( + std::optional<RVVTypes> PolicyTypes = TypeCache.computeTypes( BaseType, Log2LMUL, Record.NF, PolicyPrototype); InitRVVIntrinsic(Record, SuffixStr, OverloadedSuffixStr, /*IsMask=*/false, *PolicyTypes, UnMaskedHasPolicy, @@ -286,7 +286,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { if (!Record.HasMasked) continue; // Create masked intrinsic. - Optional<RVVTypes> MaskTypes = + std::optional<RVVTypes> MaskTypes = TypeCache.computeTypes(BaseType, Log2LMUL, Record.NF, ProtoMaskSeq); InitRVVIntrinsic(Record, SuffixStr, OverloadedSuffixStr, true, *MaskTypes, MaskedHasPolicy, Policy(), @@ -300,7 +300,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { BasicProtoSeq, /*IsMasked=*/true, Record.HasMaskedOffOperand, Record.HasVL, Record.NF, Record.IsPrototypeDefaultTU, MaskedPolicyScheme, P); - Optional<RVVTypes> PolicyTypes = TypeCache.computeTypes( + std::optional<RVVTypes> PolicyTypes = TypeCache.computeTypes( BaseType, Log2LMUL, Record.NF, PolicyPrototype); InitRVVIntrinsic(Record, SuffixStr, OverloadedSuffixStr, /*IsMask=*/true, *PolicyTypes, MaskedHasPolicy, P, diff --git a/clang/lib/Sema/SemaStmtAsm.cpp b/clang/lib/Sema/SemaStmtAsm.cpp index 191d747..9740048 100644 --- a/clang/lib/Sema/SemaStmtAsm.cpp +++ b/clang/lib/Sema/SemaStmtAsm.cpp @@ -460,7 +460,7 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, << Info.getConstraintStr(); } - Optional<SourceLocation> UnwindClobberLoc; + std::optional<SourceLocation> UnwindClobberLoc; // Check that the clobbers are valid. for (unsigned i = 0; i != NumClobbers; i++) { diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp index 27a08d3..6d44383 100644 --- a/clang/lib/Sema/SemaStmtAttr.cpp +++ b/clang/lib/Sema/SemaStmtAttr.cpp @@ -425,7 +425,7 @@ static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, unsigned UnrollFactor = 0; if (A.getNumArgs() == 1) { Expr *E = A.getArgAsExpr(0); - Optional<llvm::APSInt> ArgVal; + std::optional<llvm::APSInt> ArgVal; if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) { S.Diag(A.getLoc(), diag::err_attribute_argument_type) diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 27b5906..31c2bf5 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -817,7 +817,7 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) return true; - llvm::Optional<unsigned> Note; + std::optional<unsigned> Note; QualType InstantiationTy; if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) InstantiationTy = Context.getTypeDeclType(TD); @@ -942,7 +942,7 @@ static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, TemplateName Template = Arg.getAsTemplate().get(); TemplateArgument TArg; if (Arg.getEllipsisLoc().isValid()) - TArg = TemplateArgument(Template, Optional<unsigned int>()); + TArg = TemplateArgument(Template, std::optional<unsigned int>()); else TArg = Template; return TemplateArgumentLoc( @@ -2379,7 +2379,7 @@ private: TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), TTP->isParameterPack(), TTP->hasTypeConstraint(), TTP->isExpandedParameterPack() - ? llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) + ? std::optional<unsigned>(TTP->getNumExpansionParameters()) : std::nullopt); if (const auto *TC = TTP->getTypeConstraint()) SemaRef.SubstTypeConstraint(NewTTP, TC, Args, @@ -5862,7 +5862,7 @@ bool Sema::CheckTemplateArgumentList( Param != ParamEnd; /* increment in loop */) { // If we have an expanded parameter pack, make sure we don't have too // many arguments. - if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) { + if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) { if (*Expansions == SugaredArgumentPack.size()) { // We're done with this parameter pack. Pack up its arguments and add // them to the list. diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index 4a5305a..5bf8de0 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -720,7 +720,7 @@ private: // FIXME: What if we encounter multiple packs with different numbers of // pre-expanded expansions? (This should already have been diagnosed // during substitution.) - if (Optional<unsigned> ExpandedPackExpansions = + if (std::optional<unsigned> ExpandedPackExpansions = getExpandedPackSize(TemplateParams->getParam(Index))) FixedNumExpansions = ExpandedPackExpansions; @@ -962,7 +962,7 @@ public: // If we have a pre-expanded pack and we didn't deduce enough elements // for it, fail deduction. - if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) { + if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) { if (*Expansions != PackElements) { Info.Param = makeTemplateParameter(Param); Info.FirstArg = Result; @@ -984,7 +984,7 @@ private: unsigned PackElements = 0; bool IsPartiallyExpanded = false; /// The number of expansions, if we have a fully-expanded pack in this scope. - Optional<unsigned> FixedNumExpansions; + std::optional<unsigned> FixedNumExpansions; SmallVector<DeducedPack, 2> Packs; }; @@ -1109,7 +1109,7 @@ DeduceTemplateArguments(Sema &S, // If the parameter type contains an explicitly-specified pack that we // could not expand, skip the number of parameters notionally created // by the expansion. - Optional<unsigned> NumExpansions = Expansion->getNumExpansions(); + std::optional<unsigned> NumExpansions = Expansion->getNumExpansions(); if (NumExpansions && !PackScope.isPartiallyExpanded()) { for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs; ++I, ++ArgIdx) @@ -2082,7 +2082,7 @@ static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( const auto *ACM = dyn_cast<ConstantMatrixType>(A); const auto *ADM = dyn_cast<DependentSizedMatrixType>(A); if (!ParamExpr->isValueDependent()) { - Optional<llvm::APSInt> ParamConst = + std::optional<llvm::APSInt> ParamConst = ParamExpr->getIntegerConstantExpr(S.Context); if (!ParamConst) return Sema::TDK_NonDeducedMismatch; @@ -2094,7 +2094,7 @@ static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( } Expr *ArgExpr = (ADM->*GetArgDimensionExpr)(); - if (Optional<llvm::APSInt> ArgConst = + if (std::optional<llvm::APSInt> ArgConst = ArgExpr->getIntegerConstantExpr(S.Context)) if (*ArgConst == *ParamConst) return Sema::TDK_Success; @@ -3267,7 +3267,7 @@ Sema::TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1); // If this is a fully-saturated fixed-size pack, it should be // fully-substituted, not partially-substituted. - Optional<unsigned> Expansions = getExpandedPackSize(Param); + std::optional<unsigned> Expansions = getExpandedPackSize(Param); if (!Expansions || Arg.pack_size() < *Expansions) { PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1; CurrentInstantiationScope->SetPartiallySubstitutedPack( @@ -4184,7 +4184,8 @@ Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( // If the parameter type contains an explicitly-specified pack that we // could not expand, skip the number of parameters notionally created // by the expansion. - Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions(); + std::optional<unsigned> NumExpansions = + ParamExpansion->getNumExpansions(); if (NumExpansions && !PackScope.isPartiallyExpanded()) { for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size(); ++I, ++ArgIdx) { diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp index e1329c4..8950293 100644 --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -1012,9 +1012,9 @@ void Sema::PrintInstantiationStack() { } } -Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { +std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { if (InNonInstantiationSFINAEContext) - return Optional<TemplateDeductionInfo *>(nullptr); + return std::optional<TemplateDeductionInfo *>(nullptr); for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator Active = CodeSynthesisContexts.rbegin(), @@ -1081,7 +1081,7 @@ Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { // The inner context was transparent for SFINAE. If it occurred within a // non-instantiation SFINAE context, then SFINAE applies. if (Active->SavedInNonInstantiationSFINAEContext) - return Optional<TemplateDeductionInfo *>(nullptr); + return std::optional<TemplateDeductionInfo *>(nullptr); } return std::nullopt; @@ -1137,7 +1137,7 @@ namespace { return TemplateArgs.getNewDepth(Depth); } - Optional<unsigned> getPackIndex(TemplateArgument Pack) { + std::optional<unsigned> getPackIndex(TemplateArgument Pack) { int Index = getSema().ArgumentPackSubstitutionIndex; if (Index == -1) return std::nullopt; @@ -1148,7 +1148,7 @@ namespace { SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, bool &ShouldExpand, bool &RetainExpansion, - Optional<unsigned> &NumExpansions) { + std::optional<unsigned> &NumExpansions) { return getSema().CheckParameterPacksForExpansion(EllipsisLoc, PatternRange, Unexpanded, TemplateArgs, @@ -1307,10 +1307,10 @@ namespace { Qualifiers ThisTypeQuals, Fn TransformExceptionSpec); - ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, - int indexAdjustment, - Optional<unsigned> NumExpansions, - bool ExpectParameterPack); + ParmVarDecl * + TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment, + std::optional<unsigned> NumExpansions, + bool ExpectParameterPack); using inherited::TransformTemplateTypeParmType; /// Transforms a template type parameter type by performing @@ -1321,7 +1321,7 @@ namespace { QualType BuildSubstTemplateTypeParmType( TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, - Decl *AssociatedDecl, unsigned Index, Optional<unsigned> PackIndex, + Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex, TemplateArgument Arg, SourceLocation NameLoc); /// Transforms an already-substituted template type parameter pack @@ -1437,9 +1437,11 @@ namespace { Sema::ExtParameterInfoBuilder &PInfos); private: - ExprResult transformNonTypeTemplateParmRef( - Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm, - SourceLocation loc, TemplateArgument arg, Optional<unsigned> PackIndex); + ExprResult + transformNonTypeTemplateParmRef(Decl *AssociatedDecl, + const NonTypeTemplateParmDecl *parm, + SourceLocation loc, TemplateArgument arg, + std::optional<unsigned> PackIndex); }; } @@ -1631,7 +1633,7 @@ TemplateName TemplateInstantiator::TransformTemplateName( auto [AssociatedDecl, Final] = TemplateArgs.getAssociatedDecl(TTP->getDepth()); - Optional<unsigned> PackIndex; + std::optional<unsigned> PackIndex; if (TTP->isParameterPack()) { assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); @@ -1717,7 +1719,7 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, } auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth()); - Optional<unsigned> PackIndex; + std::optional<unsigned> PackIndex; if (NTTP->isParameterPack()) { assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); @@ -1767,7 +1769,8 @@ TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm, - SourceLocation loc, TemplateArgument arg, Optional<unsigned> PackIndex) { + SourceLocation loc, TemplateArgument arg, + std::optional<unsigned> PackIndex) { ExprResult result; // Determine the substituted parameter type. We can usually infer this from @@ -2015,11 +2018,9 @@ QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); } -ParmVarDecl * -TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm, - int indexAdjustment, - Optional<unsigned> NumExpansions, - bool ExpectParameterPack) { +ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam( + ParmVarDecl *OldParm, int indexAdjustment, + std::optional<unsigned> NumExpansions, bool ExpectParameterPack) { auto NewParm = SemaRef.SubstParmVarDecl( OldParm, TemplateArgs, indexAdjustment, NumExpansions, ExpectParameterPack, EvaluateConstraints); @@ -2030,7 +2031,7 @@ TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm, QualType TemplateInstantiator::BuildSubstTemplateTypeParmType( TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, - Decl *AssociatedDecl, unsigned Index, Optional<unsigned> PackIndex, + Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex, TemplateArgument Arg, SourceLocation NameLoc) { QualType Replacement = Arg.getAsType(); @@ -2099,7 +2100,7 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, auto [AssociatedDecl, Final] = TemplateArgs.getAssociatedDecl(T->getDepth()); - Optional<unsigned> PackIndex; + std::optional<unsigned> PackIndex; if (T->isParameterPack()) { assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); @@ -2285,7 +2286,7 @@ TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { TransExpr = TransExprRes.get(); } - llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; + std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; const auto &RetReq = Req->getReturnTypeRequirement(); if (RetReq.isEmpty()) TransRetReq.emplace(); @@ -2689,11 +2690,10 @@ bool Sema::SubstTypeConstraint( : SourceLocation()); } -ParmVarDecl * -Sema::SubstParmVarDecl(ParmVarDecl *OldParm, - const MultiLevelTemplateArgumentList &TemplateArgs, - int indexAdjustment, Optional<unsigned> NumExpansions, - bool ExpectParameterPack, bool EvaluateConstraint) { +ParmVarDecl *Sema::SubstParmVarDecl( + ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs, + int indexAdjustment, std::optional<unsigned> NumExpansions, + bool ExpectParameterPack, bool EvaluateConstraint) { TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); TypeSourceInfo *NewDI = nullptr; @@ -2943,7 +2943,7 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, Unexpanded); bool ShouldExpand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), Base.getSourceRange(), Unexpanded, diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp index 04d3a05..96dde1ad 100644 --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -121,7 +121,7 @@ static void instantiateDependentAlignedAttr( // Determine whether we can expand this attribute pack yet. bool Expand = true, RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; // FIXME: Use the actual location of the ellipsis. SourceLocation EllipsisLoc = Aligned->getLocation(); if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), @@ -462,7 +462,7 @@ static void instantiateOMPDeclareVariantAttr( // Check function/variant ref for `omp declare variant` but not for `omp // begin declare variant` (which use implicit attributes). - Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = + std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(), Attr.getRange()); @@ -2373,7 +2373,8 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl( Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( CXXMethodDecl *D, TemplateParameterList *TemplateParams, - Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs, + std::optional<const ASTTemplateArgumentListInfo *> + ClassScopeSpecializationArgs, RewriteKind FunctionRewriteKind) { FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); if (FunctionTemplate && !TemplateParams) { @@ -2797,7 +2798,7 @@ Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( TemplateTypeParmDecl *D) { assert(D->getTypeForDecl()->isTemplateTypeParmType()); - Optional<unsigned> NumExpanded; + std::optional<unsigned> NumExpanded; if (const TypeConstraint *TC = D->getTypeConstraint()) { if (D->isPackExpansion() && !D->isExpandedParameterPack()) { @@ -2908,9 +2909,9 @@ Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions - = Expansion.getTypePtr()->getNumExpansions(); - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions = + Expansion.getTypePtr()->getNumExpansions(); + std::optional<unsigned> NumExpansions = OrigNumExpansions; if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), Pattern.getSourceRange(), Unexpanded, @@ -3073,7 +3074,7 @@ TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), TempParams->getSourceRange(), Unexpanded, @@ -3344,7 +3345,7 @@ Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (SemaRef.CheckParameterPacksForExpansion( D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpansions)) @@ -4409,7 +4410,7 @@ TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; - Optional<unsigned> NumArgumentsInExpansion; + std::optional<unsigned> NumArgumentsInExpansion; if (OldParam->isParameterPack()) NumArgumentsInExpansion = SemaRef.getNumArgumentsInExpansion(OldParam->getType(), @@ -4511,7 +4512,7 @@ bool Sema::addInstantiatedParametersToScope( // Expand the parameter pack. Scope.MakeInstantiatedLocalArgPack(PatternParam); - Optional<unsigned> NumArgumentsInExpansion = + std::optional<unsigned> NumArgumentsInExpansion = getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); if (NumArgumentsInExpansion) { QualType PatternType = @@ -5642,7 +5643,7 @@ Sema::InstantiateMemInitializers(CXXConstructorDecl *New, collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); bool ShouldExpand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), BaseTL.getSourceRange(), Unexpanded, diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp b/clang/lib/Sema/SemaTemplateVariadic.cpp index 95a7478..01a4356 100644 --- a/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -623,7 +623,7 @@ TypeResult Sema::ActOnPackExpansion(ParsedType Type, TypeSourceInfo * Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { // Create the pack expansion type and source-location information. QualType Result = CheckPackExpansion(Pattern->getType(), Pattern->getTypeLoc().getSourceRange(), @@ -641,7 +641,7 @@ Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { // C++11 [temp.variadic]p5: // The pattern of a pack expansion shall name one or more // parameter packs that are not expanded by a nested pack @@ -665,7 +665,7 @@ ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) { } ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { if (!Pattern) return ExprError(); @@ -689,16 +689,16 @@ bool Sema::CheckParameterPacksForExpansion( SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, - bool &RetainExpansion, Optional<unsigned> &NumExpansions) { + bool &RetainExpansion, std::optional<unsigned> &NumExpansions) { ShouldExpand = true; RetainExpansion = false; std::pair<const IdentifierInfo *, SourceLocation> FirstPack; - Optional<std::pair<unsigned, SourceLocation>> PartialExpansion; - Optional<unsigned> CurNumExpansions; + std::optional<std::pair<unsigned, SourceLocation>> PartialExpansion; + std::optional<unsigned> CurNumExpansions; for (auto [P, Loc] : Unexpanded) { // Compute the depth and index for this parameter pack. - Optional<std::pair<unsigned, unsigned>> Pos; + std::optional<std::pair<unsigned, unsigned>> Pos; unsigned NewPackSize; const auto *ND = P.dyn_cast<const NamedDecl *>(); if (ND && isa<VarDecl>(ND)) { @@ -807,13 +807,13 @@ bool Sema::CheckParameterPacksForExpansion( return false; } -Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T, - const MultiLevelTemplateArgumentList &TemplateArgs) { +std::optional<unsigned> Sema::getNumArgumentsInExpansion( + QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) { QualType Pattern = cast<PackExpansionType>(T)->getPattern(); SmallVector<UnexpandedParameterPack, 2> Unexpanded; CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern); - Optional<unsigned> Result; + std::optional<unsigned> Result; auto setResultSz = [&Result](unsigned Size) { assert((!Result || *Result == Size) && "inconsistent pack sizes"); Result = Size; @@ -1060,10 +1060,9 @@ ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, RParenLoc); } -TemplateArgumentLoc -Sema::getTemplateArgumentPackExpansionPattern( - TemplateArgumentLoc OrigLoc, - SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const { +TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern( + TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, + std::optional<unsigned> &NumExpansions) const { const TemplateArgument &Argument = OrigLoc.getArgument(); assert(Argument.isPackExpansion()); switch (Argument.getKind()) { @@ -1120,7 +1119,7 @@ Sema::getTemplateArgumentPackExpansionPattern( llvm_unreachable("Invalid TemplateArgument Kind!"); } -Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) { +std::optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) { assert(Arg.containsUnexpandedParameterPack()); // If this is a substituted pack, grab that pack. If not, we don't know @@ -1261,7 +1260,7 @@ ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { return new (Context) CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator, EllipsisLoc, RHS, RParenLoc, NumExpansions); diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 6e8ed7c..826a9ef 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -2681,7 +2681,8 @@ QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, VectorType::GenericVector); - Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context); + std::optional<llvm::APSInt> VecSize = + SizeExpr->getIntegerConstantExpr(Context); if (!VecSize) { Diag(AttrLoc, diag::err_attribute_argument_type) << "vector_size" << AANT_ArgumentIntegerConstant @@ -2758,7 +2759,8 @@ QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, } if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { - Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context); + std::optional<llvm::APSInt> vecSize = + ArraySize->getIntegerConstantExpr(Context); if (!vecSize) { Diag(AttrLoc, diag::err_attribute_argument_type) << "ext_vector_type" << AANT_ArgumentIntegerConstant @@ -2804,8 +2806,9 @@ QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols, AttrLoc); - Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context); - Optional<llvm::APSInt> ValueColumns = + std::optional<llvm::APSInt> ValueRows = + NumRows->getIntegerConstantExpr(Context); + std::optional<llvm::APSInt> ValueColumns = NumCols->getIntegerConstantExpr(Context); auto const RowRange = NumRows->getSourceRange(); @@ -4668,7 +4671,7 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, } // Determine whether we should infer _Nonnull on pointer types. - Optional<NullabilityKind> inferNullability; + std::optional<NullabilityKind> inferNullability; bool inferNullabilityCS = false; bool inferNullabilityInnerOnly = false; bool inferNullabilityInnerOnlyComplete = false; @@ -6619,7 +6622,7 @@ static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc) { if (!AddrSpace->isValueDependent()) { - Optional<llvm::APSInt> OptAddrSpace = + std::optional<llvm::APSInt> OptAddrSpace = AddrSpace->getIntegerConstantExpr(S.Context); if (!OptAddrSpace) { S.Diag(AttrLoc, diag::err_attribute_argument_type) @@ -8048,7 +8051,7 @@ static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, llvm::APSInt &Result) { const auto *AttrExpr = Attr.getArgAsExpr(0); if (!AttrExpr->isTypeDependent()) { - if (Optional<llvm::APSInt> Res = + if (std::optional<llvm::APSInt> Res = AttrExpr->getIntegerConstantExpr(S.Context)) { Result = *Res; return true; diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 8d4f30b..a13b290 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -280,9 +280,8 @@ public: bool TryExpandParameterPacks(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, - bool &ShouldExpand, - bool &RetainExpansion, - Optional<unsigned> &NumExpansions) { + bool &ShouldExpand, bool &RetainExpansion, + std::optional<unsigned> &NumExpansions) { ShouldExpand = false; return false; } @@ -731,7 +730,7 @@ public: /// scope index; can be negative ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment, - Optional<unsigned> NumExpansions, + std::optional<unsigned> NumExpansions, bool ExpectParameterPack); /// Transform the body of a lambda-expression. @@ -1223,10 +1222,9 @@ public: /// /// By default, builds a new PackExpansionType type from the given pattern. /// Subclasses may override this routine to provide different behavior. - QualType RebuildPackExpansionType(QualType Pattern, - SourceRange PatternRange, + QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc, NumExpansions); } @@ -3243,17 +3241,14 @@ public: /// /// By default, performs semantic analysis to build the new expression. /// Subclasses may override this routine to provide different behavior. - ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, - bool UseGlobal, + ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, - SourceRange TypeIdParens, - QualType AllocatedType, + SourceRange TypeIdParens, QualType AllocatedType, TypeSourceInfo *AllocatedTypeInfo, - Optional<Expr *> ArraySize, - SourceRange DirectInitRange, - Expr *Initializer) { + std::optional<Expr *> ArraySize, + SourceRange DirectInitRange, Expr *Initializer) { return getSema().BuildCXXNew(StartLoc, UseGlobal, PlacementLParen, PlacementArgs, @@ -3475,11 +3470,10 @@ public: } /// Build a new expression to compute the length of a parameter pack. - ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, - NamedDecl *Pack, + ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack, SourceLocation PackLoc, SourceLocation RParenLoc, - Optional<unsigned> Length, + std::optional<unsigned> Length, ArrayRef<TemplateArgument> PartialArgs) { return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc, RParenLoc, Length, PartialArgs); @@ -3783,9 +3777,9 @@ public: /// By default, performs semantic analysis to build a new pack expansion /// for a template argument. Subclasses may override this routine to provide /// different behavior. - TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern, - SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + TemplateArgumentLoc + RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc, + std::optional<unsigned> NumExpansions) { switch (Pattern.getArgument().getKind()) { case TemplateArgument::Expression: { ExprResult Result @@ -3832,7 +3826,7 @@ public: /// for an expression. Subclasses may override this routine to provide /// different behavior. ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions); } @@ -3845,7 +3839,7 @@ public: BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator, EllipsisLoc, RHS, RParenLoc, NumExpansions); @@ -4094,8 +4088,8 @@ bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs, // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions(); - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions(); + std::optional<unsigned> NumExpansions = OrigNumExpansions; if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(), Pattern->getSourceRange(), Unexpanded, @@ -4674,7 +4668,7 @@ bool TreeTransform<Derived>::TransformTemplateArguments( // We have a pack expansion, for which we will be substituting into // the pattern. SourceLocation Ellipsis; - Optional<unsigned> OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions; TemplateArgumentLoc Pattern = getSema().getTemplateArgumentPackExpansionPattern( In, Ellipsis, OrigNumExpansions); @@ -4687,7 +4681,7 @@ bool TreeTransform<Derived>::TransformTemplateArguments( // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> NumExpansions = OrigNumExpansions; if (getDerived().TryExpandParameterPacks(Ellipsis, Pattern.getSourceRange(), Unexpanded, @@ -5695,8 +5689,8 @@ QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB, template <typename Derived> ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam( - ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions, - bool ExpectParameterPack) { + ParmVarDecl *OldParm, int indexAdjustment, + std::optional<unsigned> NumExpansions, bool ExpectParameterPack) { TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); TypeSourceInfo *NewDI = nullptr; @@ -5767,7 +5761,7 @@ bool TreeTransform<Derived>::TransformFunctionTypeParams( if (ParmVarDecl *OldParm = Params[i]) { assert(OldParm->getFunctionScopeIndex() == i); - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; ParmVarDecl *NewParm = nullptr; if (OldParm->isParameterPack()) { // We have a function parameter pack that may need to be expanded. @@ -5782,7 +5776,7 @@ bool TreeTransform<Derived>::TransformFunctionTypeParams( // Determine whether we should expand the parameter packs. bool ShouldExpand = false; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions; if (Unexpanded.size() > 0) { OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions(); NumExpansions = OrigNumExpansions; @@ -5885,7 +5879,7 @@ bool TreeTransform<Derived>::TransformFunctionTypeParams( assert(ParamTypes); QualType OldType = ParamTypes[i]; bool IsPackExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; QualType NewType; if (const PackExpansionType *Expansion = dyn_cast<PackExpansionType>(OldType)) { @@ -6138,7 +6132,7 @@ bool TreeTransform<Derived>::TransformExceptionSpec( // be expanded. bool Expand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); + std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); // FIXME: Track the location of the ellipsis (and track source location // information for the types in the exception specification in general). if (getDerived().TryExpandParameterPacks( @@ -7274,7 +7268,7 @@ TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB, TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc(); bool Expand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); + std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); if (getDerived().TryExpandParameterPacks( PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(), Unexpanded, Expand, RetainExpansion, NumExpansions)) @@ -7592,7 +7586,7 @@ TreeTransform<Derived>::TransformIfStmt(IfStmt *S) { } // If this is a constexpr if, determine which arm we should instantiate. - llvm::Optional<bool> ConstexprConditionValue; + std::optional<bool> ConstexprConditionValue; if (S->isConstexpr()) ConstexprConditionValue = Cond.getKnownValue(); @@ -12229,10 +12223,10 @@ TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) { return ExprError(); // Transform the size of the array we're allocating (if any). - Optional<Expr *> ArraySize; + std::optional<Expr *> ArraySize; if (E->isArray()) { ExprResult NewArraySize; - if (Optional<Expr *> OldArraySize = E->getArraySize()) { + if (std::optional<Expr *> OldArraySize = E->getArraySize()) { NewArraySize = getDerived().TransformExpr(*OldArraySize); if (NewArraySize.isInvalid()) return ExprError(); @@ -12611,9 +12605,9 @@ TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) { // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions = + std::optional<unsigned> OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions(); - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> NumExpansions = OrigNumExpansions; if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(), PatternTL.getSourceRange(), Unexpanded, @@ -12829,7 +12823,7 @@ TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) TransExpr = TransExprRes.get(); } - llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; + std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; const auto &RetReq = Req->getReturnTypeRequirement(); if (RetReq.isEmpty()) TransRetReq.emplace(); @@ -13154,7 +13148,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { auto *OldVD = cast<VarDecl>(C->getCapturedVar()); auto SubstInitCapture = [&](SourceLocation EllipsisLoc, - Optional<unsigned> NumExpansions) { + std::optional<unsigned> NumExpansions) { ExprResult NewExprInitResult = getDerived().TransformInitializer( OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit); @@ -13187,9 +13181,9 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions = + std::optional<unsigned> OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions(); - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> NumExpansions = OrigNumExpansions; if (getDerived().TryExpandParameterPacks( ExpansionTL.getEllipsisLoc(), OldVD->getInit()->getSourceRange(), Unexpanded, Expand, @@ -13267,7 +13261,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { getDerived().transformedLocalDecl(OldClass, {Class}); - Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling; + std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling; if (getDerived().ReplacingOriginal()) Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(), OldClass->getLambdaManglingNumber(), @@ -13372,7 +13366,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation()); bool ShouldExpand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(), C->getLocation(), Unexpanded, @@ -13748,7 +13742,7 @@ TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) { UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc()); bool ShouldExpand = false; bool RetainExpansion = false; - Optional<unsigned> NumExpansions; + std::optional<unsigned> NumExpansions; if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(), Unexpanded, ShouldExpand, RetainExpansion, @@ -13792,7 +13786,7 @@ TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) { } // Try to compute the result without performing a partial substitution. - Optional<unsigned> Result = 0; + std::optional<unsigned> Result = 0; for (const TemplateArgument &Arg : PackArgs) { if (!Arg.isPackExpansion()) { Result = *Result + 1; @@ -13804,7 +13798,7 @@ TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) { // Find the pattern of the pack expansion. SourceLocation Ellipsis; - Optional<unsigned> OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions; TemplateArgumentLoc Pattern = getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis, OrigNumExpansions); @@ -13817,7 +13811,7 @@ TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) { return true; // See if we can determine the number of arguments from the result. - Optional<unsigned> NumExpansions = + std::optional<unsigned> NumExpansions = getSema().getFullyPackExpandedSize(OutPattern.getArgument()); if (!NumExpansions) { // No: we must be in an alias template expansion, and we're going to need @@ -13919,8 +13913,8 @@ TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) { // be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions = E->getNumExpansions(), - NumExpansions = OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(), + NumExpansions = OrigNumExpansions; if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(), Pattern->getSourceRange(), Unexpanded, @@ -14130,8 +14124,8 @@ TreeTransform<Derived>::TransformObjCDictionaryLiteral( // and should be expanded. bool Expand = true; bool RetainExpansion = false; - Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions; - Optional<unsigned> NumExpansions = OrigNumExpansions; + std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions; + std::optional<unsigned> NumExpansions = OrigNumExpansions; SourceRange PatternRange(OrigElement.Key->getBeginLoc(), OrigElement.Value->getEndLoc()); if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc, diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 2e920e2..88e3a03 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2410,8 +2410,8 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { Content, None, } Kind; - llvm::Optional<int64_t> Old = std::nullopt; - llvm::Optional<int64_t> New = std::nullopt; + std::optional<int64_t> Old = std::nullopt; + std::optional<int64_t> New = std::nullopt; }; auto HasInputFileChanged = [&]() { if (StoredSize != File->getSize()) @@ -3404,7 +3404,7 @@ llvm::Error ASTReader::ReadASTBlock(ModuleFile &F, if (!Record.empty()) { unsigned Idx = 0, End = Record.size() - 1; bool ReachedEOFWhileSkipping = Record[Idx++]; - llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo; + std::optional<Preprocessor::PreambleSkipInfo> SkipInfo; if (ReachedEOFWhileSkipping) { SourceLocation HashToken = ReadSourceLocation(F, Record, Idx); SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx); @@ -4258,7 +4258,7 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, llvm::TimeTraceScope scope("ReadAST", FileName); llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc); - llvm::SaveAndRestore<Optional<ModuleKind>> SetCurModuleKindRAII( + llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII( CurrentDeserializingModuleKind, Type); // Defer any pending actions until we get to the end of reading the AST file. @@ -6266,8 +6266,8 @@ std::pair<unsigned, unsigned> /// Optionally returns true or false if the preallocated preprocessed /// entity with index \arg Index came from file \arg FID. -Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, - FileID FID) { +std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, + FileID FID) { if (FID.isInvalid()) return false; @@ -6291,7 +6291,7 @@ namespace { /// Visitor used to search for information about a header file. class HeaderFileInfoVisitor { const FileEntry *FE; - Optional<HeaderFileInfo> HFI; + std::optional<HeaderFileInfo> HFI; public: explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {} @@ -6311,7 +6311,7 @@ namespace { return true; } - Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } + std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } }; } // namespace @@ -6319,8 +6319,8 @@ namespace { HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { HeaderFileInfoVisitor Visitor(FE); ModuleMgr.visit(Visitor); - if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) - return *HFI; + if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) + return *HFI; return HeaderFileInfo(); } @@ -6475,7 +6475,7 @@ ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { M->DeclsBlockStartOffset); } -static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { +static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { switch (code) { #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ case TYPE_##CODE_ID: return Type::CLASS_ID; @@ -8764,8 +8764,7 @@ unsigned ASTReader::getModuleFileID(ModuleFile *F) { return (I - PCHModules.end()) << 1; } -llvm::Optional<ASTSourceDescriptor> -ASTReader::getSourceDescriptor(unsigned ID) { +std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { if (Module *M = getSubmodule(ID)) return ASTSourceDescriptor(*M); diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index b87e9ac..46d653c 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -858,7 +858,7 @@ void ASTStmtReader::VisitRequiresExpr(RequiresExpr *E) { } else E = Record.readExpr(); - llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> Req; + std::optional<concepts::ExprRequirement::ReturnTypeRequirement> Req; ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; SourceLocation NoexceptLoc; if (RK == concepts::Requirement::RK_Simple) { diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index 2a5618f..50e8b26 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -2121,7 +2121,7 @@ void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, // We add one to the size so that we capture the trailing NULL // that is required by llvm::MemoryBuffer::getMemBuffer (on // the reader side). - llvm::Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager()); StringRef Name = Buffer ? Buffer->getBufferIdentifier() : ""; Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, @@ -2135,7 +2135,7 @@ void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, if (EmitBlob) { // Include the implicit terminating null character in the on-disk buffer // if we're writing it uncompressed. - llvm::Optional<llvm::MemoryBufferRef> Buffer = + std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager()); if (!Buffer) Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", ""); diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp index 2b1001a..ce16ed2 100644 --- a/clang/lib/Serialization/ASTWriterDecl.cpp +++ b/clang/lib/Serialization/ASTWriterDecl.cpp @@ -2493,7 +2493,7 @@ void ASTRecordWriter::AddFunctionDefinition(const FunctionDecl *FD) { assert(FD->doesThisDeclarationHaveABody()); bool ModulesCodegen = false; if (!FD->isDependentContext()) { - Optional<GVALinkage> Linkage; + std::optional<GVALinkage> Linkage; if (Writer->WritingModule && Writer->WritingModule->isInterfaceOrPartition()) { // When building a C++20 module interface unit or a partition unit, a diff --git a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp index a2390d4..4578372 100644 --- a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp @@ -60,7 +60,7 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph &G, if (D != P.getLocationContext()->getDecl()) continue; - if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { + if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { const CFGBlock *CB = BE->getBlock(); reachable.insert(CB); } @@ -124,7 +124,7 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph &G, if (Exit->empty()) continue; const CFGElement &CE = Exit->front(); - if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { SmallString<128> bufI; llvm::raw_svector_ostream outputI(bufI); outputI << "(" << NameOfRootFunction << ")" << diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp index bf3c92e..986b0ad 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp @@ -85,7 +85,7 @@ static SVal computeExtentBegin(SValBuilder &svalBuilder, static std::pair<NonLoc, nonloc::ConcreteInt> getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent, SValBuilder &svalBuilder) { - Optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>(); + std::optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>(); if (SymVal && SymVal->isExpression()) { if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SymVal->getSymbol())) { llvm::APSInt constant = @@ -144,7 +144,7 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion()); - if (Optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) { + if (std::optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) { if (auto ConcreteNV = NV->getAs<nonloc::ConcreteInt>()) { std::pair<NonLoc, nonloc::ConcreteInt> simplifiedOffsets = getSimplifiedOffsets(rawOffset.getByteOffset(), *ConcreteNV, @@ -156,7 +156,7 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, SVal lowerBound = svalBuilder.evalBinOpNN(state, BO_LT, rawOffsetVal, *NV, svalBuilder.getConditionType()); - Optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>(); + std::optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>(); if (!lowerBoundToCheck) return; @@ -195,7 +195,7 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, Size.castAs<NonLoc>(), svalBuilder.getConditionType()); - Optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>(); + std::optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>(); if (!upperboundToCheck) break; diff --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp index 615d994..7286f94 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -370,7 +370,7 @@ enum CFNumberType { kCFNumberCGFloatType = 16 }; -static Optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) { +static std::optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) { static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 }; if (i < kCFNumberCharType) @@ -443,12 +443,13 @@ void CFNumberChecker::checkPreStmt(const CallExpr *CE, // FIXME: We really should allow ranges of valid theType values, and // bifurcate the state appropriately. - Optional<nonloc::ConcreteInt> V = dyn_cast<nonloc::ConcreteInt>(TheTypeVal); + std::optional<nonloc::ConcreteInt> V = + dyn_cast<nonloc::ConcreteInt>(TheTypeVal); if (!V) return; uint64_t NumberKind = V->getValue().getLimitedValue(); - Optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind); + std::optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind); // FIXME: In some cases we can emit an error. if (!OptCFNumberSize) @@ -463,7 +464,7 @@ void CFNumberChecker::checkPreStmt(const CallExpr *CE, // FIXME: Eventually we should handle arbitrary locations. We can do this // by having an enhanced memory model that does low-level typing. - Optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>(); + std::optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>(); if (!LV) return; @@ -555,7 +556,7 @@ void CFRetainReleaseChecker::checkPreCall(const CallEvent &Call, // Get the argument's value. SVal ArgVal = Call.getArgSVal(0); - Optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>(); + std::optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>(); if (!DefArgVal) return; @@ -858,7 +859,8 @@ static ProgramStateRef checkCollectionNonNil(CheckerContext &C, return nullptr; SVal CollectionVal = C.getSVal(FCS->getCollection()); - Optional<DefinedSVal> KnownCollection = CollectionVal.getAs<DefinedSVal>(); + std::optional<DefinedSVal> KnownCollection = + CollectionVal.getAs<DefinedSVal>(); if (!KnownCollection) return State; @@ -890,7 +892,7 @@ static ProgramStateRef checkElementNonNil(CheckerContext &C, const Stmt *Element = FCS->getElement(); // FIXME: Copied from ExprEngineObjC. - Optional<Loc> ElementLoc; + std::optional<Loc> ElementLoc; if (const DeclStmt *DS = dyn_cast<DeclStmt>(Element)) { const VarDecl *ElemDecl = cast<VarDecl>(DS->getSingleDecl()); assert(ElemDecl->getInit() == nullptr); @@ -929,8 +931,8 @@ assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State, nonloc::SymbolVal(*CountS), SvalBuilder.makeIntVal(0, (*CountS)->getType()), SvalBuilder.getConditionType()); - Optional<DefinedSVal> CountGreaterThanZero = - CountGreaterThanZeroVal.getAs<DefinedSVal>(); + std::optional<DefinedSVal> CountGreaterThanZero = + CountGreaterThanZeroVal.getAs<DefinedSVal>(); if (!CountGreaterThanZero) { // The SValBuilder cannot construct a valid SVal for this condition. // This means we cannot properly reason about it. @@ -958,7 +960,7 @@ static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N, return false; ProgramPoint P = N->getLocation(); - if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { + if (std::optional<BlockEdge> BE = P.getAs<BlockEdge>()) { return BE->getSrc()->getLoopTarget() == FCS; } @@ -1175,7 +1177,8 @@ ObjCNonNilReturnValueChecker::assumeExprIsNonNull(const Expr *NonNullExpr, ProgramStateRef State, CheckerContext &C) const { SVal Val = C.getSVal(NonNullExpr); - if (Optional<DefinedOrUnknownSVal> DV = Val.getAs<DefinedOrUnknownSVal>()) + if (std::optional<DefinedOrUnknownSVal> DV = + Val.getAs<DefinedOrUnknownSVal>()) return State->assume(*DV, true); return State; } diff --git a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp index 2175b34..2d20e39 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp @@ -75,7 +75,7 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, // Get the value of the right-hand side. We only care about values // that are defined (UnknownVals and UndefinedVals are handled by other // checkers). - Optional<NonLoc> NV = val.getAs<NonLoc>(); + std::optional<NonLoc> NV = val.getAs<NonLoc>(); if (!NV) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index e6857ce..b38d18d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -319,7 +319,7 @@ REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal) std::pair<ProgramStateRef , ProgramStateRef > CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V, QualType Ty) { - Optional<DefinedSVal> val = V.getAs<DefinedSVal>(); + std::optional<DefinedSVal> val = V.getAs<DefinedSVal>(); if (!val) return std::pair<ProgramStateRef , ProgramStateRef >(state, state); @@ -466,7 +466,7 @@ CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State, // FIXME: This assumes the caller has already checked that the access length // is positive. And that it's unsigned. SVal LengthVal = C.getSVal(Size.Expression); - Optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); + std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); if (!Length) return State; @@ -480,7 +480,7 @@ CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State, // Check that the first buffer is sufficiently long. SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType()); - if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) { + if (std::optional<Loc> BufLoc = BufStart.getAs<Loc>()) { SVal BufEnd = svalBuilder.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy); @@ -523,11 +523,11 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, SVal firstVal = state->getSVal(First.Expression, LCtx); SVal secondVal = state->getSVal(Second.Expression, LCtx); - Optional<Loc> firstLoc = firstVal.getAs<Loc>(); + std::optional<Loc> firstLoc = firstVal.getAs<Loc>(); if (!firstLoc) return state; - Optional<Loc> secondLoc = secondVal.getAs<Loc>(); + std::optional<Loc> secondLoc = secondVal.getAs<Loc>(); if (!secondLoc) return state; @@ -550,7 +550,7 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, QualType cmpTy = svalBuilder.getConditionType(); SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT, *firstLoc, *secondLoc, cmpTy); - Optional<DefinedOrUnknownSVal> reverseTest = + std::optional<DefinedOrUnknownSVal> reverseTest = reverse.getAs<DefinedOrUnknownSVal>(); if (!reverseTest) return state; @@ -571,7 +571,7 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, // Get the length, and make sure it too is known. SVal LengthVal = state->getSVal(Size.Expression, LCtx); - Optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); + std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); if (!Length) return state; @@ -581,21 +581,21 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, QualType CharPtrTy = getCharPtrType(Ctx, CK); SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First.Expression->getType()); - Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>(); + std::optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>(); if (!FirstStartLoc) return state; // Compute the end of the first buffer. Bail out if THAT fails. SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add, *FirstStartLoc, *Length, CharPtrTy); - Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>(); + std::optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>(); if (!FirstEndLoc) return state; // Is the end of the first buffer past the start of the second buffer? SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT, *FirstEndLoc, *secondLoc, cmpTy); - Optional<DefinedOrUnknownSVal> OverlapTest = + std::optional<DefinedOrUnknownSVal> OverlapTest = Overlap.getAs<DefinedOrUnknownSVal>(); if (!OverlapTest) return state; @@ -760,7 +760,7 @@ ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C, left = right; } - if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) { + if (std::optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) { QualType cmpTy = svalBuilder.getConditionType(); // If left > max - right, we have an overflow. SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left, @@ -846,7 +846,7 @@ SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C, C.blockCount()); if (!hypothetical) { - if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) { + if (std::optional<NonLoc> strLn = strLength.getAs<NonLoc>()) { // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory(); const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy); @@ -872,7 +872,7 @@ SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state, // If we can't get a region, see if it's something we /know/ isn't a // C string. In the context of locations, the only time we can issue such // a warning is for labels. - if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) { + if (std::optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) { if (Filter.CheckCStringNotNullTerm) { SmallString<120> buf; llvm::raw_svector_ostream os(buf); @@ -977,7 +977,7 @@ bool CStringChecker::IsFirstBufInBound(CheckerContext &C, SVal BufVal = state->getSVal(FirstBuf, LCtx); SVal LengthVal = state->getSVal(Size, LCtx); - Optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); + std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); if (!Length) return true; // cf top comment. @@ -990,7 +990,7 @@ bool CStringChecker::IsFirstBufInBound(CheckerContext &C, // Check that the first buffer is sufficiently long. SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType()); - Optional<Loc> BufLoc = BufStart.getAs<Loc>(); + std::optional<Loc> BufLoc = BufStart.getAs<Loc>(); if (!BufLoc) return true; // cf top comment. @@ -1028,14 +1028,14 @@ ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C, const Expr *E, SVal V, bool IsSourceBuffer, const Expr *Size) { - Optional<Loc> L = V.getAs<Loc>(); + std::optional<Loc> L = V.getAs<Loc>(); if (!L) return state; // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes // some assumptions about the value that CFRefCount can't. Even so, it should // probably be refactored. - if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) { const MemRegion *R = MR->getRegion()->StripCasts(); // Are we dealing with an ElementRegion? If so, we should be invalidating @@ -1135,7 +1135,7 @@ bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal, RegionOffset Offset = MR->getAsOffset(); const MemRegion *BR = Offset.getRegion(); - Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>(); + std::optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>(); if (!SizeNL) return false; @@ -1507,8 +1507,8 @@ void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE, const Expr *maxlenExpr = CE->getArg(1); SVal maxlenVal = state->getSVal(maxlenExpr, LCtx); - Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); - Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>(); + std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); + std::optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>(); if (strLengthNL && maxlenValNL) { ProgramStateRef stateStringTooLong, stateStringNotTooLong; @@ -1656,11 +1656,11 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, // Get the string length of the source. SVal strLength = getCStringLength(C, state, srcExpr.Expression, srcVal); - Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); + std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); // Get the string length of the destination buffer. SVal dstStrLength = getCStringLength(C, state, Dst.Expression, DstVal); - Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>(); + std::optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>(); // If the source isn't a valid C string, give up. if (strLength.isUndef()) @@ -1698,7 +1698,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType()); - Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>(); + std::optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>(); // If we know both values, we might be able to figure out how much // we're copying. @@ -1740,7 +1740,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, freeSpace = svalBuilder.evalBinOp(state, BO_Sub, freeSpace, svalBuilder.makeIntVal(1, sizeTy), sizeTy); - Optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>(); + std::optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>(); // While unlikely, it is possible that the subtraction is // too complex to compute, let's check whether it succeeded. @@ -1865,7 +1865,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, *dstStrLengthNL, sizeTy); } - Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>(); + std::optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>(); // If we know both string lengths, we might know the final string length. if (amountCopiedNL && dstStrLengthNL) { @@ -1886,7 +1886,8 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, finalStrLength = getCStringLength(C, state, CE, DstVal, true); assert(!finalStrLength.isUndef()); - if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) { + if (std::optional<NonLoc> finalStrLengthNL = + finalStrLength.getAs<NonLoc>()) { if (amountCopiedNL && appendK == ConcatFnKind::none) { // we overwrite dst string with the src // finalStrLength >= srcStrLength @@ -1937,13 +1938,13 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, // If the destination is a MemRegion, try to check for a buffer overflow and // record the new string length. - if (Optional<loc::MemRegionVal> dstRegVal = - DstVal.getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> dstRegVal = + DstVal.getAs<loc::MemRegionVal>()) { QualType ptrTy = Dst.Expression->getType(); // If we have an exact value on a bounded copy, use that to check for // overflows, rather than our estimate about how much is actually copied. - if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) { + if (std::optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) { SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy); @@ -1953,7 +1954,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, } // Then, if the final length is known... - if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) { + if (std::optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) { SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *knownStrLength, ptrTy); @@ -2191,7 +2192,7 @@ void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const { SValBuilder &SVB = C.getSValBuilder(); SVal Result; - if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) { + if (std::optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) { // Get the current value of the search string pointer, as a char*. Result = State->getSVal(*SearchStrLoc, CharPtrTy); diff --git a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp index 92ada1f..152bdc9 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp @@ -473,7 +473,7 @@ bool CastValueChecker::evalCall(const CallEvent &Call, const CastCheck &Check = Lookup->first; CallKind Kind = Lookup->second; - Optional<DefinedOrUnknownSVal> DV; + std::optional<DefinedOrUnknownSVal> DV; switch (Kind) { case CallKind::Function: { diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp index a5e26b3..3fcf6f4 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp @@ -283,7 +283,7 @@ void ObjCDeallocChecker::checkBeginFunction( continue; SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal); - Optional<Loc> LValLoc = LVal.getAs<Loc>(); + std::optional<Loc> LValLoc = LVal.getAs<Loc>(); if (!LValLoc) continue; @@ -954,7 +954,7 @@ ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M, ProgramStateRef State = C.getState(); SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal); - Optional<Loc> LValLoc = LVal.getAs<Loc>(); + std::optional<Loc> LValLoc = LVal.getAs<Loc>(); if (!LValLoc) return nullptr; diff --git a/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp index 0f04ae6..cc01e97 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp @@ -68,7 +68,7 @@ void DivZeroChecker::checkPreStmt(const BinaryOperator *B, return; SVal Denom = C.getSVal(B->getRHS()); - Optional<DefinedSVal> DV = Denom.getAs<DefinedSVal>(); + std::optional<DefinedSVal> DV = Denom.getAs<DefinedSVal>(); // Divide-by-undefined handled in the generic checking for uses of // undefined values. diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp index 20374ff..6f26842 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp @@ -847,7 +847,7 @@ void DynamicTypePropagation::checkPreObjCMessage(const ObjCMethodCall &M, return; } - Optional<ArrayRef<QualType>> TypeArgs = + std::optional<ArrayRef<QualType>> TypeArgs = (*TrackedType)->getObjCSubstitutions(Method->getDeclContext()); // This case might happen when there is an unspecialized override of a // specialized method. @@ -980,7 +980,7 @@ void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M, if (!Method) return; - Optional<ArrayRef<QualType>> TypeArgs = + std::optional<ArrayRef<QualType>> TypeArgs = (*TrackedType)->getObjCSubstitutions(Method->getDeclContext()); if (!TypeArgs) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp index 1249080..1077ceb 100644 --- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp @@ -109,7 +109,7 @@ void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr *CE, } // Get the value of the expression to cast. - const llvm::Optional<DefinedOrUnknownSVal> ValueToCast = + const std::optional<DefinedOrUnknownSVal> ValueToCast = C.getSVal(CE->getSubExpr()).getAs<DefinedOrUnknownSVal>(); // If the value cannot be reasoned about (not even a DefinedOrUnknownSVal), diff --git a/clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp index 0a1b220..265185e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp @@ -133,7 +133,7 @@ void ErrnoChecker::generateErrnoNotCheckedBug( void ErrnoChecker::checkLocation(SVal Loc, bool IsLoad, const Stmt *S, CheckerContext &C) const { - Optional<ento::Loc> ErrnoLoc = getErrnoLoc(C.getState()); + std::optional<ento::Loc> ErrnoLoc = getErrnoLoc(C.getState()); if (!ErrnoLoc) return; @@ -207,7 +207,7 @@ void ErrnoChecker::checkPreCall(const CallEvent &Call, C.getSourceManager().isInSystemHeader(CallF->getLocation()) && !isErrno(CallF)) { if (getErrnoState(C.getState()) == MustBeChecked) { - Optional<ento::Loc> ErrnoLoc = getErrnoLoc(C.getState()); + std::optional<ento::Loc> ErrnoLoc = getErrnoLoc(C.getState()); assert(ErrnoLoc && "ErrnoLoc should exist if an errno state is set."); generateErrnoNotCheckedBug(C, setErrnoStateIrrelevant(C.getState()), ErrnoLoc->getAsRegion(), &Call); @@ -220,7 +220,7 @@ ProgramStateRef ErrnoChecker::checkRegionChanges( ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx, const CallEvent *Call) const { - Optional<ento::Loc> ErrnoLoc = getErrnoLoc(State); + std::optional<ento::Loc> ErrnoLoc = getErrnoLoc(State); if (!ErrnoLoc) return State; const MemRegion *ErrnoRegion = ErrnoLoc->getAsRegion(); diff --git a/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp index ade172c..51f39c6 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp @@ -208,7 +208,7 @@ namespace clang { namespace ento { namespace errno_modeling { -Optional<SVal> getErrnoValue(ProgramStateRef State) { +std::optional<SVal> getErrnoValue(ProgramStateRef State) { const MemRegion *ErrnoR = State->get<ErrnoRegion>(); if (!ErrnoR) return {}; @@ -240,7 +240,7 @@ ProgramStateRef setErrnoValue(ProgramStateRef State, CheckerContext &C, return State->set<ErrnoState>(EState); } -Optional<Loc> getErrnoLoc(ProgramStateRef State) { +std::optional<Loc> getErrnoLoc(ProgramStateRef State) { const MemRegion *ErrnoR = State->get<ErrnoRegion>(); if (!ErrnoR) return {}; diff --git a/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h b/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h index 765c671..2ca3979 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h +++ b/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h @@ -43,7 +43,7 @@ enum ErrnoCheckState : unsigned { }; /// Returns the value of 'errno', if 'errno' was found in the AST. -llvm::Optional<SVal> getErrnoValue(ProgramStateRef State); +std::optional<SVal> getErrnoValue(ProgramStateRef State); /// Returns the errno check state, \c Errno_Irrelevant if 'errno' was not found /// (this is not the only case for that value). @@ -52,7 +52,7 @@ ErrnoCheckState getErrnoState(ProgramStateRef State); /// Returns the location that points to the \c MemoryRegion where the 'errno' /// value is stored. Returns \c std::nullopt if 'errno' was not found. Otherwise /// it always returns a valid memory region in the system global memory space. -llvm::Optional<Loc> getErrnoLoc(ProgramStateRef State); +std::optional<Loc> getErrnoLoc(ProgramStateRef State); /// Set value of 'errno' to any SVal, if possible. /// The errno check state is set always when the 'errno' value is set. diff --git a/clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp index 9d09393..c46ebee0 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp @@ -92,7 +92,7 @@ void ErrnoTesterChecker::evalGetErrno(CheckerContext &C, const CallEvent &Call) { ProgramStateRef State = C.getState(); - Optional<SVal> ErrnoVal = getErrnoValue(State); + std::optional<SVal> ErrnoVal = getErrnoValue(State); assert(ErrnoVal && "Errno value should be available."); State = State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), *ErrnoVal); diff --git a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp index 3733e58..355e9c2 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp @@ -59,9 +59,9 @@ class ExprInspectionChecker // Optional parameter `ExprVal` for expression value to be marked interesting. ExplodedNode *reportBug(llvm::StringRef Msg, CheckerContext &C, - Optional<SVal> ExprVal = std::nullopt) const; + std::optional<SVal> ExprVal = std::nullopt) const; ExplodedNode *reportBug(llvm::StringRef Msg, BugReporter &BR, ExplodedNode *N, - Optional<SVal> ExprVal = std::nullopt) const; + std::optional<SVal> ExprVal = std::nullopt) const; template <typename T> void printAndReport(CheckerContext &C, T What) const; const Expr *getArgExpr(const CallExpr *CE, CheckerContext &C) const; @@ -162,17 +162,18 @@ static const char *getArgumentValueString(const CallExpr *CE, } } -ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg, - CheckerContext &C, - Optional<SVal> ExprVal) const { +ExplodedNode * +ExprInspectionChecker::reportBug(llvm::StringRef Msg, CheckerContext &C, + std::optional<SVal> ExprVal) const { ExplodedNode *N = C.generateNonFatalErrorNode(); reportBug(Msg, C.getBugReporter(), N, ExprVal); return N; } -ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg, - BugReporter &BR, ExplodedNode *N, - Optional<SVal> ExprVal) const { +ExplodedNode * +ExprInspectionChecker::reportBug(llvm::StringRef Msg, BugReporter &BR, + ExplodedNode *N, + std::optional<SVal> ExprVal) const { if (!N) return nullptr; @@ -467,13 +468,13 @@ void ExprInspectionChecker::analyzerDenote(const CallExpr *CE, namespace { class SymbolExpressor - : public SymExprVisitor<SymbolExpressor, Optional<std::string>> { + : public SymExprVisitor<SymbolExpressor, std::optional<std::string>> { ProgramStateRef State; public: SymbolExpressor(ProgramStateRef State) : State(State) {} - Optional<std::string> lookup(const SymExpr *S) { + std::optional<std::string> lookup(const SymExpr *S) { if (const StringLiteral *const *SLPtr = State->get<DenotedSymbols>(S)) { const StringLiteral *SL = *SLPtr; return std::string(SL->getBytes()); @@ -481,12 +482,14 @@ public: return std::nullopt; } - Optional<std::string> VisitSymExpr(const SymExpr *S) { return lookup(S); } + std::optional<std::string> VisitSymExpr(const SymExpr *S) { + return lookup(S); + } - Optional<std::string> VisitSymIntExpr(const SymIntExpr *S) { - if (Optional<std::string> Str = lookup(S)) + std::optional<std::string> VisitSymIntExpr(const SymIntExpr *S) { + if (std::optional<std::string> Str = lookup(S)) return Str; - if (Optional<std::string> Str = Visit(S->getLHS())) + if (std::optional<std::string> Str = Visit(S->getLHS())) return (*Str + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " + std::to_string(S->getRHS().getLimitedValue()) + (S->getRHS().isUnsigned() ? "U" : "")) @@ -494,29 +497,29 @@ public: return std::nullopt; } - Optional<std::string> VisitSymSymExpr(const SymSymExpr *S) { - if (Optional<std::string> Str = lookup(S)) + std::optional<std::string> VisitSymSymExpr(const SymSymExpr *S) { + if (std::optional<std::string> Str = lookup(S)) return Str; - if (Optional<std::string> Str1 = Visit(S->getLHS())) - if (Optional<std::string> Str2 = Visit(S->getRHS())) + if (std::optional<std::string> Str1 = Visit(S->getLHS())) + if (std::optional<std::string> Str2 = Visit(S->getRHS())) return (*Str1 + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " + *Str2) .str(); return std::nullopt; } - Optional<std::string> VisitUnarySymExpr(const UnarySymExpr *S) { - if (Optional<std::string> Str = lookup(S)) + std::optional<std::string> VisitUnarySymExpr(const UnarySymExpr *S) { + if (std::optional<std::string> Str = lookup(S)) return Str; - if (Optional<std::string> Str = Visit(S->getOperand())) + if (std::optional<std::string> Str = Visit(S->getOperand())) return (UnaryOperator::getOpcodeStr(S->getOpcode()) + *Str).str(); return std::nullopt; } - Optional<std::string> VisitSymbolCast(const SymbolCast *S) { - if (Optional<std::string> Str = lookup(S)) + std::optional<std::string> VisitSymbolCast(const SymbolCast *S) { + if (std::optional<std::string> Str = lookup(S)) return Str; - if (Optional<std::string> Str = Visit(S->getOperand())) + if (std::optional<std::string> Str = Visit(S->getOperand())) return (Twine("(") + S->getType().getAsString() + ")" + *Str).str(); return std::nullopt; } diff --git a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp index c093483..65ff1be 100644 --- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp @@ -301,7 +301,7 @@ getFuchsiaHandleSymbols(QualType QT, SVal Arg, ProgramStateRef State) { } } else { assert(PtrToHandleLevel == 1); - if (Optional<Loc> ArgLoc = Arg.getAs<Loc>()) { + if (std::optional<Loc> ArgLoc = Arg.getAs<Loc>()) { SymbolRef Sym = State->getSVal(*ArgLoc).getAsSymbol(); if (Sym) { return {Sym}; diff --git a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp index e9a577b..43d2eee 100644 --- a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp @@ -259,7 +259,7 @@ SVal GTestChecker::getAssertionResultSuccessFieldValue( if (!SuccessField) return UnknownVal(); - Optional<Loc> FieldLoc = + std::optional<Loc> FieldLoc = State->getLValue(SuccessField, Instance).getAs<Loc>(); if (!FieldLoc) return UnknownVal(); diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp index 80f9f88..f6e2f59 100644 --- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp @@ -125,7 +125,7 @@ SVal getPointeeOf(const CheckerContext &C, Loc LValue) { } /// Given a pointer/reference argument, return the value it refers to. -Optional<SVal> getPointeeOf(const CheckerContext &C, SVal Arg) { +std::optional<SVal> getPointeeOf(const CheckerContext &C, SVal Arg) { if (auto LValue = Arg.getAs<Loc>()) return getPointeeOf(C, *LValue); return std::nullopt; @@ -134,7 +134,8 @@ Optional<SVal> getPointeeOf(const CheckerContext &C, SVal Arg) { /// Given a pointer, return the SVal of its pointee or if it is tainted, /// otherwise return the pointer's SVal if tainted. /// Also considers stdin as a taint source. -Optional<SVal> getTaintedPointeeOrPointer(const CheckerContext &C, SVal Arg) { +std::optional<SVal> getTaintedPointeeOrPointer(const CheckerContext &C, + SVal Arg) { const ProgramStateRef State = C.getState(); if (auto Pointee = getPointeeOf(C, Arg)) @@ -163,7 +164,7 @@ class ArgSet { public: ArgSet() = default; ArgSet(ArgVecTy &&DiscreteArgs, - Optional<ArgIdxTy> VariadicIndex = std::nullopt) + std::optional<ArgIdxTy> VariadicIndex = std::nullopt) : DiscreteArgs(std::move(DiscreteArgs)), VariadicIndex(std::move(VariadicIndex)) {} @@ -178,7 +179,7 @@ public: private: ArgVecTy DiscreteArgs; - Optional<ArgIdxTy> VariadicIndex; + std::optional<ArgIdxTy> VariadicIndex; }; /// A struct used to specify taint propagation rules for a function. @@ -199,12 +200,12 @@ class GenericTaintRule { ArgSet PropDstArgs; /// A message that explains why the call is sensitive to taint. - Optional<StringRef> SinkMsg; + std::optional<StringRef> SinkMsg; GenericTaintRule() = default; GenericTaintRule(ArgSet &&Sink, ArgSet &&Filter, ArgSet &&Src, ArgSet &&Dst, - Optional<StringRef> SinkMsg = std::nullopt) + std::optional<StringRef> SinkMsg = std::nullopt) : SinkArgs(std::move(Sink)), FilterArgs(std::move(Filter)), PropSrcArgs(std::move(Src)), PropDstArgs(std::move(Dst)), SinkMsg(SinkMsg) {} @@ -213,7 +214,7 @@ public: /// Make a rule that reports a warning if taint reaches any of \p FilterArgs /// arguments. static GenericTaintRule Sink(ArgSet &&SinkArgs, - Optional<StringRef> Msg = std::nullopt) { + std::optional<StringRef> Msg = std::nullopt) { return {std::move(SinkArgs), {}, {}, {}, Msg}; } @@ -234,9 +235,9 @@ public: } /// Make a rule that taints all PropDstArgs if any of PropSrcArgs is tainted. - static GenericTaintRule SinkProp(ArgSet &&SinkArgs, ArgSet &&SrcArgs, - ArgSet &&DstArgs, - Optional<StringRef> Msg = std::nullopt) { + static GenericTaintRule + SinkProp(ArgSet &&SinkArgs, ArgSet &&SrcArgs, ArgSet &&DstArgs, + std::optional<StringRef> Msg = std::nullopt) { return { std::move(SinkArgs), {}, std::move(SrcArgs), std::move(DstArgs), Msg}; } @@ -482,7 +483,7 @@ void GenericTaintRuleParser::parseConfig(const std::string &Option, validateArgVector(Option, P.DstArgs); bool IsSrcVariadic = P.VarType == TaintConfiguration::VariadicType::Src; bool IsDstVariadic = P.VarType == TaintConfiguration::VariadicType::Dst; - Optional<ArgIdxTy> JustVarIndex = P.VarIndex; + std::optional<ArgIdxTy> JustVarIndex = P.VarIndex; ArgSet SrcDesc(std::move(P.SrcArgs), IsSrcVariadic ? JustVarIndex : std::nullopt); @@ -725,7 +726,7 @@ void GenericTaintChecker::initTaintRules(CheckerContext &C) const { std::string Option{"Config"}; StringRef ConfigFile = Mgr->getAnalyzerOptions().getCheckerStringOption(this, Option); - llvm::Optional<TaintConfiguration> Config = + std::optional<TaintConfiguration> Config = getConfiguration<TaintConfiguration>(*Mgr, this, Option, ConfigFile); if (!Config) { // We don't have external taint config, no parsing required. @@ -901,7 +902,7 @@ bool GenericTaintRule::UntrustedEnv(CheckerContext &C) { bool GenericTaintChecker::generateReportIfTainted(const Expr *E, StringRef Msg, CheckerContext &C) const { assert(E); - Optional<SVal> TaintedSVal{getTaintedPointeeOrPointer(C, C.getSVal(E))}; + std::optional<SVal> TaintedSVal{getTaintedPointeeOrPointer(C, C.getSVal(E))}; if (!TaintedSVal) return false; diff --git a/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp index 6b0b6c6..bca10ec 100644 --- a/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp @@ -1005,7 +1005,7 @@ NonLocalizedStringBRVisitor::VisitNode(const ExplodedNode *Succ, if (Satisfied) return nullptr; - Optional<StmtPoint> Point = Succ->getLocation().getAs<StmtPoint>(); + std::optional<StmtPoint> Point = Succ->getLocation().getAs<StmtPoint>(); if (!Point) return nullptr; @@ -1142,7 +1142,7 @@ void EmptyLocalizationContextChecker::MethodCrawler::VisitObjCMessageExpr( SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first); } - llvm::Optional<llvm::MemoryBufferRef> BF = + std::optional<llvm::MemoryBufferRef> BF = Mgr.getSourceManager().getBufferOrNone(SLInfo.first, SL); if (!BF) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp index b5f3916..153a0a5 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp @@ -158,7 +158,7 @@ static bool isInMIGCall(CheckerContext &C) { const Decl *D = SFC->getDecl(); - if (Optional<AnyCall> AC = AnyCall::forDecl(D)) { + if (std::optional<AnyCall> AC = AnyCall::forDecl(D)) { // Even though there's a Sema warning when the return type of an annotated // function is not a kern_return_t, this warning isn't an error, so we need // an extra check here. diff --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp index 65867dc..c1b85ac 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp @@ -210,7 +210,7 @@ static SymbolRef getAsPointeeSymbol(const Expr *Expr, ProgramStateRef State = C.getState(); SVal ArgV = C.getSVal(Expr); - if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) { StoreManager& SM = C.getStoreManager(); SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol(); if (sym) diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index aa24f1a03..f05cd92 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -224,7 +224,7 @@ static bool isReleased(SymbolRef Sym, CheckerContext &C); static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family, - Optional<SVal> RetVal = std::nullopt); + std::optional<SVal> RetVal = std::nullopt); //===----------------------------------------------------------------------===// // The modeling of memory reallocation. @@ -446,7 +446,7 @@ private: // TODO: Remove mutable by moving the initializtaion to the registry function. mutable std::optional<uint64_t> KernelZeroFlagVal; - using KernelZeroSizePtrValueTy = Optional<int>; + using KernelZeroSizePtrValueTy = std::optional<int>; /// Store the value of macro called `ZERO_SIZE_PTR`. /// The value is initialized at first use, before first use the outer /// Optional is empty, afterwards it contains another Optional that indicates @@ -470,7 +470,7 @@ private: [[nodiscard]] static ProgramStateRef ProcessZeroAllocCheck(const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State, - Optional<SVal> RetVal = std::nullopt); + std::optional<SVal> RetVal = std::nullopt); /// Model functions with the ownership_returns attribute. /// @@ -520,7 +520,7 @@ private: // Check if this malloc() for special flags. At present that means M_ZERO or // __GFP_ZERO (in which case, treat it like calloc). - [[nodiscard]] llvm::Optional<ProgramStateRef> + [[nodiscard]] std::optional<ProgramStateRef> performKernelMalloc(const CallEvent &Call, CheckerContext &C, const ProgramStateRef &State) const; @@ -673,11 +673,11 @@ private: /// Tells if a given family/call/symbol is tracked by the current checker. /// Sets CheckKind to the kind of the checker responsible for this /// family/call/symbol. - Optional<CheckKind> getCheckIfTracked(AllocationFamily Family, - bool IsALeakCheck = false) const; + std::optional<CheckKind> getCheckIfTracked(AllocationFamily Family, + bool IsALeakCheck = false) const; - Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym, - bool IsALeakCheck = false) const; + std::optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym, + bool IsALeakCheck = false) const; ///@} static bool SummarizeValue(raw_ostream &os, SVal V); static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR); @@ -1118,7 +1118,7 @@ bool MallocChecker::isMemCall(const CallEvent &Call) const { return Func && Func->hasAttr<OwnershipAttr>(); } -llvm::Optional<ProgramStateRef> +std::optional<ProgramStateRef> MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C, const ProgramStateRef &State) const { // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels: @@ -1221,7 +1221,7 @@ void MallocChecker::checkBasicAlloc(const CallEvent &Call, void MallocChecker::checkKernelMalloc(const CallEvent &Call, CheckerContext &C) const { ProgramStateRef State = C.getState(); - llvm::Optional<ProgramStateRef> MaybeState = + std::optional<ProgramStateRef> MaybeState = performKernelMalloc(Call, C, State); if (MaybeState) State = *MaybeState; @@ -1491,7 +1491,7 @@ void MallocChecker::checkPostCall(const CallEvent &Call, // Performs a 0-sized allocations check. ProgramStateRef MallocChecker::ProcessZeroAllocCheck( const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State, - Optional<SVal> RetVal) { + std::optional<SVal> RetVal) { if (!State) return nullptr; @@ -1748,7 +1748,7 @@ ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family, - Optional<SVal> RetVal) { + std::optional<SVal> RetVal) { if (!State) return nullptr; @@ -2063,7 +2063,7 @@ ProgramStateRef MallocChecker::FreeMemAux( RefState::getReleased(Family, ParentExpr)); } -Optional<MallocChecker::CheckKind> +std::optional<MallocChecker::CheckKind> MallocChecker::getCheckIfTracked(AllocationFamily Family, bool IsALeakCheck) const { switch (Family) { @@ -2098,7 +2098,7 @@ MallocChecker::getCheckIfTracked(AllocationFamily Family, llvm_unreachable("unhandled family"); } -Optional<MallocChecker::CheckKind> +std::optional<MallocChecker::CheckKind> MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym, bool IsALeakCheck) const { if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) @@ -2110,11 +2110,13 @@ MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym, } bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) { - if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>()) + if (std::optional<nonloc::ConcreteInt> IntVal = + V.getAs<nonloc::ConcreteInt>()) os << "an integer (" << IntVal->getValue() << ")"; - else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>()) + else if (std::optional<loc::ConcreteInt> ConstAddr = + V.getAs<loc::ConcreteInt>()) os << "a constant address (" << ConstAddr->getValue() << ")"; - else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>()) + else if (std::optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>()) os << "the address of the label '" << Label->getLabel()->getName() << "'"; else return false; @@ -2206,7 +2208,7 @@ void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); if (!CheckKind) return; @@ -2339,7 +2341,7 @@ void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); if (!CheckKind) return; @@ -2396,7 +2398,7 @@ void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); if (!CheckKind) return; @@ -2435,7 +2437,7 @@ void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); if (!CheckKind) return; @@ -2465,7 +2467,7 @@ void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const { return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); if (!CheckKind) return; @@ -2492,7 +2494,7 @@ void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); if (!CheckKind) return; @@ -2525,7 +2527,7 @@ void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, return; } - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); + std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); if (!CheckKind) return; @@ -2736,8 +2738,8 @@ void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N, if (Family == AF_Alloca) return; - Optional<MallocChecker::CheckKind> - CheckKind = getCheckIfTracked(Family, true); + std::optional<MallocChecker::CheckKind> CheckKind = + getCheckIfTracked(Family, true); if (!CheckKind) return; @@ -3559,7 +3561,8 @@ void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State, for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { const RefState *RefS = State->get<RegionState>(I.getKey()); AllocationFamily Family = RefS->getAllocationFamily(); - Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); + std::optional<MallocChecker::CheckKind> CheckKind = + getCheckIfTracked(Family); if (!CheckKind) CheckKind = getCheckIfTracked(Family, true); diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp index 9fba90d..5266df2 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp @@ -309,26 +309,27 @@ void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D, CFGBlock *block = *it; for (CFGBlock::iterator bi = block->begin(), be = block->end(); bi != be; ++bi) { - if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) { - if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) { - // Get the callee. - const FunctionDecl *FD = TheCall->getDirectCallee(); - - if (!FD) - continue; - - // Get the name of the callee. If it's a builtin, strip off the prefix. - IdentifierInfo *FnInfo = FD->getIdentifier(); - if (!FnInfo) - continue; - - if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) { - if (TheCall->getNumArgs() == 1) - CheckMallocArgument(PossibleMallocOverflows, TheCall, - mgr.getASTContext()); + if (std::optional<CFGStmt> CS = bi->getAs<CFGStmt>()) { + if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) { + // Get the callee. + const FunctionDecl *FD = TheCall->getDirectCallee(); + + if (!FD) + continue; + + // Get the name of the callee. If it's a builtin, strip off the + // prefix. + IdentifierInfo *FnInfo = FD->getIdentifier(); + if (!FnInfo) + continue; + + if (FnInfo->isStr("malloc") || FnInfo->isStr("_MALLOC")) { + if (TheCall->getNumArgs() == 1) + CheckMallocArgument(PossibleMallocOverflows, TheCall, + mgr.getASTContext()); + } } } - } } } diff --git a/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp index 6226c0e..59741dd 100644 --- a/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp @@ -198,7 +198,7 @@ static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) { static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) { const StackFrameContext * SFC = C.getStackFrame(); - if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) { const MemRegion* R = X->getRegion(); if (const VarRegion *VR = R->getAs<VarRegion>()) if (const StackArgumentsSpaceRegion * diff --git a/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp index e92cbae..72c6a86 100644 --- a/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp @@ -78,7 +78,8 @@ void NonnullGlobalConstantsChecker::checkLocation(SVal location, bool isLoad, if (isGlobalConstString(location)) { SVal V = State->getSVal(location.castAs<Loc>()); - Optional<DefinedOrUnknownSVal> Constr = V.getAs<DefinedOrUnknownSVal>(); + std::optional<DefinedOrUnknownSVal> Constr = + V.getAs<DefinedOrUnknownSVal>(); if (Constr) { @@ -92,7 +93,7 @@ void NonnullGlobalConstantsChecker::checkLocation(SVal location, bool isLoad, /// \param V loaded lvalue. /// \return whether @c val is a string-like const global. bool NonnullGlobalConstantsChecker::isGlobalConstString(SVal V) const { - Optional<loc::MemRegionVal> RegionVal = V.getAs<loc::MemRegionVal>(); + std::optional<loc::MemRegionVal> RegionVal = V.getAs<loc::MemRegionVal>(); if (!RegionVal) return false; auto *Region = dyn_cast<VarRegion>(RegionVal->getAsRegion()); diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp index e52a54a..01c71d9 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp @@ -285,7 +285,7 @@ void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex, void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const { - Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>(); + std::optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>(); if (!IVarLoc) return; @@ -413,8 +413,8 @@ static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { return RetTy; } -static Optional<RefVal> refValFromRetEffect(RetEffect RE, - QualType ResultTy) { +static std::optional<RefVal> refValFromRetEffect(RetEffect RE, + QualType ResultTy) { if (RE.isOwned()) { return RefVal::makeOwned(RE.getObjKind(), ResultTy); } else if (RE.notOwned()) { @@ -693,7 +693,7 @@ void RetainCountChecker::checkSummary(const RetainSummary &Summ, assert(Ex); ResultTy = GetReturnType(Ex, C.getASTContext()); } - if (Optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy)) + if (std::optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy)) state = setRefBinding(state, Sym, *updatedRefVal); } @@ -908,7 +908,7 @@ bool RetainCountChecker::evalCall(const CallEvent &Call, const LocationContext *LCtx = C.getLocationContext(); using BehaviorSummary = RetainSummaryManager::BehaviorSummary; - Optional<BehaviorSummary> BSmr = + std::optional<BehaviorSummary> BSmr = SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation); // See if it's one of the specific functions we know how to eval. @@ -1337,7 +1337,7 @@ void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const { RetainSummaryManager &SmrMgr = getSummaryManager(Ctx); const LocationContext *LCtx = Ctx.getLocationContext(); const Decl *D = LCtx->getDecl(); - Optional<AnyCall> C = AnyCall::forDecl(D); + std::optional<AnyCall> C = AnyCall::forDecl(D); if (!C || SmrMgr.isTrustedReferenceCountImplementation(D)) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp index afacf73..e11e509 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp @@ -167,10 +167,9 @@ static bool shouldGenerateNote(llvm::raw_string_ostream &os, /// Finds argument index of the out paramter in the call @c S /// corresponding to the symbol @c Sym. /// If none found, returns std::nullopt. -static std::optional<unsigned> findArgIdxOfSymbol(ProgramStateRef CurrSt, - const LocationContext *LCtx, - SymbolRef &Sym, - Optional<CallEventRef<>> CE) { +static std::optional<unsigned> +findArgIdxOfSymbol(ProgramStateRef CurrSt, const LocationContext *LCtx, + SymbolRef &Sym, std::optional<CallEventRef<>> CE) { if (!CE) return std::nullopt; @@ -251,7 +250,7 @@ static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt, } } - Optional<CallEventRef<>> CE = Mgr.getCall(S, CurrSt, LCtx); + std::optional<CallEventRef<>> CE = Mgr.getCall(S, CurrSt, LCtx); auto Idx = findArgIdxOfSymbol(CurrSt, LCtx, Sym, CE); // If index is not found, we assume that the symbol was returned. @@ -731,7 +730,7 @@ static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr, const LocationContext *InterestingMethodContext = nullptr; if (InitMethodContext) { const ProgramPoint AllocPP = AllocationNode->getLocation(); - if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>()) + if (std::optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>()) if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>()) if (ME->getMethodFamily() == OMF_alloc) InterestingMethodContext = InitMethodContext; diff --git a/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp index baf443c..b098a3e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp @@ -71,8 +71,8 @@ static std::string getName(const CallEvent &Call) { // The predefinitions ('CDM') could break due to the ever growing code base. // Check for the expected invariants and see whether they apply. -static Optional<bool> isInvariantBreak(bool ExpectedValue, SVal ReturnV, - CheckerContext &C) { +static std::optional<bool> isInvariantBreak(bool ExpectedValue, SVal ReturnV, + CheckerContext &C) { auto ReturnDV = ReturnV.getAs<DefinedOrUnknownSVal>(); if (!ReturnDV) return std::nullopt; @@ -91,7 +91,8 @@ void ReturnValueChecker::checkPostCall(const CallEvent &Call, SVal ReturnV = Call.getReturnValue(); bool ExpectedValue = *RawExpectedValue; - Optional<bool> IsInvariantBreak = isInvariantBreak(ExpectedValue, ReturnV, C); + std::optional<bool> IsInvariantBreak = + isInvariantBreak(ExpectedValue, ReturnV, C); if (!IsInvariantBreak) return; @@ -138,7 +139,8 @@ void ReturnValueChecker::checkEndFunction(const ReturnStmt *RS, SVal ReturnV = State->getSVal(RS->getRetValue(), C.getLocationContext()); bool ExpectedValue = *RawExpectedValue; - Optional<bool> IsInvariantBreak = isInvariantBreak(ExpectedValue, ReturnV, C); + std::optional<bool> IsInvariantBreak = + isInvariantBreak(ExpectedValue, ReturnV, C); if (!IsInvariantBreak) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp index 5b921e7..5689a63 100644 --- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp @@ -299,8 +299,9 @@ bool SmartPtrModeling::evalCall(const CallEvent &Call, if (matchesAny(Call, StdMakeUniqueCall, StdMakeUniqueForOverwriteCall)) { if (!ModelSmartPtrDereference) return false; - - const Optional<SVal> ThisRegionOpt = Call.getReturnValueUnderConstruction(); + + const std::optional<SVal> ThisRegionOpt = + Call.getReturnValueUnderConstruction(); if (!ThisRegionOpt) return false; diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp index 4a15efd..49b3db5 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp @@ -541,8 +541,8 @@ class StdLibraryFunctionsChecker StringRef getNote() const { return Note; } }; - using ArgTypes = std::vector<Optional<QualType>>; - using RetType = Optional<QualType>; + using ArgTypes = std::vector<std::optional<QualType>>; + using RetType = std::optional<QualType>; // A placeholder type, we use it whenever we do not care about the concrete // type in a Signature. @@ -564,7 +564,7 @@ class StdLibraryFunctionsChecker // Construct a signature from optional types. If any of the optional types // are not set then the signature will be invalid. Signature(ArgTypes ArgTys, RetType RetTy) { - for (Optional<QualType> Arg : ArgTys) { + for (std::optional<QualType> Arg : ArgTys) { if (!Arg) { Invalid = true; return; @@ -717,10 +717,10 @@ public: bool ShouldAssumeControlledEnvironment = false; private: - Optional<Summary> findFunctionSummary(const FunctionDecl *FD, - CheckerContext &C) const; - Optional<Summary> findFunctionSummary(const CallEvent &Call, - CheckerContext &C) const; + std::optional<Summary> findFunctionSummary(const FunctionDecl *FD, + CheckerContext &C) const; + std::optional<Summary> findFunctionSummary(const CallEvent &Call, + CheckerContext &C) const; void initFunctionSummaries(CheckerContext &C) const; @@ -969,7 +969,7 @@ ProgramStateRef StdLibraryFunctionsChecker::ComparisonConstraint::apply( void StdLibraryFunctionsChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { - Optional<Summary> FoundSummary = findFunctionSummary(Call, C); + std::optional<Summary> FoundSummary = findFunctionSummary(Call, C); if (!FoundSummary) return; @@ -1013,7 +1013,7 @@ void StdLibraryFunctionsChecker::checkPreCall(const CallEvent &Call, void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const { - Optional<Summary> FoundSummary = findFunctionSummary(Call, C); + std::optional<Summary> FoundSummary = findFunctionSummary(Call, C); if (!FoundSummary) return; @@ -1068,7 +1068,7 @@ void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call, bool StdLibraryFunctionsChecker::evalCall(const CallEvent &Call, CheckerContext &C) const { - Optional<Summary> FoundSummary = findFunctionSummary(Call, C); + std::optional<Summary> FoundSummary = findFunctionSummary(Call, C); if (!FoundSummary) return false; @@ -1135,7 +1135,7 @@ bool StdLibraryFunctionsChecker::Signature::matches( return true; } -Optional<StdLibraryFunctionsChecker::Summary> +std::optional<StdLibraryFunctionsChecker::Summary> StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD, CheckerContext &C) const { if (!FD) @@ -1149,7 +1149,7 @@ StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD, return FSMI->second; } -Optional<StdLibraryFunctionsChecker::Summary> +std::optional<StdLibraryFunctionsChecker::Summary> StdLibraryFunctionsChecker::findFunctionSummary(const CallEvent &Call, CheckerContext &C) const { const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl()); @@ -1175,7 +1175,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( LookupType(const ASTContext &ACtx) : ACtx(ACtx) {} // Find the type. If not found then the optional is not set. - llvm::Optional<QualType> operator()(StringRef Name) { + std::optional<QualType> operator()(StringRef Name) { IdentifierInfo &II = ACtx.Idents.get(Name); auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II); if (LookupRes.empty()) @@ -1211,7 +1211,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( QualType operator()(QualType Ty) { return ACtx.getLangOpts().C99 ? ACtx.getRestrictType(Ty) : Ty; } - Optional<QualType> operator()(Optional<QualType> Ty) { + std::optional<QualType> operator()(std::optional<QualType> Ty) { if (Ty) return operator()(*Ty); return std::nullopt; @@ -1223,7 +1223,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( public: GetPointerTy(const ASTContext &ACtx) : ACtx(ACtx) {} QualType operator()(QualType Ty) { return ACtx.getPointerType(Ty); } - Optional<QualType> operator()(Optional<QualType> Ty) { + std::optional<QualType> operator()(std::optional<QualType> Ty) { if (Ty) return operator()(*Ty); return std::nullopt; @@ -1231,8 +1231,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( } getPointerTy(ACtx); class { public: - Optional<QualType> operator()(Optional<QualType> Ty) { - return Ty ? Optional<QualType>(Ty->withConst()) : std::nullopt; + std::optional<QualType> operator()(std::optional<QualType> Ty) { + return Ty ? std::optional<QualType>(Ty->withConst()) : std::nullopt; } QualType operator()(QualType Ty) { return Ty.withConst(); } } getConstTy; @@ -1241,10 +1241,10 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( public: GetMaxValue(BasicValueFactory &BVF) : BVF(BVF) {} - Optional<RangeInt> operator()(QualType Ty) { + std::optional<RangeInt> operator()(QualType Ty) { return BVF.getMaxValue(Ty).getLimitedValue(); } - Optional<RangeInt> operator()(Optional<QualType> Ty) { + std::optional<RangeInt> operator()(std::optional<QualType> Ty) { if (Ty) { return operator()(*Ty); } @@ -1304,7 +1304,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( // The platform dependent value of EOF. // Try our best to parse this from the Preprocessor, otherwise fallback to -1. const auto EOFv = [&C]() -> RangeInt { - if (const llvm::Optional<int> OptInt = + if (const std::optional<int> OptInt = tryExpandAsInteger("EOF", C.getPreprocessor())) return *OptInt; return -1; @@ -1377,13 +1377,13 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( auto operator()(RangeInt b, RangeInt e) { return IntRangeVector{std::pair<RangeInt, RangeInt>{b, e}}; } - auto operator()(RangeInt b, Optional<RangeInt> e) { + auto operator()(RangeInt b, std::optional<RangeInt> e) { if (e) return IntRangeVector{std::pair<RangeInt, RangeInt>{b, *e}}; return IntRangeVector{}; } auto operator()(std::pair<RangeInt, RangeInt> i0, - std::pair<RangeInt, Optional<RangeInt>> i1) { + std::pair<RangeInt, std::optional<RangeInt>> i1) { if (i1.second) return IntRangeVector{i0, {i1.first, *(i1.second)}}; return IntRangeVector{i0}; @@ -1400,14 +1400,14 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( return std::make_shared<NotNullConstraint>(ArgN, false); }; - Optional<QualType> FileTy = lookupTy("FILE"); - Optional<QualType> FilePtrTy = getPointerTy(FileTy); - Optional<QualType> FilePtrRestrictTy = getRestrictTy(FilePtrTy); + std::optional<QualType> FileTy = lookupTy("FILE"); + std::optional<QualType> FilePtrTy = getPointerTy(FileTy); + std::optional<QualType> FilePtrRestrictTy = getRestrictTy(FilePtrTy); - Optional<QualType> FPosTTy = lookupTy("fpos_t"); - Optional<QualType> FPosTPtrTy = getPointerTy(FPosTTy); - Optional<QualType> ConstFPosTPtrTy = getPointerTy(getConstTy(FPosTTy)); - Optional<QualType> FPosTPtrRestrictTy = getRestrictTy(FPosTPtrTy); + std::optional<QualType> FPosTTy = lookupTy("fpos_t"); + std::optional<QualType> FPosTPtrTy = getPointerTy(FPosTTy); + std::optional<QualType> ConstFPosTPtrTy = getPointerTy(getConstTy(FPosTTy)); + std::optional<QualType> FPosTPtrRestrictTy = getRestrictTy(FPosTPtrTy); // We are finally ready to define specifications for all supported functions. // @@ -1668,8 +1668,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( RetType{SizeTy}), FreadSummary); - Optional<QualType> Ssize_tTy = lookupTy("ssize_t"); - Optional<RangeInt> Ssize_tMax = getMaxValue(Ssize_tTy); + std::optional<QualType> Ssize_tTy = lookupTy("ssize_t"); + std::optional<RangeInt> Ssize_tMax = getMaxValue(Ssize_tTy); auto ReadSummary = Summary(NoEvalCall) @@ -1947,7 +1947,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint(ArgumentCondition( 0, WithinRange, Range(0, IntMax)))); - Optional<QualType> Off_tTy = lookupTy("off_t"); + std::optional<QualType> Off_tTy = lookupTy("off_t"); // int truncate(const char *path, off_t length); addToFunctionSummaryMap( @@ -1989,7 +1989,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint( ArgumentCondition(0, WithinRange, Range(0, IntMax)))); - Optional<QualType> Mode_tTy = lookupTy("mode_t"); + std::optional<QualType> Mode_tTy = lookupTy("mode_t"); // int creat(const char *pathname, mode_t mode); addToFunctionSummaryMap( @@ -2006,8 +2006,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint( ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax)))); - Optional<QualType> DirTy = lookupTy("DIR"); - Optional<QualType> DirPtrTy = getPointerTy(DirTy); + std::optional<QualType> DirTy = lookupTy("DIR"); + std::optional<QualType> DirPtrTy = getPointerTy(DirTy); // int dirfd(DIR *dirp); addToFunctionSummaryMap( @@ -2090,7 +2090,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(1)))); - Optional<QualType> Dev_tTy = lookupTy("dev_t"); + std::optional<QualType> Dev_tTy = lookupTy("dev_t"); // int mknod(const char *pathname, mode_t mode, dev_t dev); addToFunctionSummaryMap( @@ -2139,8 +2139,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint( ArgumentCondition(0, WithinRange, Range(0, IntMax)))); - Optional<QualType> Uid_tTy = lookupTy("uid_t"); - Optional<QualType> Gid_tTy = lookupTy("gid_t"); + std::optional<QualType> Uid_tTy = lookupTy("uid_t"); + std::optional<QualType> Gid_tTy = lookupTy("gid_t"); // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, // int flags); @@ -2239,9 +2239,10 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) .ArgConstraint(NotNull(ArgNo(1)))); - Optional<QualType> StructStatTy = lookupTy("stat"); - Optional<QualType> StructStatPtrTy = getPointerTy(StructStatTy); - Optional<QualType> StructStatPtrRestrictTy = getRestrictTy(StructStatPtrTy); + std::optional<QualType> StructStatTy = lookupTy("stat"); + std::optional<QualType> StructStatPtrTy = getPointerTy(StructStatTy); + std::optional<QualType> StructStatPtrRestrictTy = + getRestrictTy(StructStatPtrTy); // int fstat(int fd, struct stat *statbuf); addToFunctionSummaryMap( @@ -2395,7 +2396,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint( ArgumentCondition(4, WithinRange, Range(-1, IntMax)))); - Optional<QualType> Off64_tTy = lookupTy("off64_t"); + std::optional<QualType> Off64_tTy = lookupTy("off64_t"); // void *mmap64(void *addr, size_t length, int prot, int flags, int fd, // off64_t offset); // FIXME: Improve for errno modeling. @@ -2520,18 +2521,20 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint(NotNull(ArgNo(1))) .ArgConstraint(NotNull(ArgNo(2)))); - Optional<QualType> StructSockaddrTy = lookupTy("sockaddr"); - Optional<QualType> StructSockaddrPtrTy = getPointerTy(StructSockaddrTy); - Optional<QualType> ConstStructSockaddrPtrTy = + std::optional<QualType> StructSockaddrTy = lookupTy("sockaddr"); + std::optional<QualType> StructSockaddrPtrTy = + getPointerTy(StructSockaddrTy); + std::optional<QualType> ConstStructSockaddrPtrTy = getPointerTy(getConstTy(StructSockaddrTy)); - Optional<QualType> StructSockaddrPtrRestrictTy = + std::optional<QualType> StructSockaddrPtrRestrictTy = getRestrictTy(StructSockaddrPtrTy); - Optional<QualType> ConstStructSockaddrPtrRestrictTy = + std::optional<QualType> ConstStructSockaddrPtrRestrictTy = getRestrictTy(ConstStructSockaddrPtrTy); - Optional<QualType> Socklen_tTy = lookupTy("socklen_t"); - Optional<QualType> Socklen_tPtrTy = getPointerTy(Socklen_tTy); - Optional<QualType> Socklen_tPtrRestrictTy = getRestrictTy(Socklen_tPtrTy); - Optional<RangeInt> Socklen_tMax = getMaxValue(Socklen_tTy); + std::optional<QualType> Socklen_tTy = lookupTy("socklen_t"); + std::optional<QualType> Socklen_tPtrTy = getPointerTy(Socklen_tTy); + std::optional<QualType> Socklen_tPtrRestrictTy = + getRestrictTy(Socklen_tPtrTy); + std::optional<RangeInt> Socklen_tMax = getMaxValue(Socklen_tTy); // In 'socket.h' of some libc implementations with C99, sockaddr parameter // is a transparent union of the underlying sockaddr_ family of pointers @@ -2730,9 +2733,9 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), /*BufSize=*/ArgNo(2)))); - Optional<QualType> StructMsghdrTy = lookupTy("msghdr"); - Optional<QualType> StructMsghdrPtrTy = getPointerTy(StructMsghdrTy); - Optional<QualType> ConstStructMsghdrPtrTy = + std::optional<QualType> StructMsghdrTy = lookupTy("msghdr"); + std::optional<QualType> StructMsghdrPtrTy = getPointerTy(StructMsghdrTy); + std::optional<QualType> ConstStructMsghdrPtrTy = getPointerTy(getConstTy(StructMsghdrTy)); // ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); @@ -2838,8 +2841,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .ArgConstraint( ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax)))); - Optional<QualType> StructUtimbufTy = lookupTy("utimbuf"); - Optional<QualType> StructUtimbufPtrTy = getPointerTy(StructUtimbufTy); + std::optional<QualType> StructUtimbufTy = lookupTy("utimbuf"); + std::optional<QualType> StructUtimbufPtrTy = getPointerTy(StructUtimbufTy); // int utime(const char *filename, struct utimbuf *buf); addToFunctionSummaryMap( @@ -2850,9 +2853,10 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(0)))); - Optional<QualType> StructTimespecTy = lookupTy("timespec"); - Optional<QualType> StructTimespecPtrTy = getPointerTy(StructTimespecTy); - Optional<QualType> ConstStructTimespecPtrTy = + std::optional<QualType> StructTimespecTy = lookupTy("timespec"); + std::optional<QualType> StructTimespecPtrTy = + getPointerTy(StructTimespecTy); + std::optional<QualType> ConstStructTimespecPtrTy = getPointerTy(getConstTy(StructTimespecTy)); // int futimens(int fd, const struct timespec times[2]); @@ -2876,8 +2880,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(1)))); - Optional<QualType> StructTimevalTy = lookupTy("timeval"); - Optional<QualType> ConstStructTimevalPtrTy = + std::optional<QualType> StructTimevalTy = lookupTy("timeval"); + std::optional<QualType> ConstStructTimevalPtrTy = getPointerTy(getConstTy(StructTimevalTy)); // int utimes(const char *filename, const struct timeval times[2]); @@ -2900,17 +2904,19 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(0)))); - Optional<QualType> Time_tTy = lookupTy("time_t"); - Optional<QualType> ConstTime_tPtrTy = getPointerTy(getConstTy(Time_tTy)); - Optional<QualType> ConstTime_tPtrRestrictTy = + std::optional<QualType> Time_tTy = lookupTy("time_t"); + std::optional<QualType> ConstTime_tPtrTy = + getPointerTy(getConstTy(Time_tTy)); + std::optional<QualType> ConstTime_tPtrRestrictTy = getRestrictTy(ConstTime_tPtrTy); - Optional<QualType> StructTmTy = lookupTy("tm"); - Optional<QualType> StructTmPtrTy = getPointerTy(StructTmTy); - Optional<QualType> StructTmPtrRestrictTy = getRestrictTy(StructTmPtrTy); - Optional<QualType> ConstStructTmPtrTy = + std::optional<QualType> StructTmTy = lookupTy("tm"); + std::optional<QualType> StructTmPtrTy = getPointerTy(StructTmTy); + std::optional<QualType> StructTmPtrRestrictTy = + getRestrictTy(StructTmPtrTy); + std::optional<QualType> ConstStructTmPtrTy = getPointerTy(getConstTy(StructTmTy)); - Optional<QualType> ConstStructTmPtrRestrictTy = + std::optional<QualType> ConstStructTmPtrRestrictTy = getRestrictTy(ConstStructTmPtrTy); // struct tm * localtime(const time_t *tp); @@ -2966,7 +2972,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( "gmtime", Signature(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}), Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); - Optional<QualType> Clockid_tTy = lookupTy("clockid_t"); + std::optional<QualType> Clockid_tTy = lookupTy("clockid_t"); // int clock_gettime(clockid_t clock_id, struct timespec *tp); addToFunctionSummaryMap( @@ -2977,8 +2983,9 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(1)))); - Optional<QualType> StructItimervalTy = lookupTy("itimerval"); - Optional<QualType> StructItimervalPtrTy = getPointerTy(StructItimervalTy); + std::optional<QualType> StructItimervalTy = lookupTy("itimerval"); + std::optional<QualType> StructItimervalPtrTy = + getPointerTy(StructItimervalTy); // int getitimer(int which, struct itimerval *curr_value); addToFunctionSummaryMap( @@ -2989,25 +2996,30 @@ void StdLibraryFunctionsChecker::initFunctionSummaries( .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant) .ArgConstraint(NotNull(ArgNo(1)))); - Optional<QualType> Pthread_cond_tTy = lookupTy("pthread_cond_t"); - Optional<QualType> Pthread_cond_tPtrTy = getPointerTy(Pthread_cond_tTy); - Optional<QualType> Pthread_tTy = lookupTy("pthread_t"); - Optional<QualType> Pthread_tPtrTy = getPointerTy(Pthread_tTy); - Optional<QualType> Pthread_tPtrRestrictTy = getRestrictTy(Pthread_tPtrTy); - Optional<QualType> Pthread_mutex_tTy = lookupTy("pthread_mutex_t"); - Optional<QualType> Pthread_mutex_tPtrTy = getPointerTy(Pthread_mutex_tTy); - Optional<QualType> Pthread_mutex_tPtrRestrictTy = + std::optional<QualType> Pthread_cond_tTy = lookupTy("pthread_cond_t"); + std::optional<QualType> Pthread_cond_tPtrTy = + getPointerTy(Pthread_cond_tTy); + std::optional<QualType> Pthread_tTy = lookupTy("pthread_t"); + std::optional<QualType> Pthread_tPtrTy = getPointerTy(Pthread_tTy); + std::optional<QualType> Pthread_tPtrRestrictTy = + getRestrictTy(Pthread_tPtrTy); + std::optional<QualType> Pthread_mutex_tTy = lookupTy("pthread_mutex_t"); + std::optional<QualType> Pthread_mutex_tPtrTy = + getPointerTy(Pthread_mutex_tTy); + std::optional<QualType> Pthread_mutex_tPtrRestrictTy = getRestrictTy(Pthread_mutex_tPtrTy); - Optional<QualType> Pthread_attr_tTy = lookupTy("pthread_attr_t"); - Optional<QualType> Pthread_attr_tPtrTy = getPointerTy(Pthread_attr_tTy); - Optional<QualType> ConstPthread_attr_tPtrTy = + std::optional<QualType> Pthread_attr_tTy = lookupTy("pthread_attr_t"); + std::optional<QualType> Pthread_attr_tPtrTy = + getPointerTy(Pthread_attr_tTy); + std::optional<QualType> ConstPthread_attr_tPtrTy = getPointerTy(getConstTy(Pthread_attr_tTy)); - Optional<QualType> ConstPthread_attr_tPtrRestrictTy = + std::optional<QualType> ConstPthread_attr_tPtrRestrictTy = getRestrictTy(ConstPthread_attr_tPtrTy); - Optional<QualType> Pthread_mutexattr_tTy = lookupTy("pthread_mutexattr_t"); - Optional<QualType> ConstPthread_mutexattr_tPtrTy = + std::optional<QualType> Pthread_mutexattr_tTy = + lookupTy("pthread_mutexattr_t"); + std::optional<QualType> ConstPthread_mutexattr_tPtrTy = getPointerTy(getConstTy(Pthread_mutexattr_tTy)); - Optional<QualType> ConstPthread_mutexattr_tPtrRestrictTy = + std::optional<QualType> ConstPthread_mutexattr_tPtrRestrictTy = getRestrictTy(ConstPthread_mutexattr_tPtrTy); QualType PthreadStartRoutineTy = getPointerTy( diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 8ce8c4f..3f61dd8 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -284,7 +284,7 @@ private: 0}}, }; - mutable Optional<int> EofVal; + mutable std::optional<int> EofVal; void evalFopen(const FnDescription *Desc, const CallEvent &Call, CheckerContext &C) const; @@ -435,7 +435,7 @@ private: if (EofVal) return; - if (const llvm::Optional<int> OptInt = + if (const std::optional<int> OptInt = tryExpandAsInteger("EOF", C.getPreprocessor())) EofVal = *OptInt; else @@ -558,7 +558,7 @@ void StreamChecker::evalFreopen(const FnDescription *Desc, if (!CE) return; - Optional<DefinedSVal> StreamVal = + std::optional<DefinedSVal> StreamVal = getStreamArg(Desc, Call).getAs<DefinedSVal>(); if (!StreamVal) return; @@ -684,10 +684,10 @@ void StreamChecker::evalFreadFwrite(const FnDescription *Desc, if (!CE) return; - Optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>(); + std::optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>(); if (!SizeVal) return; - Optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>(); + std::optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>(); if (!NMembVal) return; @@ -1144,7 +1144,8 @@ ProgramStateRef StreamChecker::ensureNoFilePositionIndeterminate( ProgramStateRef StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C, ProgramStateRef State) const { - Optional<nonloc::ConcreteInt> CI = WhenceVal.getAs<nonloc::ConcreteInt>(); + std::optional<nonloc::ConcreteInt> CI = + WhenceVal.getAs<nonloc::ConcreteInt>(); if (!CI) return State; diff --git a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp index e20895f..a95c0e1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp @@ -64,7 +64,7 @@ ProgramStateRef taint::addTaint(ProgramStateRef State, SVal V, // their parent region, which is a conjured symbol default-bound to the base // region of the parent region. if (auto LCV = V.getAs<nonloc::LazyCompoundVal>()) { - if (Optional<SVal> binding = + if (std::optional<SVal> binding = State->getStateManager().getStoreManager().getDefaultBinding( *LCV)) { if (SymbolRef Sym = binding->getAsSymbol()) diff --git a/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp index ce43c55..28fe11d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp @@ -101,7 +101,7 @@ DivisionBRVisitor::VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC, const Expr *E = nullptr; - if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) + if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) { BinaryOperator::Opcode Op = BO->getOpcode(); if (Op == BO_Div || Op == BO_Rem || Op == BO_DivAssign || @@ -133,7 +133,7 @@ DivisionBRVisitor::VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC, } bool TestAfterDivZeroChecker::isZero(SVal S, CheckerContext &C) const { - Optional<DefinedSVal> DSV = S.getAs<DefinedSVal>(); + std::optional<DefinedSVal> DSV = S.getAs<DefinedSVal>(); if (!DSV) return false; diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp index 8146d30..b17b983 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp @@ -94,7 +94,7 @@ void UndefBranchChecker::checkBranchCondition(const Stmt *Condition, ProgramPoint P = PrevN->getLocation(); ProgramStateRef St = N->getState(); - if (Optional<PostStmt> PS = P.getAs<PostStmt>()) + if (std::optional<PostStmt> PS = P.getAs<PostStmt>()) if (PS->getStmt() == Ex) St = PrevN->getState(); diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp index c0dd5f9..27f3345 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp @@ -70,8 +70,8 @@ UndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE, continue; // Get the VarRegion associated with VD in the local stack frame. - if (Optional<UndefinedVal> V = - state->getSVal(I.getOriginalRegion()).getAs<UndefinedVal>()) { + if (std::optional<UndefinedVal> V = + state->getSVal(I.getOriginalRegion()).getAs<UndefinedVal>()) { if (ExplodedNode *N = C.generateErrorNode()) { if (!BT) BT.reset( diff --git a/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp b/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp index 0c3c4399b..54e1e0e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp @@ -123,8 +123,8 @@ struct DereferenceInfo { /// Dereferences \p FR and returns with the pointee's region, and whether it /// needs to be casted back to it's location type. If for whatever reason /// dereferencing fails, returns std::nullopt. -static llvm::Optional<DereferenceInfo> dereference(ProgramStateRef State, - const FieldRegion *FR); +static std::optional<DereferenceInfo> dereference(ProgramStateRef State, + const FieldRegion *FR); /// Returns whether \p T can be (transitively) dereferenced to a void pointer /// type (void*, void**, ...). @@ -160,7 +160,7 @@ bool FindUninitializedFields::isDereferencableUninit( // At this point the pointer itself is initialized and points to a valid // location, we'll now check the pointee. - llvm::Optional<DereferenceInfo> DerefInfo = dereference(State, FR); + std::optional<DereferenceInfo> DerefInfo = dereference(State, FR); if (!DerefInfo) { IsAnyFieldInitialized = true; return false; @@ -218,8 +218,8 @@ bool FindUninitializedFields::isDereferencableUninit( // Utility functions. //===----------------------------------------------------------------------===// -static llvm::Optional<DereferenceInfo> dereference(ProgramStateRef State, - const FieldRegion *FR) { +static std::optional<DereferenceInfo> dereference(ProgramStateRef State, + const FieldRegion *FR) { llvm::SmallSet<const TypedValueRegion *, 5> VisitedRegions; diff --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp index 032afb2..3ad6858 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp @@ -75,7 +75,7 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, if (!PM) PM = &LC->getParentMap(); - if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { + if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { const CFGBlock *CB = BE->getBlock(); reachable.insert(CB->getBlockID()); } @@ -130,7 +130,7 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, bool foundUnreachable = false; for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end(); ci != ce; ++ci) { - if (Optional<CFGStmt> S = (*ci).getAs<CFGStmt>()) + if (std::optional<CFGStmt> S = (*ci).getAs<CFGStmt>()) if (const CallExpr *CE = dyn_cast<CallExpr>(S->getStmt())) { if (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable || CE->isBuiltinAssumeFalse(Eng.getContext())) { @@ -200,7 +200,7 @@ void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB, // Find the Stmt* in a CFGBlock for reporting a warning const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) { for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) { - if (Optional<CFGStmt> S = I->getAs<CFGStmt>()) { + if (std::optional<CFGStmt> S = I->getAs<CFGStmt>()) { if (!isa<DeclStmt>(S->getStmt())) return S->getStmt(); } diff --git a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp index 11b3a37..fe910ce 100644 --- a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp @@ -193,7 +193,7 @@ ProgramStateRef VLASizeChecker::checkVLAIndexSize(CheckerContext &C, DefinedOrUnknownSVal Zero = SVB.makeZeroVal(SizeTy); SVal LessThanZeroVal = SVB.evalBinOp(State, BO_LT, SizeD, Zero, SizeTy); - if (Optional<DefinedSVal> LessThanZeroDVal = + if (std::optional<DefinedSVal> LessThanZeroDVal = LessThanZeroVal.getAs<DefinedSVal>()) { ConstraintManager &CM = C.getConstraintManager(); ProgramStateRef StatePos, StateNeg; diff --git a/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp index d0d16af..86a4e6f 100644 --- a/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp @@ -155,8 +155,8 @@ void VforkChecker::checkPostCall(const CallEvent &Call, // Get return value of vfork. SVal VforkRetVal = Call.getReturnValue(); - Optional<DefinedOrUnknownSVal> DVal = - VforkRetVal.getAs<DefinedOrUnknownSVal>(); + std::optional<DefinedOrUnknownSVal> DVal = + VforkRetVal.getAs<DefinedOrUnknownSVal>(); if (!DVal) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp index d2f4bda..5b2cb4f 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp @@ -35,8 +35,7 @@ tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) { } if (auto *call = dyn_cast<CallExpr>(E)) { if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(call)) { - Optional<bool> IsGetterOfRefCt = - isGetterOfRefCounted(memberCall->getMethodDecl()); + std::optional<bool> IsGetterOfRefCt = isGetterOfRefCounted(memberCall->getMethodDecl()); if (IsGetterOfRefCt && *IsGetterOfRefCt) { E = memberCall->getImplicitObjectArgument(); if (StopAtFirstRefCountedObj) { diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp index edd7a1e..66d8588 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp @@ -78,9 +78,9 @@ public: if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) { // If we don't see the definition we just don't know. if (MemberCXXRD->hasDefinition()) { - llvm::Optional<bool> isRCAble = isRefCountable(MemberCXXRD); - if (isRCAble && *isRCAble) - reportBug(Member, MemberType, MemberCXXRD, RD); + std::optional<bool> isRCAble = isRefCountable(MemberCXXRD); + if (isRCAble && *isRCAble) + reportBug(Member, MemberType, MemberCXXRD, RD); } } } diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp index a7216e2..182cb34 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp @@ -46,8 +46,9 @@ bool hasPublicRefAndDeref(const CXXRecordDecl *R) { namespace clang { -llvm::Optional<const clang::CXXRecordDecl *> -isRefCountable(const CXXBaseSpecifier *Base) { +std::optional<const clang::CXXRecordDecl*> +isRefCountable(const CXXBaseSpecifier* Base) +{ assert(Base); const Type *T = Base->getType().getTypePtrOrNull(); @@ -63,7 +64,8 @@ isRefCountable(const CXXBaseSpecifier *Base) { return hasPublicRefAndDeref(R) ? R : nullptr; } -llvm::Optional<bool> isRefCountable(const CXXRecordDecl *R) { +std::optional<bool> isRefCountable(const CXXRecordDecl* R) +{ assert(R); R = R->getDefinition(); @@ -78,14 +80,13 @@ llvm::Optional<bool> isRefCountable(const CXXRecordDecl *R) { bool AnyInconclusiveBase = false; const auto isRefCountableBase = - [&AnyInconclusiveBase](const CXXBaseSpecifier *Base, CXXBasePath &) { - Optional<const clang::CXXRecordDecl *> IsRefCountable = - clang::isRefCountable(Base); - if (!IsRefCountable) { - AnyInconclusiveBase = true; - return false; - } - return (*IsRefCountable) != nullptr; + [&AnyInconclusiveBase](const CXXBaseSpecifier* Base, CXXBasePath&) { + std::optional<const clang::CXXRecordDecl*> IsRefCountable = clang::isRefCountable(Base); + if (!IsRefCountable) { + AnyInconclusiveBase = true; + return false; + } + return (*IsRefCountable) != nullptr; }; bool BasesResult = R->lookupInBases(isRefCountableBase, Paths, @@ -113,19 +114,21 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) { || FunctionName == "Identifier"; } -llvm::Optional<bool> isUncounted(const CXXRecordDecl *Class) { +std::optional<bool> isUncounted(const CXXRecordDecl* Class) +{ // Keep isRefCounted first as it's cheaper. if (isRefCounted(Class)) return false; - llvm::Optional<bool> IsRefCountable = isRefCountable(Class); + std::optional<bool> IsRefCountable = isRefCountable(Class); if (!IsRefCountable) return std::nullopt; return (*IsRefCountable); } -llvm::Optional<bool> isUncountedPtr(const Type *T) { +std::optional<bool> isUncountedPtr(const Type* T) +{ assert(T); if (T->isPointerType() || T->isReferenceType()) { @@ -136,7 +139,8 @@ llvm::Optional<bool> isUncountedPtr(const Type *T) { return false; } -Optional<bool> isGetterOfRefCounted(const CXXMethodDecl *M) { +std::optional<bool> isGetterOfRefCounted(const CXXMethodDecl* M) +{ assert(M); if (isa<CXXMethodDecl>(M)) { diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp index 754ca76..48dcfc4 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp @@ -77,8 +77,7 @@ public: (AccSpec == AS_none && RD->isClass())) return false; - llvm::Optional<const CXXRecordDecl *> RefCntblBaseRD = - isRefCountable(Base); + std::optional<const CXXRecordDecl*> RefCntblBaseRD = isRefCountable(Base); if (!RefCntblBaseRD || !(*RefCntblBaseRD)) return false; diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp index cc4b08d..4ae8c44 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp @@ -86,7 +86,7 @@ public: continue; // FIXME? Should we bail? // FIXME: more complex types (arrays, references to raw pointers, etc) - Optional<bool> IsUncounted = isUncountedPtr(ArgType); + std::optional<bool> IsUncounted = isUncountedPtr(ArgType); if (!IsUncounted || !(*IsUncounted)) continue; diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp index dd95abb..004b0b9 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp @@ -60,10 +60,10 @@ public: if (C.capturesVariable()) { ValueDecl *CapturedVar = C.getCapturedVar(); if (auto *CapturedVarType = CapturedVar->getType().getTypePtrOrNull()) { - Optional<bool> IsUncountedPtr = isUncountedPtr(CapturedVarType); - if (IsUncountedPtr && *IsUncountedPtr) { - reportBug(C, CapturedVar, CapturedVarType); - } + std::optional<bool> IsUncountedPtr = isUncountedPtr(CapturedVarType); + if (IsUncountedPtr && *IsUncountedPtr) { + reportBug(C, CapturedVar, CapturedVarType); + } } } } diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 74468b0..fa74759 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -170,7 +170,7 @@ public: if (!ArgType) return; - Optional<bool> IsUncountedPtr = isUncountedPtr(ArgType); + std::optional<bool> IsUncountedPtr = isUncountedPtr(ArgType); if (IsUncountedPtr && *IsUncountedPtr) { const Expr *const InitExpr = V->getInit(); if (!InitExpr) diff --git a/clang/lib/StaticAnalyzer/Checkers/Yaml.h b/clang/lib/StaticAnalyzer/Checkers/Yaml.h index 3484091..4159e14 100644 --- a/clang/lib/StaticAnalyzer/Checkers/Yaml.h +++ b/clang/lib/StaticAnalyzer/Checkers/Yaml.h @@ -26,8 +26,8 @@ namespace ento { /// template parameter must have a yaml MappingTraits. /// Emit diagnostic error in case of any failure. template <class T, class Checker> -llvm::Optional<T> getConfiguration(CheckerManager &Mgr, Checker *Chk, - StringRef Option, StringRef ConfigFile) { +std::optional<T> getConfiguration(CheckerManager &Mgr, Checker *Chk, + StringRef Option, StringRef ConfigFile) { if (ConfigFile.trim().empty()) return std::nullopt; diff --git a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp index fb5da11..86ef4a5 100644 --- a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -65,7 +65,7 @@ void AnalyzerOptions::printFormattedEntry( ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() const { auto K = - llvm::StringSwitch<llvm::Optional<ExplorationStrategyKind>>( + llvm::StringSwitch<std::optional<ExplorationStrategyKind>>( ExplorationStrategy) .Case("dfs", ExplorationStrategyKind::DFS) .Case("bfs", ExplorationStrategyKind::BFS) @@ -82,7 +82,7 @@ AnalyzerOptions::getExplorationStrategy() const { } CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { - auto K = llvm::StringSwitch<llvm::Optional<CTUPhase1InliningKind>>( + auto K = llvm::StringSwitch<std::optional<CTUPhase1InliningKind>>( CTUPhase1InliningMode) .Case("none", CTUPhase1InliningKind::None) .Case("small", CTUPhase1InliningKind::Small) @@ -93,7 +93,7 @@ CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { } IPAKind AnalyzerOptions::getIPAMode() const { - auto K = llvm::StringSwitch<llvm::Optional<IPAKind>>(IPAMode) + auto K = llvm::StringSwitch<std::optional<IPAKind>>(IPAMode) .Case("none", IPAK_None) .Case("basic-inlining", IPAK_BasicInlining) .Case("inlining", IPAK_Inlining) @@ -111,7 +111,7 @@ AnalyzerOptions::mayInlineCXXMemberFunction( if (getIPAMode() < IPAK_Inlining) return false; - auto K = llvm::StringSwitch<llvm::Optional<CXXInlineableMemberKind>>( + auto K = llvm::StringSwitch<std::optional<CXXInlineableMemberKind>>( CXXMemberInliningMode) .Case("constructors", CIMK_Constructors) .Case("destructors", CIMK_Destructors) @@ -162,7 +162,7 @@ bool AnalyzerOptions::getCheckerBooleanOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents) const { auto Ret = - llvm::StringSwitch<llvm::Optional<bool>>( + llvm::StringSwitch<std::optional<bool>>( getCheckerStringOption(CheckerName, OptionName, SearchInParents)) .Case("true", true) .Case("false", false) diff --git a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp index 64935df..2bbc823 100644 --- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -309,7 +309,7 @@ std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){ } // Check if the parameter is a pointer to the symbol. - if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) { // Do not attempt to dereference void*. if ((*I)->getType()->isVoidPointerType()) continue; @@ -1033,7 +1033,7 @@ static bool isContainedByStmt(const ParentMap &PM, const Stmt *S, static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term, const ExplodedNode *N) { while (N) { - Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>(); + std::optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>(); if (SP) { const Stmt *S = SP->getStmt(); if (!isContainedByStmt(PM, Term, S)) @@ -1194,7 +1194,7 @@ void PathDiagnosticBuilder::generatePathDiagnosticsForNode( "location context associated with the active path!"); // Have we encountered an exit from a function call? - if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { + if (std::optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { // We are descending into a call (backwards). Construct // a new call piece to contain the path pieces for that call. @@ -1579,7 +1579,7 @@ static std::optional<size_t> getLengthOnSingleLine(const SourceManager &SM, if (FID != SM.getFileID(ExpansionRange.getEnd())) return std::nullopt; - Optional<MemoryBufferRef> Buffer = SM.getBufferOrNone(FID); + std::optional<MemoryBufferRef> Buffer = SM.getBufferOrNone(FID); if (!Buffer) return std::nullopt; @@ -2311,7 +2311,7 @@ void PathSensitiveBugReport::markInteresting(const LocationContext *LC) { InterestingLocationContexts.insert(LC); } -Optional<bugreporter::TrackingKind> +std::optional<bugreporter::TrackingKind> PathSensitiveBugReport::getInterestingnessKind(SVal V) const { auto RKind = getInterestingnessKind(V.getAsRegion()); auto SKind = getInterestingnessKind(V.getAsSymbol()); @@ -2336,7 +2336,7 @@ PathSensitiveBugReport::getInterestingnessKind(SVal V) const { return std::nullopt; } -Optional<bugreporter::TrackingKind> +std::optional<bugreporter::TrackingKind> PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym) const { if (!sym) return std::nullopt; @@ -2348,7 +2348,7 @@ PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym) const { return It->getSecond(); } -Optional<bugreporter::TrackingKind> +std::optional<bugreporter::TrackingKind> PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const { if (!R) return std::nullopt; @@ -2388,7 +2388,7 @@ const Stmt *PathSensitiveBugReport::getStmt() const { ProgramPoint ProgP = ErrorNode->getLocation(); const Stmt *S = nullptr; - if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) { + if (std::optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) { CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); if (BE->getBlock() == &Exit) S = ErrorNode->getPreviousStmtForDiagnostics(); @@ -2420,7 +2420,7 @@ PathSensitiveBugReport::getLocation() const { if (!S) { // If this is an implicit call, return the implicit call point location. - if (Optional<PreImplicitCall> PIE = P.getAs<PreImplicitCall>()) + if (std::optional<PreImplicitCall> PIE = P.getAs<PreImplicitCall>()) return PathDiagnosticLocation(PIE->getLocation(), SM); if (auto FE = P.getAs<FunctionExitPoint>()) { if (const ReturnStmt *RS = FE->getStmt()) diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp index 5281b45..bdc9280 100644 --- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -249,7 +249,8 @@ static bool isVarAnInterestingCondition(const Expr *CondVarExpr, return false; if (std::optional<SVal> V = getSValForVar(CondVarExpr, N)) - if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V)) + if (std::optional<bugreporter::TrackingKind> K = + B->getInterestingnessKind(*V)) return *K == bugreporter::TrackingKind::Condition; return false; @@ -539,7 +540,7 @@ private: /// Note that \p Vec is passed by value, leading to quadratic copying cost, /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT. /// \return A chain fields leading to the region of interest or std::nullopt. - const Optional<RegionVector> + const std::optional<RegionVector> findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State, const MemRegion *R, const RegionVector &Vec = {}, int depth = 0); @@ -620,7 +621,7 @@ static bool potentiallyWritesIntoIvar(const Decl *Parent, /// Note that \p Vec is passed by value, leading to quadratic copying cost, /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT. /// \return A chain fields leading to the region of interest or std::nullopt. -const Optional<NoStoreFuncVisitor::RegionVector> +const std::optional<NoStoreFuncVisitor::RegionVector> NoStoreFuncVisitor::findRegionOfInterestInRecord( const RecordDecl *RD, ProgramStateRef State, const MemRegion *R, const NoStoreFuncVisitor::RegionVector &Vec /* = {} */, @@ -638,7 +639,7 @@ NoStoreFuncVisitor::findRegionOfInterestInRecord( if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD)) for (const auto &II : RDX->bases()) if (const RecordDecl *RRD = II.getType()->getAsRecordDecl()) - if (Optional<RegionVector> Out = + if (std::optional<RegionVector> Out = findRegionOfInterestInRecord(RRD, State, R, Vec, depth)) return Out; @@ -664,7 +665,7 @@ NoStoreFuncVisitor::findRegionOfInterestInRecord( continue; if (const RecordDecl *RRD = PT->getAsRecordDecl()) - if (Optional<RegionVector> Out = + if (std::optional<RegionVector> Out = findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1)) return Out; } @@ -730,7 +731,7 @@ PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNoteForParameters( ProgramStateRef State = N->getState(); if (const RecordDecl *RD = PT->getAsRecordDecl()) - if (Optional<RegionVector> P = + if (std::optional<RegionVector> P = findRegionOfInterestInRecord(RD, State, MR)) return maybeEmitNote(R, Call, N, *P, RegionOfInterest, ParamName, ParamIsReferenceType, IndirectionLevel); @@ -928,7 +929,7 @@ public: private: /// \return Source location of right hand side of an assignment /// into \c RegionOfInterest, empty optional if none found. - Optional<SourceLocation> matchAssignment(const ExplodedNode *N) { + std::optional<SourceLocation> matchAssignment(const ExplodedNode *N) { const Stmt *S = N->getStmtForDiagnostics(); ProgramStateRef State = N->getState(); auto *LCtx = N->getLocationContext(); @@ -1001,7 +1002,7 @@ public: if (N->getLocationContext() != CalleeSFC) return nullptr; - Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>(); + std::optional<StmtPoint> SP = N->getLocationAs<StmtPoint>(); if (!SP) return nullptr; @@ -1023,7 +1024,7 @@ public: assert(RetE && "Tracking a return value for a void function"); // Handle cases where a reference is returned and then immediately used. - Optional<Loc> LValue; + std::optional<Loc> LValue; if (RetE->isGLValue()) { if ((LValue = V.getAs<Loc>())) { SVal RValue = State->getRawSVal(*LValue, RetE->getType()); @@ -1122,7 +1123,7 @@ public: assert(Options.ShouldAvoidSuppressingNullArgumentPaths); // Are we at the entry node for this call? - Optional<CallEnter> CE = N->getLocationAs<CallEnter>(); + std::optional<CallEnter> CE = N->getLocationAs<CallEnter>(); if (!CE) return nullptr; @@ -1140,7 +1141,7 @@ public: ProgramStateRef State = N->getState(); CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State); for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) { - Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>(); + std::optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>(); if (!ArgV) continue; @@ -1240,7 +1241,7 @@ void StoreSiteFinder::Profile(llvm::FoldingSetNodeID &ID) const { /// Returns true if \p N represents the DeclStmt declaring and initializing /// \p VR. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) { - Optional<PostStmt> P = N->getLocationAs<PostStmt>(); + std::optional<PostStmt> P = N->getLocationAs<PostStmt>(); if (!P) return false; @@ -1513,7 +1514,8 @@ PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ, // If this is a post initializer expression, initializing the region, we // should track the initializer expression. - if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) { + if (std::optional<PostInitializer> PIP = + Pred->getLocationAs<PostInitializer>()) { const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue(); if (FieldReg == R) { StoreSite = Pred; @@ -1531,14 +1533,14 @@ PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ, return nullptr; if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) { - Optional<PostStore> PS = Succ->getLocationAs<PostStore>(); + std::optional<PostStore> PS = Succ->getLocationAs<PostStore>(); if (!PS || PS->getLocationValue() != R) return nullptr; } StoreSite = Succ; - if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) { + if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) { // If this is an assignment expression, we can track the value // being assigned. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) { @@ -1625,7 +1627,7 @@ PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ, // FIXME: Handle CXXThisRegion as well. (This is not a priority because // 'this' should never be NULL, but this visitor isn't just for NULL and // UndefinedVal.) - if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) { + if (std::optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) { if (const auto *VR = dyn_cast<VarRegion>(R)) { if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) { @@ -1748,7 +1750,7 @@ PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ, R, OldRegion}; - if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) { + if (std::optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) { const Stmt *S = PS->getStmt(); const auto *DS = dyn_cast<DeclStmt>(S); const auto *VR = dyn_cast<VarRegion>(R); @@ -2141,7 +2143,7 @@ static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N) { const ExplodedNode *NI = N; do { ProgramPoint ProgPoint = NI->getLocation(); - if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { + if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { const CFGBlock *srcBlk = BE->getSrc(); if (const Stmt *term = srcBlk->getTerminatorStmt()) { if (term == CO) { @@ -2414,7 +2416,8 @@ class InlinedFunctionCallHandler final : public ExpressionHandler { do { // If that is satisfied we found our statement as an inlined call. - if (Optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>()) + if (std::optional<CallExitEnd> CEE = + ExprNode->getLocationAs<CallExitEnd>()) if (CEE->getCalleeContext()->getCallSite() == E) break; @@ -2429,7 +2432,7 @@ class InlinedFunctionCallHandler final : public ExpressionHandler { // FIXME: This code currently bypasses the call site for the // conservatively evaluated allocator. if (!BypassCXXNewExprEval) - if (Optional<StmtPoint> SP = ExprNode->getLocationAs<StmtPoint>()) + if (std::optional<StmtPoint> SP = ExprNode->getLocationAs<StmtPoint>()) // See if we do not enter into another context. if (SP->getStmt() == E && CurrentSFC == PredSFC) break; @@ -2444,7 +2447,7 @@ class InlinedFunctionCallHandler final : public ExpressionHandler { return {}; // Finally, see if we inlined the call. - Optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>(); + std::optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>(); if (!CEE) return {}; @@ -2458,7 +2461,7 @@ class InlinedFunctionCallHandler final : public ExpressionHandler { // Handle cases where a reference is returned and then immediately used. if (cast<Expr>(E)->isGLValue()) - if (Optional<Loc> LValue = RetVal.getAs<Loc>()) + if (std::optional<Loc> LValue = RetVal.getAs<Loc>()) RetVal = State->getSVal(*LValue); // See if the return value is NULL. If so, suppress the report. @@ -2466,7 +2469,7 @@ class InlinedFunctionCallHandler final : public ExpressionHandler { bool EnableNullFPSuppression = false; if (Opts.EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths) - if (Optional<Loc> RetLoc = RetVal.getAs<Loc>()) + if (std::optional<Loc> RetLoc = RetVal.getAs<Loc>()) EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue(); PathSensitiveBugReport &Report = getParentTracker().getReport(); @@ -2700,7 +2703,7 @@ const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S, PathDiagnosticPieceRef NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) { - Optional<PreStmt> P = N->getLocationAs<PreStmt>(); + std::optional<PreStmt> P = N->getLocationAs<PreStmt>(); if (!P) return nullptr; @@ -2764,7 +2767,7 @@ ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, // If an assumption was made on a branch, it should be caught // here by looking at the state transition. - if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { + if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { const CFGBlock *SrcBlock = BE->getSrc(); if (const Stmt *Term = SrcBlock->getTerminatorStmt()) { // If the tag of the previous node is 'Eagerly Assume...' the current @@ -2781,7 +2784,7 @@ ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, return nullptr; } - if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) { + if (std::optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) { const ProgramPointTag *CurrentNodeTag = PS->getTag(); if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second) return nullptr; @@ -2920,13 +2923,11 @@ ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC, Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage); } -bool ConditionBRVisitor::patternMatch(const Expr *Ex, - const Expr *ParentEx, - raw_ostream &Out, - BugReporterContext &BRC, +bool ConditionBRVisitor::patternMatch(const Expr *Ex, const Expr *ParentEx, + raw_ostream &Out, BugReporterContext &BRC, PathSensitiveBugReport &report, const ExplodedNode *N, - Optional<bool> &prunable, + std::optional<bool> &prunable, bool IsSameFieldName) { const Expr *OriginalExpr = Ex; Ex = Ex->IgnoreParenCasts(); @@ -3012,7 +3013,7 @@ PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue, bool IsAssuming) { bool shouldInvert = false; - Optional<bool> shouldPrune; + std::optional<bool> shouldPrune; // Check if the field name of the MemberExprs is ambiguous. Example: // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'. @@ -3372,7 +3373,7 @@ UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC, ProgramPoint ProgLoc = N->getLocation(); // We are only interested in visiting CallEnter nodes. - Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); + std::optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); if (!CEnter) return nullptr; @@ -3510,7 +3511,7 @@ PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N, if (!T) return nullptr; - if (Optional<std::string> Msg = T->generateMessage(BRC, R)) { + if (std::optional<std::string> Msg = T->generateMessage(BRC, R)) { PathDiagnosticLocation Loc = PathDiagnosticLocation::create(PP, BRC.getSourceManager()); auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg); diff --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp index 38d80df..fdd80d2 100644 --- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp +++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp @@ -24,7 +24,7 @@ using namespace llvm; using namespace clang; -using MaybeCount = Optional<unsigned>; +using MaybeCount = std::optional<unsigned>; // A constructor helper. static MaybeCount readRequiredParams(MaybeCount RequiredArgs, diff --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp index cff2fde..0e9cca5 100644 --- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp +++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp @@ -515,8 +515,7 @@ const ConstructionContext *CallEvent::getConstructionContext() const { return nullptr; } -Optional<SVal> -CallEvent::getReturnValueUnderConstruction() const { +std::optional<SVal> CallEvent::getReturnValueUnderConstruction() const { const auto *CC = getConstructionContext(); if (!CC) return std::nullopt; @@ -808,7 +807,7 @@ void CXXInstanceCall::getInitialStackFrameContents( QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. - Optional<SVal> V = + std::optional<SVal> V = StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty); if (!V) { // We might have suffered some sort of placement new earlier, so @@ -1223,10 +1222,10 @@ lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, // stays around until clang quits, which also may be bad if we // need to release memory. using PrivateMethodCache = - llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>; + llvm::DenseMap<PrivateMethodKey, std::optional<const ObjCMethodDecl *>>; static PrivateMethodCache PMC; - Optional<const ObjCMethodDecl *> &Val = + std::optional<const ObjCMethodDecl *> &Val = PMC[{Interface, LookupSelector, InstanceMethod}]; // Query lookupPrivateMethod() if the cache does not hit. @@ -1436,9 +1435,10 @@ CallEventManager::getCaller(const StackFrameContext *CalleeCtx, SVal ThisVal = State->getSVal(ThisPtr); const Stmt *Trigger; - if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) + if (std::optional<CFGAutomaticObjDtor> AutoDtor = + E.getAs<CFGAutomaticObjDtor>()) Trigger = AutoDtor->getTriggerStmt(); - else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) + else if (std::optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) Trigger = DeleteDtor->getDeleteExpr(); else Trigger = Dtor->getBody(); diff --git a/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp b/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp index 76d731b..84ad20a 100644 --- a/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp +++ b/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp @@ -111,8 +111,7 @@ Nullability getNullabilityAnnotation(QualType Type) { return Nullability::Unspecified; } -llvm::Optional<int> tryExpandAsInteger(StringRef Macro, - const Preprocessor &PP) { +std::optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP) { const auto *MacroII = PP.getIdentifierInfo(Macro); if (!MacroII) return std::nullopt; diff --git a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp index c23e3bc..6fc1622 100644 --- a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp +++ b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp @@ -654,7 +654,7 @@ void CheckerManager::runCheckersForEvalCall(ExplodedNodeSet &Dst, ExprEngine &Eng, const EvalCallOptions &CallOpts) { for (auto *const Pred : Src) { - Optional<CheckerNameRef> evaluatorChecker; + std::optional<CheckerNameRef> evaluatorChecker; ExplodedNodeSet checkDst; NodeBuilder B(Pred, checkDst, Eng.getBuilderContext()); diff --git a/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp b/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp index 8e15ef9..1d804f6 100644 --- a/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp +++ b/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp @@ -274,10 +274,10 @@ void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) { const ReturnStmt *RS = nullptr; if (!L.getSrc()->empty()) { CFGElement LastElement = L.getSrc()->back(); - if (Optional<CFGStmt> LastStmt = LastElement.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> LastStmt = LastElement.getAs<CFGStmt>()) { RS = dyn_cast<ReturnStmt>(LastStmt->getStmt()); - } else if (Optional<CFGAutomaticObjDtor> AutoDtor = - LastElement.getAs<CFGAutomaticObjDtor>()) { + } else if (std::optional<CFGAutomaticObjDtor> AutoDtor = + LastElement.getAs<CFGAutomaticObjDtor>()) { RS = dyn_cast<ReturnStmt>(AutoDtor->getTriggerStmt()); } } @@ -315,11 +315,10 @@ void CoreEngine::HandleBlockEntrance(const BlockEntrance &L, setBlockCounter(Counter); // Process the entrance of the block. - if (Optional<CFGElement> E = L.getFirstElement()) { + if (std::optional<CFGElement> E = L.getFirstElement()) { NodeBuilderContext Ctx(*this, L.getBlock(), Pred); ExprEng.processCFGElement(*E, Pred, 0, &Ctx); - } - else + } else HandleBlockExit(L.getBlock(), Pred); } diff --git a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp index 23526d0..c0d906b 100644 --- a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp @@ -140,7 +140,7 @@ bool ExplodedGraph::shouldCollect(const ExplodedNode *node) { // Condition 10. const ProgramPoint SuccLoc = succ->getLocation(); - if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>()) + if (std::optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>()) if (CallEvent::isCallStmt(SP->getStmt())) return false; diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp index 1dc1102..8ea77f6 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -271,7 +271,7 @@ ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { svalBuilder.makeZeroVal(T), svalBuilder.getConditionType()); - Optional<DefinedOrUnknownSVal> Constraint = + std::optional<DefinedOrUnknownSVal> Constraint = Constraint_untested.getAs<DefinedOrUnknownSVal>(); if (!Constraint) @@ -291,7 +291,7 @@ ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { const MemRegion *R = state->getRegion(SelfD, InitLoc); SVal V = state->getSVal(loc::MemRegionVal(R)); - if (Optional<Loc> LV = V.getAs<Loc>()) { + if (std::optional<Loc> LV = V.getAs<Loc>()) { // Assume that the pointer value in 'self' is non-null. state = state->assume(*LV, true); assert(state && "'self' cannot be null"); @@ -307,7 +307,7 @@ ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { if (SFC->getParent() == nullptr) { loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC); SVal V = state->getSVal(L); - if (Optional<Loc> LV = V.getAs<Loc>()) { + if (std::optional<Loc> LV = V.getAs<Loc>()) { state = state->assume(*LV, true); assert(state && "'this' cannot be null"); } @@ -383,7 +383,7 @@ ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded( // into that region. This is not correct, but it is better than nothing. const TypedValueRegion *TR = nullptr; if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) { - if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) { + if (std::optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) { State = finishObjectConstruction(State, MT, LC); State = State->BindExpr(Result, LC, *V); return State; @@ -478,9 +478,9 @@ ProgramStateRef ExprEngine::setIndexOfElementToConstruct( return State->set<IndexOfElementToConstruct>(Key, Idx); } -Optional<unsigned> ExprEngine::getPendingInitLoop(ProgramStateRef State, - const CXXConstructExpr *E, - const LocationContext *LCtx) { +std::optional<unsigned> +ExprEngine::getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, + const LocationContext *LCtx) { const unsigned *V = State->get<PendingInitLoop>({E, LCtx->getStackFrame()}); return V ? std::make_optional(*V) : std::nullopt; } @@ -505,7 +505,7 @@ ProgramStateRef ExprEngine::setPendingInitLoop(ProgramStateRef State, return State->set<PendingInitLoop>(Key, Size); } -Optional<unsigned> +std::optional<unsigned> ExprEngine::getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx) { @@ -524,7 +524,7 @@ ExprEngine::removeIndexOfElementToConstruct(ProgramStateRef State, return State->remove<IndexOfElementToConstruct>(Key); } -Optional<unsigned> +std::optional<unsigned> ExprEngine::getPendingArrayDestruction(ProgramStateRef State, const LocationContext *LCtx) { assert(LCtx && "LocationContext shouldn't be null!"); @@ -595,7 +595,7 @@ ExprEngine::addObjectUnderConstruction(ProgramStateRef State, return State->set<ObjectsUnderConstruction>(Key, V); } -Optional<SVal> +std::optional<SVal> ExprEngine::getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC) { @@ -1200,7 +1200,7 @@ void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit, SVal LValue = State->getSVal(Init, stackFrame); if (!Field->getType()->isReferenceType()) - if (Optional<Loc> LValueLoc = LValue.getAs<Loc>()) + if (std::optional<Loc> LValueLoc = LValue.getAs<Loc>()) InitVal = State->getSVal(*LValueLoc); // If we fail to get the value for some reason, use a symbolic value. @@ -1549,9 +1549,8 @@ void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, const LocationContext *LC = Pred->getLocationContext(); const MemRegion *MR = nullptr; - if (Optional<SVal> V = - getObjectUnderConstruction(State, D.getBindTemporaryExpr(), - Pred->getLocationContext())) { + if (std::optional<SVal> V = getObjectUnderConstruction( + State, D.getBindTemporaryExpr(), Pred->getLocationContext())) { // FIXME: Currently we insert temporary destructors for default parameters, // but we don't insert the constructors, so the entry in // ObjectsUnderConstruction may be missing. @@ -1962,7 +1961,7 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, IsTemporary = true; } - Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); + std::optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); if (!ConstantVal) ConstantVal = UnknownVal(); @@ -2428,7 +2427,7 @@ bool ExprEngine::replayWithoutInlining(ExplodedNode *N, continue; if (L.getAs<CallEnter>()) continue; - if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) + if (std::optional<StmtPoint> SP = L.getAs<StmtPoint>()) if (SP->getStmt() == CE) continue; break; @@ -2635,7 +2634,7 @@ static const Stmt *ResolveCondition(const Stmt *Condition, CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); for (; I != E; ++I) { CFGElement Elem = *I; - Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); + std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); if (!CS) continue; const Stmt *LastStmt = CS->getStmt(); @@ -2675,7 +2674,7 @@ bool ExprEngine::hasMoreIteration(ProgramStateRef State, /// Split the state on whether there are any more iterations left for this loop. /// Returns a (HasMoreIteration, HasNoMoreIteration) pair, or std::nullopt when /// the acquisition of the loop condition value failed. -static Optional<std::pair<ProgramStateRef, ProgramStateRef>> +static std::optional<std::pair<ProgramStateRef, ProgramStateRef>> assumeCondition(const Stmt *Condition, ExplodedNode *N) { ProgramStateRef State = N->getState(); if (const auto *ObjCFor = dyn_cast<ObjCForCollectionStmt>(Condition)) { @@ -2839,7 +2838,7 @@ void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { using iterator = IndirectGotoNodeBuilder::iterator; - if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { + if (std::optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { const LabelDecl *L = LV->getLabel(); for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { @@ -2991,7 +2990,7 @@ void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { V2 = V1; ProgramStateRef StateCase; - if (Optional<NonLoc> NL = CondV.getAs<NonLoc>()) + if (std::optional<NonLoc> NL = CondV.getAs<NonLoc>()) std::tie(StateCase, DefaultSt) = DefaultSt->assumeInclusiveRange(*NL, V1, V2); else // UnknownVal @@ -3050,7 +3049,7 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, const Decl *D = LocCtxt->getDecl(); const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); - Optional<std::pair<SVal, QualType>> VInfo; + std::optional<std::pair<SVal, QualType>> VInfo; if (AMgr.options.ShouldInlineLambdas && DeclRefEx && DeclRefEx->refersToEnclosingVariableOrCapture() && MD && @@ -3588,7 +3587,7 @@ void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, Val, LC, /* notifyChanges = */ !atDeclInit); const MemRegion *LocReg = nullptr; - if (Optional<loc::MemRegionVal> LocRegVal = + if (std::optional<loc::MemRegionVal> LocRegVal = location.getAs<loc::MemRegionVal>()) { LocReg = LocRegVal->getRegion(); } @@ -3729,7 +3728,7 @@ void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ProgramStateRef state = Pred->getState(); SVal V = state->getSVal(Ex, Pred->getLocationContext()); - Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); + std::optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); if (SEV && SEV->isExpression()) { const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = geteagerlyAssumeBinOpBifurcationTags(); @@ -3770,7 +3769,7 @@ void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, SVal X = state->getSVal(O, Pred->getLocationContext()); assert(!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. - if (Optional<Loc> LV = X.getAs<Loc>()) + if (std::optional<Loc> LV = X.getAs<Loc>()) state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext()); } diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp index 397561f..6652c06 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp @@ -447,10 +447,10 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, // Check if the value being cast does not evaluates to 0. if (!val.isZeroConstant()) - if (Optional<SVal> V = + if (std::optional<SVal> V = StateMgr.getStoreManager().evalBaseToDerived(val, T)) { - val = *V; - Failed = false; + val = *V; + Failed = false; } if (Failed) { @@ -485,7 +485,7 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, resultType = getContext().getPointerType(resultType); if (!val.isConstant()) { - Optional<SVal> V = getStoreManager().evalBaseToDerived(val, T); + std::optional<SVal> V = getStoreManager().evalBaseToDerived(val, T); val = V ? *V : UnknownVal(); } @@ -824,7 +824,7 @@ void ExprEngine::VisitGuardedExpr(const Expr *Ex, SVal V; for (CFGElement CE : llvm::reverse(*SrcBlock)) { - if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { + if (std::optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { const Expr *ValEx = cast<Expr>(CS->getStmt()); ValEx = ValEx->IgnoreParens(); @@ -1044,16 +1044,15 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred, // Note: technically we do "E == 0", but this is the same in the // transfer functions as "0 == E". SVal Result; - if (Optional<Loc> LV = V.getAs<Loc>()) { - Loc X = svalBuilder.makeNullWithType(Ex->getType()); - Result = evalBinOp(state, BO_EQ, *LV, X, U->getType()); + if (std::optional<Loc> LV = V.getAs<Loc>()) { + Loc X = svalBuilder.makeNullWithType(Ex->getType()); + Result = evalBinOp(state, BO_EQ, *LV, X, U->getType()); } else if (Ex->getType()->isFloatingType()) { - // FIXME: handle floating point types. - Result = UnknownVal(); + // FIXME: handle floating point types. + Result = UnknownVal(); } else { - nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); - Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X, - U->getType()); + nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); + Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X, U->getType()); } state = state->BindExpr(U, LCtx, Result); diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp index 3bee680..6eb3728 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp @@ -76,7 +76,7 @@ void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, // If the value being copied is not unknown, load from its location to get // an aggregate rvalue. - if (Optional<Loc> L = V.getAs<Loc>()) + if (std::optional<Loc> L = V.getAs<Loc>()) V = Pred->getState()->getSVal(*L); else assert(V.isUnknownOrUndef()); @@ -328,7 +328,7 @@ SVal ExprEngine::computeObjectUnderConstruction( unsigned Idx = ACC->getIndex(); CallEventManager &CEMgr = getStateManager().getCallEventManager(); - auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> { + auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> { const LocationContext *FutureSFC = Caller->getCalleeStackFrame(BldrCtx->blockCount()); // Return early if we are unable to reliably foresee @@ -358,7 +358,7 @@ SVal ExprEngine::computeObjectUnderConstruction( if (const auto *CE = dyn_cast<CallExpr>(E)) { CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx); - if (Optional<SVal> V = getArgLoc(Caller)) + if (std::optional<SVal> V = getArgLoc(Caller)) return *V; else break; @@ -367,13 +367,13 @@ SVal ExprEngine::computeObjectUnderConstruction( // constructor because we won't need it. CallEventRef<> Caller = CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx); - if (Optional<SVal> V = getArgLoc(Caller)) + if (std::optional<SVal> V = getArgLoc(Caller)) return *V; else break; } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx); - if (Optional<SVal> V = getArgLoc(Caller)) + if (std::optional<SVal> V = getArgLoc(Caller)) return *V; else break; @@ -584,18 +584,18 @@ void ExprEngine::handleConstructor(const Expr *E, SVal Target = UnknownVal(); if (CE) { - if (Optional<SVal> ElidedTarget = + if (std::optional<SVal> ElidedTarget = getObjectUnderConstruction(State, CE, LCtx)) { - // We've previously modeled an elidable constructor by pretending that it - // in fact constructs into the correct target. This constructor can - // therefore be skipped. - Target = *ElidedTarget; - StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); - State = finishObjectConstruction(State, CE, LCtx); - if (auto L = Target.getAs<Loc>()) - State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); - Bldr.generateNode(CE, Pred, State); - return; + // We've previously modeled an elidable constructor by pretending that + // it in fact constructs into the correct target. This constructor can + // therefore be skipped. + Target = *ElidedTarget; + StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); + State = finishObjectConstruction(State, CE, LCtx); + if (auto L = Target.getAs<Loc>()) + State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); + Bldr.generateNode(CE, Pred, State); + return; } } diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp index 2db6545..54528475 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp @@ -86,10 +86,10 @@ static std::pair<const Stmt*, const ProgramPoint &PP = Node->getLocation(); if (PP.getStackFrame() == SF) { - if (Optional<StmtPoint> SP = PP.getAs<StmtPoint>()) { + if (std::optional<StmtPoint> SP = PP.getAs<StmtPoint>()) { S = SP->getStmt(); break; - } else if (Optional<CallExitEnd> CEE = PP.getAs<CallExitEnd>()) { + } else if (std::optional<CallExitEnd> CEE = PP.getAs<CallExitEnd>()) { S = CEE->getCalleeContext()->getCallSite(); if (S) break; @@ -97,17 +97,17 @@ static std::pair<const Stmt*, // If there is no statement, this is an implicitly-generated call. // We'll walk backwards over it and then continue the loop to find // an actual statement. - Optional<CallEnter> CE; + std::optional<CallEnter> CE; do { Node = Node->getFirstPred(); CE = Node->getLocationAs<CallEnter>(); } while (!CE || CE->getCalleeContext() != CEE->getCalleeContext()); // Continue searching the graph. - } else if (Optional<BlockEdge> BE = PP.getAs<BlockEdge>()) { + } else if (std::optional<BlockEdge> BE = PP.getAs<BlockEdge>()) { Blk = BE->getSrc(); } - } else if (Optional<CallEnter> CE = PP.getAs<CallEnter>()) { + } else if (std::optional<CallEnter> CE = PP.getAs<CallEnter>()) { // If we reached the CallEnter for this function, it has no statements. if (CE->getCalleeContext() == SF) break; @@ -640,8 +640,7 @@ ProgramStateRef ExprEngine::finishArgumentConstruction(ProgramStateRef State, const LocationContext *LC = Call.getLocationContext(); for (unsigned CallI = 0, CallN = Call.getNumArgs(); CallI != CallN; ++CallI) { unsigned I = Call.getASTArgumentIndex(CallI); - if (Optional<SVal> V = - getObjectUnderConstruction(State, {E, I}, LC)) { + if (std::optional<SVal> V = getObjectUnderConstruction(State, {E, I}, LC)) { SVal VV = *V; (void)VV; assert(cast<VarRegion>(VV.castAs<loc::MemRegionVal>().getRegion()) @@ -1091,7 +1090,7 @@ bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D, return false; // Check if this function has been marked as non-inlinable. - Optional<bool> MayInline = Engine.FunctionSummaries->mayInline(D); + std::optional<bool> MayInline = Engine.FunctionSummaries->mayInline(D); if (MayInline) { if (!*MayInline) return false; diff --git a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp index 357d95c..a803528 100644 --- a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp +++ b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp @@ -287,7 +287,7 @@ bool madeNewBranch(ExplodedNode *N, const Stmt *LoopStmt) { return true; ProgramPoint P = N->getLocation(); - if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) + if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) S = BE->getBlock()->getTerminatorStmt(); if (S == LoopStmt) diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp index 1bd53ec..b484860 100644 --- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp +++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp @@ -1555,7 +1555,7 @@ static RegionOffset calculateOffset(const MemRegion *R) { } SVal Index = ER->getIndex(); - if (Optional<nonloc::ConcreteInt> CI = + if (std::optional<nonloc::ConcreteInt> CI = Index.getAs<nonloc::ConcreteInt>()) { // Don't bother calculating precise offsets if we already have a // symbolic offset somewhere in the chain. diff --git a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp index 7fc53b1..a3b08d4 100644 --- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp @@ -166,7 +166,7 @@ static void printCoverage(const PathDiagnostic *D, FIDMap &FM, llvm::raw_fd_ostream &o); -static Optional<StringRef> getExpandedMacro( +static std::optional<StringRef> getExpandedMacro( SourceLocation MacroLoc, const cross_tu::CrossTranslationUnitContext &CTU, const MacroExpansionContext &MacroExpansions, const SourceManager &SM); @@ -385,9 +385,9 @@ void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) { SourceLocation MacroExpansionLoc = P->getLocation().asLocation().getExpansionLoc(); - const Optional<StringRef> MacroName = + const std::optional<StringRef> MacroName = MacroExpansions.getOriginalText(MacroExpansionLoc); - const Optional<StringRef> ExpansionText = + const std::optional<StringRef> ExpansionText = getExpandedMacro(MacroExpansionLoc, CTU, MacroExpansions, SM); if (!MacroName || !ExpansionText) @@ -826,7 +826,7 @@ void PlistDiagnostics::FlushDiagnosticsImpl( // Definitions of helper functions and methods for expanding macros. //===----------------------------------------------------------------------===// -static Optional<StringRef> +static std::optional<StringRef> getExpandedMacro(SourceLocation MacroExpansionLoc, const cross_tu::CrossTranslationUnitContext &CTU, const MacroExpansionContext &MacroExpansions, diff --git a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp index 87ba432..90ebbaa 100644 --- a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp +++ b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp @@ -579,20 +579,20 @@ bool ScanReachableSymbols::scan(const SymExpr *sym) { } bool ScanReachableSymbols::scan(SVal val) { - if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) + if (std::optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) return scan(X->getRegion()); - if (Optional<nonloc::LazyCompoundVal> X = + if (std::optional<nonloc::LazyCompoundVal> X = val.getAs<nonloc::LazyCompoundVal>()) return scan(*X); - if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>()) + if (std::optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>()) return scan(X->getLoc()); if (SymbolRef Sym = val.getAsSymbol()) return scan(Sym); - if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>()) + if (std::optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>()) return scan(*X); return true; diff --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp index 2212170..3725e49 100644 --- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp +++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp @@ -961,10 +961,10 @@ public: [[nodiscard]] inline ClassSet getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const; - [[nodiscard]] static inline Optional<bool> areEqual(ProgramStateRef State, - EquivalenceClass First, - EquivalenceClass Second); - [[nodiscard]] static inline Optional<bool> + [[nodiscard]] static inline std::optional<bool> + areEqual(ProgramStateRef State, EquivalenceClass First, + EquivalenceClass Second); + [[nodiscard]] static inline std::optional<bool> areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second); /// Remove one member from the class. @@ -1084,7 +1084,7 @@ areFeasible(ConstraintRangeTy Constraints) { /// \returns true if assuming this Sym to be true means equality of operands /// false if it means disequality of operands /// None otherwise -Optional<bool> meansEquality(const SymSymExpr *Sym) { +std::optional<bool> meansEquality(const SymSymExpr *Sym) { switch (Sym->getOpcode()) { case BO_Sub: // This case is: A - B != 0 -> disequality check. @@ -1118,7 +1118,7 @@ template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> { template <> struct IntersectionTraits<> { // We ran out of types, and we didn't find any RangeSet, so the result should // be optional. - using Type = Optional<RangeSet>; + using Type = std::optional<RangeSet>; }; template <class OptionalOrPointer, class... TailTy> @@ -1129,14 +1129,15 @@ struct IntersectionTraits<OptionalOrPointer, TailTy...> { template <class EndTy> [[nodiscard]] inline EndTy intersect(RangeSet::Factory &F, EndTy End) { - // If the list contains only RangeSet or Optional<RangeSet>, simply return - // that range set. + // If the list contains only RangeSet or std::optional<RangeSet>, simply + // return that range set. return End; } -[[nodiscard]] LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet> +[[nodiscard]] LLVM_ATTRIBUTE_UNUSED inline std::optional<RangeSet> intersect(RangeSet::Factory &F, const RangeSet *End) { - // This is an extraneous conversion from a raw pointer into Optional<RangeSet> + // This is an extraneous conversion from a raw pointer into + // std::optional<RangeSet> if (End) { return *End; } @@ -1170,7 +1171,7 @@ template <class SecondTy, class... RestTy> /// /// Available representations for the arguments are: /// * RangeSet -/// * Optional<RangeSet> +/// * std::optional<RangeSet> /// * RangeSet * /// Pointer to a RangeSet is automatically assumed to be nullable and will get /// checked as well as the optional version. If this behaviour is undesired, @@ -1178,11 +1179,12 @@ template <class SecondTy, class... RestTy> /// /// Return type depends on the arguments' types. If we can be sure in compile /// time that there will be a range set as a result, the returning type is -/// simply RangeSet, in other cases we have to back off to Optional<RangeSet>. +/// simply RangeSet, in other cases we have to back off to +/// std::optional<RangeSet>. /// /// Please, prefer optional range sets to raw pointers. If the last argument is /// a raw pointer and all previous arguments are std::nullopt, it will cost one -/// additional check to convert RangeSet * into Optional<RangeSet>. +/// additional check to convert RangeSet * into std::optional<RangeSet>. template <class HeadTy, class SecondTy, class... RestTy> [[nodiscard]] inline typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type @@ -1214,7 +1216,7 @@ public: } RangeSet VisitSymExpr(SymbolRef Sym) { - if (Optional<RangeSet> RS = getRangeForNegatedSym(Sym)) + if (std::optional<RangeSet> RS = getRangeForNegatedSym(Sym)) return *RS; // If we've reached this line, the actual type of the symbolic // expression is not supported for advanced inference. @@ -1224,7 +1226,7 @@ public: } RangeSet VisitUnarySymExpr(const UnarySymExpr *USE) { - if (Optional<RangeSet> RS = getRangeForNegatedUnarySym(USE)) + if (std::optional<RangeSet> RS = getRangeForNegatedUnarySym(USE)) return *RS; return infer(USE->getType()); } @@ -1353,7 +1355,7 @@ private: /// Try to convert given range into the given type. /// /// It will return std::nullopt only when the trivial conversion is possible. - llvm::Optional<Range> convert(const Range &Origin, APSIntType To) { + std::optional<Range> convert(const Range &Origin, APSIntType To) { if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within || To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) { return std::nullopt; @@ -1437,8 +1439,8 @@ private: } template <typename ProduceNegatedSymFunc> - Optional<RangeSet> getRangeForNegatedExpr(ProduceNegatedSymFunc F, - QualType T) { + std::optional<RangeSet> getRangeForNegatedExpr(ProduceNegatedSymFunc F, + QualType T) { // Do not negate if the type cannot be meaningfully negated. if (!T->isUnsignedIntegerOrEnumerationType() && !T->isSignedIntegerOrEnumerationType()) @@ -1451,7 +1453,7 @@ private: return std::nullopt; } - Optional<RangeSet> getRangeForNegatedUnarySym(const UnarySymExpr *USE) { + std::optional<RangeSet> getRangeForNegatedUnarySym(const UnarySymExpr *USE) { // Just get the operand when we negate a symbol that is already negated. // -(-a) == a return getRangeForNegatedExpr( @@ -1463,7 +1465,7 @@ private: USE->getType()); } - Optional<RangeSet> getRangeForNegatedSymSym(const SymSymExpr *SSE) { + std::optional<RangeSet> getRangeForNegatedSymSym(const SymSymExpr *SSE) { return getRangeForNegatedExpr( [SSE, State = this->State]() -> SymbolRef { if (SSE->getOpcode() == BO_Sub) @@ -1474,7 +1476,7 @@ private: SSE->getType()); } - Optional<RangeSet> getRangeForNegatedSym(SymbolRef Sym) { + std::optional<RangeSet> getRangeForNegatedSym(SymbolRef Sym) { return getRangeForNegatedExpr( [Sym, State = this->State]() { return State->getSymbolManager().getUnarySymExpr(Sym, UO_Minus, @@ -1493,7 +1495,7 @@ private: // It covers all possible combinations (see CmpOpTable description). // Note that `x` and `y` can also stand for subexpressions, // not only for actual symbols. - Optional<RangeSet> getRangeForComparisonSymbol(const SymSymExpr *SSE) { + std::optional<RangeSet> getRangeForComparisonSymbol(const SymSymExpr *SSE) { const BinaryOperatorKind CurrentOP = SSE->getOpcode(); // We currently do not support <=> (C++20). @@ -1571,13 +1573,13 @@ private: return std::nullopt; } - Optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) { - Optional<bool> Equality = meansEquality(Sym); + std::optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) { + std::optional<bool> Equality = meansEquality(Sym); if (!Equality) return std::nullopt; - if (Optional<bool> AreEqual = + if (std::optional<bool> AreEqual = EquivalenceClass::areEqual(State, Sym->getLHS(), Sym->getRHS())) { // Here we cover two cases at once: // * if Sym is equality and its operands are known to be equal -> true @@ -2132,7 +2134,7 @@ private: return EquivalenceClass::merge(RangeFactory, State, LHS, RHS); } - [[nodiscard]] Optional<bool> interpreteAsBool(RangeSet Constraint) { + [[nodiscard]] std::optional<bool> interpreteAsBool(RangeSet Constraint) { assert(!Constraint.isEmpty() && "Empty ranges shouldn't get here"); if (Constraint.getConcreteValue()) @@ -2196,12 +2198,12 @@ bool ConstraintAssignor::assignSymSymExprToRangeSet(const SymSymExpr *Sym, if (!handleRemainderOp(Sym, Constraint)) return false; - Optional<bool> ConstraintAsBool = interpreteAsBool(Constraint); + std::optional<bool> ConstraintAsBool = interpreteAsBool(Constraint); if (!ConstraintAsBool) return true; - if (Optional<bool> Equality = meansEquality(Sym)) { + if (std::optional<bool> Equality = meansEquality(Sym)) { // Here we cover two cases: // * if Sym is equality and the new constraint is true -> Sym's operands // should be marked as equal @@ -2339,7 +2341,7 @@ EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory, // // Intersection here makes perfect sense because both of these constraints // must hold for the whole new class. - if (Optional<RangeSet> NewClassConstraint = + if (std::optional<RangeSet> NewClassConstraint = intersect(RangeFactory, getConstraint(State, *this), getConstraint(State, Other))) { // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because @@ -2537,16 +2539,16 @@ inline bool EquivalenceClass::addToDisequalityInfo( return true; } -inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, - SymbolRef FirstSym, - SymbolRef SecondSym) { +inline std::optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, + SymbolRef FirstSym, + SymbolRef SecondSym) { return EquivalenceClass::areEqual(State, find(State, FirstSym), find(State, SecondSym)); } -inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, - EquivalenceClass First, - EquivalenceClass Second) { +inline std::optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, + EquivalenceClass First, + EquivalenceClass Second) { // The same equivalence class => symbols are equal. if (First == Second) return true; @@ -2750,7 +2752,7 @@ bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) { //===----------------------------------------------------------------------===// bool RangeConstraintManager::canReasonAbout(SVal X) const { - Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); + std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); if (SymVal && SymVal->isExpression()) { const SymExpr *SE = SymVal->getSymbol(); diff --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp index 91ac36f..7cf570b 100644 --- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp +++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp @@ -213,11 +213,11 @@ public: removeBinding(R, BindingKey::Default); } - Optional<SVal> getDirectBinding(const MemRegion *R) const; + std::optional<SVal> getDirectBinding(const MemRegion *R) const; /// getDefaultBinding - Returns an SVal* representing an optional default /// binding associated with a region and its subregions. - Optional<SVal> getDefaultBinding(const MemRegion *R) const; + std::optional<SVal> getDefaultBinding(const MemRegion *R) const; /// Return the internal tree as a Store. Store asStore() const { @@ -263,14 +263,16 @@ public: typedef const RegionBindingsRef& RegionBindingsConstRef; -Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const { +std::optional<SVal> +RegionBindingsRef::getDirectBinding(const MemRegion *R) const { const SVal *V = lookup(R, BindingKey::Direct); - return V ? Optional<SVal>(*V) : std::nullopt; + return V ? std::optional<SVal>(*V) : std::nullopt; } -Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const { +std::optional<SVal> +RegionBindingsRef::getDefaultBinding(const MemRegion *R) const { const SVal *V = lookup(R, BindingKey::Default); - return V ? Optional<SVal>(*V) : std::nullopt; + return V ? std::optional<SVal>(*V) : std::nullopt; } RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const { @@ -424,10 +426,10 @@ public: RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B, const SubRegion *R); - Optional<SVal> + std::optional<SVal> getConstantValFromConstArrayInitializer(RegionBindingsConstRef B, const ElementRegion *R); - Optional<SVal> + std::optional<SVal> getSValFromInitListExpr(const InitListExpr *ILE, const SmallVector<uint64_t, 2> &ConcreteOffsets, QualType ElemT); @@ -488,10 +490,9 @@ public: // Part of public interface to class. /// /// \returns The updated store bindings, or \c std::nullopt if binding /// non-lazily would be too expensive. - Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B, - const TypedValueRegion *R, - const RecordDecl *RD, - nonloc::LazyCompoundVal LCV); + std::optional<RegionBindingsRef> + tryBindSmallStruct(RegionBindingsConstRef B, const TypedValueRegion *R, + const RecordDecl *RD, nonloc::LazyCompoundVal LCV); /// BindStruct - Bind a compound value to a structure. RegionBindingsRef bindStruct(RegionBindingsConstRef B, @@ -501,10 +502,9 @@ public: // Part of public interface to class. RegionBindingsRef bindVector(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V); - Optional<RegionBindingsRef> tryBindSmallArray(RegionBindingsConstRef B, - const TypedValueRegion *R, - const ArrayType *AT, - nonloc::LazyCompoundVal LCV); + std::optional<RegionBindingsRef> + tryBindSmallArray(RegionBindingsConstRef B, const TypedValueRegion *R, + const ArrayType *AT, nonloc::LazyCompoundVal LCV); RegionBindingsRef bindArray(RegionBindingsConstRef B, const TypedValueRegion* R, @@ -551,7 +551,7 @@ public: // Part of public interface to class. return getBinding(getRegionBindings(S), L, T); } - Optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override { + std::optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override { RegionBindingsRef B = getRegionBindings(S); // Default bindings are always applied over a base region so look up the // base region's default binding, otherwise the lookup will fail when R @@ -592,10 +592,10 @@ public: // Part of public interface to class. /// /// Note that callers may need to specially handle LazyCompoundVals, which /// are returned as is in case the caller needs to treat them differently. - Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B, - const MemRegion *superR, - const TypedValueRegion *R, - QualType Ty); + std::optional<SVal> + getBindingForDerivedDefaultValue(RegionBindingsConstRef B, + const MemRegion *superR, + const TypedValueRegion *R, QualType Ty); /// Get the state and region whose binding this region \p R corresponds to. /// @@ -864,7 +864,7 @@ collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, // Find the length (in bits) of the region being invalidated. uint64_t Length = UINT64_MAX; SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB); - if (Optional<nonloc::ConcreteInt> ExtentCI = + if (std::optional<nonloc::ConcreteInt> ExtentCI = Extent.getAs<nonloc::ConcreteInt>()) { const llvm::APSInt &ExtentInt = ExtentCI->getValue(); assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); @@ -1036,7 +1036,7 @@ void InvalidateRegionsWorker::VisitBinding(SVal V) { } // Is it a LazyCompoundVal? All references get invalidated as well. - if (Optional<nonloc::LazyCompoundVal> LCS = + if (std::optional<nonloc::LazyCompoundVal> LCS = V.getAs<nonloc::LazyCompoundVal>()) { // `getInterestingValues()` returns SVals contained within LazyCompoundVals, @@ -1109,7 +1109,7 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR, // a pointer value, but the thing pointed by that pointer may // get invalidated. SVal V = RM.getBinding(B, loc::MemRegionVal(VR)); - if (Optional<Loc> L = V.getAs<Loc>()) { + if (std::optional<Loc> L = V.getAs<Loc>()) { if (const MemRegion *LR = L->getAsRegion()) AddToWorkList(LR); } @@ -1169,7 +1169,7 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR, if (doNotInvalidateSuperRegion) { // We are not doing blank invalidation of the whole array region so we // have to manually invalidate each elements. - Optional<uint64_t> NumElements; + std::optional<uint64_t> NumElements; // Compute lower and upper offsets for region within array. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) @@ -1204,8 +1204,8 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR, for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) { const BindingKey &BK = I.getKey(); - Optional<uint64_t> ROffset = - BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset(); + std::optional<uint64_t> ROffset = + BK.hasSymbolicOffset() ? std::optional<uint64_t>() : BK.getOffset(); // Check offset is not symbolic and within array's boundaries. // Handles arrays of 0 elements and of 0-sized elements as well. @@ -1293,8 +1293,8 @@ void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W, for (ArrayRef<SVal>::iterator I = Values.begin(), E = Values.end(); I != E; ++I) { SVal V = *I; - if (Optional<nonloc::LazyCompoundVal> LCS = - V.getAs<nonloc::LazyCompoundVal>()) { + if (std::optional<nonloc::LazyCompoundVal> LCS = + V.getAs<nonloc::LazyCompoundVal>()) { for (SVal S : getInterestingValues(*LCS)) if (const MemRegion *R = S.getAsRegion()) @@ -1539,14 +1539,15 @@ static QualType getUnderlyingType(const SubRegion *R) { /// /// Note that unlike RegionStoreManager::findLazyBinding, this will not search /// for lazy bindings for super-regions of \p R. -static Optional<nonloc::LazyCompoundVal> +static std::optional<nonloc::LazyCompoundVal> getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, const SubRegion *R, bool AllowSubregionBindings) { - Optional<SVal> V = B.getDefaultBinding(R); + std::optional<SVal> V = B.getDefaultBinding(R); if (!V) return std::nullopt; - Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>(); + std::optional<nonloc::LazyCompoundVal> LCV = + V->getAs<nonloc::LazyCompoundVal>(); if (!LCV) return std::nullopt; @@ -1573,14 +1574,13 @@ getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, return *LCV; } - std::pair<Store, const SubRegion *> RegionStoreManager::findLazyBinding(RegionBindingsConstRef B, const SubRegion *R, const SubRegion *originalRegion) { if (originalRegion != R) { - if (Optional<nonloc::LazyCompoundVal> V = - getExistingLazyBinding(svalBuilder, B, R, true)) + if (std::optional<nonloc::LazyCompoundVal> V = + getExistingLazyBinding(svalBuilder, B, R, true)) return std::make_pair(V->getStore(), V->getRegion()); } @@ -1680,7 +1680,7 @@ getElementRegionOffsetsWithBase(const ElementRegion *ER) { /// // returns std::nullopt /// int x2 = arr[42][5][-6]; // returns UndefinedVal /// int x3 = arr[4][5][x2]; // returns UnknownVal -static Optional<SVal> +static std::optional<SVal> convertOffsetsFromSvalToUnsigneds(const SmallVector<SVal, 2> &SrcOffsets, const SmallVector<uint64_t, 2> ArrayExtents, SmallVector<uint64_t, 2> &DstOffsets) { @@ -1723,7 +1723,7 @@ convertOffsetsFromSvalToUnsigneds(const SmallVector<SVal, 2> &SrcOffsets, return std::nullopt; } -Optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( +std::optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( RegionBindingsConstRef B, const ElementRegion *R) { assert(R && "ElementRegion should not be null"); @@ -1780,8 +1780,8 @@ Optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( return std::nullopt; SmallVector<uint64_t, 2> ConcreteOffsets; - if (Optional<SVal> V = convertOffsetsFromSvalToUnsigneds(SValOffsets, Extents, - ConcreteOffsets)) + if (std::optional<SVal> V = convertOffsetsFromSvalToUnsigneds( + SValOffsets, Extents, ConcreteOffsets)) return *V; // Handle InitListExpr. @@ -1819,7 +1819,7 @@ Optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( /// NOTE: Inorder to get a valid SVal, a caller shall guarantee valid offsets /// for the given initialization list. Otherwise SVal can be an equivalent to 0 /// or lead to assertion. -Optional<SVal> RegionStoreManager::getSValFromInitListExpr( +std::optional<SVal> RegionStoreManager::getSValFromInitListExpr( const InitListExpr *ILE, const SmallVector<uint64_t, 2> &Offsets, QualType ElemT) { assert(ILE && "InitListExpr should not be null"); @@ -1890,7 +1890,7 @@ SVal RegionStoreManager::getSValFromStringLiteral(const StringLiteral *SL, return svalBuilder.makeIntVal(Code, ElemT); } -static Optional<SVal> getDerivedSymbolForBinding( +static std::optional<SVal> getDerivedSymbolForBinding( RegionBindingsConstRef B, const TypedValueRegion *BaseRegion, const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) { assert(BaseRegion); @@ -1898,7 +1898,8 @@ static Optional<SVal> getDerivedSymbolForBinding( QualType Ty = SubReg->getValueType(); if (BaseTy->isScalarType() && Ty->isScalarType()) { if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) { - if (const Optional<SVal> &ParentValue = B.getDirectBinding(BaseRegion)) { + if (const std::optional<SVal> &ParentValue = + B.getDirectBinding(BaseRegion)) { if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol()) return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg); @@ -1917,7 +1918,7 @@ static Optional<SVal> getDerivedSymbolForBinding( SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, const ElementRegion* R) { // Check if the region has a binding. - if (const Optional<SVal> &V = B.getDirectBinding(R)) + if (const std::optional<SVal> &V = B.getDirectBinding(R)) return *V; const MemRegion* superR = R->getSuperRegion(); @@ -1938,7 +1939,7 @@ SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, return getSValFromStringLiteral(SL, Idx.getZExtValue(), T); } } else if (isa<ElementRegion, VarRegion>(superR)) { - if (Optional<SVal> V = getConstantValFromConstArrayInitializer(B, R)) + if (std::optional<SVal> V = getConstantValFromConstArrayInitializer(B, R)) return *V; } @@ -1969,7 +1970,7 @@ SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, const FieldRegion* R) { // Check if the region has a binding. - if (const Optional<SVal> &V = B.getDirectBinding(R)) + if (const std::optional<SVal> &V = B.getDirectBinding(R)) return *V; // If the containing record was initialized, try to get its constant value. @@ -1989,7 +1990,7 @@ SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, if (const auto *InitList = dyn_cast<InitListExpr>(Init)) { if (Index < InitList->getNumInits()) { if (const Expr *FieldInit = InitList->getInit(Index)) - if (Optional<SVal> V = svalBuilder.getConstantVal(FieldInit)) + if (std::optional<SVal> V = svalBuilder.getConstantVal(FieldInit)) return *V; } else { return svalBuilder.makeZeroVal(Ty); @@ -2020,13 +2021,11 @@ SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, return getBindingForFieldOrElementCommon(B, R, Ty); } -Optional<SVal> -RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B, - const MemRegion *superR, - const TypedValueRegion *R, - QualType Ty) { +std::optional<SVal> RegionStoreManager::getBindingForDerivedDefaultValue( + RegionBindingsConstRef B, const MemRegion *superR, + const TypedValueRegion *R, QualType Ty) { - if (const Optional<SVal> &D = B.getDefaultBinding(superR)) { + if (const std::optional<SVal> &D = B.getDefaultBinding(superR)) { const SVal &val = *D; if (SymbolRef parentSym = val.getAsSymbol()) return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); @@ -2116,7 +2115,8 @@ RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, const SubRegion *SR = R; while (SR) { const MemRegion *Base = SR->getSuperRegion(); - if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) { + if (std::optional<SVal> D = + getBindingForDerivedDefaultValue(B, Base, R, Ty)) { if (D->getAs<nonloc::LazyCompoundVal>()) { hasPartialLazyBinding = true; break; @@ -2158,7 +2158,7 @@ RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, // Try to get direct binding if all other attempts failed thus far. // Else, return UndefinedVal() if (!hasPartialLazyBinding && !isa<BlockDataRegion>(R->getBaseRegion())) { - if (const Optional<SVal> &V = B.getDefaultBinding(R)) + if (const std::optional<SVal> &V = B.getDefaultBinding(R)) return *V; return UndefinedVal(); } @@ -2171,13 +2171,13 @@ RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion* R) { // Check if the region has a binding. - if (const Optional<SVal> &V = B.getDirectBinding(R)) + if (const std::optional<SVal> &V = B.getDirectBinding(R)) return *V; const MemRegion *superR = R->getSuperRegion(); // Check if the super region has a default binding. - if (const Optional<SVal> &V = B.getDefaultBinding(superR)) { + if (const std::optional<SVal> &V = B.getDefaultBinding(superR)) { if (SymbolRef parentSym = V->getAsSymbol()) return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); @@ -2192,10 +2192,10 @@ SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, const VarRegion *R) { // Check if the region has a binding. - if (Optional<SVal> V = B.getDirectBinding(R)) + if (std::optional<SVal> V = B.getDirectBinding(R)) return *V; - if (Optional<SVal> V = B.getDefaultBinding(R)) + if (std::optional<SVal> V = B.getDefaultBinding(R)) return *V; // Lazily derive a value for the VarRegion. @@ -2209,7 +2209,7 @@ SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, // Is 'VD' declared constant? If so, retrieve the constant value. if (VD->getType().isConstQualified()) { if (const Expr *Init = VD->getAnyInitializer()) { - if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) + if (std::optional<SVal> V = svalBuilder.getConstantVal(Init)) return *V; // If the variable is const qualified and has an initializer but @@ -2230,7 +2230,7 @@ SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, // If we're in main(), then global initializers have not become stale yet. if (B.isMainAnalysis()) if (const Expr *Init = VD->getAnyInitializer()) - if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) + if (std::optional<SVal> V = svalBuilder.getConstantVal(Init)) return *V; // Function-scoped static variables are default-initialized to 0; if they @@ -2240,7 +2240,7 @@ SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, if (isa<StaticGlobalSpaceRegion>(MS)) return svalBuilder.makeZeroVal(T); - if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { + if (std::optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { assert(!V->getAs<nonloc::LazyCompoundVal>()); return *V; } @@ -2298,8 +2298,8 @@ RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) { NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R) { - if (Optional<nonloc::LazyCompoundVal> V = - getExistingLazyBinding(svalBuilder, B, R, false)) + if (std::optional<nonloc::LazyCompoundVal> V = + getExistingLazyBinding(svalBuilder, B, R, false)) return *V; return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R); @@ -2359,7 +2359,7 @@ bool RegionStoreManager::includedInBindings(Store store, //===----------------------------------------------------------------------===// StoreRef RegionStoreManager::killBinding(Store ST, Loc L) { - if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) + if (std::optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) if (const MemRegion* R = LV->getRegion()) return StoreRef(getRegionBindings(ST).removeBinding(R) .asImmutableMap() @@ -2434,7 +2434,7 @@ RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B, return B.addBinding(R, BindingKey::Default, V); } -Optional<RegionBindingsRef> RegionStoreManager::tryBindSmallArray( +std::optional<RegionBindingsRef> RegionStoreManager::tryBindSmallArray( RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT, nonloc::LazyCompoundVal LCV) { @@ -2475,7 +2475,7 @@ RegionStoreManager::bindArray(RegionBindingsConstRef B, const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); QualType ElementTy = AT->getElementType(); - Optional<uint64_t> Size; + std::optional<uint64_t> Size; if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) Size = CAT->getSize().getZExtValue(); @@ -2483,15 +2483,16 @@ RegionStoreManager::bindArray(RegionBindingsConstRef B, // Check if the init expr is a literal. If so, bind the rvalue instead. // FIXME: It's not responsibility of the Store to transform this lvalue // to rvalue. ExprEngine or maybe even CFG should do this before binding. - if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { SVal V = getBinding(B.asStore(), *MRV, R->getValueType()); return bindAggregate(B, R, V); } // Handle lazy compound values. - if (Optional<nonloc::LazyCompoundVal> LCV = + if (std::optional<nonloc::LazyCompoundVal> LCV = Init.getAs<nonloc::LazyCompoundVal>()) { - if (Optional<RegionBindingsRef> NewB = tryBindSmallArray(B, R, AT, *LCV)) + if (std::optional<RegionBindingsRef> NewB = + tryBindSmallArray(B, R, AT, *LCV)) return *NewB; return bindAggregate(B, R, Init); @@ -2572,11 +2573,9 @@ RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B, return NewB; } -Optional<RegionBindingsRef> -RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B, - const TypedValueRegion *R, - const RecordDecl *RD, - nonloc::LazyCompoundVal LCV) { +std::optional<RegionBindingsRef> RegionStoreManager::tryBindSmallStruct( + RegionBindingsConstRef B, const TypedValueRegion *R, const RecordDecl *RD, + nonloc::LazyCompoundVal LCV) { FieldVector Fields; if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD)) @@ -2631,9 +2630,10 @@ RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B, return B; // Handle lazy compound values and symbolic values. - if (Optional<nonloc::LazyCompoundVal> LCV = - V.getAs<nonloc::LazyCompoundVal>()) { - if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV)) + if (std::optional<nonloc::LazyCompoundVal> LCV = + V.getAs<nonloc::LazyCompoundVal>()) { + if (std::optional<RegionBindingsRef> NewB = + tryBindSmallStruct(B, R, RD, *LCV)) return *NewB; return bindAggregate(B, R, V); } diff --git a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp index 0affc6f..8ac9baf 100644 --- a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp +++ b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp @@ -124,7 +124,8 @@ SVal SValBuilder::convertToArrayIndex(SVal val) { return val; // Common case: we have an appropriately sized integer. - if (Optional<nonloc::ConcreteInt> CI = val.getAs<nonloc::ConcreteInt>()) { + if (std::optional<nonloc::ConcreteInt> CI = + val.getAs<nonloc::ConcreteInt>()) { const llvm::APSInt& I = CI->getValue(); if (I.getBitWidth() == ArrayIndexWidth && I.isSigned()) return val; @@ -297,7 +298,7 @@ DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block, return loc::MemRegionVal(BD); } -Optional<loc::MemRegionVal> +std::optional<loc::MemRegionVal> SValBuilder::getCastedMemRegionVal(const MemRegion *R, QualType Ty) { if (auto OptR = StateMgr.getStoreManager().castRegion(R, Ty)) return loc::MemRegionVal(*OptR); @@ -319,7 +320,7 @@ loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D, return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC)); } -Optional<SVal> SValBuilder::getConstantVal(const Expr *E) { +std::optional<SVal> SValBuilder::getConstantVal(const Expr *E) { E = E->IgnoreParens(); switch (E->getStmtClass()) { @@ -389,7 +390,7 @@ Optional<SVal> SValBuilder::getConstantVal(const Expr *E) { case CK_NoOp: case CK_BitCast: { const Expr *SE = CE->getSubExpr(); - Optional<SVal> Val = getConstantVal(SE); + std::optional<SVal> Val = getConstantVal(SE); if (!Val) return std::nullopt; return evalCast(*Val, CE->getType(), SE->getType()); @@ -434,11 +435,13 @@ SVal SValBuilder::makeSymExprValNN(BinaryOperator::Opcode Op, return makeNonLoc(symLHS, Op, symRHS, ResultTy); if (symLHS && symLHS->computeComplexity() < MaxComp) - if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>()) + if (std::optional<nonloc::ConcreteInt> rInt = + RHS.getAs<nonloc::ConcreteInt>()) return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy); if (symRHS && symRHS->computeComplexity() < MaxComp) - if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>()) + if (std::optional<nonloc::ConcreteInt> lInt = + LHS.getAs<nonloc::ConcreteInt>()) return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy); return UnknownVal(); @@ -501,14 +504,14 @@ SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, return UnknownVal(); } - if (Optional<Loc> LV = lhs.getAs<Loc>()) { - if (Optional<Loc> RV = rhs.getAs<Loc>()) + if (std::optional<Loc> LV = lhs.getAs<Loc>()) { + if (std::optional<Loc> RV = rhs.getAs<Loc>()) return evalBinOpLL(state, op, *LV, *RV, type); return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type); } - if (const Optional<Loc> RV = rhs.getAs<Loc>()) { + if (const std::optional<Loc> RV = rhs.getAs<Loc>()) { const auto IsCommutative = [](BinaryOperatorKind Op) { return Op == BO_Mul || Op == BO_Add || Op == BO_And || Op == BO_Xor || Op == BO_Or; diff --git a/clang/lib/StaticAnalyzer/Core/SVals.cpp b/clang/lib/StaticAnalyzer/Core/SVals.cpp index ae2f3ff..ecff623 100644 --- a/clang/lib/StaticAnalyzer/Core/SVals.cpp +++ b/clang/lib/StaticAnalyzer/Core/SVals.cpp @@ -45,7 +45,7 @@ using namespace ento; //===----------------------------------------------------------------------===// const FunctionDecl *SVal::getAsFunctionDecl() const { - if (Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>()) { + if (std::optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>()) { const MemRegion* R = X->getRegion(); if (const FunctionCodeRegion *CTR = R->getAs<FunctionCodeRegion>()) if (const auto *FD = dyn_cast<FunctionDecl>(CTR->getDecl())) @@ -79,7 +79,7 @@ SymbolRef SVal::getAsLocSymbol(bool IncludeBaseRegions) const { /// Get the symbol in the SVal or its base region. SymbolRef SVal::getLocSymbolInBase() const { - Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>(); + std::optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>(); if (!X) return nullptr; @@ -104,7 +104,7 @@ SymbolRef SVal::getLocSymbolInBase() const { /// should continue to the base regions if the region is not symbolic. SymbolRef SVal::getAsSymbol(bool IncludeBaseRegions) const { // FIXME: should we consider SymbolRef wrapped in CodeTextRegion? - if (Optional<nonloc::SymbolVal> X = getAs<nonloc::SymbolVal>()) + if (std::optional<nonloc::SymbolVal> X = getAs<nonloc::SymbolVal>()) return X->getSymbol(); return getAsLocSymbol(IncludeBaseRegions); @@ -119,10 +119,10 @@ const llvm::APSInt *SVal::getAsInteger() const { } const MemRegion *SVal::getAsRegion() const { - if (Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>()) + if (std::optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>()) return X->getRegion(); - if (Optional<nonloc::LocAsInteger> X = getAs<nonloc::LocAsInteger>()) + if (std::optional<nonloc::LocAsInteger> X = getAs<nonloc::LocAsInteger>()) return X->getLoc().getAsRegion(); return nullptr; @@ -252,9 +252,9 @@ bool SVal::isConstant() const { } bool SVal::isConstant(int I) const { - if (Optional<loc::ConcreteInt> LV = getAs<loc::ConcreteInt>()) + if (std::optional<loc::ConcreteInt> LV = getAs<loc::ConcreteInt>()) return LV->getValue() == I; - if (Optional<nonloc::ConcreteInt> NV = getAs<nonloc::ConcreteInt>()) + if (std::optional<nonloc::ConcreteInt> NV = getAs<nonloc::ConcreteInt>()) return NV->getValue() == I; return false; } diff --git a/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp b/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp index 5c4eed9..3286d7f 100644 --- a/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp +++ b/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp @@ -27,7 +27,7 @@ ProgramStateRef SimpleConstraintManager::assumeInternal(ProgramStateRef State, DefinedSVal Cond, bool Assumption) { // If we have a Loc value, cast it to a bool NonLoc first. - if (Optional<Loc> LV = Cond.getAs<Loc>()) { + if (std::optional<Loc> LV = Cond.getAs<Loc>()) { SValBuilder &SVB = State->getStateManager().getSValBuilder(); QualType T; const MemRegion *MR = LV->getAsRegion(); diff --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp index 6f0abe5..58d360a 100644 --- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp +++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp @@ -349,9 +349,9 @@ static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, isWithinConstantOverflowBounds(Int))); } -static Optional<NonLoc> tryRearrange(ProgramStateRef State, - BinaryOperator::Opcode Op, NonLoc Lhs, - NonLoc Rhs, QualType ResultTy) { +static std::optional<NonLoc> tryRearrange(ProgramStateRef State, + BinaryOperator::Opcode Op, NonLoc Lhs, + NonLoc Rhs, QualType ResultTy) { ProgramStateManager &StateMgr = State->getStateManager(); SValBuilder &SVB = StateMgr.getSValBuilder(); @@ -681,7 +681,7 @@ SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state, if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) return MakeSymIntVal(Sym, op, *RHSValue, resultTy); - if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) + if (std::optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) return *V; // Give up -- this is not a symbolic expression we can handle. @@ -844,7 +844,7 @@ SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, } // If both operands are constants, just perform the operation. - if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { + if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub); if (const auto *ResultInt = @@ -878,7 +878,7 @@ SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, return UnknownVal(); } case loc::MemRegionValKind: { - if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { + if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { // If one of the operands is a symbol and the other is a constant, // build an expression for use by the constraint manager. if (SymbolRef lSym = lhs.getAsLocSymbol(true)) { @@ -975,7 +975,7 @@ SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, // Get the left index and cast it to the correct type. // If the index is unknown or undefined, bail out here. SVal LeftIndexVal = LeftER->getIndex(); - Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); + std::optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); if (!LeftIndex) return UnknownVal(); LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{}); @@ -985,7 +985,7 @@ SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, // Do the same for the right index. SVal RightIndexVal = RightER->getIndex(); - Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); + std::optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); if (!RightIndex) return UnknownVal(); RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{}); @@ -1093,8 +1093,10 @@ SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, // We are dealing with pointer arithmetic. // Handle pointer arithmetic on constant values. - if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) { - if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) { + if (std::optional<nonloc::ConcreteInt> rhsInt = + rhs.getAs<nonloc::ConcreteInt>()) { + if (std::optional<loc::ConcreteInt> lhsInt = + lhs.getAs<loc::ConcreteInt>()) { const llvm::APSInt &leftI = lhsInt->getValue(); assert(leftI.isUnsigned()); llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); @@ -1158,7 +1160,7 @@ SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, if (elementType->isVoidType()) elementType = getContext().CharTy; - if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) { + if (std::optional<NonLoc> indexV = index.getAs<NonLoc>()) { return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, superR, getContext())); } @@ -1171,10 +1173,10 @@ const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state, if (V.isUnknownOrUndef()) return nullptr; - if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) + if (std::optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) return &X->getValue(); - if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) + if (std::optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) return &X->getValue(); if (SymbolRef Sym = V.getAsSymbol()) diff --git a/clang/lib/StaticAnalyzer/Core/Store.cpp b/clang/lib/StaticAnalyzer/Core/Store.cpp index 37a3a6f..d169630 100644 --- a/clang/lib/StaticAnalyzer/Core/Store.cpp +++ b/clang/lib/StaticAnalyzer/Core/Store.cpp @@ -72,8 +72,8 @@ const ElementRegion *StoreManager::GetElementZeroRegion(const SubRegion *R, return MRMgr.getElementRegion(T, idx, R, Ctx); } -Optional<const MemRegion *> StoreManager::castRegion(const MemRegion *R, - QualType CastToTy) { +std::optional<const MemRegion *> StoreManager::castRegion(const MemRegion *R, + QualType CastToTy) { ASTContext &Ctx = StateMgr.getContext(); // Handle casts to Objective-C objects. @@ -315,7 +315,8 @@ static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) { return nullptr; } -Optional<SVal> StoreManager::evalBaseToDerived(SVal Base, QualType TargetType) { +std::optional<SVal> StoreManager::evalBaseToDerived(SVal Base, + QualType TargetType) { const MemRegion *MR = Base.getAsRegion(); if (!MR) return UnknownVal(); diff --git a/clang/lib/Tooling/ASTDiff/ASTDiff.cpp b/clang/lib/Tooling/ASTDiff/ASTDiff.cpp index bfaa902..52e5797 100644 --- a/clang/lib/Tooling/ASTDiff/ASTDiff.cpp +++ b/clang/lib/Tooling/ASTDiff/ASTDiff.cpp @@ -687,7 +687,7 @@ ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); } StringRef Node::getTypeLabel() const { return getType().asStringRef(); } -llvm::Optional<std::string> Node::getQualifiedIdentifier() const { +std::optional<std::string> Node::getQualifiedIdentifier() const { if (auto *ND = ASTNode.get<NamedDecl>()) { if (ND->getDeclName().isIdentifier()) return ND->getQualifiedNameAsString(); @@ -695,7 +695,7 @@ llvm::Optional<std::string> Node::getQualifiedIdentifier() const { return std::nullopt; } -llvm::Optional<StringRef> Node::getIdentifier() const { +std::optional<StringRef> Node::getIdentifier() const { if (auto *ND = ASTNode.get<NamedDecl>()) { if (ND->getDeclName().isIdentifier()) return ND->getName(); diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp index 859497b..97b41fc 100644 --- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp +++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp @@ -68,7 +68,7 @@ EntryRef DependencyScanningWorkerFilesystem::scanForDirectivesIfNecessary( Directives)) { Contents->DepDirectiveTokens.clear(); // FIXME: Propagate the diagnostic if desired by the client. - Contents->DepDirectives.store(new Optional<DependencyDirectivesTy>()); + Contents->DepDirectives.store(new std::optional<DependencyDirectivesTy>()); return EntryRef(Filename, Entry); } @@ -77,7 +77,7 @@ EntryRef DependencyScanningWorkerFilesystem::scanForDirectivesIfNecessary( // threads may skip the // critical section (`DepDirectives != nullptr`), leading to a data race. Contents->DepDirectives.store( - new Optional<DependencyDirectivesTy>(std::move(Directives))); + new std::optional<DependencyDirectivesTy>(std::move(Directives))); return EntryRef(Filename, Entry); } diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp index 70832f4..3fcef00 100644 --- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp +++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp @@ -42,7 +42,7 @@ DependencyScanningTool::DependencyScanningTool( llvm::Expected<std::string> DependencyScanningTool::getDependencyFile( const std::vector<std::string> &CommandLine, StringRef CWD, - llvm::Optional<StringRef> ModuleName) { + std::optional<StringRef> ModuleName) { /// Prints out all of the gathered dependencies into a string. class MakeDependencyPrinterConsumer : public DependencyConsumer { public: @@ -116,7 +116,7 @@ DependencyScanningTool::getFullDependencies( const std::vector<std::string> &CommandLine, StringRef CWD, const llvm::StringSet<> &AlreadySeen, LookupModuleOutputCallback LookupModuleOutput, - llvm::Optional<StringRef> ModuleName) { + std::optional<StringRef> ModuleName) { FullDependencyConsumer Consumer(AlreadySeen, LookupModuleOutput, Worker.shouldEagerLoadModules()); llvm::Error Result = @@ -131,7 +131,7 @@ DependencyScanningTool::getFullDependenciesLegacyDriverCommand( const std::vector<std::string> &CommandLine, StringRef CWD, const llvm::StringSet<> &AlreadySeen, LookupModuleOutputCallback LookupModuleOutput, - llvm::Optional<StringRef> ModuleName) { + std::optional<StringRef> ModuleName) { FullDependencyConsumer Consumer(AlreadySeen, LookupModuleOutput, Worker.shouldEagerLoadModules()); llvm::Error Result = diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp index 957e016..b54b8de 100644 --- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp +++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp @@ -148,7 +148,7 @@ public: StringRef WorkingDirectory, DependencyConsumer &Consumer, llvm::IntrusiveRefCntPtr<DependencyScanningWorkerFilesystem> DepFS, ScanningOutputFormat Format, bool OptimizeArgs, bool EagerLoadModules, - bool DisableFree, llvm::Optional<StringRef> ModuleName = std::nullopt) + bool DisableFree, std::optional<StringRef> ModuleName = std::nullopt) : WorkingDirectory(WorkingDirectory), Consumer(Consumer), DepFS(std::move(DepFS)), Format(Format), OptimizeArgs(OptimizeArgs), EagerLoadModules(EagerLoadModules), DisableFree(DisableFree), @@ -216,7 +216,7 @@ public: DepFS; ScanInstance.getPreprocessorOpts().DependencyDirectivesForFile = [LocalDepFS = std::move(LocalDepFS)](FileEntryRef File) - -> Optional<ArrayRef<dependency_directives_scan::Directive>> { + -> std::optional<ArrayRef<dependency_directives_scan::Directive>> { if (llvm::ErrorOr<EntryRef> Entry = LocalDepFS->getOrCreateFileSystemEntry(File.getName())) return Entry->getDirectiveTokens(); @@ -303,8 +303,8 @@ private: bool OptimizeArgs; bool EagerLoadModules; bool DisableFree; - Optional<StringRef> ModuleName; - Optional<CompilerInstance> ScanInstanceStorage; + std::optional<StringRef> ModuleName; + std::optional<CompilerInstance> ScanInstanceStorage; std::shared_ptr<ModuleDepCollector> MDC; std::vector<std::string> LastCC1Arguments; bool Scanned = false; @@ -340,7 +340,7 @@ DependencyScanningWorker::DependencyScanningWorker( llvm::Error DependencyScanningWorker::computeDependencies( StringRef WorkingDirectory, const std::vector<std::string> &CommandLine, - DependencyConsumer &Consumer, llvm::Optional<StringRef> ModuleName) { + DependencyConsumer &Consumer, std::optional<StringRef> ModuleName) { std::vector<const char *> CLI; for (const std::string &Arg : CommandLine) CLI.push_back(Arg.c_str()); @@ -387,11 +387,11 @@ static bool forEachDriverJob( bool DependencyScanningWorker::computeDependencies( StringRef WorkingDirectory, const std::vector<std::string> &CommandLine, DependencyConsumer &Consumer, DiagnosticConsumer &DC, - llvm::Optional<StringRef> ModuleName) { + std::optional<StringRef> ModuleName) { // Reset what might have been modified in the previous worker invocation. BaseFS->setCurrentWorkingDirectory(WorkingDirectory); - Optional<std::vector<std::string>> ModifiedCommandLine; + std::optional<std::vector<std::string>> ModifiedCommandLine; llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> ModifiedFS; if (ModuleName) { ModifiedCommandLine = CommandLine; diff --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp index a91157c..1ae35c2 100644 --- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp +++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp @@ -328,7 +328,7 @@ void ModuleDepCollectorPP::FileChanged(SourceLocation Loc, // Dependency generation really does want to go all the way to the // file entry for a source location to find out what is depended on. // We do not want #line markers to affect dependency generation! - if (Optional<StringRef> Filename = + if (std::optional<StringRef> Filename = SM.getNonBuiltinFilenameForID(SM.getFileID(SM.getExpansionLoc(Loc)))) MDC.addFileDep(llvm::sys::path::remove_leading_dotslash(*Filename)); } diff --git a/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp b/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp index c7128f2..08d4cdab 100644 --- a/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp +++ b/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp @@ -59,7 +59,7 @@ unsigned getOffsetAfterTokenSequence( // (second) raw_identifier name is checked. bool checkAndConsumeDirectiveWithName( Lexer &Lex, StringRef Name, Token &Tok, - llvm::Optional<StringRef> RawIDName = std::nullopt) { + std::optional<StringRef> RawIDName = std::nullopt) { bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) && Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) && @@ -344,7 +344,7 @@ void HeaderIncludes::addExistingInclude(Include IncludeToAdd, } } -llvm::Optional<tooling::Replacement> +std::optional<tooling::Replacement> HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled, IncludeDirective Directive) const { assert(IncludeName == trimInclude(IncludeName)); diff --git a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp index 338797c..55ec67b 100644 --- a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp +++ b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp @@ -129,7 +129,7 @@ struct TransferableCommand { // Flags that should not apply to all files are stripped from CommandLine. CompileCommand Cmd; // Language detected from -x or the filename. Never TY_INVALID. - Optional<types::ID> Type; + std::optional<types::ID> Type; // Standard specified by -std. LangStandard::Kind Std = LangStandard::lang_unspecified; // Whether the command line is for the cl-compatible driver. @@ -280,7 +280,7 @@ private: } // Try to interpret the argument as a type specifier, e.g. '-x'. - Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) { + std::optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) { const llvm::opt::Option &Opt = Arg.getOption(); using namespace driver::options; if (ClangCLMode) { @@ -296,7 +296,7 @@ private: } // Try to interpret the argument as '-std='. - Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) { + std::optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) { using namespace driver::options; if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) return LangStandard::getLangKind(Arg.getValue()); diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp b/clang/lib/Tooling/JSONCompilationDatabase.cpp index cc5bd4a..41e502d 100644 --- a/clang/lib/Tooling/JSONCompilationDatabase.cpp +++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp @@ -350,7 +350,7 @@ bool JSONCompilationDatabase::parse(std::string &ErrorMessage) { return false; } llvm::yaml::ScalarNode *Directory = nullptr; - llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command; + std::optional<std::vector<llvm::yaml::ScalarNode *>> Command; llvm::yaml::ScalarNode *File = nullptr; llvm::yaml::ScalarNode *Output = nullptr; for (auto& NextKeyValue : *Object) { diff --git a/clang/lib/Tooling/Refactoring/ASTSelection.cpp b/clang/lib/Tooling/Refactoring/ASTSelection.cpp index 943d4ed..058574d 100644 --- a/clang/lib/Tooling/Refactoring/ASTSelection.cpp +++ b/clang/lib/Tooling/Refactoring/ASTSelection.cpp @@ -51,7 +51,7 @@ public: SourceSelectionKind::None)); } - Optional<SelectedASTNode> getSelectedASTNode() { + std::optional<SelectedASTNode> getSelectedASTNode() { assert(SelectionStack.size() == 1 && "stack was not popped"); SelectedASTNode Result = std::move(SelectionStack.back()); SelectionStack.pop_back(); @@ -179,7 +179,7 @@ private: } // end anonymous namespace -Optional<SelectedASTNode> +std::optional<SelectedASTNode> clang::tooling::findSelectedASTNodes(const ASTContext &Context, SourceRange SelectionRange) { assert(SelectionRange.isValid() && @@ -376,7 +376,7 @@ static void findDeepestWithKind( findDeepestWithKind(ASTSelection, MatchingNodes, Kind, ParentStack); } -Optional<CodeRangeASTSelection> +std::optional<CodeRangeASTSelection> CodeRangeASTSelection::create(SourceRange SelectionRange, const SelectedASTNode &ASTSelection) { // Code range is selected when the selection range is not empty. diff --git a/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp b/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp index e6a8e12..0e052bb1 100644 --- a/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp +++ b/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp @@ -21,7 +21,7 @@ ASTSelectionRequirement::evaluate(RefactoringRuleContext &Context) const { if (!Range) return Range.takeError(); - Optional<SelectedASTNode> Selection = + std::optional<SelectedASTNode> Selection = findSelectedASTNodes(Context.getASTContext(), *Range); if (!Selection) return Context.createDiagnosticError( @@ -38,8 +38,9 @@ Expected<CodeRangeASTSelection> CodeRangeASTSelectionRequirement::evaluate( return ASTSelection.takeError(); std::unique_ptr<SelectedASTNode> StoredSelection = std::make_unique<SelectedASTNode>(std::move(*ASTSelection)); - Optional<CodeRangeASTSelection> CodeRange = CodeRangeASTSelection::create( - Context.getSelectionRange(), *StoredSelection); + std::optional<CodeRangeASTSelection> CodeRange = + CodeRangeASTSelection::create(Context.getSelectionRange(), + *StoredSelection); if (!CodeRange) return Context.createDiagnosticError( Context.getSelectionRange().getBegin(), diff --git a/clang/lib/Tooling/Refactoring/Extract/Extract.cpp b/clang/lib/Tooling/Refactoring/Extract/Extract.cpp index efd29fc..d437f4c 100644 --- a/clang/lib/Tooling/Refactoring/Extract/Extract.cpp +++ b/clang/lib/Tooling/Refactoring/Extract/Extract.cpp @@ -69,7 +69,7 @@ const RefactoringDescriptor &ExtractFunction::describe() { Expected<ExtractFunction> ExtractFunction::initiate(RefactoringRuleContext &Context, CodeRangeASTSelection Code, - Optional<std::string> DeclName) { + std::optional<std::string> DeclName) { // We would like to extract code out of functions/methods/blocks. // Prohibit extraction from things like global variable / field // initializers and other top-level expressions. diff --git a/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp b/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp index d4de57f..5e69fb8 100644 --- a/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp +++ b/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp @@ -101,7 +101,7 @@ ExtractionSemicolonPolicy::compute(const Stmt *S, SourceRange &ExtractedRange, /// Other statements should generally have a trailing ';'. We can try to find /// it and move it together it with the extracted code. - Optional<Token> NextToken = Lexer::findNextToken(End, SM, LangOpts); + std::optional<Token> NextToken = Lexer::findNextToken(End, SM, LangOpts); if (NextToken && NextToken->is(tok::semi) && areOnSameLine(NextToken->getLocation(), End, SM)) { ExtractedRange.setEnd(NextToken->getLocation()); diff --git a/clang/lib/Tooling/Syntax/Tokens.cpp b/clang/lib/Tooling/Syntax/Tokens.cpp index d99eda3..df2a4e80 100644 --- a/clang/lib/Tooling/Syntax/Tokens.cpp +++ b/clang/lib/Tooling/Syntax/Tokens.cpp @@ -806,7 +806,7 @@ private: // In the simplest case, skips spelled tokens until finding one that produced // the NextExpanded token, and creates an empty mapping for them. // If Drain is provided, skips remaining tokens from that file instead. - void discard(llvm::Optional<FileID> Drain = std::nullopt) { + void discard(std::optional<FileID> Drain = std::nullopt) { SourceLocation Target = Drain ? SM.getLocForEndOfFile(*Drain) : SM.getExpansionLoc( diff --git a/clang/lib/Tooling/Transformer/Parsing.cpp b/clang/lib/Tooling/Transformer/Parsing.cpp index dade271..53a78e8 100644 --- a/clang/lib/Tooling/Transformer/Parsing.cpp +++ b/clang/lib/Tooling/Transformer/Parsing.cpp @@ -120,8 +120,8 @@ getBinaryRangeSelectors() { } template <typename Element> -llvm::Optional<Element> findOptional(const llvm::StringMap<Element> &Map, - llvm::StringRef Key) { +std::optional<Element> findOptional(const llvm::StringMap<Element> &Map, + llvm::StringRef Key) { auto it = Map.find(Key); if (it == Map.end()) return std::nullopt; diff --git a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp index 071923c..2a1e605 100644 --- a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp +++ b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp @@ -83,7 +83,7 @@ void MapExtDefNamesConsumer::handleDecl(const Decl *D) { void MapExtDefNamesConsumer::addIfInMain(const DeclaratorDecl *DD, SourceLocation defStart) { - llvm::Optional<std::string> LookupName = + std::optional<std::string> LookupName = CrossTranslationUnitContext::getLookupName(DD); if (!LookupName) return; diff --git a/clang/tools/clang-refactor/ClangRefactor.cpp b/clang/tools/clang-refactor/ClangRefactor.cpp index e66bf665..d362eec 100644 --- a/clang/tools/clang-refactor/ClangRefactor.cpp +++ b/clang/tools/clang-refactor/ClangRefactor.cpp @@ -148,14 +148,14 @@ std::unique_ptr<SourceSelectionArgument> SourceSelectionArgument::fromString(StringRef Value) { if (Value.startswith("test:")) { StringRef Filename = Value.drop_front(strlen("test:")); - Optional<TestSelectionRangesInFile> ParsedTestSelection = + std::optional<TestSelectionRangesInFile> ParsedTestSelection = findTestSelectionRanges(Filename); if (!ParsedTestSelection) return nullptr; // A parsing error was already reported. return std::make_unique<TestSourceSelectionArgument>( std::move(*ParsedTestSelection)); } - Optional<ParsedSourceRange> Range = ParsedSourceRange::fromString(Value); + std::optional<ParsedSourceRange> Range = ParsedSourceRange::fromString(Value); if (Range) return std::make_unique<SourceRangeSelectionArgument>(std::move(*Range)); llvm::errs() << "error: '-selection' option must be specified using " @@ -195,7 +195,7 @@ public: : Options(Options) {} void visit(const RefactoringOption &Opt, - Optional<std::string> &Value) override { + std::optional<std::string> &Value) override { const cl::opt<std::string> &CLOpt = Options.getStringOption(Opt); if (!CLOpt.getValue().empty()) { Value = CLOpt.getValue(); @@ -225,7 +225,8 @@ public: RefactoringActionCommandLineOptions &Options) : Category(Category), Subcommand(Subcommand), Options(Options) {} - void visit(const RefactoringOption &Opt, Optional<std::string> &) override { + void visit(const RefactoringOption &Opt, + std::optional<std::string> &) override { if (Visited.insert(&Opt).second) Options.addStringOption(Opt, create<std::string>(Opt)); } @@ -317,7 +318,7 @@ public: ClangRefactorConsumer(AtomicChanges &Changes) : SourceChanges(&Changes) {} void handleError(llvm::Error Err) override { - Optional<PartialDiagnosticAt> Diag = DiagnosticError::take(Err); + std::optional<PartialDiagnosticAt> Diag = DiagnosticError::take(Err); if (!Diag) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; return; diff --git a/clang/tools/clang-refactor/TestSupport.cpp b/clang/tools/clang-refactor/TestSupport.cpp index 9736d1e..400313e 100644 --- a/clang/tools/clang-refactor/TestSupport.cpp +++ b/clang/tools/clang-refactor/TestSupport.cpp @@ -178,8 +178,8 @@ bool TestRefactoringResultConsumer::handleAllResults() { bool Failed = false; for (auto &Group : llvm::enumerate(Results)) { // All ranges in the group must produce the same result. - Optional<tooling::AtomicChanges> CanonicalResult; - Optional<std::string> CanonicalErrorMessage; + std::optional<tooling::AtomicChanges> CanonicalResult; + std::optional<std::string> CanonicalErrorMessage; for (auto &I : llvm::enumerate(Group.value())) { Expected<tooling::AtomicChanges> &Result = I.value(); std::string ErrorMessage; @@ -292,7 +292,7 @@ static unsigned addEndLineOffsetAndEndColumn(StringRef Source, unsigned Offset, Source, LineStart == StringRef::npos ? 0 : LineStart + 1, Column - 1); } -Optional<TestSelectionRangesInFile> +std::optional<TestSelectionRangesInFile> findTestSelectionRanges(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> ErrOrFile = MemoryBuffer::getFile(Filename); diff --git a/clang/tools/clang-refactor/TestSupport.h b/clang/tools/clang-refactor/TestSupport.h index 7ce1094..c82dd81 100644 --- a/clang/tools/clang-refactor/TestSupport.h +++ b/clang/tools/clang-refactor/TestSupport.h @@ -96,7 +96,8 @@ struct TestSelectionRangesInFile { /// /// \returns std::nullopt on failure (errors are emitted to stderr), or a set of /// grouped source ranges in the given file otherwise. -Optional<TestSelectionRangesInFile> findTestSelectionRanges(StringRef Filename); +std::optional<TestSelectionRangesInFile> +findTestSelectionRanges(StringRef Filename); } // end namespace refactor } // end namespace clang diff --git a/clang/tools/clang-repl/ClangRepl.cpp b/clang/tools/clang-repl/ClangRepl.cpp index 42b2452..401a31d 100644 --- a/clang/tools/clang-repl/ClangRepl.cpp +++ b/clang/tools/clang-repl/ClangRepl.cpp @@ -113,7 +113,7 @@ int main(int argc, const char **argv) { if (OptInputs.empty()) { llvm::LineEditor LE("clang-repl"); // FIXME: Add LE.setListCompleter - while (llvm::Optional<std::string> Line = LE.readLine()) { + while (std::optional<std::string> Line = LE.readLine()) { if (*Line == R"(%quit)") break; if (*Line == R"(%undo)") { diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp b/clang/tools/clang-scan-deps/ClangScanDeps.cpp index f8b915d..0db7124 100644 --- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp +++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp @@ -563,7 +563,7 @@ int main(int argc, const char **argv) { Filename = std::move(Input->Filename); CWD = std::move(Input->Directory); } - Optional<StringRef> MaybeModuleName; + std::optional<StringRef> MaybeModuleName; if (!ModuleName.empty()) MaybeModuleName = ModuleName; diff --git a/clang/tools/diagtool/FindDiagnosticID.cpp b/clang/tools/diagtool/FindDiagnosticID.cpp index 2e57a65..6ced701 100644 --- a/clang/tools/diagtool/FindDiagnosticID.cpp +++ b/clang/tools/diagtool/FindDiagnosticID.cpp @@ -27,7 +27,7 @@ static StringRef getNameFromID(StringRef Name) { return StringRef(); } -static Optional<DiagnosticRecord> +static std::optional<DiagnosticRecord> findDiagnostic(ArrayRef<DiagnosticRecord> Diagnostics, StringRef Name) { for (const auto &Diag : Diagnostics) { StringRef DiagName = Diag.getName(); @@ -56,7 +56,7 @@ int FindDiagnosticID::run(unsigned int argc, char **argv, "Diagnostic ID mapping utility"); ArrayRef<DiagnosticRecord> AllDiagnostics = getBuiltinDiagnosticsByName(); - Optional<DiagnosticRecord> Diag = + std::optional<DiagnosticRecord> Diag = findDiagnostic(AllDiagnostics, DiagnosticName); if (!Diag) { // Name to id failed, so try id to name. diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp index 2a87266..f944113 100644 --- a/clang/tools/driver/cc1as_main.cpp +++ b/clang/tools/driver/cc1as_main.cpp @@ -151,7 +151,7 @@ struct AssemblerInvocation { /// Darwin target variant triple, the variant of the deployment target /// for which the code is being compiled. - llvm::Optional<llvm::Triple> DarwinTargetVariantTriple; + std::optional<llvm::Triple> DarwinTargetVariantTriple; /// The version of the darwin target variant SDK which was used during the /// compilation diff --git a/clang/tools/driver/cc1gen_reproducer_main.cpp b/clang/tools/driver/cc1gen_reproducer_main.cpp index 08d518d..9dbfc51 100644 --- a/clang/tools/driver/cc1gen_reproducer_main.cpp +++ b/clang/tools/driver/cc1gen_reproducer_main.cpp @@ -109,7 +109,7 @@ static std::string generateReproducerMetaInfo(const ClangInvocationInfo &Info) { } /// Generates a reproducer for a set of arguments from a specific invocation. -static llvm::Optional<driver::Driver::CompilationDiagnosticReport> +static std::optional<driver::Driver::CompilationDiagnosticReport> generateReproducerForInvocationArguments(ArrayRef<const char *> Argv, const ClangInvocationInfo &Info) { using namespace driver; @@ -181,7 +181,7 @@ int cc1gen_reproducer_main(ArrayRef<const char *> Argv, const char *Argv0, DriverArgs.push_back(Arg.c_str()); std::string Path = GetExecutablePath(Argv0, /*CanonicalPrefixes=*/true); DriverArgs[0] = Path.c_str(); - llvm::Optional<driver::Driver::CompilationDiagnosticReport> Report = + std::optional<driver::Driver::CompilationDiagnosticReport> Report = generateReproducerForInvocationArguments(DriverArgs, InvocationInfo); // Emit the information about the reproduce files to stdout. diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index a4a9d8e..d7474123 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -533,12 +533,13 @@ int clang_main(int Argc, char **Argv) { Driver::ReproLevel ReproLevel = Driver::ReproLevel::OnCrash; if (Arg *A = C->getArgs().getLastArg(options::OPT_gen_reproducer_eq)) { - auto Level = llvm::StringSwitch<Optional<Driver::ReproLevel>>(A->getValue()) - .Case("off", Driver::ReproLevel::Off) - .Case("crash", Driver::ReproLevel::OnCrash) - .Case("error", Driver::ReproLevel::OnError) - .Case("always", Driver::ReproLevel::Always) - .Default(std::nullopt); + auto Level = + llvm::StringSwitch<std::optional<Driver::ReproLevel>>(A->getValue()) + .Case("off", Driver::ReproLevel::Off) + .Case("crash", Driver::ReproLevel::OnCrash) + .Case("error", Driver::ReproLevel::OnError) + .Case("always", Driver::ReproLevel::Always) + .Default(std::nullopt); if (!Level) { llvm::errs() << "Unknown value for " << A->getSpelling() << ": '" << A->getValue() << "'\n"; diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp index 536b4ab..6aa0ac6 100644 --- a/clang/tools/libclang/CIndex.cpp +++ b/clang/tools/libclang/CIndex.cpp @@ -536,7 +536,7 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) { for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), TLEnd = CXXUnit->top_level_end(); TL != TLEnd; ++TL) { - const Optional<bool> V = handleDeclForVisitation(*TL); + const std::optional<bool> V = handleDeclForVisitation(*TL); if (!V) continue; return *V; @@ -601,7 +601,7 @@ bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { return false; } -Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { +std::optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { if (RegionOfInterest.isValid()) { SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); if (Range.isInvalid()) @@ -641,7 +641,7 @@ bool CursorVisitor::VisitDeclContext(DeclContext *DC) { if (auto *OMD = dyn_cast<ObjCMethodDecl>(D)) if (OMD->isSynthesizedAccessorStub()) continue; - const Optional<bool> V = handleDeclForVisitation(D); + const std::optional<bool> V = handleDeclForVisitation(D); if (!V) continue; return *V; @@ -649,7 +649,7 @@ bool CursorVisitor::VisitDeclContext(DeclContext *DC) { return false; } -Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { +std::optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); // Ignore synthesized ivars here, otherwise if we have something like: @@ -675,7 +675,7 @@ Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); } - const Optional<bool> V = shouldVisitCursor(Cursor); + const std::optional<bool> V = shouldVisitCursor(Cursor); if (!V) return std::nullopt; if (!*V) @@ -1074,7 +1074,7 @@ bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { E = DeclsInContainer.end(); I != E; ++I) { CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); - const Optional<bool> &V = shouldVisitCursor(Cursor); + const std::optional<bool> &V = shouldVisitCursor(Cursor); if (!V) continue; if (!*V) @@ -4627,7 +4627,7 @@ const char *clang_getFileContents(CXTranslationUnit TU, CXFile file, const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); FileID fid = SM.translateFile(static_cast<FileEntry *>(file)); - llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid); + std::optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid); if (!buf) { if (size) *size = 0; diff --git a/clang/tools/libclang/CXType.cpp b/clang/tools/libclang/CXType.cpp index f5534dc..a833da3 100644 --- a/clang/tools/libclang/CXType.cpp +++ b/clang/tools/libclang/CXType.cpp @@ -181,7 +181,7 @@ static inline CXTranslationUnit GetTU(CXType CT) { return static_cast<CXTranslationUnit>(CT.data[1]); } -static Optional<ArrayRef<TemplateArgument>> +static std::optional<ArrayRef<TemplateArgument>> GetTemplateArguments(QualType Type) { assert(!Type.isNull()); if (const auto *Specialization = Type->getAs<TemplateSpecializationType>()) @@ -197,13 +197,14 @@ GetTemplateArguments(QualType Type) { return std::nullopt; } -static Optional<QualType> TemplateArgumentToQualType(const TemplateArgument &A) { +static std::optional<QualType> +TemplateArgumentToQualType(const TemplateArgument &A) { if (A.getKind() == TemplateArgument::Type) return A.getAsType(); return std::nullopt; } -static Optional<QualType> +static std::optional<QualType> FindTemplateArgumentTypeAt(ArrayRef<TemplateArgument> TA, unsigned index) { unsigned current = 0; for (const auto &A : TA) { @@ -1176,7 +1177,7 @@ CXType clang_Type_getTemplateArgumentAsType(CXType CT, unsigned index) { if (!TA) return MakeCXType(QualType(), GetTU(CT)); - Optional<QualType> QT = FindTemplateArgumentTypeAt(*TA, index); + std::optional<QualType> QT = FindTemplateArgumentTypeAt(*TA, index); return MakeCXType(QT.value_or(QualType()), GetTU(CT)); } diff --git a/clang/tools/libclang/CursorVisitor.h b/clang/tools/libclang/CursorVisitor.h index b8a9d34..2a9d7a7d 100644 --- a/clang/tools/libclang/CursorVisitor.h +++ b/clang/tools/libclang/CursorVisitor.h @@ -208,7 +208,7 @@ public: bool VisitAttributes(Decl *D); bool VisitBlockDecl(BlockDecl *B); bool VisitCXXRecordDecl(CXXRecordDecl *D); - Optional<bool> shouldVisitCursor(CXCursor C); + std::optional<bool> shouldVisitCursor(CXCursor C); bool VisitDeclContext(DeclContext *DC); bool VisitTranslationUnitDecl(TranslationUnitDecl *D); bool VisitTypedefDecl(TypedefDecl *D); @@ -279,7 +279,7 @@ public: LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S); private: - Optional<bool> handleDeclForVisitation(const Decl *D); + std::optional<bool> handleDeclForVisitation(const Decl *D); }; } // namespace cxcursor diff --git a/clang/unittests/AST/ASTImporterTest.cpp b/clang/unittests/AST/ASTImporterTest.cpp index 415cbc0..cd33d50 100644 --- a/clang/unittests/AST/ASTImporterTest.cpp +++ b/clang/unittests/AST/ASTImporterTest.cpp @@ -3359,7 +3359,7 @@ TEST_P(ASTImporterOptionSpecificTestBase, ImportUnnamedFieldsInCorrectOrder) { ASSERT_FALSE(FromField->getDeclName()); auto *ToField = cast_or_null<FieldDecl>(Import(FromField, Lang_CXX11)); EXPECT_TRUE(ToField); - Optional<unsigned> ToIndex = ASTImporter::getFieldIndex(ToField); + std::optional<unsigned> ToIndex = ASTImporter::getFieldIndex(ToField); EXPECT_TRUE(ToIndex); EXPECT_EQ(*ToIndex, FromIndex); ++FromIndex; @@ -4806,7 +4806,7 @@ TEST_P(ASTImporterOptionSpecificTestBase, ImportSubstTemplateTypeParmType) { FromTU, classTemplateSpecializationDecl()); auto testType = [&](ASTContext &Ctx, const char *Name, - llvm::Optional<unsigned> PackIndex) { + std::optional<unsigned> PackIndex) { const auto *Subst = selectFirst<SubstTemplateTypeParmType>( "sttp", match(substTemplateTypeParmType( hasReplacementType(hasCanonicalType(asString(Name)))) @@ -5510,7 +5510,8 @@ TEST_P(ErrorHandlingTest, ErrorHappensBeforeCreatingANewNode) { // But an error is set to the counterpart in the "from" context. ASTImporter *Importer = findFromTU(FromSpec)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromSpec); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromSpec); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::NameConflict); } @@ -5534,7 +5535,8 @@ TEST_P(ErrorHandlingTest, 0u); ASTImporter *Importer = findFromTU(FromFoo)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFoo); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromFoo); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); } @@ -5567,7 +5569,7 @@ TEST_P(ErrorHandlingTest, ErrorHappensAfterNodeIsCreatedAndLinked) { // An error is set to the counterpart in the "from" context both for the fwd // decl and the definition. ASTImporter *Importer = findFromTU(FromProto)->Importer.get(); - Optional<ASTImportError> OptErr = + std::optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromProto); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); @@ -5593,7 +5595,8 @@ TEST_P(ErrorHandlingTest, ErrorIsPropagatedFromMemberToClass) { // An error is set for X. EXPECT_FALSE(ImportedX); ASTImporter *Importer = findFromTU(FromX)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromX); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); @@ -5660,7 +5663,8 @@ TEST_P(ErrorHandlingTest, ErrorPropagatesThroughImportCycles) { // An error is set to the templated CXXRecordDecl of F. ASTImporter *Importer = findFromTU(FromFRD)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFRD); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromFRD); EXPECT_TRUE(OptErr); // An error is set to A. @@ -5718,7 +5722,8 @@ TEST_P(ErrorHandlingTest, ErrorIsNotPropagatedFromMemberToNamespace) { // There is no error set for X. EXPECT_TRUE(ImportedX); ASTImporter *Importer = findFromTU(FromX)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromX); ASSERT_FALSE(OptErr); // An error is set for f(). @@ -5797,7 +5802,8 @@ TEST_P(ErrorHandlingTest, // An error is set for X ... EXPECT_FALSE(ImportedX); ASTImporter *Importer = findFromTU(FromX)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromX); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); } @@ -5805,7 +5811,7 @@ TEST_P(ErrorHandlingTest, auto *ToXDef = FirstDeclMatcher<CXXRecordDecl>().match( ToTU, cxxRecordDecl(hasName("X"), isDefinition())); // An error is set for "ToXDef" in the shared state. - Optional<ASTImportError> OptErr = + std::optional<ASTImportError> OptErr = SharedStatePtr->getImportDeclErrorIfAny(ToXDef); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); @@ -5840,7 +5846,8 @@ TEST_P(ErrorHandlingTest, // The import should fail. EXPECT_FALSE(ImportedX); ASTImporter *Importer = findFromTU(FromX)->Importer.get(); - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromX); // And an error is set for this new X in the "from" ctx. ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); @@ -5880,7 +5887,8 @@ TEST_P(ErrorHandlingTest, ImportOfOverriddenMethods) { EXPECT_FALSE(Import(FromFooA, Lang_CXX11)); ASTImporter *Importer = findFromTU(FromFooA)->Importer.get(); auto CheckError = [&Importer](Decl *FromD) { - Optional<ASTImportError> OptErr = Importer->getImportDeclErrorIfAny(FromD); + std::optional<ASTImportError> OptErr = + Importer->getImportDeclErrorIfAny(FromD); ASSERT_TRUE(OptErr); EXPECT_EQ(OptErr->Error, ASTImportError::UnsupportedConstruct); }; diff --git a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp index ac09b27..30a5f00 100644 --- a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp +++ b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp @@ -52,8 +52,7 @@ public: Errors.push_back(Error.toStringFull()); } - llvm::Optional<MatcherCtor> - lookupMatcherCtor(StringRef MatcherName) override { + std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) override { const ExpectedMatchersTy::value_type *Matcher = &*ExpectedMatchers.find(std::string(MatcherName)); return reinterpret_cast<MatcherCtor>(Matcher); @@ -147,9 +146,8 @@ bool matchesRange(SourceRange Range, unsigned StartLine, Range.Start.Column == StartColumn && Range.End.Column == EndColumn; } -llvm::Optional<DynTypedMatcher> getSingleMatcher(const VariantValue &Value) { - llvm::Optional<DynTypedMatcher> Result = - Value.getMatcher().getSingleMatcher(); +std::optional<DynTypedMatcher> getSingleMatcher(const VariantValue &Value) { + std::optional<DynTypedMatcher> Result = Value.getMatcher().getSingleMatcher(); EXPECT_TRUE(Result); return Result; } @@ -224,7 +222,7 @@ TEST(ParserTest, FullParserTest) { StringRef Code = "varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral())," " hasOperatorName(\"+\"))))"; - llvm::Optional<DynTypedMatcher> VarDecl( + std::optional<DynTypedMatcher> VarDecl( Parser::parseMatcherExpression(Code, &Error)); EXPECT_EQ("", Error.toStringFull()); Matcher<Decl> M = VarDecl->unconditionalConvertTo<Decl>(); @@ -234,7 +232,7 @@ TEST(ParserTest, FullParserTest) { EXPECT_FALSE(matches("int x = true - 1;", M)); Code = "implicitCastExpr(hasCastKind(\"CK_IntegralToBoolean\"))"; - llvm::Optional<DynTypedMatcher> implicitIntBooleanCast( + std::optional<DynTypedMatcher> implicitIntBooleanCast( Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error)); EXPECT_EQ("", Error.toStringFull()); Matcher<Stmt> MCastStmt = @@ -243,7 +241,7 @@ TEST(ParserTest, FullParserTest) { EXPECT_FALSE(matches("bool X = true;", MCastStmt)); Code = "functionDecl(hasParameter(1, hasName(\"x\")))"; - llvm::Optional<DynTypedMatcher> HasParameter( + std::optional<DynTypedMatcher> HasParameter( Parser::parseMatcherExpression(Code, &Error)); EXPECT_EQ("", Error.toStringFull()); M = HasParameter->unconditionalConvertTo<Decl>(); @@ -255,7 +253,7 @@ TEST(ParserTest, FullParserTest) { auto NamedValues = getTestNamedValues(); Code = "functionDecl(hasParamA, hasParameter(1, hasName(nameX)))"; - llvm::Optional<DynTypedMatcher> HasParameterWithNamedValues( + std::optional<DynTypedMatcher> HasParameterWithNamedValues( Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error)); EXPECT_EQ("", Error.toStringFull()); M = HasParameterWithNamedValues->unconditionalConvertTo<Decl>(); @@ -264,7 +262,7 @@ TEST(ParserTest, FullParserTest) { EXPECT_FALSE(matches("void f(int x, int a);", M)); Code = "unaryExprOrTypeTraitExpr(ofKind(\"UETT_SizeOf\"))"; - llvm::Optional<DynTypedMatcher> UnaryExprSizeOf( + std::optional<DynTypedMatcher> UnaryExprSizeOf( Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error)); EXPECT_EQ("", Error.toStringFull()); Matcher<Stmt> MStmt = UnaryExprSizeOf->unconditionalConvertTo<Stmt>(); @@ -273,7 +271,7 @@ TEST(ParserTest, FullParserTest) { Code = R"query(namedDecl(matchesName("^::[ABC]*$", "IgnoreCase | BasicRegex")))query"; - llvm::Optional<DynTypedMatcher> MatchesName( + std::optional<DynTypedMatcher> MatchesName( Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error)); EXPECT_EQ("", Error.toStringFull()); M = MatchesName->unconditionalConvertTo<Decl>(); @@ -295,7 +293,7 @@ TEST(ParserTest, VariadicMatchTest) { StringRef Code = "stmt(objcMessageExpr(hasAnySelector(\"methodA\", \"methodB:\")))"; - llvm::Optional<DynTypedMatcher> OM( + std::optional<DynTypedMatcher> OM( Parser::parseMatcherExpression(Code, &Error)); EXPECT_EQ("", Error.toStringFull()); auto M = OM->unconditionalConvertTo<Stmt>(); @@ -415,7 +413,7 @@ TEST(ParserTest, OverloadErrors) { TEST(ParserTest, ParseMultiline) { StringRef Code; - llvm::Optional<DynTypedMatcher> M; + std::optional<DynTypedMatcher> M; { Code = R"matcher(varDecl( hasName("foo") @@ -610,7 +608,7 @@ TEST(ParserTest, ParseBindOnLet) { { StringRef Code = "hasParamA.bind(\"parmABinding\")"; - llvm::Optional<DynTypedMatcher> TopLevelLetBinding( + std::optional<DynTypedMatcher> TopLevelLetBinding( Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error)); EXPECT_EQ("", Error.toStringFull()); auto M = TopLevelLetBinding->unconditionalConvertTo<Decl>(); @@ -625,7 +623,7 @@ TEST(ParserTest, ParseBindOnLet) { { StringRef Code = "functionDecl(hasParamA.bind(\"parmABinding\"))"; - llvm::Optional<DynTypedMatcher> NestedLetBinding( + std::optional<DynTypedMatcher> NestedLetBinding( Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error)); EXPECT_EQ("", Error.toStringFull()); auto M = NestedLetBinding->unconditionalConvertTo<Decl>(); diff --git a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp index dddd13b..9428f06 100644 --- a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp +++ b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp @@ -35,7 +35,7 @@ public: return Out; } - llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) { + std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) { return Registry::lookupMatcherCtor(MatcherName); } @@ -43,7 +43,7 @@ public: Diagnostics *Error = nullptr) { Diagnostics DummyError; if (!Error) Error = &DummyError; - llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); + std::optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); VariantMatcher Out; if (Ctor) Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(), Error); @@ -56,7 +56,7 @@ public: Diagnostics *Error = nullptr) { Diagnostics DummyError; if (!Error) Error = &DummyError; - llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); + std::optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); VariantMatcher Out; if (Ctor) Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1), Error); @@ -70,7 +70,7 @@ public: Diagnostics *Error = nullptr) { Diagnostics DummyError; if (!Error) Error = &DummyError; - llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); + std::optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName); VariantMatcher Out; if (Ctor) Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1, Arg2), @@ -89,7 +89,7 @@ public: CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1) { std::vector<std::pair<MatcherCtor, unsigned> > Context; - llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1); + std::optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1); if (!Ctor) return CompVector(); Context.push_back(std::make_pair(*Ctor, ArgNo1)); @@ -100,7 +100,7 @@ public: CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1, StringRef MatcherName2, unsigned ArgNo2) { std::vector<std::pair<MatcherCtor, unsigned> > Context; - llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1); + std::optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1); if (!Ctor) return CompVector(); Context.push_back(std::make_pair(*Ctor, ArgNo1)); diff --git a/clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp b/clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp index 8b5fc1f..c0b4f31 100644 --- a/clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp @@ -59,7 +59,7 @@ struct ValueLattice { ValueState State; // When `None`, the lattice is either at top or bottom, based on `State`. - llvm::Optional<int64_t> Value; + std::optional<int64_t> Value; constexpr ValueLattice() : State(ValueState::Undefined), Value(std::nullopt) {} diff --git a/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp b/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp index 62ea155..818576e 100644 --- a/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp @@ -61,7 +61,7 @@ struct ConstantPropagationLattice { } }; // `None` is "bottom". - llvm::Optional<VarValue> Data; + std::optional<VarValue> Data; static constexpr ConstantPropagationLattice bottom() { return {std::nullopt}; diff --git a/clang/unittests/Analysis/FlowSensitive/TestingSupport.h b/clang/unittests/Analysis/FlowSensitive/TestingSupport.h index 97cebfc..c3243d5 100644 --- a/clang/unittests/Analysis/FlowSensitive/TestingSupport.h +++ b/clang/unittests/Analysis/FlowSensitive/TestingSupport.h @@ -100,7 +100,7 @@ struct AnalysisOutputs { const Environment &InitEnv; // Stores the state of a CFG block if it has been evaluated by the analysis. // The indices correspond to the block IDs. - llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates; + llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockStates; }; /// Arguments for building the dataflow analysis. @@ -260,7 +260,7 @@ checkDataflow(AnalysisInputs<AnalysisT> AI, // If successful, the dataflow analysis returns a mapping from block IDs to // the post-analysis states for the CFG blocks that have been evaluated. - llvm::Expected<std::vector<llvm::Optional<TypeErasedDataflowAnalysisState>>> + llvm::Expected<std::vector<std::optional<TypeErasedDataflowAnalysisState>>> MaybeBlockStates = runTypeErasedDataflowAnalysis(CFCtx, Analysis, InitEnv, PostVisitCFGClosure); if (!MaybeBlockStates) diff --git a/clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp index 4aadf75..d608198 100644 --- a/clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp @@ -27,7 +27,7 @@ namespace { using namespace ast_matchers; struct TestLattice { - llvm::Optional<bool> Branch; + std::optional<bool> Branch; static TestLattice bottom() { return {}; } // Does not matter for this test, but we must provide some definition of join. diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp index 95e53de..1c06755 100644 --- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp @@ -55,7 +55,7 @@ void runDataflow(llvm::StringRef Code, Matcher Match, return NoopAnalysis( C, DataflowAnalysisOptions{UseBuiltinModel ? Env.getAnalysisOptions() - : llvm::Optional<BuiltinOptions>()}); + : std::optional<BuiltinOptions>()}); }); AI.ASTBuildArgs = ASTBuildArgs; if (Options.BuiltinOpts) diff --git a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp index e03576f..f3b3050 100644 --- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp @@ -55,7 +55,7 @@ using ::testing::UnorderedElementsAre; template <typename AnalysisT> llvm::Expected<std::vector< - llvm::Optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>> + std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>> runAnalysis(llvm::StringRef Code, AnalysisT (*MakeAnalysis)(ASTContext &)) { std::unique_ptr<ASTUnit> AST = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++11"}); diff --git a/clang/unittests/Basic/DarwinSDKInfoTest.cpp b/clang/unittests/Basic/DarwinSDKInfoTest.cpp index 40c6c66..5f24e6e 100644 --- a/clang/unittests/Basic/DarwinSDKInfoTest.cpp +++ b/clang/unittests/Basic/DarwinSDKInfoTest.cpp @@ -17,7 +17,7 @@ using namespace clang; // Check the version mapping logic in DarwinSDKInfo. TEST(DarwinSDKInfo, VersionMapping) { llvm::json::Object Obj({{"3.0", "1.0"}, {"3.1", "1.2"}}); - Optional<DarwinSDKInfo::RelatedTargetVersionMapping> Mapping = + std::optional<DarwinSDKInfo::RelatedTargetVersionMapping> Mapping = DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple()); EXPECT_TRUE(Mapping); @@ -55,7 +55,7 @@ TEST(DarwinSDKInfo, VersionMapping) { // Check the version mapping logic in DarwinSDKInfo. TEST(DarwinSDKInfo, VersionMappingMissingKey) { llvm::json::Object Obj({{"3.0", "1.0"}, {"5.0", "1.2"}}); - Optional<DarwinSDKInfo::RelatedTargetVersionMapping> Mapping = + std::optional<DarwinSDKInfo::RelatedTargetVersionMapping> Mapping = DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple()); EXPECT_TRUE(Mapping); diff --git a/clang/unittests/Basic/DiagnosticTest.cpp b/clang/unittests/Basic/DiagnosticTest.cpp index fd8042c..f4ce7e1 100644 --- a/clang/unittests/Basic/DiagnosticTest.cpp +++ b/clang/unittests/Basic/DiagnosticTest.cpp @@ -117,7 +117,7 @@ TEST(DiagnosticTest, diagnosticError) { << "error"); ASSERT_TRUE(!Value); llvm::Error Err = Value.takeError(); - Optional<PartialDiagnosticAt> ErrDiag = DiagnosticError::take(Err); + std::optional<PartialDiagnosticAt> ErrDiag = DiagnosticError::take(Err); llvm::cantFail(std::move(Err)); ASSERT_FALSE(!ErrDiag); EXPECT_EQ(ErrDiag->first, SourceLocation()); diff --git a/clang/unittests/Driver/SanitizerArgsTest.cpp b/clang/unittests/Driver/SanitizerArgsTest.cpp index e9252ff..685c9e6 100644 --- a/clang/unittests/Driver/SanitizerArgsTest.cpp +++ b/clang/unittests/Driver/SanitizerArgsTest.cpp @@ -89,7 +89,7 @@ private: return FS; } - llvm::Optional<Driver> DriverInstance; + std::optional<Driver> DriverInstance; std::unique_ptr<driver::Compilation> CompilationJob; }; diff --git a/clang/unittests/Frontend/ParsedSourceLocationTest.cpp b/clang/unittests/Frontend/ParsedSourceLocationTest.cpp index 3e8f9e2..30b95cf 100644 --- a/clang/unittests/Frontend/ParsedSourceLocationTest.cpp +++ b/clang/unittests/Frontend/ParsedSourceLocationTest.cpp @@ -18,7 +18,7 @@ namespace { TEST(ParsedSourceRange, ParseTest) { auto Check = [](StringRef Value, StringRef Filename, unsigned BeginLine, unsigned BeginColumn, unsigned EndLine, unsigned EndColumn) { - Optional<ParsedSourceRange> PSR = ParsedSourceRange::fromString(Value); + std::optional<ParsedSourceRange> PSR = ParsedSourceRange::fromString(Value); ASSERT_TRUE(PSR); EXPECT_EQ(PSR->FileName, Filename); EXPECT_EQ(PSR->Begin.first, BeginLine); diff --git a/clang/unittests/Lex/PPDependencyDirectivesTest.cpp b/clang/unittests/Lex/PPDependencyDirectivesTest.cpp index 840821a..2a3f241 100644 --- a/clang/unittests/Lex/PPDependencyDirectivesTest.cpp +++ b/clang/unittests/Lex/PPDependencyDirectivesTest.cpp @@ -106,7 +106,7 @@ TEST_F(PPDependencyDirectivesTest, MacroGuard) { SmallVector<std::unique_ptr<DepDirectives>> DepDirectivesObjects; auto getDependencyDirectives = [&](FileEntryRef File) - -> Optional<ArrayRef<dependency_directives_scan::Directive>> { + -> std::optional<ArrayRef<dependency_directives_scan::Directive>> { DepDirectivesObjects.push_back(std::make_unique<DepDirectives>()); StringRef Input = (*FileMgr.getBufferForFile(File))->getBuffer(); bool Err = scanSourceForDependencyDirectives( @@ -118,7 +118,7 @@ TEST_F(PPDependencyDirectivesTest, MacroGuard) { auto PPOpts = std::make_shared<PreprocessorOptions>(); PPOpts->DependencyDirectivesForFile = [&](FileEntryRef File) - -> Optional<ArrayRef<dependency_directives_scan::Directive>> { + -> std::optional<ArrayRef<dependency_directives_scan::Directive>> { return getDependencyDirectives(File); }; diff --git a/clang/unittests/Serialization/SourceLocationEncodingTest.cpp b/clang/unittests/Serialization/SourceLocationEncodingTest.cpp index d32e242..2640ea4 100644 --- a/clang/unittests/Serialization/SourceLocationEncodingTest.cpp +++ b/clang/unittests/Serialization/SourceLocationEncodingTest.cpp @@ -22,7 +22,7 @@ using LocSeq = SourceLocationSequence; // If ExpectedEncoded is provided, verify the encoded value too. // Loc is the raw (in-memory) form of SourceLocation. void roundTrip(SourceLocation::UIntTy Loc, - llvm::Optional<uint64_t> ExpectedEncoded = std::nullopt) { + std::optional<uint64_t> ExpectedEncoded = std::nullopt) { uint64_t ActualEncoded = SourceLocationEncoding::encode(SourceLocation::getFromRawEncoding(Loc)); if (ExpectedEncoded) diff --git a/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp b/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp index c4a3cf1..5fc084a 100644 --- a/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp +++ b/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp @@ -33,7 +33,7 @@ public: // in an object of type `C` constructed into variable `c`. Thus the // return value of `CallEvent::getReturnValueUnderConstruction()` must // be non-empty and has to be a `MemRegion`. - Optional<SVal> RetVal = Call.getReturnValueUnderConstruction(); + std::optional<SVal> RetVal = Call.getReturnValueUnderConstruction(); ASSERT_TRUE(RetVal); ASSERT_TRUE(RetVal->getAsRegion()); diff --git a/clang/unittests/Tooling/ASTSelectionTest.cpp b/clang/unittests/Tooling/ASTSelectionTest.cpp index 504d105..38b7df8 100644 --- a/clang/unittests/Tooling/ASTSelectionTest.cpp +++ b/clang/unittests/Tooling/ASTSelectionTest.cpp @@ -28,17 +28,17 @@ using FileRange = std::pair<FileLocation, FileLocation>; class SelectionFinderVisitor : public TestVisitor<SelectionFinderVisitor> { FileLocation Location; - Optional<FileRange> SelectionRange; + std::optional<FileRange> SelectionRange; llvm::function_ref<void(SourceRange SelectionRange, - Optional<SelectedASTNode>)> + std::optional<SelectedASTNode>)> Consumer; public: - SelectionFinderVisitor(FileLocation Location, - Optional<FileRange> SelectionRange, - llvm::function_ref<void(SourceRange SelectionRange, - Optional<SelectedASTNode>)> - Consumer) + SelectionFinderVisitor( + FileLocation Location, std::optional<FileRange> SelectionRange, + llvm::function_ref<void(SourceRange SelectionRange, + std::optional<SelectedASTNode>)> + Consumer) : Location(Location), SelectionRange(SelectionRange), Consumer(Consumer) { } @@ -65,9 +65,10 @@ public: /// A location roughly corresponds to a cursor location in an editor, while /// the optional range corresponds to the selection range in an editor. void findSelectedASTNodesWithRange( - StringRef Source, FileLocation Location, Optional<FileRange> SelectionRange, + StringRef Source, FileLocation Location, + std::optional<FileRange> SelectionRange, llvm::function_ref<void(SourceRange SelectionRange, - Optional<SelectedASTNode>)> + std::optional<SelectedASTNode>)> Consumer, SelectionFinderVisitor::Language Language = SelectionFinderVisitor::Lang_CXX11) { @@ -76,13 +77,14 @@ void findSelectedASTNodesWithRange( } void findSelectedASTNodes( - StringRef Source, FileLocation Location, Optional<FileRange> SelectionRange, - llvm::function_ref<void(Optional<SelectedASTNode>)> Consumer, + StringRef Source, FileLocation Location, + std::optional<FileRange> SelectionRange, + llvm::function_ref<void(std::optional<SelectedASTNode>)> Consumer, SelectionFinderVisitor::Language Language = SelectionFinderVisitor::Lang_CXX11) { findSelectedASTNodesWithRange( Source, Location, SelectionRange, - [&](SourceRange, Optional<SelectedASTNode> Selection) { + [&](SourceRange, std::optional<SelectedASTNode> Selection) { Consumer(std::move(Selection)); }, Language); @@ -151,12 +153,13 @@ ForAllChildrenOf allChildrenOf(const SelectedASTNode &Node) { TEST(ASTSelectionFinder, CursorNoSelection) { findSelectedASTNodes( " void f() { }", {1, 1}, std::nullopt, - [](Optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); + [](std::optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); } TEST(ASTSelectionFinder, CursorAtStartOfFunction) { findSelectedASTNodes( - "void f() { }", {1, 1}, std::nullopt, [](Optional<SelectedASTNode> Node) { + "void f() { }", {1, 1}, std::nullopt, + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); checkNode<TranslationUnitDecl>(*Node, SourceSelectionKind::None, /*NumChildren=*/1); @@ -175,15 +178,15 @@ TEST(ASTSelectionFinder, CursorAtStartOfFunction) { TEST(ASTSelectionFinder, RangeNoSelection) { findSelectedASTNodes( " void f() { }", {1, 1}, FileRange{{1, 1}, {1, 1}}, - [](Optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); + [](std::optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); findSelectedASTNodes( " void f() { }", {1, 1}, FileRange{{1, 1}, {1, 2}}, - [](Optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); + [](std::optional<SelectedASTNode> Node) { EXPECT_FALSE(Node); }); } TEST(ASTSelectionFinder, EmptyRangeFallbackToCursor) { findSelectedASTNodes("void f() { }", {1, 1}, FileRange{{1, 1}, {1, 1}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); checkNode<FunctionDecl>( Node->Children[0], @@ -198,7 +201,7 @@ TEST(ASTSelectionFinder, WholeFunctionSelection) { findSelectedASTNodes( Source, {1, 1}, FileRange{{1, 1}, {2, 2}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -222,7 +225,7 @@ TEST(ASTSelectionFinder, WholeFunctionSelection) { // From 'int' until just before '}': findSelectedASTNodes( Source, {2, 1}, FileRange{{1, 1}, {2, 1}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -238,7 +241,7 @@ TEST(ASTSelectionFinder, WholeFunctionSelection) { // From '{' until just after '}': findSelectedASTNodes( Source, {1, 14}, FileRange{{1, 14}, {2, 2}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -254,7 +257,7 @@ TEST(ASTSelectionFinder, WholeFunctionSelection) { // From 'x' until just after '}': findSelectedASTNodes( Source, {2, 2}, FileRange{{1, 11}, {2, 2}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -278,7 +281,7 @@ void f1() { } void f2() { } void f3() { } )"; - auto SelectedF1F2 = [](Optional<SelectedASTNode> Node) { + auto SelectedF1F2 = [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 2u); checkNode<FunctionDecl>(Node->Children[0], @@ -308,7 +311,7 @@ TEST(ASTSelectionFinder, MultipleStatementSelection) { // From 'f(2,3)' until just before 'x = 1;': findSelectedASTNodes( Source, {3, 2}, FileRange{{3, 2}, {7, 1}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -329,7 +332,7 @@ TEST(ASTSelectionFinder, MultipleStatementSelection) { // From 'f(2,3)' until just before ';' in 'x = 1;': findSelectedASTNodes( Source, {3, 2}, FileRange{{3, 2}, {7, 8}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -351,7 +354,7 @@ TEST(ASTSelectionFinder, MultipleStatementSelection) { // From the middle of 'int z = 3' until the middle of 'x = 1;': findSelectedASTNodes( Source, {2, 10}, FileRange{{2, 10}, {7, 5}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Fn = checkNode<FunctionDecl>( @@ -399,7 +402,7 @@ void outerFunction() { } // Just the 'x' expression in 'selected': findSelectedASTNodes( Source, {9, 10}, FileRange{{9, 10}, {9, 11}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Impl = checkNode<ObjCImplementationDecl>( @@ -415,7 +418,7 @@ void outerFunction() { } // The entire 'catF': findSelectedASTNodes( Source, {15, 1}, FileRange{{15, 1}, {15, 16}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Impl = checkNode<ObjCCategoryImplDecl>( @@ -431,7 +434,7 @@ void outerFunction() { } // From the line before 'selected' to the line after 'catF': findSelectedASTNodes( Source, {16, 1}, FileRange{{7, 1}, {16, 1}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 2u); const auto &Impl = checkNode<ObjCImplementationDecl>( @@ -453,16 +456,16 @@ void outerFunction() { } }, SelectionFinderVisitor::Lang_OBJC); // Just the 'outer' function: - findSelectedASTNodes(Source, {19, 1}, FileRange{{19, 1}, {19, 25}}, - [](Optional<SelectedASTNode> Node) { - EXPECT_TRUE(Node); - EXPECT_EQ(Node->Children.size(), 1u); - checkNode<FunctionDecl>( - Node->Children[0], - SourceSelectionKind::ContainsSelection, - /*NumChildren=*/1, /*Name=*/"outerFunction"); - }, - SelectionFinderVisitor::Lang_OBJC); + findSelectedASTNodes( + Source, {19, 1}, FileRange{{19, 1}, {19, 25}}, + [](std::optional<SelectedASTNode> Node) { + EXPECT_TRUE(Node); + EXPECT_EQ(Node->Children.size(), 1u); + checkNode<FunctionDecl>(Node->Children[0], + SourceSelectionKind::ContainsSelection, + /*NumChildren=*/1, /*Name=*/"outerFunction"); + }, + SelectionFinderVisitor::Lang_OBJC); } TEST(ASTSelectionFinder, FunctionInObjCImplementationCarefulWithEarlyExit) { @@ -481,7 +484,7 @@ void selected() { // Just 'selected' findSelectedASTNodes( Source, {6, 1}, FileRange{{6, 1}, {7, 2}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Impl = checkNode<ObjCImplementationDecl>( @@ -507,7 +510,7 @@ void foo() { // The entire struct 'Copy': findSelectedASTNodes( Source, {2, 1}, FileRange{{2, 1}, {4, 3}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); const auto &Record = checkNode<CXXRecordDecl>( @@ -528,7 +531,7 @@ TEST(ASTSelectionFinder, CorrectEndForObjectiveCImplementation) { // Just after '@ end' findSelectedASTNodes( Source, {5, 6}, std::nullopt, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); checkNode<ObjCImplementationDecl>( @@ -537,7 +540,7 @@ TEST(ASTSelectionFinder, CorrectEndForObjectiveCImplementation) { SelectionFinderVisitor::Lang_OBJC); } -const SelectedASTNode &checkFnBody(const Optional<SelectedASTNode> &Node, +const SelectedASTNode &checkFnBody(const std::optional<SelectedASTNode> &Node, StringRef Name) { EXPECT_TRUE(Node); EXPECT_EQ(Node->Children.size(), 1u); @@ -573,7 +576,7 @@ void selectSubscript(NSMutableArray *array, I *i) { // Just 'i.prop'. findSelectedASTNodes( Source, {6, 7}, FileRange{{6, 7}, {6, 13}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { const auto &CS = checkFnBody(Node, /*Name=*/"selectProp"); const auto &CCast = checkNode<CStyleCastExpr>( CS.Children[0], SourceSelectionKind::ContainsSelection, @@ -594,7 +597,7 @@ void selectSubscript(NSMutableArray *array, I *i) { // Just 'i.prop = 21' findSelectedASTNodes( Source, {7, 1}, FileRange{{7, 1}, {7, 12}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { const auto &CS = checkFnBody(Node, /*Name=*/"selectProp"); const auto &POE = checkNode<PseudoObjectExpr>( CS.Children[0], SourceSelectionKind::ContainsSelection, @@ -617,7 +620,7 @@ void selectSubscript(NSMutableArray *array, I *i) { // Just 'array[10]' findSelectedASTNodes( Source, {17, 9}, FileRange{{17, 9}, {17, 18}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { const auto &CS = checkFnBody(Node, /*Name=*/"selectSubscript"); const auto &CCast = checkNode<CStyleCastExpr>( CS.Children[0], SourceSelectionKind::ContainsSelection, @@ -640,7 +643,7 @@ void selectSubscript(NSMutableArray *array, I *i) { // Just 'array[i.prop] = array' findSelectedASTNodes( Source, {18, 3}, FileRange{{18, 3}, {18, 20}}, - [](Optional<SelectedASTNode> Node) { + [](std::optional<SelectedASTNode> Node) { const auto &CS = checkFnBody(Node, /*Name=*/"selectSubscript"); const auto &POE = checkNode<PseudoObjectExpr>( CS.Children[0], SourceSelectionKind::ContainsSelection, @@ -690,35 +693,35 @@ void f2() { // No selection range. findSelectedASTNodesWithRange( Source, {2, 2}, std::nullopt, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_FALSE(SelectedCode); }); findSelectedASTNodesWithRange( Source, {2, 2}, FileRange{{2, 2}, {2, 2}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_FALSE(SelectedCode); }); // Range that spans multiple functions is an invalid code range. findSelectedASTNodesWithRange( Source, {2, 2}, FileRange{{7, 2}, {12, 1}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_FALSE(SelectedCode); }); // Just 'z = x;': findSelectedASTNodesWithRange( Source, {2, 2}, FileRange{{2, 2}, {2, 13}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -736,9 +739,9 @@ void f2() { // From 'f(2,3)' until just before 'x = 1;': findSelectedASTNodesWithRange( Source, {3, 2}, FileRange{{3, 2}, {7, 1}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 2u); @@ -757,9 +760,9 @@ void f2() { // From 'f(2,3)' until just before ';' in 'x = 1;': findSelectedASTNodesWithRange( Source, {3, 2}, FileRange{{3, 2}, {7, 8}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 3u); @@ -770,10 +773,10 @@ void f2() { // From the middle of 'int z = 3' until the middle of 'x = 1;': findSelectedASTNodesWithRange( Source, {2, 10}, FileRange{{2, 10}, {7, 5}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 4u); @@ -791,9 +794,9 @@ int codeRange = 2 + 3; // '2+3' expression. findSelectedASTNodesWithRange( Source, {2, 17}, FileRange{{2, 17}, {2, 22}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -819,9 +822,9 @@ void f() { // 'int a' findSelectedASTNodesWithRange( Source, {4, 8}, FileRange{{4, 8}, {4, 14}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -849,9 +852,9 @@ void f(int x, int y) { // 'int a = x * y' findSelectedASTNodesWithRange( Source, {3, 4}, FileRange{{3, 4}, {3, 17}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -877,9 +880,9 @@ void f(int x, int y) { // 'b = x - y' findSelectedASTNodesWithRange( Source, {3, 19}, FileRange{{3, 19}, {3, 28}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -916,9 +919,9 @@ TEST(ASTSelectionFinder, SimpleCodeRangeASTSelectionInObjCMethod) { // Range that spans multiple methods is an invalid code range. findSelectedASTNodesWithRange( Source, {9, 2}, FileRange{{9, 2}, {13, 1}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_FALSE(SelectedCode); }, @@ -926,9 +929,9 @@ TEST(ASTSelectionFinder, SimpleCodeRangeASTSelectionInObjCMethod) { // Just 'z = x;': findSelectedASTNodesWithRange( Source, {4, 2}, FileRange{{4, 2}, {4, 13}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -949,9 +952,9 @@ TEST(ASTSelectionFinder, SimpleCodeRangeASTSelectionInObjCMethod) { // From '[self f: 2 with: 3]' until just before 'x = 1;': findSelectedASTNodesWithRange( Source, {5, 2}, FileRange{{5, 2}, {9, 1}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 2u); @@ -981,9 +984,9 @@ void foo() { // Just '"test"': findSelectedASTNodesWithRange( Source, {3, 10}, FileRange{{3, 10}, {3, 16}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -993,9 +996,9 @@ void foo() { // Just 'test': findSelectedASTNodesWithRange( Source, {3, 11}, FileRange{{3, 11}, {3, 15}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -1024,9 +1027,9 @@ void dontSelectArgument(AClass &a) { // Just 'method' with implicit 'this': findSelectedASTNodesWithRange( Source, {6, 5}, FileRange{{6, 5}, {6, 11}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -1035,9 +1038,9 @@ void dontSelectArgument(AClass &a) { // Just 'method': findSelectedASTNodesWithRange( Source, {11, 5}, FileRange{{11, 5}, {11, 11}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -1046,9 +1049,9 @@ void dontSelectArgument(AClass &a) { // Just 'afield', which should not select the call. findSelectedASTNodesWithRange( Source, {14, 5}, FileRange{{14, 45}, {14, 51}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); @@ -1067,10 +1070,10 @@ void test() { // Just 'function': findSelectedASTNodesWithRange( Source, {5, 3}, FileRange{{5, 3}, {5, 11}}, - [](SourceRange SelectionRange, Optional<SelectedASTNode> Node) { + [](SourceRange SelectionRange, std::optional<SelectedASTNode> Node) { EXPECT_TRUE(Node); Node->dump(); - Optional<CodeRangeASTSelection> SelectedCode = + std::optional<CodeRangeASTSelection> SelectedCode = CodeRangeASTSelection::create(SelectionRange, std::move(*Node)); EXPECT_TRUE(SelectedCode); EXPECT_EQ(SelectedCode->size(), 1u); diff --git a/clang/unittests/Tooling/RefactoringActionRulesTest.cpp b/clang/unittests/Tooling/RefactoringActionRulesTest.cpp index e80f75a..cdd1faf 100644 --- a/clang/unittests/Tooling/RefactoringActionRulesTest.cpp +++ b/clang/unittests/Tooling/RefactoringActionRulesTest.cpp @@ -48,7 +48,7 @@ createReplacements(const std::unique_ptr<RefactoringActionRule> &Rule, } public: - Optional<Expected<AtomicChanges>> Result; + std::optional<Expected<AtomicChanges>> Result; }; Consumer C; @@ -176,8 +176,8 @@ TEST_F(RefactoringActionRulesTest, ReturnError) { EXPECT_EQ(Message, "Error"); } -Optional<SymbolOccurrences> findOccurrences(RefactoringActionRule &Rule, - RefactoringRuleContext &Context) { +std::optional<SymbolOccurrences> +findOccurrences(RefactoringActionRule &Rule, RefactoringRuleContext &Context) { class Consumer final : public RefactoringResultConsumer { void handleError(llvm::Error) override {} void handle(SymbolOccurrences Occurrences) override { @@ -188,7 +188,7 @@ Optional<SymbolOccurrences> findOccurrences(RefactoringActionRule &Rule, } public: - Optional<SymbolOccurrences> Result; + std::optional<SymbolOccurrences> Result; }; Consumer C; @@ -225,7 +225,7 @@ TEST_F(RefactoringActionRulesTest, ReturnSymbolOccurrences) { SourceLocation Cursor = Context.Sources.getLocForStartOfFile(Context.Sources.getMainFileID()); RefContext.setSelectionRange({Cursor, Cursor}); - Optional<SymbolOccurrences> Result = findOccurrences(*Rule, RefContext); + std::optional<SymbolOccurrences> Result = findOccurrences(*Rule, RefContext); ASSERT_FALSE(!Result); SymbolOccurrences Occurrences = std::move(*Result); diff --git a/clang/unittests/Tooling/RefactoringTest.cpp b/clang/unittests/Tooling/RefactoringTest.cpp index 2f3bd22..77d410f 100644 --- a/clang/unittests/Tooling/RefactoringTest.cpp +++ b/clang/unittests/Tooling/RefactoringTest.cpp @@ -105,8 +105,8 @@ TEST_F(ReplacementTest, ReturnsInvalidPath) { // error code, expected new replacement, and expected existing replacement. static bool checkReplacementError(llvm::Error &&Error, replacement_error ExpectedErr, - llvm::Optional<Replacement> ExpectedExisting, - llvm::Optional<Replacement> ExpectedNew) { + std::optional<Replacement> ExpectedExisting, + std::optional<Replacement> ExpectedNew) { if (!Error) { llvm::errs() << "Error is a success."; return false; diff --git a/clang/unittests/Tooling/SourceCodeBuildersTest.cpp b/clang/unittests/Tooling/SourceCodeBuildersTest.cpp index 6db3031..95aa29e 100644 --- a/clang/unittests/Tooling/SourceCodeBuildersTest.cpp +++ b/clang/unittests/Tooling/SourceCodeBuildersTest.cpp @@ -66,8 +66,8 @@ struct TestMatch { // matcher correspondingly. `Matcher` should match one of the statements in // `StatementCode` exactly -- that is, produce exactly one match. However, // `StatementCode` may contain other statements not described by `Matcher`. -static llvm::Optional<TestMatch> matchStmt(StringRef StatementCode, - StatementMatcher Matcher) { +static std::optional<TestMatch> matchStmt(StringRef StatementCode, + StatementMatcher Matcher) { auto AstUnit = buildASTFromCodeWithArgs(wrapSnippet(StatementCode), {"-Wno-unused-value"}); if (AstUnit == nullptr) { diff --git a/clang/unittests/Tooling/StencilTest.cpp b/clang/unittests/Tooling/StencilTest.cpp index 68d3a6c..26257cf 100644 --- a/clang/unittests/Tooling/StencilTest.cpp +++ b/clang/unittests/Tooling/StencilTest.cpp @@ -70,9 +70,9 @@ struct TestMatch { // `StatementCode` exactly -- that is, produce exactly one match. However, // `StatementCode` may contain other statements not described by `Matcher`. // `ExtraPreface` (optionally) adds extra decls to the TU, before the code. -static llvm::Optional<TestMatch> matchStmt(StringRef StatementCode, - StatementMatcher Matcher, - StringRef ExtraPreface = "") { +static std::optional<TestMatch> matchStmt(StringRef StatementCode, + StatementMatcher Matcher, + StringRef ExtraPreface = "") { auto AstUnit = tooling::buildASTFromCodeWithArgs( wrapSnippet(ExtraPreface, StatementCode), {"-Wno-unused-value"}); if (AstUnit == nullptr) { diff --git a/clang/unittests/Tooling/Syntax/TokensTest.cpp b/clang/unittests/Tooling/Syntax/TokensTest.cpp index 8f15046..959ece0 100644 --- a/clang/unittests/Tooling/Syntax/TokensTest.cpp +++ b/clang/unittests/Tooling/Syntax/TokensTest.cpp @@ -115,7 +115,7 @@ public: private: TokenBuffer &Result; - llvm::Optional<TokenCollector> Collector; + std::optional<TokenCollector> Collector; }; constexpr const char *FileName = "./input.cpp"; diff --git a/clang/unittests/Tooling/TransformerTest.cpp b/clang/unittests/Tooling/TransformerTest.cpp index 8d10f38..09fcf04 100644 --- a/clang/unittests/Tooling/TransformerTest.cpp +++ b/clang/unittests/Tooling/TransformerTest.cpp @@ -84,7 +84,7 @@ static std::string format(StringRef Code) { } static void compareSnippets(StringRef Expected, - const llvm::Optional<std::string> &MaybeActual) { + const std::optional<std::string> &MaybeActual) { ASSERT_TRUE(MaybeActual) << "Rewrite failed. Expecting: " << Expected; auto Actual = *MaybeActual; std::string HL = "#include \"header.h\"\n"; @@ -103,7 +103,7 @@ protected: FileContents.emplace_back(std::string(Filename), std::string(Content)); } - llvm::Optional<std::string> rewrite(StringRef Input) { + std::optional<std::string> rewrite(StringRef Input) { std::string Code = ("#include \"header.h\"\n" + Input).str(); auto Factory = newFrontendActionFactory(&MatchFinder); if (!runToolOnCodeWithArgs( diff --git a/clang/utils/TableGen/ASTTableGen.cpp b/clang/utils/TableGen/ASTTableGen.cpp index 79383bf..60f563d 100644 --- a/clang/utils/TableGen/ASTTableGen.cpp +++ b/clang/utils/TableGen/ASTTableGen.cpp @@ -82,7 +82,7 @@ void PropertyType::emitCXXValueTypeName(bool forRead, raw_ostream &out) const { elementType.emitCXXValueTypeName(forRead, out); out << ">"; } else if (auto valueType = getOptionalElementType()) { - out << "llvm::Optional<"; + out << "std::optional<"; valueType.emitCXXValueTypeName(forRead, out); out << ">"; } else { diff --git a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp index 3401e03..1961388 100644 --- a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp +++ b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp @@ -526,7 +526,8 @@ void ASTPropsEmitter::emitReadOfProperty(StringRef readerName, // get a pr-value back from read(), and we should be able to forward // that in the creation rule. Out << " "; - if (!condition.empty()) Out << "llvm::Optional<"; + if (!condition.empty()) + Out << "std::optional<"; type.emitCXXValueTypeName(true, Out); if (!condition.empty()) Out << ">"; Out << " " << name; @@ -663,9 +664,7 @@ ASTPropsEmitter::emitDispatcherTemplate(const ReaderWriterInfo &info) { declareSpecialization("<class T>", "llvm::ArrayRef<T>", "Array"); - declareSpecialization("<class T>", - "llvm::Optional<T>", - "Optional"); + declareSpecialization("<class T>", "std::optional<T>", "Optional"); Out << "\n"; } @@ -678,15 +677,20 @@ ASTPropsEmitter::emitPackUnpackOptionalTemplate(const ReaderWriterInfo &info) { Out << "template <class ValueType>\n" "struct " << classPrefix << "OptionalValue;\n"; - auto declareSpecialization = [&](const Twine &typeName, - StringRef code) { + auto declareSpecialization = [&](const Twine &typeName, StringRef code) { Out << "template <>\n" - "struct " << classPrefix << "OptionalValue<" << typeName << "> {\n" - " static " << (info.IsReader ? "Optional<" : "") << typeName - << (info.IsReader ? "> " : " ") << methodName << "(" - << (info.IsReader ? "" : "Optional<") << typeName - << (info.IsReader ? "" : ">") << " value) {\n" - " return " << code << ";\n" + "struct " + << classPrefix << "OptionalValue<" << typeName + << "> {\n" + " static " + << (info.IsReader ? "std::optional<" : "") << typeName + << (info.IsReader ? "> " : " ") << methodName << "(" + << (info.IsReader ? "" : "std::optional<") << typeName + << (info.IsReader ? "" : ">") + << " value) {\n" + " return " + << code + << ";\n" " }\n" "};\n"; }; diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index a261cf2..de608c7 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -978,13 +978,14 @@ namespace { OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type << "(StringRef Val, " << type << " &Out) {\n"; - OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<"; + OS << " std::optional<" << type + << "> R = llvm::StringSwitch<std::optional<"; OS << type << ">>(Val)\n"; for (size_t I = 0; I < enums.size(); ++I) { OS << " .Case(\"" << values[I] << "\", "; OS << getAttrName() << "Attr::" << enums[I] << ")\n"; } - OS << " .Default(Optional<" << type << ">());\n"; + OS << " .Default(std::optional<" << type << ">());\n"; OS << " if (R) {\n"; OS << " Out = *R;\n return true;\n }\n"; OS << " return false;\n"; @@ -1099,13 +1100,14 @@ namespace { OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type << "(StringRef Val, "; OS << type << " &Out) {\n"; - OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<"; + OS << " std::optional<" << type + << "> R = llvm::StringSwitch<std::optional<"; OS << type << ">>(Val)\n"; for (size_t I = 0; I < enums.size(); ++I) { OS << " .Case(\"" << values[I] << "\", "; OS << getAttrName() << "Attr::" << enums[I] << ")\n"; } - OS << " .Default(Optional<" << type << ">());\n"; + OS << " .Default(std::optional<" << type << ">());\n"; OS << " if (R) {\n"; OS << " Out = *R;\n return true;\n }\n"; OS << " return false;\n"; @@ -2115,7 +2117,7 @@ PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr, void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) { // Generate routines that check the names of sub-rules. - OS << "Optional<attr::SubjectMatchRule> " + OS << "std::optional<attr::SubjectMatchRule> " "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n"; OS << " return std::nullopt;\n"; OS << "}\n\n"; @@ -2129,12 +2131,13 @@ void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) { } for (const auto &SubMatchRule : SubMatchRules) { - OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_" + OS << "std::optional<attr::SubjectMatchRule> " + "isAttributeSubjectMatchSubRuleFor_" << SubMatchRule.first->getValueAsString("Name") << "(StringRef Name, bool IsUnless) {\n"; OS << " if (IsUnless)\n"; OS << " return " - "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n"; + "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n"; for (const auto &Rule : SubMatchRule.second) { if (Rule.isNegatedSubRule()) OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue() @@ -2142,7 +2145,7 @@ void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) { } OS << " Default(std::nullopt);\n"; OS << " return " - "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n"; + "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n"; for (const auto &Rule : SubMatchRule.second) { if (!Rule.isNegatedSubRule()) OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue() @@ -2153,12 +2156,12 @@ void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) { } // Generate the function that checks for the top-level rules. - OS << "std::pair<Optional<attr::SubjectMatchRule>, " - "Optional<attr::SubjectMatchRule> (*)(StringRef, " + OS << "std::pair<std::optional<attr::SubjectMatchRule>, " + "std::optional<attr::SubjectMatchRule> (*)(StringRef, " "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n"; OS << " return " - "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, " - "Optional<attr::SubjectMatchRule> (*) (StringRef, " + "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, " + "std::optional<attr::SubjectMatchRule> (*) (StringRef, " "bool)>>(Name).\n"; for (const auto &Rule : Rules) { if (Rule.isSubRule()) |