aboutsummaryrefslogtreecommitdiff
path: root/contrib/llvm-project/clang/include
diff options
context:
space:
mode:
Diffstat (limited to 'contrib/llvm-project/clang/include')
-rw-r--r--contrib/llvm-project/clang/include/clang-c/Index.h88
-rw-r--r--contrib/llvm-project/clang/include/clang-c/Rewrite.h63
-rw-r--r--contrib/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h24
-rw-r--r--contrib/llvm-project/clang/include/clang/APINotes/Types.h734
-rw-r--r--contrib/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/APValue.h163
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTContext.h130
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTFwd.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTImporter.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h72
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h7
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ASTTypeTraits.h74
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/AbstractBasicReader.h34
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h35
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Attr.h39
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/CXXInheritance.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def7
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/CanonicalType.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/CommentLexer.h31
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ComputeDependence.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Decl.h123
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DeclBase.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DeclCXX.h102
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DeclObjC.h45
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DeclOpenMP.h246
-rwxr-xr-xcontrib/llvm-project/clang/include/clang/AST/DeclTemplate.h117
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DeclarationName.h23
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DependenceFlags.h1
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/DependentDiagnostic.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Expr.h399
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ExprCXX.h297
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ExprConcepts.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ExprObjC.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ExternalASTSource.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/GlobalDecl.h1
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/IgnoreExpr.h161
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Mangle.h20
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/MangleNumberingContext.h5
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h34
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/OpenMPClause.h494
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/OperationKinds.def11
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ParentMap.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/ParentMapContext.h13
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/PrettyPrinter.h40
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td308
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/RecordLayout.h65
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h68
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Redeclarable.h15
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Stmt.h60
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/StmtIterator.h9
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/StmtOpenMP.h1653
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/TemplateBase.h72
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/TemplateName.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/TextNodeDumper.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/Type.h163
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/TypeLoc.h93
-rw-r--r--contrib/llvm-project/clang/include/clang/AST/TypeProperties.td12
-rw-r--r--contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h574
-rw-r--r--contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h938
-rw-r--r--contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h58
-rw-r--r--contrib/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h40
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h112
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h70
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h18
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/CallGraph.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/IssueHash.h49
-rw-r--r--contrib/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h39
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/AddressSpaces.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Attr.td286
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td1102
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Builtins.def58
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def11
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def6
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def8
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def236
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def136
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def51
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def11
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def53
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h52
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Cuda.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DeclNodes.td1
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Diagnostic.h408
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Diagnostic.td10
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticAST.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td11
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticComment.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td6
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td39
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td22
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td46
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h12
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticLex.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td9
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def1
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h12
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticParse.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td86
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticSema.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td386
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td19
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/DirectoryEntry.h298
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/FPOptions.def4
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Features.def3
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/FileEntry.h406
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/FileManager.h158
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/FixedPoint.h215
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/LLVM.h1
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/LangOptions.def42
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/LangOptions.h165
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/LangStandard.h14
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/LangStandards.def14
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Module.h55
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def142
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/OpenCLOptions.h213
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.def20
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.h23
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/OperatorKinds.h5
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/PPCTypes.def38
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h277
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/ProfileList.h58
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Sanitizers.def4
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/SourceLocation.h31
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/SourceManager.h1022
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/Specifiers.h34
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/TargetCXXABI.h25
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/TargetID.h56
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h78
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/TargetOptions.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/TokenKinds.def17
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/arm_mve.td12
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/arm_mve_defs.td8
-rw-r--r--contrib/llvm-project/clang/include/clang/Basic/arm_neon.td73
-rw-r--r--contrib/llvm-project/clang/include/clang/CodeGen/BackendUtil.h5
-rw-r--r--contrib/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h60
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Compilation.h17
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Distro.h17
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Driver.h4
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Job.h29
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Options.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/Options.td3043
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/SanitizerArgs.h5
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/ToolChain.h32
-rw-r--r--contrib/llvm-project/clang/include/clang/Driver/XRayArgs.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Edit/EditedSource.h2
-rwxr-xr-xcontrib/llvm-project/clang/include/clang/Format/Format.h1081
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/ASTUnit.h18
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/CompilerInstance.h68
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h22
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/FrontendAction.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/FrontendOptions.h35
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h9
-rw-r--r--contrib/llvm-project/clang/include/clang/Frontend/Utils.h8
-rw-r--r--contrib/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h129
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h34
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h9
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/Lexer.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/ModuleMap.h13
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h24
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h26
-rw-r--r--contrib/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/Parse/Parser.h70
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h581
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h19
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Designator.h49
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Initialization.h61
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Overload.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Ownership.h23
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/ParsedAttr.h44
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/ScopeInfo.h15
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Sema.h839
-rw-r--r--contrib/llvm-project/clang/include/clang/Sema/Template.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ASTReader.h51
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h15
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ASTWriter.h10
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ModuleFile.h19
-rw-r--r--contrib/llvm-project/clang/include/clang/Serialization/ModuleManager.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td16
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h34
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h5
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/IssueHash.h50
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h7
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h16
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h56
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h20
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h17
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h22
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h18
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h14
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h3
-rw-r--r--contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h12
-rw-r--r--contrib/llvm-project/clang/include/clang/Testing/TestClangConfig.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h22
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h21
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Lookup.h (renamed from contrib/llvm-project/clang/include/clang/Tooling/Core/Lookup.h)6
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h2
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h13
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h35
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h648
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td296
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td85
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h12
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h216
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Tooling.h11
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h6
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h29
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h290
-rw-r--r--contrib/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h11
-rw-r--r--contrib/llvm-project/clang/include/clang/module.modulemap1
231 files changed, 16079 insertions, 7272 deletions
diff --git a/contrib/llvm-project/clang/include/clang-c/Index.h b/contrib/llvm-project/clang/include/clang-c/Index.h
index 5fa728d6d66c..e305283bbaf1 100644
--- a/contrib/llvm-project/clang/include/clang-c/Index.h
+++ b/contrib/llvm-project/clang/include/clang-c/Index.h
@@ -33,7 +33,7 @@
* compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
*/
#define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 60
+#define CINDEX_VERSION_MINOR 61
#define CINDEX_VERSION_ENCODE(major, minor) (((major)*10000) + ((minor)*1))
@@ -2052,62 +2052,58 @@ enum CXCursorKind {
*/
CXCursor_CXXFunctionalCastExpr = 128,
- /** OpenCL's addrspace_cast<> expression.
- */
- CXCursor_CXXAddrspaceCastExpr = 129,
-
/** A C++ typeid expression (C++ [expr.typeid]).
*/
- CXCursor_CXXTypeidExpr = 130,
+ CXCursor_CXXTypeidExpr = 129,
/** [C++ 2.13.5] C++ Boolean Literal.
*/
- CXCursor_CXXBoolLiteralExpr = 131,
+ CXCursor_CXXBoolLiteralExpr = 130,
/** [C++0x 2.14.7] C++ Pointer Literal.
*/
- CXCursor_CXXNullPtrLiteralExpr = 132,
+ CXCursor_CXXNullPtrLiteralExpr = 131,
/** Represents the "this" expression in C++
*/
- CXCursor_CXXThisExpr = 133,
+ CXCursor_CXXThisExpr = 132,
/** [C++ 15] C++ Throw Expression.
*
* This handles 'throw' and 'throw' assignment-expression. When
* assignment-expression isn't present, Op will be null.
*/
- CXCursor_CXXThrowExpr = 134,
+ CXCursor_CXXThrowExpr = 133,
/** A new expression for memory allocation and constructor calls, e.g:
* "new CXXNewExpr(foo)".
*/
- CXCursor_CXXNewExpr = 135,
+ CXCursor_CXXNewExpr = 134,
/** A delete expression for memory deallocation and destructor calls,
* e.g. "delete[] pArray".
*/
- CXCursor_CXXDeleteExpr = 136,
+ CXCursor_CXXDeleteExpr = 135,
/** A unary expression. (noexcept, sizeof, or other traits)
*/
- CXCursor_UnaryExpr = 137,
+ CXCursor_UnaryExpr = 136,
/** An Objective-C string literal i.e. @"foo".
*/
- CXCursor_ObjCStringLiteral = 138,
+ CXCursor_ObjCStringLiteral = 137,
/** An Objective-C \@encode expression.
*/
- CXCursor_ObjCEncodeExpr = 139,
+ CXCursor_ObjCEncodeExpr = 138,
/** An Objective-C \@selector expression.
*/
- CXCursor_ObjCSelectorExpr = 140,
+ CXCursor_ObjCSelectorExpr = 139,
/** An Objective-C \@protocol expression.
*/
- CXCursor_ObjCProtocolExpr = 141,
+ CXCursor_ObjCProtocolExpr = 140,
/** An Objective-C "bridged" cast expression, which casts between
* Objective-C pointers and C pointers, transferring ownership in the process.
@@ -2116,7 +2112,7 @@ enum CXCursorKind {
* NSString *str = (__bridge_transfer NSString *)CFCreateString();
* \endcode
*/
- CXCursor_ObjCBridgedCastExpr = 142,
+ CXCursor_ObjCBridgedCastExpr = 141,
/** Represents a C++0x pack expansion that produces a sequence of
* expressions.
@@ -2131,7 +2127,7 @@ enum CXCursorKind {
* }
* \endcode
*/
- CXCursor_PackExpansionExpr = 143,
+ CXCursor_PackExpansionExpr = 142,
/** Represents an expression that computes the length of a parameter
* pack.
@@ -2143,7 +2139,7 @@ enum CXCursorKind {
* };
* \endcode
*/
- CXCursor_SizeOfPackExpr = 144,
+ CXCursor_SizeOfPackExpr = 143,
/* Represents a C++ lambda expression that produces a local function
* object.
@@ -2157,39 +2153,43 @@ enum CXCursorKind {
* }
* \endcode
*/
- CXCursor_LambdaExpr = 145,
+ CXCursor_LambdaExpr = 144,
/** Objective-c Boolean Literal.
*/
- CXCursor_ObjCBoolLiteralExpr = 146,
+ CXCursor_ObjCBoolLiteralExpr = 145,
/** Represents the "self" expression in an Objective-C method.
*/
- CXCursor_ObjCSelfExpr = 147,
+ CXCursor_ObjCSelfExpr = 146,
/** OpenMP 5.0 [2.1.5, Array Section].
*/
- CXCursor_OMPArraySectionExpr = 148,
+ CXCursor_OMPArraySectionExpr = 147,
/** Represents an @available(...) check.
*/
- CXCursor_ObjCAvailabilityCheckExpr = 149,
+ CXCursor_ObjCAvailabilityCheckExpr = 148,
/**
* Fixed point literal
*/
- CXCursor_FixedPointLiteral = 150,
+ CXCursor_FixedPointLiteral = 149,
/** OpenMP 5.0 [2.1.4, Array Shaping].
*/
- CXCursor_OMPArrayShapingExpr = 151,
+ CXCursor_OMPArrayShapingExpr = 150,
/**
* OpenMP 5.0 [2.1.6 Iterators]
*/
- CXCursor_OMPIteratorExpr = 152,
+ CXCursor_OMPIteratorExpr = 151,
- CXCursor_LastExpr = CXCursor_OMPIteratorExpr,
+ /** OpenCL's addrspace_cast<> expression.
+ */
+ CXCursor_CXXAddrspaceCastExpr = 152,
+
+ CXCursor_LastExpr = CXCursor_CXXAddrspaceCastExpr,
/* Statements */
CXCursor_FirstStmt = 200,
@@ -2941,6 +2941,26 @@ CINDEX_LINKAGE void
clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability);
/**
+ * If cursor refers to a variable declaration and it has initializer returns
+ * cursor referring to the initializer otherwise return null cursor.
+ */
+CINDEX_LINKAGE CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor);
+
+/**
+ * If cursor refers to a variable declaration that has global storage returns 1.
+ * If cursor refers to a variable declaration that doesn't have global storage
+ * returns 0. Otherwise returns -1.
+ */
+CINDEX_LINKAGE int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor);
+
+/**
+ * If cursor refers to a variable declaration that has external storage
+ * returns 1. If cursor refers to a variable declaration that doesn't have
+ * external storage returns 0. Otherwise returns -1.
+ */
+CINDEX_LINKAGE int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor);
+
+/**
* Describe the "language" of the entity referred to by a cursor.
*/
enum CXLanguageKind {
@@ -3841,7 +3861,15 @@ enum CXTypeNullabilityKind {
/**
* Nullability is not applicable to this type.
*/
- CXTypeNullability_Invalid = 3
+ CXTypeNullability_Invalid = 3,
+
+ /**
+ * Generally behaves like Nullable, except when used in a block parameter that
+ * was imported into a swift async method. There, swift will assume that the
+ * parameter can get null even if no error occured. _Nullable parameters are
+ * assumed to only get null on error.
+ */
+ CXTypeNullability_NullableResult = 4
};
/**
diff --git a/contrib/llvm-project/clang/include/clang-c/Rewrite.h b/contrib/llvm-project/clang/include/clang-c/Rewrite.h
new file mode 100644
index 000000000000..ce1b05594b38
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang-c/Rewrite.h
@@ -0,0 +1,63 @@
+/*===-- clang-c/Rewrite.h - C CXRewriter --------------------------*- C -*-===*\
+|* *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
+|* Exceptions. *|
+|* See https://llvm.org/LICENSE.txt for license information. *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
+|* *|
+|*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_CLANG_C_REWRITE_H
+#define LLVM_CLANG_C_REWRITE_H
+
+#include "clang-c/CXString.h"
+#include "clang-c/ExternC.h"
+#include "clang-c/Index.h"
+#include "clang-c/Platform.h"
+
+LLVM_CLANG_C_EXTERN_C_BEGIN
+
+typedef void *CXRewriter;
+
+/**
+ * Create CXRewriter.
+ */
+CINDEX_LINKAGE CXRewriter clang_CXRewriter_create(CXTranslationUnit TU);
+
+/**
+ * Insert the specified string at the specified location in the original buffer.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_insertTextBefore(CXRewriter Rew, CXSourceLocation Loc,
+ const char *Insert);
+
+/**
+ * Replace the specified range of characters in the input with the specified
+ * replacement.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_replaceText(CXRewriter Rew, CXSourceRange ToBeReplaced,
+ const char *Replacement);
+
+/**
+ * Remove the specified range.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_removeText(CXRewriter Rew, CXSourceRange ToBeRemoved);
+
+/**
+ * Save all changed files to disk.
+ * Returns 1 if any files were not saved successfully, returns 0 otherwise.
+ */
+CINDEX_LINKAGE int clang_CXRewriter_overwriteChangedFiles(CXRewriter Rew);
+
+/**
+ * Write out rewritten version of the main file to stdout.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_writeMainFileToStdOut(CXRewriter Rew);
+
+/**
+ * Free the given CXRewriter.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_dispose(CXRewriter Rew);
+
+LLVM_CLANG_C_EXTERN_C_END
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h b/contrib/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h
new file mode 100644
index 000000000000..6098d0ee36fc
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h
@@ -0,0 +1,24 @@
+//===-- APINotesYAMLCompiler.h - API Notes YAML Format Reader ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_APINOTES_APINOTESYAMLCOMPILER_H
+#define LLVM_CLANG_APINOTES_APINOTESYAMLCOMPILER_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace clang {
+namespace api_notes {
+/// Parses the APINotes YAML content and writes the representation back to the
+/// specified stream. This provides a means of testing the YAML processing of
+/// the APINotes format.
+bool parseAndDumpAPINotes(llvm::StringRef YI, llvm::raw_ostream &OS);
+} // namespace api_notes
+} // namespace clang
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/APINotes/Types.h b/contrib/llvm-project/clang/include/clang/APINotes/Types.h
new file mode 100644
index 000000000000..d9bf2f07291f
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/APINotes/Types.h
@@ -0,0 +1,734 @@
+//===-- Types.h - API Notes Data Types --------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_APINOTES_TYPES_H
+#define LLVM_CLANG_APINOTES_TYPES_H
+
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include <climits>
+#include <vector>
+
+namespace clang {
+namespace api_notes {
+enum class RetainCountConventionKind {
+ None,
+ CFReturnsRetained,
+ CFReturnsNotRetained,
+ NSReturnsRetained,
+ NSReturnsNotRetained,
+};
+
+/// The payload for an enum_extensibility attribute. This is a tri-state rather
+/// than just a boolean because the presence of the attribute indicates
+/// auditing.
+enum class EnumExtensibilityKind {
+ None,
+ Open,
+ Closed,
+};
+
+/// The kind of a swift_wrapper/swift_newtype.
+enum class SwiftNewTypeKind {
+ None,
+ Struct,
+ Enum,
+};
+
+/// Describes API notes data for any entity.
+///
+/// This is used as the base of all API notes.
+class CommonEntityInfo {
+public:
+ /// Message to use when this entity is unavailable.
+ std::string UnavailableMsg;
+
+ /// Whether this entity is marked unavailable.
+ unsigned Unavailable : 1;
+
+ /// Whether this entity is marked unavailable in Swift.
+ unsigned UnavailableInSwift : 1;
+
+private:
+ /// Whether SwiftPrivate was specified.
+ unsigned SwiftPrivateSpecified : 1;
+
+ /// Whether this entity is considered "private" to a Swift overlay.
+ unsigned SwiftPrivate : 1;
+
+public:
+ /// Swift name of this entity.
+ std::string SwiftName;
+
+ CommonEntityInfo()
+ : Unavailable(0), UnavailableInSwift(0), SwiftPrivateSpecified(0),
+ SwiftPrivate(0) {}
+
+ llvm::Optional<bool> isSwiftPrivate() const {
+ return SwiftPrivateSpecified ? llvm::Optional<bool>(SwiftPrivate)
+ : llvm::None;
+ }
+
+ void setSwiftPrivate(llvm::Optional<bool> Private) {
+ SwiftPrivateSpecified = Private.hasValue();
+ SwiftPrivate = Private.hasValue() ? *Private : 0;
+ }
+
+ friend bool operator==(const CommonEntityInfo &, const CommonEntityInfo &);
+
+ CommonEntityInfo &operator|=(const CommonEntityInfo &RHS) {
+ // Merge unavailability.
+ if (RHS.Unavailable) {
+ Unavailable = true;
+ if (UnavailableMsg.empty())
+ UnavailableMsg = RHS.UnavailableMsg;
+ }
+
+ if (RHS.UnavailableInSwift) {
+ UnavailableInSwift = true;
+ if (UnavailableMsg.empty())
+ UnavailableMsg = RHS.UnavailableMsg;
+ }
+
+ if (!SwiftPrivateSpecified)
+ setSwiftPrivate(RHS.isSwiftPrivate());
+
+ if (SwiftName.empty())
+ SwiftName = RHS.SwiftName;
+
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const CommonEntityInfo &LHS,
+ const CommonEntityInfo &RHS) {
+ return LHS.UnavailableMsg == RHS.UnavailableMsg &&
+ LHS.Unavailable == RHS.Unavailable &&
+ LHS.UnavailableInSwift == RHS.UnavailableInSwift &&
+ LHS.SwiftPrivateSpecified == RHS.SwiftPrivateSpecified &&
+ LHS.SwiftPrivate == RHS.SwiftPrivate && LHS.SwiftName == RHS.SwiftName;
+}
+
+inline bool operator!=(const CommonEntityInfo &LHS,
+ const CommonEntityInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes for types.
+class CommonTypeInfo : public CommonEntityInfo {
+ /// The Swift type to which a given type is bridged.
+ ///
+ /// Reflects the swift_bridge attribute.
+ llvm::Optional<std::string> SwiftBridge;
+
+ /// The NS error domain for this type.
+ llvm::Optional<std::string> NSErrorDomain;
+
+public:
+ CommonTypeInfo() : CommonEntityInfo() {}
+
+ const llvm::Optional<std::string> &getSwiftBridge() const {
+ return SwiftBridge;
+ }
+
+ void setSwiftBridge(const llvm::Optional<std::string> &SwiftType) {
+ SwiftBridge = SwiftType;
+ }
+
+ void setSwiftBridge(const llvm::Optional<llvm::StringRef> &SwiftType) {
+ SwiftBridge = SwiftType
+ ? llvm::Optional<std::string>(std::string(*SwiftType))
+ : llvm::None;
+ }
+
+ const llvm::Optional<std::string> &getNSErrorDomain() const {
+ return NSErrorDomain;
+ }
+
+ void setNSErrorDomain(const llvm::Optional<std::string> &Domain) {
+ NSErrorDomain = Domain;
+ }
+
+ void setNSErrorDomain(const llvm::Optional<llvm::StringRef> &Domain) {
+ NSErrorDomain =
+ Domain ? llvm::Optional<std::string>(std::string(*Domain)) : llvm::None;
+ }
+
+ friend bool operator==(const CommonTypeInfo &, const CommonTypeInfo &);
+
+ CommonTypeInfo &operator|=(const CommonTypeInfo &RHS) {
+ // Merge inherited info.
+ static_cast<CommonEntityInfo &>(*this) |= RHS;
+
+ if (!SwiftBridge)
+ setSwiftBridge(RHS.getSwiftBridge());
+ if (!NSErrorDomain)
+ setNSErrorDomain(RHS.getNSErrorDomain());
+
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const CommonTypeInfo &LHS, const CommonTypeInfo &RHS) {
+ return static_cast<const CommonEntityInfo &>(LHS) == RHS &&
+ LHS.SwiftBridge == RHS.SwiftBridge &&
+ LHS.NSErrorDomain == RHS.NSErrorDomain;
+}
+
+inline bool operator!=(const CommonTypeInfo &LHS, const CommonTypeInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes data for an Objective-C class or protocol.
+class ObjCContextInfo : public CommonTypeInfo {
+ /// Whether this class has a default nullability.
+ unsigned HasDefaultNullability : 1;
+
+ /// The default nullability.
+ unsigned DefaultNullability : 2;
+
+ /// Whether this class has designated initializers recorded.
+ unsigned HasDesignatedInits : 1;
+
+ unsigned SwiftImportAsNonGenericSpecified : 1;
+ unsigned SwiftImportAsNonGeneric : 1;
+
+ unsigned SwiftObjCMembersSpecified : 1;
+ unsigned SwiftObjCMembers : 1;
+
+public:
+ ObjCContextInfo()
+ : CommonTypeInfo(), HasDefaultNullability(0), DefaultNullability(0),
+ HasDesignatedInits(0), SwiftImportAsNonGenericSpecified(false),
+ SwiftImportAsNonGeneric(false), SwiftObjCMembersSpecified(false),
+ SwiftObjCMembers(false) {}
+
+ /// Determine the default nullability for properties and methods of this
+ /// class.
+ ///
+ /// eturns the default nullability, if implied, or None if there is no
+ llvm::Optional<NullabilityKind> getDefaultNullability() const {
+ return HasDefaultNullability
+ ? llvm::Optional<NullabilityKind>(
+ static_cast<NullabilityKind>(DefaultNullability))
+ : llvm::None;
+ }
+
+ /// Set the default nullability for properties and methods of this class.
+ void setDefaultNullability(NullabilityKind Kind) {
+ HasDefaultNullability = true;
+ DefaultNullability = static_cast<unsigned>(Kind);
+ }
+
+ bool hasDesignatedInits() const { return HasDesignatedInits; }
+ void setHasDesignatedInits(bool Value) { HasDesignatedInits = Value; }
+
+ llvm::Optional<bool> getSwiftImportAsNonGeneric() const {
+ return SwiftImportAsNonGenericSpecified
+ ? llvm::Optional<bool>(SwiftImportAsNonGeneric)
+ : llvm::None;
+ }
+ void setSwiftImportAsNonGeneric(llvm::Optional<bool> Value) {
+ SwiftImportAsNonGenericSpecified = Value.hasValue();
+ SwiftImportAsNonGeneric = Value.hasValue() ? *Value : false;
+ }
+
+ llvm::Optional<bool> getSwiftObjCMembers() const {
+ return SwiftObjCMembersSpecified ? llvm::Optional<bool>(SwiftObjCMembers)
+ : llvm::None;
+ }
+ void setSwiftObjCMembers(llvm::Optional<bool> Value) {
+ SwiftObjCMembersSpecified = Value.hasValue();
+ SwiftObjCMembers = Value.hasValue() ? *Value : false;
+ }
+
+ /// Strip off any information within the class information structure that is
+ /// module-local, such as 'audited' flags.
+ void stripModuleLocalInfo() {
+ HasDefaultNullability = false;
+ DefaultNullability = 0;
+ }
+
+ friend bool operator==(const ObjCContextInfo &, const ObjCContextInfo &);
+
+ ObjCContextInfo &operator|=(const ObjCContextInfo &RHS) {
+ // Merge inherited info.
+ static_cast<CommonTypeInfo &>(*this) |= RHS;
+
+ // Merge nullability.
+ if (!getDefaultNullability())
+ if (auto Nullability = RHS.getDefaultNullability())
+ setDefaultNullability(*Nullability);
+
+ if (!SwiftImportAsNonGenericSpecified)
+ setSwiftImportAsNonGeneric(RHS.getSwiftImportAsNonGeneric());
+
+ if (!SwiftObjCMembersSpecified)
+ setSwiftObjCMembers(RHS.getSwiftObjCMembers());
+
+ HasDesignatedInits |= RHS.HasDesignatedInits;
+
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS);
+};
+
+inline bool operator==(const ObjCContextInfo &LHS, const ObjCContextInfo &RHS) {
+ return static_cast<const CommonTypeInfo &>(LHS) == RHS &&
+ LHS.getDefaultNullability() == RHS.getDefaultNullability() &&
+ LHS.HasDesignatedInits == RHS.HasDesignatedInits &&
+ LHS.getSwiftImportAsNonGeneric() == RHS.getSwiftImportAsNonGeneric() &&
+ LHS.getSwiftObjCMembers() == RHS.getSwiftObjCMembers();
+}
+
+inline bool operator!=(const ObjCContextInfo &LHS, const ObjCContextInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// API notes for a variable/property.
+class VariableInfo : public CommonEntityInfo {
+ /// Whether this property has been audited for nullability.
+ unsigned NullabilityAudited : 1;
+
+ /// The kind of nullability for this property. Only valid if the nullability
+ /// has been audited.
+ unsigned Nullable : 2;
+
+ /// The C type of the variable, as a string.
+ std::string Type;
+
+public:
+ VariableInfo() : CommonEntityInfo(), NullabilityAudited(false), Nullable(0) {}
+
+ llvm::Optional<NullabilityKind> getNullability() const {
+ return NullabilityAudited ? llvm::Optional<NullabilityKind>(
+ static_cast<NullabilityKind>(Nullable))
+ : llvm::None;
+ }
+
+ void setNullabilityAudited(NullabilityKind kind) {
+ NullabilityAudited = true;
+ Nullable = static_cast<unsigned>(kind);
+ }
+
+ const std::string &getType() const { return Type; }
+ void setType(const std::string &type) { Type = type; }
+
+ friend bool operator==(const VariableInfo &, const VariableInfo &);
+
+ VariableInfo &operator|=(const VariableInfo &RHS) {
+ static_cast<CommonEntityInfo &>(*this) |= RHS;
+
+ if (!NullabilityAudited && RHS.NullabilityAudited)
+ setNullabilityAudited(*RHS.getNullability());
+ if (Type.empty())
+ Type = RHS.Type;
+
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const VariableInfo &LHS, const VariableInfo &RHS) {
+ return static_cast<const CommonEntityInfo &>(LHS) == RHS &&
+ LHS.NullabilityAudited == RHS.NullabilityAudited &&
+ LHS.Nullable == RHS.Nullable && LHS.Type == RHS.Type;
+}
+
+inline bool operator!=(const VariableInfo &LHS, const VariableInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes data for an Objective-C property.
+class ObjCPropertyInfo : public VariableInfo {
+ unsigned SwiftImportAsAccessorsSpecified : 1;
+ unsigned SwiftImportAsAccessors : 1;
+
+public:
+ ObjCPropertyInfo()
+ : VariableInfo(), SwiftImportAsAccessorsSpecified(false),
+ SwiftImportAsAccessors(false) {}
+
+ llvm::Optional<bool> getSwiftImportAsAccessors() const {
+ return SwiftImportAsAccessorsSpecified
+ ? llvm::Optional<bool>(SwiftImportAsAccessors)
+ : llvm::None;
+ }
+ void setSwiftImportAsAccessors(llvm::Optional<bool> Value) {
+ SwiftImportAsAccessorsSpecified = Value.hasValue();
+ SwiftImportAsAccessors = Value.hasValue() ? *Value : false;
+ }
+
+ friend bool operator==(const ObjCPropertyInfo &, const ObjCPropertyInfo &);
+
+ /// Merge class-wide information into the given property.
+ ObjCPropertyInfo &operator|=(const ObjCContextInfo &RHS) {
+ static_cast<CommonEntityInfo &>(*this) |= RHS;
+
+ // Merge nullability.
+ if (!getNullability())
+ if (auto Nullable = RHS.getDefaultNullability())
+ setNullabilityAudited(*Nullable);
+
+ return *this;
+ }
+
+ ObjCPropertyInfo &operator|=(const ObjCPropertyInfo &RHS) {
+ static_cast<VariableInfo &>(*this) |= RHS;
+
+ if (!SwiftImportAsAccessorsSpecified)
+ setSwiftImportAsAccessors(RHS.getSwiftImportAsAccessors());
+
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const ObjCPropertyInfo &LHS,
+ const ObjCPropertyInfo &RHS) {
+ return static_cast<const VariableInfo &>(LHS) == RHS &&
+ LHS.getSwiftImportAsAccessors() == RHS.getSwiftImportAsAccessors();
+}
+
+inline bool operator!=(const ObjCPropertyInfo &LHS,
+ const ObjCPropertyInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes a function or method parameter.
+class ParamInfo : public VariableInfo {
+ /// Whether noescape was specified.
+ unsigned NoEscapeSpecified : 1;
+
+ /// Whether the this parameter has the 'noescape' attribute.
+ unsigned NoEscape : 1;
+
+ /// A biased RetainCountConventionKind, where 0 means "unspecified".
+ ///
+ /// Only relevant for out-parameters.
+ unsigned RawRetainCountConvention : 3;
+
+public:
+ ParamInfo()
+ : VariableInfo(), NoEscapeSpecified(false), NoEscape(false),
+ RawRetainCountConvention() {}
+
+ llvm::Optional<bool> isNoEscape() const {
+ if (!NoEscapeSpecified)
+ return llvm::None;
+ return NoEscape;
+ }
+ void setNoEscape(llvm::Optional<bool> Value) {
+ NoEscapeSpecified = Value.hasValue();
+ NoEscape = Value.hasValue() ? *Value : false;
+ }
+
+ llvm::Optional<RetainCountConventionKind> getRetainCountConvention() const {
+ if (!RawRetainCountConvention)
+ return llvm::None;
+ return static_cast<RetainCountConventionKind>(RawRetainCountConvention - 1);
+ }
+ void
+ setRetainCountConvention(llvm::Optional<RetainCountConventionKind> Value) {
+ RawRetainCountConvention =
+ Value.hasValue() ? static_cast<unsigned>(Value.getValue()) + 1 : 0;
+ assert(getRetainCountConvention() == Value && "bitfield too small");
+ }
+
+ ParamInfo &operator|=(const ParamInfo &RHS) {
+ static_cast<VariableInfo &>(*this) |= RHS;
+
+ if (!NoEscapeSpecified && RHS.NoEscapeSpecified) {
+ NoEscapeSpecified = true;
+ NoEscape = RHS.NoEscape;
+ }
+
+ if (!RawRetainCountConvention)
+ RawRetainCountConvention = RHS.RawRetainCountConvention;
+
+ return *this;
+ }
+
+ friend bool operator==(const ParamInfo &, const ParamInfo &);
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const ParamInfo &LHS, const ParamInfo &RHS) {
+ return static_cast<const VariableInfo &>(LHS) == RHS &&
+ LHS.NoEscapeSpecified == RHS.NoEscapeSpecified &&
+ LHS.NoEscape == RHS.NoEscape &&
+ LHS.RawRetainCountConvention == RHS.RawRetainCountConvention;
+}
+
+inline bool operator!=(const ParamInfo &LHS, const ParamInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// API notes for a function or method.
+class FunctionInfo : public CommonEntityInfo {
+private:
+ static constexpr const unsigned NullabilityKindMask = 0x3;
+ static constexpr const unsigned NullabilityKindSize = 2;
+
+ static constexpr const unsigned ReturnInfoIndex = 0;
+
+public:
+ // If yes, we consider all types to be non-nullable unless otherwise noted.
+ // If this flag is not set, the pointer types are considered to have
+ // unknown nullability.
+
+ /// Whether the signature has been audited with respect to nullability.
+ unsigned NullabilityAudited : 1;
+
+ /// Number of types whose nullability is encoded with the NullabilityPayload.
+ unsigned NumAdjustedNullable : 8;
+
+ /// A biased RetainCountConventionKind, where 0 means "unspecified".
+ unsigned RawRetainCountConvention : 3;
+
+ // NullabilityKindSize bits are used to encode the nullability. The info
+ // about the return type is stored at position 0, followed by the nullability
+ // of the parameters.
+
+ /// Stores the nullability of the return type and the parameters.
+ uint64_t NullabilityPayload = 0;
+
+ /// The result type of this function, as a C type.
+ std::string ResultType;
+
+ /// The function parameters.
+ std::vector<ParamInfo> Params;
+
+ FunctionInfo()
+ : CommonEntityInfo(), NullabilityAudited(false), NumAdjustedNullable(0),
+ RawRetainCountConvention() {}
+
+ static unsigned getMaxNullabilityIndex() {
+ return ((sizeof(NullabilityPayload) * CHAR_BIT) / NullabilityKindSize);
+ }
+
+ void addTypeInfo(unsigned index, NullabilityKind kind) {
+ assert(index <= getMaxNullabilityIndex());
+ assert(static_cast<unsigned>(kind) < NullabilityKindMask);
+
+ NullabilityAudited = true;
+ if (NumAdjustedNullable < index + 1)
+ NumAdjustedNullable = index + 1;
+
+ // Mask the bits.
+ NullabilityPayload &=
+ ~(NullabilityKindMask << (index * NullabilityKindSize));
+
+ // Set the value.
+ unsigned kindValue = (static_cast<unsigned>(kind))
+ << (index * NullabilityKindSize);
+ NullabilityPayload |= kindValue;
+ }
+
+ /// Adds the return type info.
+ void addReturnTypeInfo(NullabilityKind kind) {
+ addTypeInfo(ReturnInfoIndex, kind);
+ }
+
+ /// Adds the parameter type info.
+ void addParamTypeInfo(unsigned index, NullabilityKind kind) {
+ addTypeInfo(index + 1, kind);
+ }
+
+ NullabilityKind getParamTypeInfo(unsigned index) const {
+ return getTypeInfo(index + 1);
+ }
+
+ NullabilityKind getReturnTypeInfo() const { return getTypeInfo(0); }
+
+ llvm::Optional<RetainCountConventionKind> getRetainCountConvention() const {
+ if (!RawRetainCountConvention)
+ return llvm::None;
+ return static_cast<RetainCountConventionKind>(RawRetainCountConvention - 1);
+ }
+ void
+ setRetainCountConvention(llvm::Optional<RetainCountConventionKind> Value) {
+ RawRetainCountConvention =
+ Value.hasValue() ? static_cast<unsigned>(Value.getValue()) + 1 : 0;
+ assert(getRetainCountConvention() == Value && "bitfield too small");
+ }
+
+ friend bool operator==(const FunctionInfo &, const FunctionInfo &);
+
+private:
+ NullabilityKind getTypeInfo(unsigned index) const {
+ assert(NullabilityAudited &&
+ "Checking the type adjustment on non-audited method.");
+
+ // If we don't have info about this parameter, return the default.
+ if (index > NumAdjustedNullable)
+ return NullabilityKind::NonNull;
+ auto nullability = NullabilityPayload >> (index * NullabilityKindSize);
+ return static_cast<NullabilityKind>(nullability & NullabilityKindMask);
+ }
+
+public:
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const FunctionInfo &LHS, const FunctionInfo &RHS) {
+ return static_cast<const CommonEntityInfo &>(LHS) == RHS &&
+ LHS.NullabilityAudited == RHS.NullabilityAudited &&
+ LHS.NumAdjustedNullable == RHS.NumAdjustedNullable &&
+ LHS.NullabilityPayload == RHS.NullabilityPayload &&
+ LHS.ResultType == RHS.ResultType && LHS.Params == RHS.Params &&
+ LHS.RawRetainCountConvention == RHS.RawRetainCountConvention;
+}
+
+inline bool operator!=(const FunctionInfo &LHS, const FunctionInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes data for an Objective-C method.
+class ObjCMethodInfo : public FunctionInfo {
+public:
+ /// Whether this is a designated initializer of its class.
+ unsigned DesignatedInit : 1;
+
+ /// Whether this is a required initializer.
+ unsigned RequiredInit : 1;
+
+ ObjCMethodInfo()
+ : FunctionInfo(), DesignatedInit(false), RequiredInit(false) {}
+
+ friend bool operator==(const ObjCMethodInfo &, const ObjCMethodInfo &);
+
+ ObjCMethodInfo &operator|=(const ObjCContextInfo &RHS) {
+ // Merge Nullability.
+ if (!NullabilityAudited) {
+ if (auto Nullable = RHS.getDefaultNullability()) {
+ NullabilityAudited = true;
+ addTypeInfo(0, *Nullable);
+ }
+ }
+ return *this;
+ }
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS);
+};
+
+inline bool operator==(const ObjCMethodInfo &LHS, const ObjCMethodInfo &RHS) {
+ return static_cast<const FunctionInfo &>(LHS) == RHS &&
+ LHS.DesignatedInit == RHS.DesignatedInit &&
+ LHS.RequiredInit == RHS.RequiredInit;
+}
+
+inline bool operator!=(const ObjCMethodInfo &LHS, const ObjCMethodInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes data for a global variable.
+class GlobalVariableInfo : public VariableInfo {
+public:
+ GlobalVariableInfo() : VariableInfo() {}
+};
+
+/// Describes API notes data for a global function.
+class GlobalFunctionInfo : public FunctionInfo {
+public:
+ GlobalFunctionInfo() : FunctionInfo() {}
+};
+
+/// Describes API notes data for an enumerator.
+class EnumConstantInfo : public CommonEntityInfo {
+public:
+ EnumConstantInfo() : CommonEntityInfo() {}
+};
+
+/// Describes API notes data for a tag.
+class TagInfo : public CommonTypeInfo {
+ unsigned HasFlagEnum : 1;
+ unsigned IsFlagEnum : 1;
+
+public:
+ llvm::Optional<EnumExtensibilityKind> EnumExtensibility;
+
+ TagInfo() : CommonTypeInfo(), HasFlagEnum(0), IsFlagEnum(0) {}
+
+ llvm::Optional<bool> isFlagEnum() const {
+ if (HasFlagEnum)
+ return IsFlagEnum;
+ return llvm::None;
+ }
+ void setFlagEnum(llvm::Optional<bool> Value) {
+ HasFlagEnum = Value.hasValue();
+ IsFlagEnum = Value.hasValue() ? *Value : false;
+ }
+
+ TagInfo &operator|=(const TagInfo &RHS) {
+ static_cast<CommonTypeInfo &>(*this) |= RHS;
+
+ if (!HasFlagEnum && HasFlagEnum)
+ setFlagEnum(RHS.isFlagEnum());
+
+ if (!EnumExtensibility.hasValue())
+ EnumExtensibility = RHS.EnumExtensibility;
+
+ return *this;
+ }
+
+ friend bool operator==(const TagInfo &, const TagInfo &);
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS);
+};
+
+inline bool operator==(const TagInfo &LHS, const TagInfo &RHS) {
+ return static_cast<const CommonTypeInfo &>(LHS) == RHS &&
+ LHS.isFlagEnum() == RHS.isFlagEnum() &&
+ LHS.EnumExtensibility == RHS.EnumExtensibility;
+}
+
+inline bool operator!=(const TagInfo &LHS, const TagInfo &RHS) {
+ return !(LHS == RHS);
+}
+
+/// Describes API notes data for a typedef.
+class TypedefInfo : public CommonTypeInfo {
+public:
+ llvm::Optional<SwiftNewTypeKind> SwiftWrapper;
+
+ TypedefInfo() : CommonTypeInfo() {}
+
+ TypedefInfo &operator|=(const TypedefInfo &RHS) {
+ static_cast<CommonTypeInfo &>(*this) |= RHS;
+ if (!SwiftWrapper.hasValue())
+ SwiftWrapper = RHS.SwiftWrapper;
+ return *this;
+ }
+
+ friend bool operator==(const TypedefInfo &, const TypedefInfo &);
+
+ LLVM_DUMP_METHOD void dump(llvm::raw_ostream &OS) const;
+};
+
+inline bool operator==(const TypedefInfo &LHS, const TypedefInfo &RHS) {
+ return static_cast<const CommonTypeInfo &>(LHS) == RHS &&
+ LHS.SwiftWrapper == RHS.SwiftWrapper;
+}
+
+inline bool operator!=(const TypedefInfo &LHS, const TypedefInfo &RHS) {
+ return !(LHS == RHS);
+}
+} // namespace api_notes
+} // namespace clang
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h b/contrib/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h
index 76b65b2f6884..4da68a678be2 100644
--- a/contrib/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h
+++ b/contrib/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h
@@ -12,11 +12,13 @@
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include <memory>
namespace llvm {
class MemoryBuffer;
+ class MemoryBufferRef;
}
namespace clang {
@@ -55,6 +57,12 @@ public:
void applyMappings(PreprocessorOptions &PPOpts) const;
+ /// Iterate through all the mappings.
+ void forEachMapping(
+ llvm::function_ref<void(StringRef, StringRef)> CaptureFile,
+ llvm::function_ref<void(StringRef, const llvm::MemoryBufferRef &)>
+ CaptureBuffer) const;
+
void clear(StringRef outputDir = StringRef());
private:
diff --git a/contrib/llvm-project/clang/include/clang/AST/APValue.h b/contrib/llvm-project/clang/include/clang/AST/APValue.h
index cca92b5f8235..5f4ac02f53c9 100644
--- a/contrib/llvm-project/clang/include/clang/AST/APValue.h
+++ b/contrib/llvm-project/clang/include/clang/AST/APValue.h
@@ -13,14 +13,20 @@
#ifndef LLVM_CLANG_AST_APVALUE_H
#define LLVM_CLANG_AST_APVALUE_H
-#include "clang/Basic/FixedPoint.h"
#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/APFixedPoint.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APSInt.h"
+#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
+#include "llvm/Support/AlignOf.h"
namespace clang {
+namespace serialization {
+template <typename T> class BasicReaderBase;
+} // end namespace serialization
+
class AddrLabelExpr;
class ASTContext;
class CharUnits;
@@ -32,6 +38,7 @@ namespace clang {
struct PrintingPolicy;
class Type;
class ValueDecl;
+ class QualType;
/// Symbolic representation of typeid(T) for some type T.
class TypeInfoLValue {
@@ -113,6 +120,7 @@ namespace clang {
/// [APSInt] [APFloat], [Complex APSInt] [Complex APFloat], [Expr + Offset],
/// [Vector: N * APValue], [Array: N * APValue]
class APValue {
+ typedef llvm::APFixedPoint APFixedPoint;
typedef llvm::APSInt APSInt;
typedef llvm::APFloat APFloat;
public:
@@ -147,6 +155,8 @@ public:
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type);
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo);
+ void Profile(llvm::FoldingSetNodeID &ID) const;
+
template <class T>
bool is() const { return Ptr.is<T>(); }
@@ -167,11 +177,14 @@ public:
QualType getTypeInfoType() const;
QualType getDynamicAllocType() const;
+ QualType getType() const;
+
friend bool operator==(const LValueBase &LHS, const LValueBase &RHS);
friend bool operator!=(const LValueBase &LHS, const LValueBase &RHS) {
return !(LHS == RHS);
}
friend llvm::hash_code hash_value(const LValueBase &Base);
+ friend struct llvm::DenseMapInfo<LValueBase>;
private:
PtrTy Ptr;
@@ -199,8 +212,7 @@ public:
public:
LValuePathEntry() : Value() {}
- LValuePathEntry(BaseOrMemberType BaseOrMember)
- : Value{reinterpret_cast<uintptr_t>(BaseOrMember.getOpaqueValue())} {}
+ LValuePathEntry(BaseOrMemberType BaseOrMember);
static LValuePathEntry ArrayIndex(uint64_t Index) {
LValuePathEntry Result;
Result.Value = Index;
@@ -213,6 +225,8 @@ public:
}
uint64_t getAsArrayIndex() const { return Value; }
+ void Profile(llvm::FoldingSetNodeID &ID) const;
+
friend bool operator==(LValuePathEntry A, LValuePathEntry B) {
return A.Value == B.Value;
}
@@ -223,12 +237,22 @@ public:
return llvm::hash_value(A.Value);
}
};
+ class LValuePathSerializationHelper {
+ const void *ElemTy;
+
+ public:
+ ArrayRef<LValuePathEntry> Path;
+
+ LValuePathSerializationHelper(ArrayRef<LValuePathEntry>, QualType);
+ QualType getType();
+ };
struct NoLValuePath {};
struct UninitArray {};
struct UninitStruct {};
- friend class ASTReader;
- friend class ASTWriter;
+ template <typename Impl> friend class clang::serialization::BasicReaderBase;
+ friend class ASTImporter;
+ friend class ASTNodeImporter;
private:
ValueKind Kind;
@@ -302,7 +326,7 @@ public:
MakeComplexFloat(); setComplexFloat(std::move(R), std::move(I));
}
APValue(const APValue &RHS);
- APValue(APValue &&RHS) : Kind(None) { swap(RHS); }
+ APValue(APValue &&RHS);
APValue(LValueBase B, const CharUnits &O, NoLValuePath N,
bool IsNullPtr = false)
: Kind(None) {
@@ -337,6 +361,9 @@ public:
return Result;
}
+ APValue &operator=(const APValue &RHS);
+ APValue &operator=(APValue &&RHS);
+
~APValue() {
if (Kind != None && Kind != Indeterminate)
DestroyDataAndMakeUninit();
@@ -352,6 +379,11 @@ public:
/// Swaps the contents of this and the given APValue.
void swap(APValue &RHS);
+ /// profile this value. There is no guarantee that values of different
+ /// types will not produce the same profiled value, so the type should
+ /// typically also be profiled if it's not implied by the context.
+ void Profile(llvm::FoldingSetNodeID &ID) const;
+
ValueKind getKind() const { return Kind; }
bool isAbsent() const { return Kind == None; }
@@ -375,11 +407,14 @@ public:
void dump(raw_ostream &OS, const ASTContext &Context) const;
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const;
+ void printPretty(raw_ostream &OS, const PrintingPolicy &Policy, QualType Ty,
+ const ASTContext *Ctx = nullptr) const;
+
std::string getAsString(const ASTContext &Ctx, QualType Ty) const;
APSInt &getInt() {
assert(isInt() && "Invalid accessor");
- return *(APSInt*)(char*)Data.buffer;
+ return *(APSInt *)(char *)&Data;
}
const APSInt &getInt() const {
return const_cast<APValue*>(this)->getInt();
@@ -393,7 +428,7 @@ public:
APFloat &getFloat() {
assert(isFloat() && "Invalid accessor");
- return *(APFloat*)(char*)Data.buffer;
+ return *(APFloat *)(char *)&Data;
}
const APFloat &getFloat() const {
return const_cast<APValue*>(this)->getFloat();
@@ -401,7 +436,7 @@ public:
APFixedPoint &getFixedPoint() {
assert(isFixedPoint() && "Invalid accessor");
- return *(APFixedPoint *)(char *)Data.buffer;
+ return *(APFixedPoint *)(char *)&Data;
}
const APFixedPoint &getFixedPoint() const {
return const_cast<APValue *>(this)->getFixedPoint();
@@ -409,7 +444,7 @@ public:
APSInt &getComplexIntReal() {
assert(isComplexInt() && "Invalid accessor");
- return ((ComplexAPSInt*)(char*)Data.buffer)->Real;
+ return ((ComplexAPSInt *)(char *)&Data)->Real;
}
const APSInt &getComplexIntReal() const {
return const_cast<APValue*>(this)->getComplexIntReal();
@@ -417,7 +452,7 @@ public:
APSInt &getComplexIntImag() {
assert(isComplexInt() && "Invalid accessor");
- return ((ComplexAPSInt*)(char*)Data.buffer)->Imag;
+ return ((ComplexAPSInt *)(char *)&Data)->Imag;
}
const APSInt &getComplexIntImag() const {
return const_cast<APValue*>(this)->getComplexIntImag();
@@ -425,7 +460,7 @@ public:
APFloat &getComplexFloatReal() {
assert(isComplexFloat() && "Invalid accessor");
- return ((ComplexAPFloat*)(char*)Data.buffer)->Real;
+ return ((ComplexAPFloat *)(char *)&Data)->Real;
}
const APFloat &getComplexFloatReal() const {
return const_cast<APValue*>(this)->getComplexFloatReal();
@@ -433,7 +468,7 @@ public:
APFloat &getComplexFloatImag() {
assert(isComplexFloat() && "Invalid accessor");
- return ((ComplexAPFloat*)(char*)Data.buffer)->Imag;
+ return ((ComplexAPFloat *)(char *)&Data)->Imag;
}
const APFloat &getComplexFloatImag() const {
return const_cast<APValue*>(this)->getComplexFloatImag();
@@ -454,20 +489,20 @@ public:
APValue &getVectorElt(unsigned I) {
assert(isVector() && "Invalid accessor");
assert(I < getVectorLength() && "Index out of range");
- return ((Vec*)(char*)Data.buffer)->Elts[I];
+ return ((Vec *)(char *)&Data)->Elts[I];
}
const APValue &getVectorElt(unsigned I) const {
return const_cast<APValue*>(this)->getVectorElt(I);
}
unsigned getVectorLength() const {
assert(isVector() && "Invalid accessor");
- return ((const Vec*)(const void *)Data.buffer)->NumElts;
+ return ((const Vec *)(const void *)&Data)->NumElts;
}
APValue &getArrayInitializedElt(unsigned I) {
assert(isArray() && "Invalid accessor");
assert(I < getArrayInitializedElts() && "Index out of range");
- return ((Arr*)(char*)Data.buffer)->Elts[I];
+ return ((Arr *)(char *)&Data)->Elts[I];
}
const APValue &getArrayInitializedElt(unsigned I) const {
return const_cast<APValue*>(this)->getArrayInitializedElt(I);
@@ -478,35 +513,37 @@ public:
APValue &getArrayFiller() {
assert(isArray() && "Invalid accessor");
assert(hasArrayFiller() && "No array filler");
- return ((Arr*)(char*)Data.buffer)->Elts[getArrayInitializedElts()];
+ return ((Arr *)(char *)&Data)->Elts[getArrayInitializedElts()];
}
const APValue &getArrayFiller() const {
return const_cast<APValue*>(this)->getArrayFiller();
}
unsigned getArrayInitializedElts() const {
assert(isArray() && "Invalid accessor");
- return ((const Arr*)(const void *)Data.buffer)->NumElts;
+ return ((const Arr *)(const void *)&Data)->NumElts;
}
unsigned getArraySize() const {
assert(isArray() && "Invalid accessor");
- return ((const Arr*)(const void *)Data.buffer)->ArrSize;
+ return ((const Arr *)(const void *)&Data)->ArrSize;
}
unsigned getStructNumBases() const {
assert(isStruct() && "Invalid accessor");
- return ((const StructData*)(const char*)Data.buffer)->NumBases;
+ return ((const StructData *)(const char *)&Data)->NumBases;
}
unsigned getStructNumFields() const {
assert(isStruct() && "Invalid accessor");
- return ((const StructData*)(const char*)Data.buffer)->NumFields;
+ return ((const StructData *)(const char *)&Data)->NumFields;
}
APValue &getStructBase(unsigned i) {
assert(isStruct() && "Invalid accessor");
- return ((StructData*)(char*)Data.buffer)->Elts[i];
+ assert(i < getStructNumBases() && "base class index OOB");
+ return ((StructData *)(char *)&Data)->Elts[i];
}
APValue &getStructField(unsigned i) {
assert(isStruct() && "Invalid accessor");
- return ((StructData*)(char*)Data.buffer)->Elts[getStructNumBases() + i];
+ assert(i < getStructNumFields() && "field index OOB");
+ return ((StructData *)(char *)&Data)->Elts[getStructNumBases() + i];
}
const APValue &getStructBase(unsigned i) const {
return const_cast<APValue*>(this)->getStructBase(i);
@@ -517,11 +554,11 @@ public:
const FieldDecl *getUnionField() const {
assert(isUnion() && "Invalid accessor");
- return ((const UnionData*)(const char*)Data.buffer)->Field;
+ return ((const UnionData *)(const char *)&Data)->Field;
}
APValue &getUnionValue() {
assert(isUnion() && "Invalid accessor");
- return *((UnionData*)(char*)Data.buffer)->Value;
+ return *((UnionData *)(char *)&Data)->Value;
}
const APValue &getUnionValue() const {
return const_cast<APValue*>(this)->getUnionValue();
@@ -533,119 +570,125 @@ public:
const AddrLabelExpr* getAddrLabelDiffLHS() const {
assert(isAddrLabelDiff() && "Invalid accessor");
- return ((const AddrLabelDiffData*)(const char*)Data.buffer)->LHSExpr;
+ return ((const AddrLabelDiffData *)(const char *)&Data)->LHSExpr;
}
const AddrLabelExpr* getAddrLabelDiffRHS() const {
assert(isAddrLabelDiff() && "Invalid accessor");
- return ((const AddrLabelDiffData*)(const char*)Data.buffer)->RHSExpr;
+ return ((const AddrLabelDiffData *)(const char *)&Data)->RHSExpr;
}
void setInt(APSInt I) {
assert(isInt() && "Invalid accessor");
- *(APSInt *)(char *)Data.buffer = std::move(I);
+ *(APSInt *)(char *)&Data = std::move(I);
}
void setFloat(APFloat F) {
assert(isFloat() && "Invalid accessor");
- *(APFloat *)(char *)Data.buffer = std::move(F);
+ *(APFloat *)(char *)&Data = std::move(F);
}
void setFixedPoint(APFixedPoint FX) {
assert(isFixedPoint() && "Invalid accessor");
- *(APFixedPoint *)(char *)Data.buffer = std::move(FX);
+ *(APFixedPoint *)(char *)&Data = std::move(FX);
}
void setVector(const APValue *E, unsigned N) {
- assert(isVector() && "Invalid accessor");
- ((Vec*)(char*)Data.buffer)->Elts = new APValue[N];
- ((Vec*)(char*)Data.buffer)->NumElts = N;
+ MutableArrayRef<APValue> InternalElts = setVectorUninit(N);
for (unsigned i = 0; i != N; ++i)
- ((Vec*)(char*)Data.buffer)->Elts[i] = E[i];
+ InternalElts[i] = E[i];
}
void setComplexInt(APSInt R, APSInt I) {
assert(R.getBitWidth() == I.getBitWidth() &&
"Invalid complex int (type mismatch).");
assert(isComplexInt() && "Invalid accessor");
- ((ComplexAPSInt *)(char *)Data.buffer)->Real = std::move(R);
- ((ComplexAPSInt *)(char *)Data.buffer)->Imag = std::move(I);
+ ((ComplexAPSInt *)(char *)&Data)->Real = std::move(R);
+ ((ComplexAPSInt *)(char *)&Data)->Imag = std::move(I);
}
void setComplexFloat(APFloat R, APFloat I) {
assert(&R.getSemantics() == &I.getSemantics() &&
"Invalid complex float (type mismatch).");
assert(isComplexFloat() && "Invalid accessor");
- ((ComplexAPFloat *)(char *)Data.buffer)->Real = std::move(R);
- ((ComplexAPFloat *)(char *)Data.buffer)->Imag = std::move(I);
+ ((ComplexAPFloat *)(char *)&Data)->Real = std::move(R);
+ ((ComplexAPFloat *)(char *)&Data)->Imag = std::move(I);
}
void setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
bool IsNullPtr);
void setLValue(LValueBase B, const CharUnits &O,
ArrayRef<LValuePathEntry> Path, bool OnePastTheEnd,
bool IsNullPtr);
- void setUnion(const FieldDecl *Field, const APValue &Value) {
- assert(isUnion() && "Invalid accessor");
- ((UnionData*)(char*)Data.buffer)->Field = Field;
- *((UnionData*)(char*)Data.buffer)->Value = Value;
- }
+ void setUnion(const FieldDecl *Field, const APValue &Value);
void setAddrLabelDiff(const AddrLabelExpr* LHSExpr,
const AddrLabelExpr* RHSExpr) {
- ((AddrLabelDiffData*)(char*)Data.buffer)->LHSExpr = LHSExpr;
- ((AddrLabelDiffData*)(char*)Data.buffer)->RHSExpr = RHSExpr;
- }
-
- /// Assign by swapping from a copy of the RHS.
- APValue &operator=(APValue RHS) {
- swap(RHS);
- return *this;
+ ((AddrLabelDiffData *)(char *)&Data)->LHSExpr = LHSExpr;
+ ((AddrLabelDiffData *)(char *)&Data)->RHSExpr = RHSExpr;
}
private:
void DestroyDataAndMakeUninit();
void MakeInt() {
assert(isAbsent() && "Bad state change");
- new ((void*)Data.buffer) APSInt(1);
+ new ((void *)&Data) APSInt(1);
Kind = Int;
}
void MakeFloat() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) APFloat(0.0);
+ new ((void *)(char *)&Data) APFloat(0.0);
Kind = Float;
}
void MakeFixedPoint(APFixedPoint &&FX) {
assert(isAbsent() && "Bad state change");
- new ((void *)(char *)Data.buffer) APFixedPoint(std::move(FX));
+ new ((void *)(char *)&Data) APFixedPoint(std::move(FX));
Kind = FixedPoint;
}
void MakeVector() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) Vec();
+ new ((void *)(char *)&Data) Vec();
Kind = Vector;
}
void MakeComplexInt() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) ComplexAPSInt();
+ new ((void *)(char *)&Data) ComplexAPSInt();
Kind = ComplexInt;
}
void MakeComplexFloat() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) ComplexAPFloat();
+ new ((void *)(char *)&Data) ComplexAPFloat();
Kind = ComplexFloat;
}
void MakeLValue();
void MakeArray(unsigned InitElts, unsigned Size);
void MakeStruct(unsigned B, unsigned M) {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) StructData(B, M);
+ new ((void *)(char *)&Data) StructData(B, M);
Kind = Struct;
}
void MakeUnion() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) UnionData();
+ new ((void *)(char *)&Data) UnionData();
Kind = Union;
}
void MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
ArrayRef<const CXXRecordDecl*> Path);
void MakeAddrLabelDiff() {
assert(isAbsent() && "Bad state change");
- new ((void*)(char*)Data.buffer) AddrLabelDiffData();
+ new ((void *)(char *)&Data) AddrLabelDiffData();
Kind = AddrLabelDiff;
}
+
+private:
+ /// The following functions are used as part of initialization, during
+ /// deserialization and importing. Reserve the space so that it can be
+ /// filled in by those steps.
+ MutableArrayRef<APValue> setVectorUninit(unsigned N) {
+ assert(isVector() && "Invalid accessor");
+ Vec *V = ((Vec *)(char *)&Data);
+ V->Elts = new APValue[N];
+ V->NumElts = N;
+ return {V->Elts, V->NumElts};
+ }
+ MutableArrayRef<LValuePathEntry>
+ setLValueUninit(LValueBase B, const CharUnits &O, unsigned Size,
+ bool OnePastTheEnd, bool IsNullPtr);
+ MutableArrayRef<const CXXRecordDecl *>
+ setMemberPointerUninit(const ValueDecl *Member, bool IsDerivedMember,
+ unsigned Size);
};
} // end namespace clang.
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTContext.h b/contrib/llvm-project/clang/include/clang/AST/ASTContext.h
index 3700d0101daf..ae69a68608b7 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTContext.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTContext.h
@@ -36,6 +36,7 @@
#include "clang/Basic/Linkage.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/ProfileList.h"
#include "clang/Basic/SanitizerBlacklist.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
@@ -43,6 +44,7 @@
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/MapVector.h"
@@ -73,6 +75,8 @@
namespace llvm {
+class APFixedPoint;
+class FixedPointSemantics;
struct fltSemantics;
template <typename T, unsigned N> class SmallPtrSet;
@@ -80,7 +84,6 @@ template <typename T, unsigned N> class SmallPtrSet;
namespace clang {
-class APFixedPoint;
class APValue;
class ASTMutationListener;
class ASTRecordLayout;
@@ -98,7 +101,6 @@ class ParentMapContext;
class DynTypedNode;
class DynTypedNodeList;
class Expr;
-class FixedPointSemantics;
class GlobalDecl;
class MangleContext;
class MangleNumberingContext;
@@ -170,6 +172,16 @@ struct TypeInfo {
: Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
};
+struct TypeInfoChars {
+ CharUnits Width;
+ CharUnits Align;
+ bool AlignIsRequired : 1;
+
+ TypeInfoChars() : AlignIsRequired(false) {}
+ TypeInfoChars(CharUnits Width, CharUnits Align, bool AlignIsRequired)
+ : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
+};
+
/// Holds long-lived AST nodes (such as types and decls) that can be
/// referred to throughout the semantic analysis of a file.
class ASTContext : public RefCountedBase<ASTContext> {
@@ -278,8 +290,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// Mapping from GUIDs to the corresponding MSGuidDecl.
mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
- /// Used to cleanups APValues stored in the AST.
- mutable llvm::SmallVector<APValue *, 0> APValueCleanups;
+ /// Mapping from APValues to the corresponding TemplateParamObjects.
+ mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
/// A cache mapping a string value to a StringLiteral object with the same
/// value.
@@ -526,6 +538,9 @@ private:
/// need them (like static local vars).
llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
+ /// Mapping the associated device lambda mangling number if present.
+ mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
+ DeviceLambdaManglingNumbers;
/// Mapping that stores parameterIndex values for ParmVarDecls when
/// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
@@ -555,6 +570,10 @@ private:
/// should be imbued with the XRay "always" or "never" attributes.
std::unique_ptr<XRayFunctionFilter> XRayFilter;
+ /// ProfileList object that is used by the profile instrumentation
+ /// to decide which entities should be instrumented.
+ std::unique_ptr<ProfileList> ProfList;
+
/// The allocator used to create AST objects.
///
/// AST objects are never destructed; rather, all memory associated with the
@@ -562,7 +581,7 @@ private:
mutable llvm::BumpPtrAllocator BumpAlloc;
/// Allocator for partial diagnostics.
- PartialDiagnostic::StorageAllocator DiagAllocator;
+ PartialDiagnostic::DiagStorageAllocator DiagAllocator;
/// The current C++ ABI.
std::unique_ptr<CXXABI> ABI;
@@ -641,7 +660,7 @@ public:
/// Return the total memory used for various side tables.
size_t getSideTableAllocatedMemory() const;
- PartialDiagnostic::StorageAllocator &getDiagAllocator() {
+ PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
return DiagAllocator;
}
@@ -664,6 +683,14 @@ public:
const LangOptions& getLangOpts() const { return LangOpts; }
+ // If this condition is false, typo correction must be performed eagerly
+ // rather than delayed in many places, as it makes use of dependent types.
+ // the condition is false for clang's C-only codepath, as it doesn't support
+ // dependent types yet.
+ bool isDependenceAllowed() const {
+ return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
+ }
+
const SanitizerBlacklist &getSanitizerBlacklist() const {
return *SanitizerBL;
}
@@ -672,6 +699,8 @@ public:
return *XRayFilter;
}
+ const ProfileList &getProfileList() const { return *ProfList; }
+
DiagnosticsEngine &getDiagnostics() const;
FullSourceLoc getFullLoc(SourceLocation Loc) const {
@@ -988,6 +1017,9 @@ public:
#define SVE_TYPE(Name, Id, SingletonId) \
CanQualType SingletonId;
#include "clang/Basic/AArch64SVEACLETypes.def"
+#define PPC_VECTOR_TYPE(Name, Id, Size) \
+ CanQualType Id##Ty;
+#include "clang/Basic/PPCTypes.def"
// Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
mutable QualType AutoDeductTy; // Deduction against 'auto'.
@@ -1000,6 +1032,9 @@ public:
// Implicitly-declared type 'struct _GUID'.
mutable TagDecl *MSGuidTagDecl = nullptr;
+ /// Keep track of CUDA/HIP static device variables referenced by host code.
+ llvm::DenseSet<const VarDecl *> CUDAStaticDeviceVarReferencedByHost;
+
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
SelectorTable &sels, Builtin::Context &builtins);
ASTContext(const ASTContext &) = delete;
@@ -1406,7 +1441,7 @@ public:
/// Return the unique reference to the type for the specified
/// typedef-name decl.
QualType getTypedefType(const TypedefNameDecl *Decl,
- QualType Canon = QualType()) const;
+ QualType Underlying = QualType()) const;
QualType getRecordType(const RecordDecl *Decl) const;
@@ -1981,9 +2016,9 @@ public:
unsigned char getFixedPointScale(QualType Ty) const;
unsigned char getFixedPointIBits(QualType Ty) const;
- FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
- APFixedPoint getFixedPointMax(QualType Ty) const;
- APFixedPoint getFixedPointMin(QualType Ty) const;
+ llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
+ llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
+ llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
DeclarationNameInfo getNameForTemplate(TemplateName Name,
SourceLocation NameLoc) const;
@@ -2022,6 +2057,10 @@ public:
GE_Missing_ucontext
};
+ QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
+ ASTContext::GetBuiltinTypeError &Error,
+ bool &RequireICE, bool AllowTypeModifiers) const;
+
/// Return the type for the specified builtin.
///
/// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
@@ -2054,6 +2093,15 @@ public:
/// types.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
+ /// Return true if the given types are an SVE builtin and a VectorType that
+ /// is a fixed-length representation of the SVE builtin for a specific
+ /// vector-length.
+ bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
+
+ /// Return true if the given vector types are lax-compatible SVE vector types,
+ /// false otherwise.
+ bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
+
/// Return true if the type has been explicitly qualified with ObjC ownership.
/// A type may be implicitly qualified with ownership under ObjC ARC, and in
/// some cases the compiler treats these differently.
@@ -2125,16 +2173,25 @@ public:
}
unsigned getTypeUnadjustedAlign(const Type *T) const;
- /// Return the ABI-specified alignment of a type, in bits, or 0 if
+ /// Return the alignment of a type, in bits, or 0 if
/// the type is incomplete and we cannot determine the alignment (for
- /// example, from alignment attributes).
- unsigned getTypeAlignIfKnown(QualType T) const;
+ /// example, from alignment attributes). The returned alignment is the
+ /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
+ /// ABI alignment.
+ unsigned getTypeAlignIfKnown(QualType T,
+ bool NeedsPreferredAlignment = false) const;
/// Return the ABI-specified alignment of a (complete) type \p T, in
/// characters.
CharUnits getTypeAlignInChars(QualType T) const;
CharUnits getTypeAlignInChars(const Type *T) const;
+ /// Return the PreferredAlignment of a (complete) type \p T, in
+ /// characters.
+ CharUnits getPreferredTypeAlignInChars(QualType T) const {
+ return toCharUnitsFromBits(getPreferredTypeAlign(T));
+ }
+
/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
/// in characters, before alignment adjustments. This method does not work on
/// incomplete types.
@@ -2143,10 +2200,10 @@ public:
// getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
// type is a record, its data size is returned.
- std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
+ TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
- std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
- std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
+ TypeInfoChars getTypeInfoInChars(const Type *T) const;
+ TypeInfoChars getTypeInfoInChars(QualType T) const;
/// Determine if the alignment the type has was required using an
/// alignment attribute.
@@ -2157,7 +2214,12 @@ public:
/// the current target, in bits.
///
/// This can be different than the ABI alignment in cases where it is
- /// beneficial for performance to overalign a data type.
+ /// beneficial for performance or backwards compatibility preserving to
+ /// overalign a data type. (Note: despite the name, the preferred alignment
+ /// is ABI-impacting, and not an optimization.)
+ unsigned getPreferredTypeAlign(QualType T) const {
+ return getPreferredTypeAlign(T.getTypePtr());
+ }
unsigned getPreferredTypeAlign(const Type *T) const;
/// Return the default alignment for __attribute__((aligned)) on
@@ -2250,6 +2312,10 @@ public:
const ObjCImplementationDecl *ID,
const ObjCIvarDecl *Ivar) const;
+ /// Find the 'this' offset for the member path in a pointer-to-member
+ /// APValue.
+ CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
+
bool isNearlyEmpty(const CXXRecordDecl *RD) const;
VTableContextBase *getVTableContext();
@@ -2345,12 +2411,10 @@ public:
return (*SuperTnullability == NullabilityKind::NonNull &&
*SubTnullability == NullabilityKind::Nullable);
}
- else {
- // For the return type, it's okay for the superclass method to specify
- // "nullable" and the subclass method specify "nonnull"
- return (*SuperTnullability == NullabilityKind::Nullable &&
- *SubTnullability == NullabilityKind::NonNull);
- }
+ // For the return type, it's okay for the superclass method to specify
+ // "nullable" and the subclass method specify "nonnull"
+ return (*SuperTnullability == NullabilityKind::Nullable &&
+ *SubTnullability == NullabilityKind::NonNull);
}
return true;
}
@@ -2830,6 +2894,11 @@ public:
/// GUID value.
MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
+ /// Return the template parameter object of the given type with the given
+ /// value.
+ TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
+ const APValue &V) const;
+
/// Parses the target attributes passed in, and returns only the ones that are
/// valid feature names.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
@@ -3025,13 +3094,12 @@ public:
};
struct SectionInfo {
- DeclaratorDecl *Decl;
+ NamedDecl *Decl;
SourceLocation PragmaSectionLocation;
int SectionFlags;
SectionInfo() = default;
- SectionInfo(DeclaratorDecl *Decl,
- SourceLocation PragmaSectionLocation,
+ SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
int SectionFlags)
: Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
SectionFlags(SectionFlags) {}
@@ -3042,6 +3110,12 @@ public:
/// Return a new OMPTraitInfo object owned by this context.
OMPTraitInfo &getNewOMPTraitInfo();
+ /// Whether a C++ static variable may be externalized.
+ bool mayExternalizeStaticVar(const Decl *D) const;
+
+ /// Whether a C++ static variable should be externalized.
+ bool shouldExternalizeStaticVar(const Decl *D) const;
+
private:
/// All OMPTraitInfo objects live in this collection, one per
/// `pragma omp [begin] declare variant` directive.
@@ -3049,8 +3123,8 @@ private:
};
/// Insertion operator for diagnostics.
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const ASTContext::SectionInfo &Section);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const ASTContext::SectionInfo &Section);
/// Utility function for constructing a nullary selector.
inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTFwd.h b/contrib/llvm-project/clang/include/clang/AST/ASTFwd.h
index 65319a19728b..649b57113424 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTFwd.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTFwd.h
@@ -27,9 +27,9 @@ class Type;
#include "clang/AST/TypeNodes.inc"
class CXXCtorInitializer;
class OMPClause;
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) class Class;
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
-
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) class Class;
+#include "llvm/Frontend/OpenMP/OMP.inc"
} // end namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTImporter.h b/contrib/llvm-project/clang/include/clang/AST/ASTImporter.h
index 205d7ec67754..a6d822ba2ea6 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTImporter.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTImporter.h
@@ -14,6 +14,7 @@
#ifndef LLVM_CLANG_AST_ASTIMPORTER_H
#define LLVM_CLANG_AST_ASTIMPORTER_H
+#include "clang/AST/APValue.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/ExprCXX.h"
@@ -503,6 +504,13 @@ class TypeSourceInfo;
/// "to" context, or the import error.
llvm::Expected<CXXBaseSpecifier *> Import(const CXXBaseSpecifier *FromSpec);
+ /// Import the given APValue from the "from" context into
+ /// the "to" context.
+ ///
+ /// \return the equivalent APValue in the "to" context or the import
+ /// error.
+ llvm::Expected<APValue> Import(const APValue &FromValue);
+
/// Import the definition of the given declaration, including all of
/// the declarations it contains.
LLVM_NODISCARD llvm::Error ImportDefinition(Decl *From);
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h b/contrib/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h
index 26656b7162b6..bb5b0c73f028 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h
@@ -82,8 +82,12 @@ public:
bool getDeserialize() const { return Deserialize; }
void SetTraversalKind(TraversalKind TK) { Traversal = TK; }
+ TraversalKind GetTraversalKind() const { return Traversal; }
void Visit(const Decl *D) {
+ if (Traversal == TK_IgnoreUnlessSpelledInSource && D->isImplicit())
+ return;
+
getNodeDelegate().AddChild([=] {
getNodeDelegate().Visit(D);
if (!D)
@@ -100,6 +104,14 @@ public:
// Decls within functions are visited by the body.
if (!isa<FunctionDecl>(*D) && !isa<ObjCMethodDecl>(*D)) {
+ if (Traversal != TK_AsIs) {
+ if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
+ auto SK = CTSD->getSpecializationKind();
+ if (SK == TSK_ExplicitInstantiationDeclaration ||
+ SK == TSK_ExplicitInstantiationDefinition)
+ return;
+ }
+ }
if (const auto *DC = dyn_cast<DeclContext>(D))
dumpDeclContext(DC);
}
@@ -114,9 +126,6 @@ public:
switch (Traversal) {
case TK_AsIs:
break;
- case TK_IgnoreImplicitCastsAndParentheses:
- S = E->IgnoreParenImpCasts();
- break;
case TK_IgnoreUnlessSpelledInSource:
S = E->IgnoreUnlessSpelledInSource();
break;
@@ -135,7 +144,9 @@ public:
if (isa<DeclStmt>(S) || isa<GenericSelectionExpr>(S))
return;
- if (isa<LambdaExpr>(S) && Traversal == TK_IgnoreUnlessSpelledInSource)
+ if (Traversal == TK_IgnoreUnlessSpelledInSource &&
+ isa<LambdaExpr, CXXForRangeStmt, CallExpr,
+ CXXRewrittenBinaryOperator>(S))
return;
for (const Stmt *SubStmt : S->children())
@@ -176,6 +187,8 @@ public:
}
void Visit(const CXXCtorInitializer *Init) {
+ if (Traversal == TK_IgnoreUnlessSpelledInSource && !Init->isWritten())
+ return;
getNodeDelegate().AddChild([=] {
getNodeDelegate().Visit(Init);
Visit(Init->getInit());
@@ -392,6 +405,9 @@ public:
if (const Expr *TRC = D->getTrailingRequiresClause())
Visit(TRC);
+ if (Traversal == TK_IgnoreUnlessSpelledInSource && D->isDefaulted())
+ return;
+
if (const auto *C = dyn_cast<CXXConstructorDecl>(D))
for (const auto *I : C->inits())
Visit(I);
@@ -408,6 +424,9 @@ public:
}
void VisitVarDecl(const VarDecl *D) {
+ if (Traversal == TK_IgnoreUnlessSpelledInSource && D->isCXXForRangeDecl())
+ return;
+
if (D->hasInit())
Visit(D->getInit());
}
@@ -481,8 +500,10 @@ public:
Visit(D->getTemplatedDecl());
- for (const auto *Child : D->specializations())
- dumpTemplateDeclSpecialization(Child);
+ if (Traversal == TK_AsIs) {
+ for (const auto *Child : D->specializations())
+ dumpTemplateDeclSpecialization(Child);
+ }
}
void VisitTypeAliasDecl(const TypeAliasDecl *D) {
@@ -543,9 +564,7 @@ public:
void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
if (const auto *TC = D->getTypeConstraint())
- if (TC->hasExplicitTemplateArgs())
- for (const auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
- dumpTemplateArgumentLoc(ArgLoc);
+ Visit(TC->getImmediatelyDeclaredConstraint());
if (D->hasDefaultArgument())
Visit(D->getDefaultArgument(), SourceRange(),
D->getDefaultArgStorage().getInheritedFrom(),
@@ -574,6 +593,12 @@ public:
Visit(D->getConstraintExpr());
}
+ void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *CSE) {
+ if (CSE->hasExplicitTemplateArgs())
+ for (const auto &ArgLoc : CSE->getTemplateArgsAsWritten()->arguments())
+ dumpTemplateArgumentLoc(ArgLoc);
+ }
+
void VisitUsingShadowDecl(const UsingShadowDecl *D) {
if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
Visit(TD->getTypeForDecl());
@@ -702,6 +727,35 @@ public:
Visit(CatchParam);
}
+ void VisitCXXForRangeStmt(const CXXForRangeStmt *Node) {
+ if (Traversal == TK_IgnoreUnlessSpelledInSource) {
+ Visit(Node->getInit());
+ Visit(Node->getLoopVariable());
+ Visit(Node->getRangeInit());
+ Visit(Node->getBody());
+ }
+ }
+
+ void VisitCallExpr(const CallExpr *Node) {
+ for (const auto *Child :
+ make_filter_range(Node->children(), [this](const Stmt *Child) {
+ if (Traversal != TK_IgnoreUnlessSpelledInSource)
+ return false;
+ return !isa<CXXDefaultArgExpr>(Child);
+ })) {
+ Visit(Child);
+ }
+ }
+
+ void VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *Node) {
+ if (Traversal == TK_IgnoreUnlessSpelledInSource) {
+ Visit(Node->getLHS());
+ Visit(Node->getRHS());
+ } else {
+ ConstStmtVisitor<Derived>::VisitCXXRewrittenBinaryOperator(Node);
+ }
+ }
+
void VisitExpressionTemplateArgument(const TemplateArgument &TA) {
Visit(TA.getAsExpr());
}
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h b/contrib/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h
index 36a42070fd28..c958a16aba21 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h
@@ -97,6 +97,13 @@ struct StructuralEquivalenceContext {
/// \c VisitedDecls members) and can cause faulty equivalent results.
bool IsEquivalent(QualType T1, QualType T2);
+ /// Determine whether the two statements are structurally equivalent.
+ /// Implementation functions (all static functions in
+ /// ASTStructuralEquivalence.cpp) must never call this function because that
+ /// will wreak havoc the internal state (\c DeclsToCheck and
+ /// \c VisitedDecls members) and can cause faulty equivalent results.
+ bool IsEquivalent(Stmt *S1, Stmt *S2);
+
/// Find the index of the given anonymous struct/union within its
/// context.
///
diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTTypeTraits.h b/contrib/llvm-project/clang/include/clang/AST/ASTTypeTraits.h
index 328b7bce6ba5..57195a9d6066 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ASTTypeTraits.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ASTTypeTraits.h
@@ -40,10 +40,6 @@ enum TraversalKind {
/// Will traverse all child nodes.
TK_AsIs,
- /// Will not traverse implicit casts and parentheses.
- /// Corresponds to Expr::IgnoreParenImpCasts()
- TK_IgnoreImplicitCastsAndParentheses,
-
/// Ignore AST nodes not written in the source
TK_IgnoreUnlessSpelledInSource
};
@@ -104,6 +100,8 @@ public:
static ASTNodeKind getMostDerivedCommonAncestor(ASTNodeKind Kind1,
ASTNodeKind Kind2);
+ ASTNodeKind getCladeKind() const;
+
/// Hooks for using ASTNodeKind as a key in a DenseMap.
struct DenseMapInfo {
// ASTNodeKind() is a good empty key because it is represented as a 0.
@@ -132,6 +130,7 @@ private:
enum NodeKindId {
NKI_None,
NKI_TemplateArgument,
+ NKI_TemplateArgumentLoc,
NKI_TemplateName,
NKI_NestedNameSpecifierLoc,
NKI_QualType,
@@ -150,8 +149,9 @@ private:
#define TYPE(DERIVED, BASE) NKI_##DERIVED##Type,
#include "clang/AST/TypeNodes.inc"
NKI_OMPClause,
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) NKI_##Class,
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) NKI_##Class,
+#include "llvm/Frontend/OpenMP/OMP.inc"
NKI_NumberOfKinds
};
@@ -191,6 +191,7 @@ private:
};
KIND_TO_KIND_ID(CXXCtorInitializer)
KIND_TO_KIND_ID(TemplateArgument)
+KIND_TO_KIND_ID(TemplateArgumentLoc)
KIND_TO_KIND_ID(TemplateName)
KIND_TO_KIND_ID(NestedNameSpecifier)
KIND_TO_KIND_ID(NestedNameSpecifierLoc)
@@ -207,8 +208,9 @@ KIND_TO_KIND_ID(CXXBaseSpecifier)
#include "clang/AST/StmtNodes.inc"
#define TYPE(DERIVED, BASE) KIND_TO_KIND_ID(DERIVED##Type)
#include "clang/AST/TypeNodes.inc"
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) KIND_TO_KIND_ID(Class)
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) KIND_TO_KIND_ID(Class)
+#include "llvm/Frontend/OpenMP/OMP.inc"
#undef KIND_TO_KIND_ID
inline raw_ostream &operator<<(raw_ostream &OS, ASTNodeKind K) {
@@ -248,9 +250,8 @@ public:
/// in the \c DynTypedNode, and the returned pointer points at
/// the storage inside DynTypedNode. For those nodes, do not
/// use the pointer outside the scope of the DynTypedNode.
- template <typename T>
- const T *get() const {
- return BaseConverter<T>::get(NodeKind, Storage.buffer);
+ template <typename T> const T *get() const {
+ return BaseConverter<T>::get(NodeKind, &Storage);
}
/// Retrieve the stored node as type \c T.
@@ -258,7 +259,7 @@ public:
/// Similar to \c get(), but asserts that the type is what we are expecting.
template <typename T>
const T &getUnchecked() const {
- return BaseConverter<T>::getUnchecked(NodeKind, Storage.buffer);
+ return BaseConverter<T>::getUnchecked(NodeKind, &Storage);
}
ASTNodeKind getNodeKind() const { return NodeKind; }
@@ -270,7 +271,7 @@ public:
/// method returns NULL.
const void *getMemoizationData() const {
return NodeKind.hasPointerIdentity()
- ? *reinterpret_cast<void *const *>(Storage.buffer)
+ ? *reinterpret_cast<void *const *>(&Storage)
: nullptr;
}
@@ -392,12 +393,12 @@ private:
/// Converter that uses dyn_cast<T> from a stored BaseT*.
template <typename T, typename BaseT> struct DynCastPtrConverter {
- static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T *get(ASTNodeKind NodeKind, const void *Storage) {
if (ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind))
return &getUnchecked(NodeKind, Storage);
return nullptr;
}
- static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T &getUnchecked(ASTNodeKind NodeKind, const void *Storage) {
assert(ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind));
return *cast<T>(static_cast<const BaseT *>(
*reinterpret_cast<const void *const *>(Storage)));
@@ -405,19 +406,19 @@ private:
static DynTypedNode create(const BaseT &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNode(Node);
- new (Result.Storage.buffer) const void *(&Node);
+ new (&Result.Storage) const void *(&Node);
return Result;
}
};
/// Converter that stores T* (by pointer).
template <typename T> struct PtrConverter {
- static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T *get(ASTNodeKind NodeKind, const void *Storage) {
if (ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind))
return &getUnchecked(NodeKind, Storage);
return nullptr;
}
- static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T &getUnchecked(ASTNodeKind NodeKind, const void *Storage) {
assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
return *static_cast<const T *>(
*reinterpret_cast<const void *const *>(Storage));
@@ -425,26 +426,26 @@ private:
static DynTypedNode create(const T &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
- new (Result.Storage.buffer) const void *(&Node);
+ new (&Result.Storage) const void *(&Node);
return Result;
}
};
/// Converter that stores T (by value).
template <typename T> struct ValueConverter {
- static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T *get(ASTNodeKind NodeKind, const void *Storage) {
if (ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind))
return reinterpret_cast<const T *>(Storage);
return nullptr;
}
- static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+ static const T &getUnchecked(ASTNodeKind NodeKind, const void *Storage) {
assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
return *reinterpret_cast<const T *>(Storage);
}
static DynTypedNode create(const T &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
- new (Result.Storage.buffer) T(Node);
+ new (&Result.Storage) T(Node);
return Result;
}
};
@@ -456,12 +457,13 @@ private:
/// Note that we can store \c Decls, \c Stmts, \c Types,
/// \c NestedNameSpecifiers and \c CXXCtorInitializer by pointer as they are
/// guaranteed to be unique pointers pointing to dedicated storage in the AST.
- /// \c QualTypes, \c NestedNameSpecifierLocs, \c TypeLocs and
- /// \c TemplateArguments on the other hand do not have storage or unique
- /// pointers and thus need to be stored by value.
+ /// \c QualTypes, \c NestedNameSpecifierLocs, \c TypeLocs,
+ /// \c TemplateArguments and \c TemplateArgumentLocs on the other hand do not
+ /// have storage or unique pointers and thus need to be stored by value.
llvm::AlignedCharArrayUnion<const void *, TemplateArgument,
- NestedNameSpecifierLoc, QualType,
- TypeLoc> Storage;
+ TemplateArgumentLoc, NestedNameSpecifierLoc,
+ QualType, TypeLoc>
+ Storage;
};
template <typename T>
@@ -497,6 +499,10 @@ struct DynTypedNode::BaseConverter<
TemplateArgument, void> : public ValueConverter<TemplateArgument> {};
template <>
+struct DynTypedNode::BaseConverter<TemplateArgumentLoc, void>
+ : public ValueConverter<TemplateArgumentLoc> {};
+
+template <>
struct DynTypedNode::BaseConverter<
TemplateName, void> : public ValueConverter<TemplateName> {};
@@ -527,20 +533,6 @@ template <typename T, typename EnablerT> struct DynTypedNode::BaseConverter {
}
};
-// Previously these types were defined in the clang::ast_type_traits namespace.
-// Provide typedefs so that legacy code can be fixed asynchronously.
-namespace ast_type_traits {
-using DynTypedNode = ::clang::DynTypedNode;
-using ASTNodeKind = ::clang::ASTNodeKind;
-using TraversalKind = ::clang::TraversalKind;
-
-constexpr TraversalKind TK_AsIs = ::clang::TK_AsIs;
-constexpr TraversalKind TK_IgnoreImplicitCastsAndParentheses =
- ::clang::TK_IgnoreImplicitCastsAndParentheses;
-constexpr TraversalKind TK_IgnoreUnlessSpelledInSource =
- ::clang::TK_IgnoreUnlessSpelledInSource;
-} // namespace ast_type_traits
-
} // end namespace clang
namespace llvm {
diff --git a/contrib/llvm-project/clang/include/clang/AST/AbstractBasicReader.h b/contrib/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
index d7b3a9da88ec..5505d661b44e 100644
--- a/contrib/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
+++ b/contrib/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
@@ -177,6 +177,40 @@ public:
return llvm::APInt(bitWidth, numWords, &data[0]);
}
+ llvm::FixedPointSemantics readFixedPointSemantics() {
+ unsigned width = asImpl().readUInt32();
+ unsigned scale = asImpl().readUInt32();
+ unsigned tmp = asImpl().readUInt32();
+ bool isSigned = tmp & 0x1;
+ bool isSaturated = tmp & 0x2;
+ bool hasUnsignedPadding = tmp & 0x4;
+ return llvm::FixedPointSemantics(width, scale, isSigned, isSaturated,
+ hasUnsignedPadding);
+ }
+
+ APValue::LValuePathSerializationHelper readLValuePathSerializationHelper(
+ SmallVectorImpl<APValue::LValuePathEntry> &path) {
+ auto elemTy = asImpl().readQualType();
+ unsigned pathLength = asImpl().readUInt32();
+ for (unsigned i = 0; i < pathLength; ++i) {
+ if (elemTy->template getAs<RecordType>()) {
+ unsigned int_ = asImpl().readUInt32();
+ Decl *decl = asImpl().template readDeclAs<Decl>();
+ if (auto *recordDecl = dyn_cast<CXXRecordDecl>(decl))
+ elemTy = getASTContext().getRecordType(recordDecl);
+ else
+ elemTy = cast<ValueDecl>(decl)->getType();
+ path.push_back(
+ APValue::LValuePathEntry(APValue::BaseOrMemberType(decl, int_)));
+ } else {
+ elemTy = getASTContext().getAsArrayType(elemTy)->getElementType();
+ path.push_back(
+ APValue::LValuePathEntry::ArrayIndex(asImpl().readUInt32()));
+ }
+ }
+ return APValue::LValuePathSerializationHelper(path, elemTy);
+ }
+
Qualifiers readQualifiers() {
static_assert(sizeof(Qualifiers().getAsOpaqueValue()) <= sizeof(uint32_t),
"update this if the value size changes");
diff --git a/contrib/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h b/contrib/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h
index 0a6730c86bbf..75aef734ba9b 100644
--- a/contrib/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h
+++ b/contrib/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h
@@ -9,6 +9,7 @@
#ifndef CLANG_AST_ABSTRACTBASICWRITER_H
#define CLANG_AST_ABSTRACTBASICWRITER_H
+#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
namespace clang {
@@ -121,6 +122,7 @@ template <class Impl>
class DataStreamBasicWriter : public BasicWriterBase<Impl> {
protected:
using BasicWriterBase<Impl>::asImpl;
+ DataStreamBasicWriter(ASTContext &ctx) : BasicWriterBase<Impl>(ctx) {}
public:
/// Implement property-find by ignoring it. We rely on properties being
@@ -163,6 +165,39 @@ public:
asImpl().writeUInt64(words[i]);
}
+ void writeFixedPointSemantics(const llvm::FixedPointSemantics &sema) {
+ asImpl().writeUInt32(sema.getWidth());
+ asImpl().writeUInt32(sema.getScale());
+ asImpl().writeUInt32(sema.isSigned() | sema.isSaturated() << 1 |
+ sema.hasUnsignedPadding() << 2);
+ }
+
+ void writeLValuePathSerializationHelper(
+ APValue::LValuePathSerializationHelper lvaluePath) {
+ ArrayRef<APValue::LValuePathEntry> path = lvaluePath.Path;
+ QualType elemTy = lvaluePath.getType();
+ asImpl().writeQualType(elemTy);
+ asImpl().writeUInt32(path.size());
+ auto &ctx = ((BasicWriterBase<Impl> *)this)->getASTContext();
+ for (auto elem : path) {
+ if (elemTy->getAs<RecordType>()) {
+ asImpl().writeUInt32(elem.getAsBaseOrMember().getInt());
+ const Decl *baseOrMember = elem.getAsBaseOrMember().getPointer();
+ if (const auto *recordDecl = dyn_cast<CXXRecordDecl>(baseOrMember)) {
+ asImpl().writeDeclRef(recordDecl);
+ elemTy = ctx.getRecordType(recordDecl);
+ } else {
+ const auto *valueDecl = cast<ValueDecl>(baseOrMember);
+ asImpl().writeDeclRef(valueDecl);
+ elemTy = valueDecl->getType();
+ }
+ } else {
+ asImpl().writeUInt32(elem.getAsArrayIndex());
+ elemTy = ctx.getAsArrayType(elemTy)->getElementType();
+ }
+ }
+ }
+
void writeQualifiers(Qualifiers value) {
static_assert(sizeof(value.getAsOpaqueValue()) <= sizeof(uint32_t),
"update this if the value size changes");
diff --git a/contrib/llvm-project/clang/include/clang/AST/Attr.h b/contrib/llvm-project/clang/include/clang/AST/Attr.h
index 1b457337d658..e453733ab92c 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Attr.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Attr.h
@@ -162,6 +162,21 @@ public:
}
};
+class DeclOrStmtAttr : public InheritableAttr {
+protected:
+ DeclOrStmtAttr(ASTContext &Context, const AttributeCommonInfo &CommonInfo,
+ attr::Kind AK, bool IsLateParsed,
+ bool InheritEvenIfAlreadyPresent)
+ : InheritableAttr(Context, CommonInfo, AK, IsLateParsed,
+ InheritEvenIfAlreadyPresent) {}
+
+public:
+ static bool classof(const Attr *A) {
+ return A->getKind() >= attr::FirstDeclOrStmtAttr &&
+ A->getKind() <= attr::LastDeclOrStmtAttr;
+ }
+};
+
class InheritableParamAttr : public InheritableAttr {
protected:
InheritableParamAttr(ASTContext &Context,
@@ -259,7 +274,10 @@ public:
/// Construct from a result from \c serialize.
static ParamIdx deserialize(SerialType S) {
- ParamIdx P(*reinterpret_cast<ParamIdx *>(&S));
+ // Using this two-step static_cast via void * instead of reinterpret_cast
+ // silences a -Wstrict-aliasing false positive from GCC7 and earlier.
+ void *ParamIdxPtr = static_cast<void *>(&S);
+ ParamIdx P(*static_cast<ParamIdx *>(ParamIdxPtr));
assert((!P.IsValid || P.Idx >= 1) && "valid Idx must be one-origin");
return P;
}
@@ -334,29 +352,28 @@ static_assert(sizeof(ParamIdx) == sizeof(ParamIdx::SerialType),
struct ParsedTargetAttr {
std::vector<std::string> Features;
StringRef Architecture;
+ StringRef Tune;
StringRef BranchProtection;
bool DuplicateArchitecture = false;
+ bool DuplicateTune = false;
bool operator ==(const ParsedTargetAttr &Other) const {
return DuplicateArchitecture == Other.DuplicateArchitecture &&
- Architecture == Other.Architecture && Features == Other.Features;
+ DuplicateTune == Other.DuplicateTune &&
+ Architecture == Other.Architecture &&
+ Tune == Other.Tune &&
+ BranchProtection == Other.BranchProtection &&
+ Features == Other.Features;
}
};
#include "clang/AST/Attrs.inc"
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const Attr *At) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const Attr *At) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(At),
DiagnosticsEngine::ak_attr);
return DB;
}
-
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const Attr *At) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(At),
- DiagnosticsEngine::ak_attr);
- return PD;
-}
} // end namespace clang
#endif
diff --git a/contrib/llvm-project/clang/include/clang/AST/CXXInheritance.h b/contrib/llvm-project/clang/include/clang/AST/CXXInheritance.h
index 8b1bcb367b3b..709f08bff82a 100644
--- a/contrib/llvm-project/clang/include/clang/AST/CXXInheritance.h
+++ b/contrib/llvm-project/clang/include/clang/AST/CXXInheritance.h
@@ -149,12 +149,6 @@ class CXXBasePaths {
/// to help build the set of paths.
CXXBasePath ScratchPath;
- /// Array of the declarations that have been found. This
- /// array is constructed only if needed, e.g., to iterate over the
- /// results within LookupResult.
- std::unique_ptr<NamedDecl *[]> DeclsFound;
- unsigned NumDeclsFound = 0;
-
/// FindAmbiguities - Whether Sema::IsDerivedFrom should try find
/// ambiguous paths while it is looking for a path from a derived
/// type to a base type.
@@ -170,8 +164,6 @@ class CXXBasePaths {
/// is also recorded.
bool DetectVirtual;
- void ComputeDeclsFound();
-
bool lookupInBases(ASTContext &Context, const CXXRecordDecl *Record,
CXXRecordDecl::BaseMatchesCallback BaseMatches,
bool LookupInDependent = false);
@@ -198,8 +190,6 @@ public:
using decl_range = llvm::iterator_range<decl_iterator>;
- decl_range found_decls();
-
/// Determine whether the path from the most-derived type to the
/// given base type is ambiguous (i.e., it refers to multiple subobjects of
/// the same base type).
diff --git a/contrib/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def b/contrib/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
index 33e65f8ebf44..d15d6698860f 100644
--- a/contrib/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
+++ b/contrib/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
@@ -131,6 +131,10 @@ FIELD(HasUninitializedFields, 1, NO_MERGE)
/// constructors from a base class.
FIELD(HasInheritedConstructor, 1, NO_MERGE)
+/// True if there are any member using-declarations that inherit
+/// default constructors from a base class.
+FIELD(HasInheritedDefaultConstructor, 1, NO_MERGE)
+
/// True if there are any member using-declarations named
/// 'operator='.
FIELD(HasInheritedAssignment, 1, NO_MERGE)
@@ -210,6 +214,9 @@ FIELD(DefaultedDestructorIsConstexpr, 1, NO_MERGE)
/// member or base class of non-literal or volatile type.
FIELD(HasNonLiteralTypeFieldsOrBases, 1, NO_MERGE)
+/// True if this class is a structural type, assuming it is a literal type.
+FIELD(StructuralIfLiteral, 1, NO_MERGE)
+
/// Whether we have a C++11 user-provided default constructor (not
/// explicitly deleted or defaulted).
FIELD(UserProvidedDefaultConstructor, 1, NO_MERGE)
diff --git a/contrib/llvm-project/clang/include/clang/AST/CanonicalType.h b/contrib/llvm-project/clang/include/clang/AST/CanonicalType.h
index 488284713bce..15d7e9efc26a 100644
--- a/contrib/llvm-project/clang/include/clang/AST/CanonicalType.h
+++ b/contrib/llvm-project/clang/include/clang/AST/CanonicalType.h
@@ -215,8 +215,8 @@ inline CanQualType Type::getCanonicalTypeUnqualified() const {
return CanQualType::CreateUnsafe(getCanonicalTypeInternal());
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- CanQualType T) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ CanQualType T) {
DB << static_cast<QualType>(T);
return DB;
}
diff --git a/contrib/llvm-project/clang/include/clang/AST/CommentLexer.h b/contrib/llvm-project/clang/include/clang/AST/CommentLexer.h
index 138fdaca0ff6..94f778501e75 100644
--- a/contrib/llvm-project/clang/include/clang/AST/CommentLexer.h
+++ b/contrib/llvm-project/clang/include/clang/AST/CommentLexer.h
@@ -62,13 +62,6 @@ class Token {
/// The actual kind of the token.
tok::TokenKind Kind;
- /// Length of the token spelling in comment. Can be 0 for synthenized
- /// tokens.
- unsigned Length;
-
- /// Contains text value associated with a token.
- const char *TextPtr;
-
/// Integer value associated with a token.
///
/// If the token is a known command, contains command ID and TextPtr is
@@ -76,6 +69,13 @@ class Token {
/// contains the length of the string that starts at TextPtr.
unsigned IntVal;
+ /// Length of the token spelling in comment. Can be 0 for synthenized
+ /// tokens.
+ unsigned Length;
+
+ /// Contains text value associated with a token.
+ const char *TextPtr;
+
public:
SourceLocation getLocation() const LLVM_READONLY { return Loc; }
void setLocation(SourceLocation SL) { Loc = SL; }
@@ -232,7 +232,6 @@ private:
const char *const BufferStart;
const char *const BufferEnd;
- SourceLocation FileLoc;
const char *BufferPtr;
@@ -240,7 +239,14 @@ private:
/// to newline or BufferEnd, for C comments points to star in '*/'.
const char *CommentEnd;
- enum LexerCommentState {
+ SourceLocation FileLoc;
+
+ /// If true, the commands, html tags, etc will be parsed and reported as
+ /// separate tokens inside the comment body. If false, the comment text will
+ /// be parsed into text and newline tokens.
+ bool ParseCommands;
+
+ enum LexerCommentState : uint8_t {
LCS_BeforeComment,
LCS_InsideBCPLComment,
LCS_InsideCComment,
@@ -250,7 +256,7 @@ private:
/// Low-level lexer state, track if we are inside or outside of comment.
LexerCommentState CommentState;
- enum LexerState {
+ enum LexerState : uint8_t {
/// Lexing normal comment text
LS_Normal,
@@ -280,11 +286,6 @@ private:
/// command, including command marker.
SmallString<16> VerbatimBlockEndCommandName;
- /// If true, the commands, html tags, etc will be parsed and reported as
- /// separate tokens inside the comment body. If false, the comment text will
- /// be parsed into text and newline tokens.
- bool ParseCommands;
-
/// Given a character reference name (e.g., "lt"), return the character that
/// it stands for (e.g., "<").
StringRef resolveHTMLNamedCharacterReference(StringRef Name) const;
diff --git a/contrib/llvm-project/clang/include/clang/AST/ComputeDependence.h b/contrib/llvm-project/clang/include/clang/AST/ComputeDependence.h
index ac2daf9eb95a..04e8e2c7d2cc 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ComputeDependence.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ComputeDependence.h
@@ -70,6 +70,7 @@ class CXXPseudoDestructorExpr;
class OverloadExpr;
class DependentScopeDeclRefExpr;
class CXXConstructExpr;
+class CXXDefaultInitExpr;
class LambdaExpr;
class CXXUnresolvedConstructExpr;
class CXXDependentScopeMemberExpr;
@@ -106,7 +107,7 @@ class ObjCMessageExpr;
ExprDependence computeDependence(FullExpr *E);
ExprDependence computeDependence(OpaqueValueExpr *E);
ExprDependence computeDependence(ParenExpr *E);
-ExprDependence computeDependence(UnaryOperator *E);
+ExprDependence computeDependence(UnaryOperator *E, const ASTContext &Ctx);
ExprDependence computeDependence(UnaryExprOrTypeTraitExpr *E);
ExprDependence computeDependence(ArraySubscriptExpr *E);
ExprDependence computeDependence(MatrixSubscriptExpr *E);
@@ -153,6 +154,7 @@ ExprDependence computeDependence(OverloadExpr *E, bool KnownDependent,
bool KnownContainsUnexpandedParameterPack);
ExprDependence computeDependence(DependentScopeDeclRefExpr *E);
ExprDependence computeDependence(CXXConstructExpr *E);
+ExprDependence computeDependence(CXXDefaultInitExpr *E);
ExprDependence computeDependence(LambdaExpr *E,
bool ContainsUnexpandedParameterPack);
ExprDependence computeDependence(CXXUnresolvedConstructExpr *E);
diff --git a/contrib/llvm-project/clang/include/clang/AST/Decl.h b/contrib/llvm-project/clang/include/clang/AST/Decl.h
index 28faa2c1fc78..1c5827b9c3a4 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Decl.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Decl.h
@@ -265,10 +265,25 @@ public:
// FIXME: Deprecated, move clients to getName().
std::string getNameAsString() const { return Name.getAsString(); }
+ /// Pretty-print the unqualified name of this declaration. Can be overloaded
+ /// by derived classes to provide a more user-friendly name when appropriate.
virtual void printName(raw_ostream &os) const;
/// Get the actual, stored name of the declaration, which may be a special
/// name.
+ ///
+ /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
+ /// should be sent into the diagnostic instead of using the result of
+ /// \p getDeclName().
+ ///
+ /// A \p DeclarationName in a diagnostic will just be streamed to the output,
+ /// which will directly result in a call to \p DeclarationName::print.
+ ///
+ /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
+ /// \p DeclarationName::print, but with two customisation points along the
+ /// way (\p getNameForDiagnostic and \p printName). These are used to print
+ /// the template arguments if any, and to provide a user-friendly name for
+ /// some entities (such as unnamed variables and anonymous records).
DeclarationName getDeclName() const { return Name; }
/// Set the name of this declaration.
@@ -788,18 +803,11 @@ struct EvaluatedStmt {
/// Whether this statement is being evaluated.
bool IsEvaluating : 1;
- /// Whether we already checked whether this statement was an
- /// integral constant expression.
- bool CheckedICE : 1;
-
- /// Whether we are checking whether this statement is an
- /// integral constant expression.
- bool CheckingICE : 1;
-
- /// Whether this statement is an integral constant expression,
- /// or in C++11, whether the statement is a constant expression. Only
- /// valid if CheckedICE is true.
- bool IsICE : 1;
+ /// Whether this variable is known to have constant initialization. This is
+ /// currently only computed in C++, for static / thread storage duration
+ /// variables that might have constant initialization and for variables that
+ /// are usable in constant expressions.
+ bool HasConstantInitialization : 1;
/// Whether this variable is known to have constant destruction. That is,
/// whether running the destructor on the initial value is a side-effect
@@ -808,12 +816,18 @@ struct EvaluatedStmt {
/// non-trivial.
bool HasConstantDestruction : 1;
+ /// In C++98, whether the initializer is an ICE. This affects whether the
+ /// variable is usable in constant expressions.
+ bool HasICEInit : 1;
+ bool CheckedForICEInit : 1;
+
Stmt *Value;
APValue Evaluated;
EvaluatedStmt()
- : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
- CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
+ : WasEvaluated(false), IsEvaluating(false),
+ HasConstantInitialization(false), HasConstantDestruction(false),
+ HasICEInit(false), CheckedForICEInit(false) {}
};
/// Represents a variable declaration or definition.
@@ -1248,14 +1262,18 @@ public:
/// constant expression, according to the relevant language standard.
/// This only checks properties of the declaration, and does not check
/// whether the initializer is in fact a constant expression.
- bool mightBeUsableInConstantExpressions(ASTContext &C) const;
+ ///
+ /// This corresponds to C++20 [expr.const]p3's notion of a
+ /// "potentially-constant" variable.
+ bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
/// Determine whether this variable's value can be used in a
/// constant expression, according to the relevant language standard,
/// including checking whether it was initialized by a constant expression.
- bool isUsableInConstantExpressions(ASTContext &C) const;
+ bool isUsableInConstantExpressions(const ASTContext &C) const;
EvaluatedStmt *ensureEvaluatedStmt() const;
+ EvaluatedStmt *getEvaluatedStmt() const;
/// Attempt to evaluate the value of the initializer attached to this
/// declaration, and produce notes explaining why it cannot be evaluated or is
@@ -1272,25 +1290,29 @@ public:
/// Evaluate the destruction of this variable to determine if it constitutes
/// constant destruction.
///
- /// \pre isInitICE()
+ /// \pre hasConstantInitialization()
/// \return \c true if this variable has constant destruction, \c false if
/// not.
bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
- /// Determines whether it is already known whether the
- /// initializer is an integral constant expression or not.
- bool isInitKnownICE() const;
-
- /// Determines whether the initializer is an integral constant
- /// expression, or in C++11, whether the initializer is a constant
- /// expression.
+ /// Determine whether this variable has constant initialization.
///
- /// \pre isInitKnownICE()
- bool isInitICE() const;
-
- /// Determine whether the value of the initializer attached to this
- /// declaration is an integral constant expression.
- bool checkInitIsICE() const;
+ /// This is only set in two cases: when the language semantics require
+ /// constant initialization (globals in C and some globals in C++), and when
+ /// the variable is usable in constant expressions (constexpr, const int, and
+ /// reference variables in C++).
+ bool hasConstantInitialization() const;
+
+ /// Determine whether the initializer of this variable is an integer constant
+ /// expression. For use in C++98, where this affects whether the variable is
+ /// usable in constant expressions.
+ bool hasICEInitializer(const ASTContext &Context) const;
+
+ /// Evaluate the initializer of this variable to determine whether it's a
+ /// constant initializer. Should only be called once, after completing the
+ /// definition of the variable.
+ bool checkForConstantInitialization(
+ SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
void setInitStyle(InitializationStyle Style) {
VarDeclBits.InitStyle = Style;
@@ -1639,6 +1661,9 @@ public:
return ParmVarDeclBits.IsObjCMethodParam;
}
+ /// Determines whether this parameter is destroyed in the callee function.
+ bool isDestroyedInCallee() const;
+
unsigned getFunctionScopeDepth() const {
if (ParmVarDeclBits.IsObjCMethodParam) return 0;
return ParmVarDeclBits.ScopeDepthOrObjCQuals;
@@ -1956,7 +1981,7 @@ public:
SourceLocation NLoc, DeclarationName N, QualType T,
TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
bool hasWrittenPrototype = true,
- ConstexprSpecKind ConstexprKind = CSK_unspecified,
+ ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
Expr *TrailingRequiresClause = nullptr) {
DeclarationNameInfo NameInfo(N, NLoc);
return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
@@ -2028,7 +2053,14 @@ public:
///
/// The variant that accepts a FunctionDecl pointer will set that function
/// declaration to the declaration that is a definition (if there is one).
- bool isDefined(const FunctionDecl *&Definition) const;
+ ///
+ /// \param CheckForPendingFriendDefinition If \c true, also check for friend
+ /// declarations that were instantiataed from function definitions.
+ /// Such a declaration behaves as if it is a definition for the
+ /// purpose of redefinition checking, but isn't actually a "real"
+ /// definition until its body is instantiated.
+ bool isDefined(const FunctionDecl *&Definition,
+ bool CheckForPendingFriendDefinition = false) const;
bool isDefined() const {
const FunctionDecl* Definition;
@@ -2074,6 +2106,11 @@ public:
willHaveBody() || hasDefiningAttr();
}
+ /// Determine whether this specific declaration of the function is a friend
+ /// declaration that was instantiated from a function definition. Such
+ /// declarations behave like definitions in some contexts.
+ bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
+
/// Returns whether this specific declaration of the function has a body.
bool doesThisDeclarationHaveABody() const {
return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
@@ -2196,19 +2233,19 @@ public:
/// Whether this is a (C++11) constexpr function or constexpr constructor.
bool isConstexpr() const {
- return FunctionDeclBits.ConstexprKind != CSK_unspecified;
+ return getConstexprKind() != ConstexprSpecKind::Unspecified;
}
void setConstexprKind(ConstexprSpecKind CSK) {
- FunctionDeclBits.ConstexprKind = CSK;
+ FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
}
ConstexprSpecKind getConstexprKind() const {
return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
}
bool isConstexprSpecified() const {
- return FunctionDeclBits.ConstexprKind == CSK_constexpr;
+ return getConstexprKind() == ConstexprSpecKind::Constexpr;
}
bool isConsteval() const {
- return FunctionDeclBits.ConstexprKind == CSK_consteval;
+ return getConstexprKind() == ConstexprSpecKind::Consteval;
}
/// Whether the instantiation of this function is pending.
@@ -2231,10 +2268,6 @@ public:
bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
- /// Indicates the function uses Floating Point constrained intrinsics
- bool usesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
- void setUsesFPIntrin(bool Val) { FunctionDeclBits.UsesFPIntrin = Val; }
-
/// Whether this function has been deleted.
///
/// A function that is "deleted" (via the C++0x "= delete" syntax)
@@ -4498,14 +4531,8 @@ public:
/// Insertion operator for diagnostics. This allows sending NamedDecl's
/// into a diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const NamedDecl* ND) {
- DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
- DiagnosticsEngine::ak_nameddecl);
- return DB;
-}
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const NamedDecl* ND) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
+ const NamedDecl *ND) {
PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
DiagnosticsEngine::ak_nameddecl);
return PD;
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclBase.h b/contrib/llvm-project/clang/include/clang/AST/DeclBase.h
index af5959c4e9c2..bdad53dfb8a0 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DeclBase.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclBase.h
@@ -1246,8 +1246,7 @@ public:
using IteratorBase =
llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
- std::random_access_iterator_tag,
- NamedDecl *const>;
+ std::random_access_iterator_tag, NamedDecl *>;
class iterator : public IteratorBase {
value_type SingleElement;
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclCXX.h b/contrib/llvm-project/clang/include/clang/AST/DeclCXX.h
index 2b8d7e879a0a..89006b1cfa7f 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DeclCXX.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclCXX.h
@@ -744,9 +744,14 @@ public:
///
/// This value is used for lazy creation of default constructors.
bool needsImplicitDefaultConstructor() const {
- return !data().UserDeclaredConstructor &&
- !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
- (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
+ return (!data().UserDeclaredConstructor &&
+ !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
+ (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
+ // FIXME: Proposed fix to core wording issue: if a class inherits
+ // a default constructor and doesn't explicitly declare one, one
+ // is declared implicitly.
+ (data().HasInheritedDefaultConstructor &&
+ !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
}
/// Determine whether this class has any user-declared constructors.
@@ -1008,8 +1013,13 @@ public:
/// Retrieve the lambda static invoker, the address of which
/// is returned by the conversion operator, and the body of which
- /// is forwarded to the lambda call operator.
+ /// is forwarded to the lambda call operator. The version that does not
+ /// take a calling convention uses the 'default' calling convention for free
+ /// functions if the Lambda's calling convention was not modified via
+ /// attribute. Otherwise, it will return the calling convention specified for
+ /// the lambda.
CXXMethodDecl *getLambdaStaticInvoker() const;
+ CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
/// Retrieve the generic lambda's template parameter list.
/// Returns null if the class does not represent a lambda or a generic
@@ -1025,7 +1035,7 @@ public:
}
/// Set the captures for this lambda closure type.
- void setCaptures(ArrayRef<LambdaCapture> Captures);
+ void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
/// For a closure type, retrieve the mapping from captured
/// variables and \c this to the non-static data members that store the
@@ -1396,6 +1406,11 @@ public:
hasTrivialDefaultConstructor());
}
+ /// Determine whether this is a structural type.
+ bool isStructural() const {
+ return isLiteral() && data().StructuralIfLiteral;
+ }
+
/// If this record is an instantiation of a member class,
/// retrieves the member class from which it was instantiated.
///
@@ -1612,58 +1627,6 @@ public:
CXXBasePath &Path,
const CXXRecordDecl *BaseRecord);
- /// Base-class lookup callback that determines whether there exists
- /// a tag with the given name.
- ///
- /// This callback can be used with \c lookupInBases() to find tag members
- /// of the given name within a C++ class hierarchy.
- static bool FindTagMember(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path, DeclarationName Name);
-
- /// Base-class lookup callback that determines whether there exists
- /// a member with the given name.
- ///
- /// This callback can be used with \c lookupInBases() to find members
- /// of the given name within a C++ class hierarchy.
- static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path, DeclarationName Name);
-
- /// Base-class lookup callback that determines whether there exists
- /// a member with the given name.
- ///
- /// This callback can be used with \c lookupInBases() to find members
- /// of the given name within a C++ class hierarchy, including dependent
- /// classes.
- static bool
- FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path, DeclarationName Name);
-
- /// Base-class lookup callback that determines whether there exists
- /// an OpenMP declare reduction member with the given name.
- ///
- /// This callback can be used with \c lookupInBases() to find members
- /// of the given name within a C++ class hierarchy.
- static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path, DeclarationName Name);
-
- /// Base-class lookup callback that determines whether there exists
- /// an OpenMP declare mapper member with the given name.
- ///
- /// This callback can be used with \c lookupInBases() to find members
- /// of the given name within a C++ class hierarchy.
- static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path, DeclarationName Name);
-
- /// Base-class lookup callback that determines whether there exists
- /// a member with the given name that can be used in a nested-name-specifier.
- ///
- /// This callback can be used with \c lookupInBases() to find members of
- /// the given name within a C++ class hierarchy that can occur within
- /// nested-name-specifiers.
- static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
- CXXBasePath &Path,
- DeclarationName Name);
-
/// Retrieve the final overriders for each virtual member
/// function in the class hierarchy where this class is the
/// most-derived class in the class hierarchy.
@@ -1672,12 +1635,20 @@ public:
/// Get the indirect primary bases for this class.
void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
+ /// Determine whether this class has a member with the given name, possibly
+ /// in a non-dependent base class.
+ ///
+ /// No check for ambiguity is performed, so this should never be used when
+ /// implementing language semantics, but it may be appropriate for warnings,
+ /// static analysis, or similar.
+ bool hasMemberName(DeclarationName N) const;
+
/// Performs an imprecise lookup of a dependent name in this class.
///
/// This function does not follow strict semantic rules and should be used
/// only when lookup rules can be relaxed, e.g. indexing.
std::vector<const NamedDecl *>
- lookupDependentName(const DeclarationName &Name,
+ lookupDependentName(DeclarationName Name,
llvm::function_ref<bool(const NamedDecl *ND)> Filter);
/// Renders and displays an inheritance diagram
@@ -1764,6 +1735,12 @@ public:
getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
}
+ /// Set the device side mangling number.
+ void setDeviceLambdaManglingNumber(unsigned Num) const;
+
+ /// Retrieve the device side mangling number.
+ unsigned getDeviceLambdaManglingNumber() const;
+
/// Returns the inheritance model used for this record.
MSInheritanceModel getMSInheritanceModel() const;
@@ -1877,7 +1854,7 @@ private:
const DeclarationNameInfo &NameInfo, QualType T,
TypeSourceInfo *TInfo, SourceLocation EndLocation)
: FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
- SC_None, false, CSK_unspecified),
+ SC_None, false, ConstexprSpecKind::Unspecified),
ExplicitSpec(ES) {
if (EndLocation.isValid())
setRangeEnd(EndLocation);
@@ -4070,11 +4047,8 @@ public:
/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
/// into a diagnostic with <<.
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- AccessSpecifier AS);
-
-const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
- AccessSpecifier AS);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ AccessSpecifier AS);
} // namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclObjC.h b/contrib/llvm-project/clang/include/clang/AST/DeclObjC.h
index 5613ed8370c0..b1bce069920c 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DeclObjC.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclObjC.h
@@ -320,6 +320,13 @@ public:
return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
}
+ /// If this method is declared or implemented in a category, return
+ /// that category.
+ ObjCCategoryDecl *getCategory();
+ const ObjCCategoryDecl *getCategory() const {
+ return const_cast<ObjCMethodDecl*>(this)->getCategory();
+ }
+
Selector getSelector() const { return getDeclName().getObjCSelector(); }
QualType getReturnType() const { return MethodDeclType; }
@@ -649,20 +656,8 @@ public:
/// \endcode
class ObjCTypeParamList final
: private llvm::TrailingObjects<ObjCTypeParamList, ObjCTypeParamDecl *> {
- /// Stores the components of a SourceRange as a POD.
- struct PODSourceRange {
- unsigned Begin;
- unsigned End;
- };
-
- union {
- /// Location of the left and right angle brackets.
- PODSourceRange Brackets;
-
- // Used only for alignment.
- ObjCTypeParamDecl *AlignmentHack;
- };
-
+ /// Location of the left and right angle brackets.
+ SourceRange Brackets;
/// The number of parameters in the list, which are tail-allocated.
unsigned NumParams;
@@ -710,17 +705,9 @@ public:
return *(end() - 1);
}
- SourceLocation getLAngleLoc() const {
- return SourceLocation::getFromRawEncoding(Brackets.Begin);
- }
-
- SourceLocation getRAngleLoc() const {
- return SourceLocation::getFromRawEncoding(Brackets.End);
- }
-
- SourceRange getSourceRange() const {
- return SourceRange(getLAngleLoc(), getRAngleLoc());
- }
+ SourceLocation getLAngleLoc() const { return Brackets.getBegin(); }
+ SourceLocation getRAngleLoc() const { return Brackets.getEnd(); }
+ SourceRange getSourceRange() const { return Brackets; }
/// Gather the default set of type arguments to be substituted for
/// these type parameters when dealing with an unspecialized type.
@@ -2171,6 +2158,14 @@ public:
data().ReferencedProtocols.set(List, Num, Locs, C);
}
+ /// This is true iff the protocol is tagged with the
+ /// `objc_non_runtime_protocol` attribute.
+ bool isNonRuntimeProtocol() const;
+
+ /// Get the set of all protocols implied by this protocols inheritance
+ /// hierarchy.
+ void getImpliedProtocols(llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const;
+
ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
// Lookup a method. First, we search locally. If a method isn't
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclOpenMP.h b/contrib/llvm-project/clang/include/clang/AST/DeclOpenMP.h
index 154ecb977692..4aa5bde92e12 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DeclOpenMP.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclOpenMP.h
@@ -14,6 +14,7 @@
#ifndef LLVM_CLANG_AST_DECLOPENMP_H
#define LLVM_CLANG_AST_DECLOPENMP_H
+#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExternalASTSource.h"
@@ -24,6 +25,76 @@
namespace clang {
+/// This is a basic class for representing single OpenMP declarative directive.
+///
+template <typename U> class OMPDeclarativeDirective : public U {
+ friend class ASTDeclReader;
+ friend class ASTDeclWriter;
+
+ /// Get the clauses storage.
+ MutableArrayRef<OMPClause *> getClauses() {
+ if (!Data)
+ return llvm::None;
+ return Data->getClauses();
+ }
+
+protected:
+ /// Data, associated with the directive.
+ OMPChildren *Data = nullptr;
+
+ /// Build instance of directive.
+ template <typename... Params>
+ OMPDeclarativeDirective(Params &&... P) : U(std::forward<Params>(P)...) {}
+
+ template <typename T, typename... Params>
+ static T *createDirective(const ASTContext &C, DeclContext *DC,
+ ArrayRef<OMPClause *> Clauses, unsigned NumChildren,
+ Params &&... P) {
+ auto *Inst = new (C, DC, size(Clauses.size(), NumChildren))
+ T(DC, std::forward<Params>(P)...);
+ Inst->Data = OMPChildren::Create(Inst + 1, Clauses,
+ /*AssociatedStmt=*/nullptr, NumChildren);
+ Inst->Data->setClauses(Clauses);
+ return Inst;
+ }
+
+ template <typename T, typename... Params>
+ static T *createEmptyDirective(const ASTContext &C, unsigned ID,
+ unsigned NumClauses, unsigned NumChildren,
+ Params &&... P) {
+ auto *Inst = new (C, ID, size(NumClauses, NumChildren))
+ T(nullptr, std::forward<Params>(P)...);
+ Inst->Data = OMPChildren::CreateEmpty(
+ Inst + 1, NumClauses, /*HasAssociatedStmt=*/false, NumChildren);
+ return Inst;
+ }
+
+ static size_t size(unsigned NumClauses, unsigned NumChildren) {
+ return OMPChildren::size(NumClauses, /*HasAssociatedStmt=*/false,
+ NumChildren);
+ }
+
+public:
+ /// Get number of clauses.
+ unsigned getNumClauses() const {
+ if (!Data)
+ return 0;
+ return Data->getNumClauses();
+ }
+
+ /// Returns specified clause.
+ ///
+ /// \param I Number of clause.
+ ///
+ OMPClause *getClause(unsigned I) const { return clauses()[I]; }
+
+ ArrayRef<OMPClause *> clauses() const {
+ if (!Data)
+ return llvm::None;
+ return Data->getClauses();
+ }
+};
+
/// This represents '#pragma omp threadprivate ...' directive.
/// For example, in the following, both 'a' and 'A::b' are threadprivate:
///
@@ -36,25 +107,23 @@ namespace clang {
/// };
/// \endcode
///
-class OMPThreadPrivateDecl final
- : public Decl,
- private llvm::TrailingObjects<OMPThreadPrivateDecl, Expr *> {
- friend class ASTDeclReader;
- friend TrailingObjects;
-
- unsigned NumVars;
+class OMPThreadPrivateDecl final : public OMPDeclarativeDirective<Decl> {
+ friend class OMPDeclarativeDirective<Decl>;
virtual void anchor();
- OMPThreadPrivateDecl(Kind DK, DeclContext *DC, SourceLocation L) :
- Decl(DK, DC, L), NumVars(0) { }
+ OMPThreadPrivateDecl(DeclContext *DC = nullptr,
+ SourceLocation L = SourceLocation())
+ : OMPDeclarativeDirective<Decl>(OMPThreadPrivate, DC, L) {}
ArrayRef<const Expr *> getVars() const {
- return llvm::makeArrayRef(getTrailingObjects<Expr *>(), NumVars);
+ auto **Storage = reinterpret_cast<Expr **>(Data->getChildren().data());
+ return llvm::makeArrayRef(Storage, Data->getNumChildren());
}
MutableArrayRef<Expr *> getVars() {
- return MutableArrayRef<Expr *>(getTrailingObjects<Expr *>(), NumVars);
+ auto **Storage = reinterpret_cast<Expr **>(Data->getChildren().data());
+ return llvm::makeMutableArrayRef(Storage, Data->getNumChildren());
}
void setVars(ArrayRef<Expr *> VL);
@@ -71,8 +140,8 @@ public:
typedef llvm::iterator_range<varlist_iterator> varlist_range;
typedef llvm::iterator_range<varlist_const_iterator> varlist_const_range;
- unsigned varlist_size() const { return NumVars; }
- bool varlist_empty() const { return NumVars == 0; }
+ unsigned varlist_size() const { return Data->getNumChildren(); }
+ bool varlist_empty() const { return Data->getChildren().empty(); }
varlist_range varlists() {
return varlist_range(varlist_begin(), varlist_end());
@@ -94,7 +163,7 @@ public:
/// 'float':
///
/// \code
-/// #pragma omp declare reduction (foo : int,float : omp_out += omp_in) \
+/// #pragma omp declare reduction (foo : int,float : omp_out += omp_in)
/// initializer (omp_priv = 0)
/// \endcode
///
@@ -214,11 +283,11 @@ public:
/// \code
/// #pragma omp declare mapper(mid: struct vec v) map(v.len, v.data[0:N])
/// \endcode
-class OMPDeclareMapperDecl final : public ValueDecl, public DeclContext {
+class OMPDeclareMapperDecl final : public OMPDeclarativeDirective<ValueDecl>,
+ public DeclContext {
+ friend class OMPDeclarativeDirective<ValueDecl>;
friend class ASTDeclReader;
-
- /// Clauses associated with this mapper declaration
- MutableArrayRef<OMPClause *> Clauses;
+ friend class ASTDeclWriter;
/// Mapper variable, which is 'v' in the example above
Expr *MapperVarRef = nullptr;
@@ -230,42 +299,36 @@ class OMPDeclareMapperDecl final : public ValueDecl, public DeclContext {
void anchor() override;
- OMPDeclareMapperDecl(Kind DK, DeclContext *DC, SourceLocation L,
- DeclarationName Name, QualType Ty,
- DeclarationName VarName,
+ OMPDeclareMapperDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
+ QualType Ty, DeclarationName VarName,
OMPDeclareMapperDecl *PrevDeclInScope)
- : ValueDecl(DK, DC, L, Name, Ty), DeclContext(DK), VarName(VarName),
+ : OMPDeclarativeDirective<ValueDecl>(OMPDeclareMapper, DC, L, Name, Ty),
+ DeclContext(OMPDeclareMapper), VarName(VarName),
PrevDeclInScope(PrevDeclInScope) {}
void setPrevDeclInScope(OMPDeclareMapperDecl *Prev) {
PrevDeclInScope = Prev;
}
- /// Sets an array of clauses to this mapper declaration
- void setClauses(ArrayRef<OMPClause *> CL);
-
public:
/// Creates declare mapper node.
static OMPDeclareMapperDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L, DeclarationName Name,
QualType T, DeclarationName VarName,
+ ArrayRef<OMPClause *> Clauses,
OMPDeclareMapperDecl *PrevDeclInScope);
/// Creates deserialized declare mapper node.
static OMPDeclareMapperDecl *CreateDeserialized(ASTContext &C, unsigned ID,
unsigned N);
- /// Creates an array of clauses to this mapper declaration and intializes
- /// them.
- void CreateClauses(ASTContext &C, ArrayRef<OMPClause *> CL);
-
using clauselist_iterator = MutableArrayRef<OMPClause *>::iterator;
using clauselist_const_iterator = ArrayRef<const OMPClause *>::iterator;
using clauselist_range = llvm::iterator_range<clauselist_iterator>;
using clauselist_const_range =
llvm::iterator_range<clauselist_const_iterator>;
- unsigned clauselist_size() const { return Clauses.size(); }
- bool clauselist_empty() const { return Clauses.empty(); }
+ unsigned clauselist_size() const { return Data->getNumClauses(); }
+ bool clauselist_empty() const { return Data->getClauses().empty(); }
clauselist_range clauselists() {
return clauselist_range(clauselist_begin(), clauselist_end());
@@ -273,16 +336,24 @@ public:
clauselist_const_range clauselists() const {
return clauselist_const_range(clauselist_begin(), clauselist_end());
}
- clauselist_iterator clauselist_begin() { return Clauses.begin(); }
- clauselist_iterator clauselist_end() { return Clauses.end(); }
- clauselist_const_iterator clauselist_begin() const { return Clauses.begin(); }
- clauselist_const_iterator clauselist_end() const { return Clauses.end(); }
+ clauselist_iterator clauselist_begin() { return Data->getClauses().begin(); }
+ clauselist_iterator clauselist_end() { return Data->getClauses().end(); }
+ clauselist_const_iterator clauselist_begin() const {
+ return Data->getClauses().begin();
+ }
+ clauselist_const_iterator clauselist_end() const {
+ return Data->getClauses().end();
+ }
/// Get the variable declared in the mapper
- Expr *getMapperVarRef() { return MapperVarRef; }
- const Expr *getMapperVarRef() const { return MapperVarRef; }
+ Expr *getMapperVarRef() { return cast_or_null<Expr>(Data->getChildren()[0]); }
+ const Expr *getMapperVarRef() const {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
/// Set the variable declared in the mapper
- void setMapperVarRef(Expr *MapperVarRefE) { MapperVarRef = MapperVarRefE; }
+ void setMapperVarRef(Expr *MapperVarRefE) {
+ Data->getChildren()[0] = MapperVarRefE;
+ }
/// Get the name of the variable declared in the mapper
DeclarationName getVarName() { return VarName; }
@@ -342,34 +413,14 @@ public:
/// #pragma omp requires unified_address
/// \endcode
///
-class OMPRequiresDecl final
- : public Decl,
- private llvm::TrailingObjects<OMPRequiresDecl, OMPClause *> {
+class OMPRequiresDecl final : public OMPDeclarativeDirective<Decl> {
+ friend class OMPDeclarativeDirective<Decl>;
friend class ASTDeclReader;
- friend TrailingObjects;
-
- // Number of clauses associated with this requires declaration
- unsigned NumClauses = 0;
virtual void anchor();
- OMPRequiresDecl(Kind DK, DeclContext *DC, SourceLocation L)
- : Decl(DK, DC, L), NumClauses(0) {}
-
- /// Returns an array of immutable clauses associated with this requires
- /// declaration
- ArrayRef<const OMPClause *> getClauses() const {
- return llvm::makeArrayRef(getTrailingObjects<OMPClause *>(), NumClauses);
- }
-
- /// Returns an array of clauses associated with this requires declaration
- MutableArrayRef<OMPClause *> getClauses() {
- return MutableArrayRef<OMPClause *>(getTrailingObjects<OMPClause *>(),
- NumClauses);
- }
-
- /// Sets an array of clauses to this requires declaration
- void setClauses(ArrayRef<OMPClause *> CL);
+ OMPRequiresDecl(DeclContext *DC, SourceLocation L)
+ : OMPDeclarativeDirective<Decl>(OMPRequires, DC, L) {}
public:
/// Create requires node.
@@ -384,8 +435,8 @@ public:
using clauselist_range = llvm::iterator_range<clauselist_iterator>;
using clauselist_const_range = llvm::iterator_range<clauselist_const_iterator>;
- unsigned clauselist_size() const { return NumClauses; }
- bool clauselist_empty() const { return NumClauses == 0; }
+ unsigned clauselist_size() const { return Data->getNumClauses(); }
+ bool clauselist_empty() const { return Data->getClauses().empty(); }
clauselist_range clauselists() {
return clauselist_range(clauselist_begin(), clauselist_end());
@@ -393,13 +444,13 @@ public:
clauselist_const_range clauselists() const {
return clauselist_const_range(clauselist_begin(), clauselist_end());
}
- clauselist_iterator clauselist_begin() { return getClauses().begin(); }
- clauselist_iterator clauselist_end() { return getClauses().end(); }
+ clauselist_iterator clauselist_begin() { return Data->getClauses().begin(); }
+ clauselist_iterator clauselist_end() { return Data->getClauses().end(); }
clauselist_const_iterator clauselist_begin() const {
- return getClauses().begin();
+ return Data->getClauses().begin();
}
clauselist_const_iterator clauselist_end() const {
- return getClauses().end();
+ return Data->getClauses().end();
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -419,53 +470,27 @@ public:
/// };
/// \endcode
///
-class OMPAllocateDecl final
- : public Decl,
- private llvm::TrailingObjects<OMPAllocateDecl, Expr *, OMPClause *> {
+class OMPAllocateDecl final : public OMPDeclarativeDirective<Decl> {
+ friend class OMPDeclarativeDirective<Decl>;
friend class ASTDeclReader;
- friend TrailingObjects;
-
- /// Number of variable within the allocate directive.
- unsigned NumVars = 0;
- /// Number of clauses associated with the allocate directive.
- unsigned NumClauses = 0;
-
- size_t numTrailingObjects(OverloadToken<Expr *>) const {
- return NumVars;
- }
- size_t numTrailingObjects(OverloadToken<OMPClause *>) const {
- return NumClauses;
- }
virtual void anchor();
- OMPAllocateDecl(Kind DK, DeclContext *DC, SourceLocation L)
- : Decl(DK, DC, L) {}
+ OMPAllocateDecl(DeclContext *DC, SourceLocation L)
+ : OMPDeclarativeDirective<Decl>(OMPAllocate, DC, L) {}
ArrayRef<const Expr *> getVars() const {
- return llvm::makeArrayRef(getTrailingObjects<Expr *>(), NumVars);
+ auto **Storage = reinterpret_cast<Expr **>(Data->getChildren().data());
+ return llvm::makeArrayRef(Storage, Data->getNumChildren());
}
MutableArrayRef<Expr *> getVars() {
- return MutableArrayRef<Expr *>(getTrailingObjects<Expr *>(), NumVars);
+ auto **Storage = reinterpret_cast<Expr **>(Data->getChildren().data());
+ return llvm::makeMutableArrayRef(Storage, Data->getNumChildren());
}
void setVars(ArrayRef<Expr *> VL);
- /// Returns an array of immutable clauses associated with this directive.
- ArrayRef<OMPClause *> getClauses() const {
- return llvm::makeArrayRef(getTrailingObjects<OMPClause *>(), NumClauses);
- }
-
- /// Returns an array of clauses associated with this directive.
- MutableArrayRef<OMPClause *> getClauses() {
- return MutableArrayRef<OMPClause *>(getTrailingObjects<OMPClause *>(),
- NumClauses);
- }
-
- /// Sets an array of clauses to this requires declaration
- void setClauses(ArrayRef<OMPClause *> CL);
-
public:
static OMPAllocateDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L, ArrayRef<Expr *> VL,
@@ -482,11 +507,10 @@ public:
using clauselist_range = llvm::iterator_range<clauselist_iterator>;
using clauselist_const_range = llvm::iterator_range<clauselist_const_iterator>;
-
- unsigned varlist_size() const { return NumVars; }
- bool varlist_empty() const { return NumVars == 0; }
- unsigned clauselist_size() const { return NumClauses; }
- bool clauselist_empty() const { return NumClauses == 0; }
+ unsigned varlist_size() const { return Data->getNumChildren(); }
+ bool varlist_empty() const { return Data->getChildren().empty(); }
+ unsigned clauselist_size() const { return Data->getNumClauses(); }
+ bool clauselist_empty() const { return Data->getClauses().empty(); }
varlist_range varlists() {
return varlist_range(varlist_begin(), varlist_end());
@@ -505,13 +529,13 @@ public:
clauselist_const_range clauselists() const {
return clauselist_const_range(clauselist_begin(), clauselist_end());
}
- clauselist_iterator clauselist_begin() { return getClauses().begin(); }
- clauselist_iterator clauselist_end() { return getClauses().end(); }
+ clauselist_iterator clauselist_begin() { return Data->getClauses().begin(); }
+ clauselist_iterator clauselist_end() { return Data->getClauses().end(); }
clauselist_const_iterator clauselist_begin() const {
- return getClauses().begin();
+ return Data->getClauses().begin();
}
clauselist_const_iterator clauselist_end() const {
- return getClauses().end();
+ return Data->getClauses().end();
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h b/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h
index e9c4879b41e8..7fbf6294970e 100755
--- a/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h
@@ -77,7 +77,7 @@ class TemplateParameterList final
/// The number of template parameters in this template
/// parameter list.
- unsigned NumParams : 30;
+ unsigned NumParams : 29;
/// Whether this template parameter list contains an unexpanded parameter
/// pack.
@@ -204,10 +204,6 @@ public:
bool OmitTemplateKW = false) const;
void print(raw_ostream &Out, const ASTContext &Context,
const PrintingPolicy &Policy, bool OmitTemplateKW = false) const;
-
-public:
- // FIXME: workaround for MSVC 2013; remove when no longer needed
- using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
};
/// Stores a list of template parameters and the associated
@@ -2270,7 +2266,7 @@ protected:
/// Retrieve the set of partial specializations of this class
/// template.
llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
- getPartialSpecializations();
+ getPartialSpecializations() const;
ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
DeclarationName Name, TemplateParameterList *Params,
@@ -2367,7 +2363,7 @@ public:
/// Retrieve the partial specializations as an ordered list.
void getPartialSpecializations(
- SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
+ SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS) const;
/// Find a class template partial specialization with the given
/// type T.
@@ -3099,7 +3095,7 @@ protected:
/// Retrieve the set of partial specializations of this class
/// template.
llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
- getPartialSpecializations();
+ getPartialSpecializations() const;
VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
DeclarationName Name, TemplateParameterList *Params,
@@ -3195,7 +3191,7 @@ public:
/// Retrieve the partial specializations as an ordered list.
void getPartialSpecializations(
- SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
+ SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS) const;
/// Find a variable template partial specialization which was
/// instantiated
@@ -3230,7 +3226,7 @@ public:
static bool classofKind(Kind K) { return K == VarTemplate; }
};
-// \brief Declaration of a C++2a concept.
+/// Declaration of a C++2a concept.
class ConceptDecl : public TemplateDecl, public Mergeable<ConceptDecl> {
protected:
Expr *ConstraintExpr;
@@ -3259,6 +3255,9 @@ public:
return isa<TemplateTypeParmDecl>(getTemplateParameters()->getParam(0));
}
+ ConceptDecl *getCanonicalDecl() override { return getFirstDecl(); }
+ const ConceptDecl *getCanonicalDecl() const { return getFirstDecl(); }
+
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Concept; }
@@ -3268,6 +3267,74 @@ public:
friend class ASTDeclWriter;
};
+/// A template parameter object.
+///
+/// Template parameter objects represent values of class type used as template
+/// arguments. There is one template parameter object for each such distinct
+/// value used as a template argument across the program.
+///
+/// \code
+/// struct A { int x, y; };
+/// template<A> struct S;
+/// S<A{1, 2}> s1;
+/// S<A{1, 2}> s2; // same type, argument is same TemplateParamObjectDecl.
+/// \endcode
+class TemplateParamObjectDecl : public ValueDecl,
+ public Mergeable<TemplateParamObjectDecl>,
+ public llvm::FoldingSetNode {
+private:
+ /// The value of this template parameter object.
+ APValue Value;
+
+ TemplateParamObjectDecl(DeclContext *DC, QualType T, const APValue &V)
+ : ValueDecl(TemplateParamObject, DC, SourceLocation(), DeclarationName(),
+ T),
+ Value(V) {}
+
+ static TemplateParamObjectDecl *Create(const ASTContext &C, QualType T,
+ const APValue &V);
+ static TemplateParamObjectDecl *CreateDeserialized(ASTContext &C,
+ unsigned ID);
+
+ /// Only ASTContext::getTemplateParamObjectDecl and deserialization
+ /// create these.
+ friend class ASTContext;
+ friend class ASTReader;
+ friend class ASTDeclReader;
+
+public:
+ /// Print this template parameter object in a human-readable format.
+ void printName(llvm::raw_ostream &OS) const override;
+
+ /// Print this object as an equivalent expression.
+ void printAsExpr(llvm::raw_ostream &OS) const;
+
+ /// Print this object as an initializer suitable for a variable of the
+ /// object's type.
+ void printAsInit(llvm::raw_ostream &OS) const;
+
+ const APValue &getValue() const { return Value; }
+
+ static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
+ const APValue &V) {
+ ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
+ V.Profile(ID);
+ }
+ void Profile(llvm::FoldingSetNodeID &ID) {
+ Profile(ID, getType(), getValue());
+ }
+
+ TemplateParamObjectDecl *getCanonicalDecl() override {
+ return getFirstDecl();
+ }
+ const TemplateParamObjectDecl *getCanonicalDecl() const {
+ return getFirstDecl();
+ }
+
+ static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+ static bool classofKind(Kind K) { return K == TemplateParamObject; }
+};
+
inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
if (auto *PD = P.dyn_cast<TemplateTypeParmDecl *>())
return PD;
@@ -3286,6 +3353,36 @@ inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
: nullptr;
}
+/// Check whether the template parameter is a pack expansion, and if so,
+/// determine the number of parameters produced by that expansion. For instance:
+///
+/// \code
+/// template<typename ...Ts> struct A {
+/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
+/// };
+/// \endcode
+///
+/// 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) {
+ if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
+ if (TTP->isExpandedParameterPack())
+ return TTP->getNumExpansionParameters();
+ }
+
+ if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
+ if (NTTP->isExpandedParameterPack())
+ return NTTP->getNumExpansionTypes();
+ }
+
+ if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
+ if (TTP->isExpandedParameterPack())
+ return TTP->getNumExpansionTemplateParameters();
+ }
+
+ return None;
+}
+
} // namespace clang
#endif // LLVM_CLANG_AST_DECLTEMPLATE_H
diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclarationName.h b/contrib/llvm-project/clang/include/clang/AST/DeclarationName.h
index 82f6868e3a7e..3cb0a02ff49b 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DeclarationName.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DeclarationName.h
@@ -811,19 +811,10 @@ private:
SourceLocation getEndLocPrivate() const;
};
-/// Insertion operator for diagnostics. This allows sending DeclarationName's
-/// into a diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- DeclarationName N) {
- DB.AddTaggedVal(N.getAsOpaqueInteger(),
- DiagnosticsEngine::ak_declarationname);
- return DB;
-}
-
/// Insertion operator for partial diagnostics. This allows binding
/// DeclarationName's into a partial diagnostic with <<.
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- DeclarationName N) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
+ DeclarationName N) {
PD.AddTaggedVal(N.getAsOpaqueInteger(),
DiagnosticsEngine::ak_declarationname);
return PD;
@@ -857,6 +848,16 @@ struct DenseMapInfo<clang::DeclarationName> {
}
};
+template <> struct PointerLikeTypeTraits<clang::DeclarationName> {
+ static inline void *getAsVoidPointer(clang::DeclarationName P) {
+ return P.getAsOpaquePtr();
+ }
+ static inline clang::DeclarationName getFromVoidPointer(void *P) {
+ return clang::DeclarationName::getFromOpaquePtr(P);
+ }
+ static constexpr int NumLowBitsAvailable = 0;
+};
+
} // namespace llvm
// The definition of AssumedTemplateStorage is factored out of TemplateName to
diff --git a/contrib/llvm-project/clang/include/clang/AST/DependenceFlags.h b/contrib/llvm-project/clang/include/clang/AST/DependenceFlags.h
index 14a7ffaecb2b..ca96b65574bd 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DependenceFlags.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DependenceFlags.h
@@ -41,6 +41,7 @@ struct ExprDependenceScope {
TypeInstantiation = Type | Instantiation,
ValueInstantiation = Value | Instantiation,
TypeValueInstantiation = Type | Value | Instantiation,
+ ErrorDependent = Error | ValueInstantiation,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Error)
};
diff --git a/contrib/llvm-project/clang/include/clang/AST/DependentDiagnostic.h b/contrib/llvm-project/clang/include/clang/AST/DependentDiagnostic.h
index 0a98dec0c25e..18276d54d540 100644
--- a/contrib/llvm-project/clang/include/clang/AST/DependentDiagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/AST/DependentDiagnostic.h
@@ -48,7 +48,7 @@ public:
QualType BaseObjectType,
const PartialDiagnostic &PDiag) {
DependentDiagnostic *DD = Create(Context, Parent, PDiag);
- DD->AccessData.Loc = Loc.getRawEncoding();
+ DD->AccessData.Loc = Loc;
DD->AccessData.IsMember = IsMemberAccess;
DD->AccessData.Access = AS;
DD->AccessData.TargetDecl = TargetDecl;
@@ -73,7 +73,7 @@ public:
SourceLocation getAccessLoc() const {
assert(getKind() == Access);
- return SourceLocation::getFromRawEncoding(AccessData.Loc);
+ return AccessData.Loc;
}
NamedDecl *getAccessTarget() const {
@@ -100,8 +100,8 @@ private:
friend class DependentStoredDeclsMap;
DependentDiagnostic(const PartialDiagnostic &PDiag,
- PartialDiagnostic::Storage *Storage)
- : Diag(PDiag, Storage) {}
+ DiagnosticStorage *Storage)
+ : Diag(PDiag, Storage) {}
static DependentDiagnostic *Create(ASTContext &Context,
DeclContext *Parent,
@@ -112,7 +112,7 @@ private:
PartialDiagnostic Diag;
struct {
- unsigned Loc;
+ SourceLocation Loc;
unsigned Access : 2;
unsigned IsMember : 1;
NamedDecl *TargetDecl;
diff --git a/contrib/llvm-project/clang/include/clang/AST/Expr.h b/contrib/llvm-project/clang/include/clang/AST/Expr.h
index c13b97119285..52f8f18af205 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Expr.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Expr.h
@@ -24,7 +24,6 @@
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/Basic/CharInfo.h"
-#include "clang/Basic/FixedPoint.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SyncScope.h"
#include "clang/Basic/TypeTraits.h"
@@ -414,6 +413,10 @@ public:
return ClassifyImpl(Ctx, &Loc);
}
+ /// Returns the set of floating point options that apply to this expression.
+ /// Only meaningful for operations on floating point values.
+ FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
+
/// getValueKindForType - Given a formal return or parameter type,
/// give its value kind.
static ExprValueKind getValueKindForType(QualType T) {
@@ -522,16 +525,15 @@ public:
/// semantically correspond to a bool.
bool isKnownToHaveBooleanValue(bool Semantic = true) const;
- /// isIntegerConstantExpr - Return true if this expression is a valid integer
- /// constant expression, and, if so, return its value in Result. If not a
- /// valid i-c-e, return false and fill in Loc (if specified) with the location
- /// of the invalid expression.
+ /// isIntegerConstantExpr - Return the value if this expression is a valid
+ /// integer constant expression. If not a valid i-c-e, return None and fill
+ /// in Loc (if specified) with the location of the invalid expression.
///
/// Note: This does not perform the implicit conversions required by C++11
/// [expr.const]p5.
- bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
- SourceLocation *Loc = nullptr,
- bool isEvaluated = true) const;
+ Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx,
+ SourceLocation *Loc = nullptr,
+ bool isEvaluated = true) const;
bool isIntegerConstantExpr(const ASTContext &Ctx,
SourceLocation *Loc = nullptr) const;
@@ -708,13 +710,26 @@ public:
ArrayRef<const Expr*> Args,
const Expr *This = nullptr) const;
- /// Indicates how the constant expression will be used.
- enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
+ enum class ConstantExprKind {
+ /// An integer constant expression (an array bound, enumerator, case value,
+ /// bit-field width, or similar) or similar.
+ Normal,
+ /// A non-class template argument. Such a value is only used for mangling,
+ /// not for code generation, so can refer to dllimported functions.
+ NonClassTemplateArgument,
+ /// A class template argument. Such a value is used for code generation.
+ ClassTemplateArgument,
+ /// An immediate invocation. The destruction of the end result of this
+ /// evaluation is not part of the evaluation, but all other temporaries
+ /// are destroyed.
+ ImmediateInvocation,
+ };
- /// Evaluate an expression that is required to be a constant expression.
- bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
- const ASTContext &Ctx,
- bool InPlace = false) const;
+ /// Evaluate an expression that is required to be a constant expression. Does
+ /// not check the syntactic constraints for C and C++98 constant expressions.
+ bool EvaluateAsConstantExpr(
+ EvalResult &Result, const ASTContext &Ctx,
+ ConstantExprKind Kind = ConstantExprKind::Normal) const;
/// If the current Expr is a pointer, this will try to statically
/// determine the number of bytes available where the pointer is pointing.
@@ -869,9 +884,9 @@ public:
/// Skip conversion operators. If this Expr is a call to a conversion
/// operator, return the argument.
- Expr *IgnoreConversionOperator() LLVM_READONLY;
- const Expr *IgnoreConversionOperator() const {
- return const_cast<Expr *>(this)->IgnoreConversionOperator();
+ Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
+ const Expr *IgnoreConversionOperatorSingleStep() const {
+ return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
}
/// Skip past any parentheses and lvalue casts which might surround this
@@ -903,9 +918,9 @@ public:
/// * What IgnoreParens() skips
/// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
/// CK_UncheckedDerivedToBase and CK_NoOp)
- Expr *ignoreParenBaseCasts() LLVM_READONLY;
- const Expr *ignoreParenBaseCasts() const {
- return const_cast<Expr *>(this)->ignoreParenBaseCasts();
+ Expr *IgnoreParenBaseCasts() LLVM_READONLY;
+ const Expr *IgnoreParenBaseCasts() const {
+ return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
}
/// Determine whether this expression is a default function argument.
@@ -962,6 +977,13 @@ public:
T->getStmtClass() <= lastExprConstant;
}
};
+// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
+// Expr. Verify that we got it right.
+static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
+ llvm::detail::ConstantLog2<alignof(Expr)>::value,
+ "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
+
+using ConstantExprKind = Expr::ConstantExprKind;
//===----------------------------------------------------------------------===//
// Wrapper Expressions.
@@ -1261,7 +1283,7 @@ public:
ValueDecl *getDecl() { return D; }
const ValueDecl *getDecl() const { return D; }
- void setDecl(ValueDecl *NewD) { D = NewD; }
+ void setDecl(ValueDecl *NewD);
DeclarationNameInfo getNameInfo() const {
return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
@@ -1923,17 +1945,13 @@ public:
/// [C99 6.4.2.2] - A predefined identifier such as __func__.
class PredefinedExpr final
: public Expr,
- private llvm::TrailingObjects<PredefinedExpr, Stmt *, Expr *,
- TypeSourceInfo *> {
+ private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
friend class ASTStmtReader;
friend TrailingObjects;
// PredefinedExpr is optionally followed by a single trailing
// "Stmt *" for the predefined identifier. It is present if and only if
// hasFunctionName() is true and is always a "StringLiteral *".
- // It can also be followed by a Expr* in the case of a
- // __builtin_unique_stable_name with an expression, or TypeSourceInfo * if
- // __builtin_unique_stable_name with a type.
public:
enum IdentKind {
@@ -1946,18 +1964,12 @@ public:
PrettyFunction,
/// The same as PrettyFunction, except that the
/// 'virtual' keyword is omitted for virtual member functions.
- PrettyFunctionNoVirtual,
- UniqueStableNameType,
- UniqueStableNameExpr,
+ PrettyFunctionNoVirtual
};
private:
PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
StringLiteral *SL);
- PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
- TypeSourceInfo *Info);
- PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
- Expr *E);
explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
@@ -1970,39 +1982,10 @@ private:
*getTrailingObjects<Stmt *>() = SL;
}
- void setTypeSourceInfo(TypeSourceInfo *Info) {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType &&
- "TypeSourceInfo only valid for UniqueStableName of a Type");
- *getTrailingObjects<TypeSourceInfo *>() = Info;
- }
-
- void setExpr(Expr *E) {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr &&
- "TypeSourceInfo only valid for UniqueStableName of n Expression.");
- *getTrailingObjects<Expr *>() = E;
- }
-
- size_t numTrailingObjects(OverloadToken<Stmt *>) const {
- return hasFunctionName();
- }
-
- size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
- return getIdentKind() == UniqueStableNameType && !hasFunctionName();
- }
- size_t numTrailingObjects(OverloadToken<Expr *>) const {
- return getIdentKind() == UniqueStableNameExpr && !hasFunctionName();
- }
-
public:
/// Create a PredefinedExpr.
static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
QualType FNTy, IdentKind IK, StringLiteral *SL);
- static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
- QualType FNTy, IdentKind IK, StringLiteral *SL,
- TypeSourceInfo *Info);
- static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
- QualType FNTy, IdentKind IK, StringLiteral *SL,
- Expr *E);
/// Create an empty PredefinedExpr.
static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
@@ -2027,34 +2010,12 @@ public:
: nullptr;
}
- TypeSourceInfo *getTypeSourceInfo() {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType &&
- "TypeSourceInfo only valid for UniqueStableName of a Type");
- return *getTrailingObjects<TypeSourceInfo *>();
- }
-
- const TypeSourceInfo *getTypeSourceInfo() const {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameType &&
- "TypeSourceInfo only valid for UniqueStableName of a Type");
- return *getTrailingObjects<TypeSourceInfo *>();
- }
-
- Expr *getExpr() {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr &&
- "TypeSourceInfo only valid for UniqueStableName of n Expression.");
- return *getTrailingObjects<Expr *>();
- }
-
- const Expr *getExpr() const {
- assert(!hasFunctionName() && getIdentKind() == UniqueStableNameExpr &&
- "TypeSourceInfo only valid for UniqueStableName of n Expression.");
- return *getTrailingObjects<Expr *>();
+ static StringRef getIdentKindName(IdentKind IK);
+ StringRef getIdentKindName() const {
+ return getIdentKindName(getIdentKind());
}
- static StringRef getIdentKindName(IdentKind IK);
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
- static std::string ComputeName(ASTContext &Context, IdentKind IK,
- const QualType Ty);
SourceLocation getBeginLoc() const { return getLocation(); }
SourceLocation getEndLoc() const { return getLocation(); }
@@ -2273,12 +2234,12 @@ public:
/// Is FPFeatures in Trailing Storage?
bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
-protected:
- /// Get FPFeatures from trailing storage
+ /// Get FPFeatures from trailing storage.
FPOptionsOverride getStoredFPFeatures() const {
return getTrailingFPFeatures();
}
+protected:
/// Set FPFeatures in trailing storage, used only by Serialization
void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
@@ -2788,6 +2749,8 @@ class CallExpr : public Expr {
//
// * An array of getNumArgs() "Stmt *" for the argument expressions.
//
+ // * An optional of type FPOptionsOverride.
+ //
// Note that we store the offset in bytes from the this pointer to the start
// of the trailing objects. It would be perfectly possible to compute it
// based on the dynamic kind of the CallExpr. However 1.) we have plenty of
@@ -2809,6 +2772,15 @@ class CallExpr : public Expr {
/// this pointer to the trailing objects.
static unsigned offsetToTrailingObjects(StmtClass SC);
+ unsigned getSizeOfTrailingStmts() const {
+ return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
+ }
+
+ size_t getOffsetOfTrailingFPFeatures() const {
+ assert(hasStoredFPFeatures());
+ return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
+ }
+
public:
enum class ADLCallKind : bool { NotADL, UsesADL };
static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
@@ -2819,16 +2791,19 @@ protected:
/// allocated for the trailing objects.
CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
- SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL);
+ SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
+ unsigned MinNumArgs, ADLCallKind UsesADL);
/// Build an empty call expression, for deserialization.
CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
- EmptyShell Empty);
+ bool hasFPFeatures, EmptyShell Empty);
/// Return the size in bytes needed for the trailing objects.
/// Used by the derived classes to allocate the right amount of storage.
- static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) {
- return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *);
+ static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
+ bool HasFPFeatures) {
+ return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
+ HasFPFeatures * sizeof(FPOptionsOverride);
}
Stmt *getPreArg(unsigned I) {
@@ -2846,22 +2821,43 @@ protected:
unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
+ /// Return a pointer to the trailing FPOptions
+ FPOptionsOverride *getTrailingFPFeatures() {
+ assert(hasStoredFPFeatures());
+ return reinterpret_cast<FPOptionsOverride *>(
+ reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
+ getSizeOfTrailingStmts());
+ }
+ const FPOptionsOverride *getTrailingFPFeatures() const {
+ assert(hasStoredFPFeatures());
+ return reinterpret_cast<const FPOptionsOverride *>(
+ reinterpret_cast<const char *>(this) +
+ CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
+ }
+
public:
- /// Create a call expression. Fn is the callee expression, Args is the
- /// argument array, Ty is the type of the call expression (which is *not*
- /// the return type in general), VK is the value kind of the call expression
- /// (lvalue, rvalue, ...), and RParenLoc is the location of the right
- /// parenthese in the call expression. MinNumArgs specifies the minimum
- /// number of arguments. The actual number of arguments will be the greater
- /// of Args.size() and MinNumArgs. This is used in a few places to allocate
- /// enough storage for the default arguments. UsesADL specifies whether the
- /// callee was found through argument-dependent lookup.
+ /// Create a call expression.
+ /// \param Fn The callee expression,
+ /// \param Args The argument array,
+ /// \param Ty The type of the call expression (which is *not* the return
+ /// type in general),
+ /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
+ /// \param RParenLoc The location of the right parenthesis in the call
+ /// expression.
+ /// \param FPFeatures Floating-point features associated with the call,
+ /// \param MinNumArgs Specifies the minimum number of arguments. The actual
+ /// number of arguments will be the greater of Args.size()
+ /// and MinNumArgs. This is used in a few places to allocate
+ /// enough storage for the default arguments.
+ /// \param UsesADL Specifies whether the callee was found through
+ /// argument-dependent lookup.
///
/// Note that you can use CreateTemporary if you need a temporary call
/// expression on the stack.
static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
- SourceLocation RParenLoc, unsigned MinNumArgs = 0,
+ SourceLocation RParenLoc,
+ FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
ADLCallKind UsesADL = NotADL);
/// Create a temporary call expression with no arguments in the memory
@@ -2878,7 +2874,7 @@ public:
/// Create an empty call expression, for deserialization.
static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
- EmptyShell Empty);
+ bool HasFPFeatures, EmptyShell Empty);
Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
@@ -2892,6 +2888,8 @@ public:
}
bool usesADL() const { return getADLCallKind() == UsesADL; }
+ bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
+
Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
const Decl *getCalleeDecl() const {
return getCallee()->getReferencedDeclOfCallee();
@@ -2984,6 +2982,31 @@ public:
/// this function call.
unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
+ /// Get FPOptionsOverride from trailing storage.
+ FPOptionsOverride getStoredFPFeatures() const {
+ assert(hasStoredFPFeatures());
+ return *getTrailingFPFeatures();
+ }
+ /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
+ void setStoredFPFeatures(FPOptionsOverride F) {
+ assert(hasStoredFPFeatures());
+ *getTrailingFPFeatures() = F;
+ }
+
+ // Get the FP features status of this operator. Only meaningful for
+ // operations on floating point types.
+ FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
+ if (hasStoredFPFeatures())
+ return getStoredFPFeatures().applyOverrides(LO);
+ return FPOptions::defaultWithoutTrailingStorage(LO);
+ }
+
+ FPOptionsOverride getFPFeatures() const {
+ if (hasStoredFPFeatures())
+ return getStoredFPFeatures();
+ return FPOptionsOverride();
+ }
+
/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
/// of the callee. If not, return 0.
unsigned getBuiltinCallee() const;
@@ -3143,7 +3166,7 @@ public:
/// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
/// static data members), a CXXMethodDecl, or an EnumConstantDecl.
ValueDecl *getMemberDecl() const { return MemberDecl; }
- void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
+ void setMemberDecl(ValueDecl *D);
/// Retrieves the declaration found by lookup.
DeclAccessPair getFoundDecl() const {
@@ -3380,9 +3403,11 @@ class CastExpr : public Expr {
}
CXXBaseSpecifier **path_buffer();
+ friend class ASTStmtReader;
+
protected:
CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
- Expr *op, unsigned BasePathSize)
+ Expr *op, unsigned BasePathSize, bool HasFPFeatures)
: Expr(SC, ty, VK, OK_Ordinary), Op(op) {
CastExprBits.Kind = kind;
CastExprBits.PartOfExplicitCast = false;
@@ -3391,17 +3416,27 @@ protected:
"BasePathSize overflow!");
setDependence(computeDependence(this));
assert(CastConsistency());
+ CastExprBits.HasFPFeatures = HasFPFeatures;
}
/// Construct an empty cast.
- CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
- : Expr(SC, Empty) {
+ CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
+ bool HasFPFeatures)
+ : Expr(SC, Empty) {
CastExprBits.PartOfExplicitCast = false;
CastExprBits.BasePathSize = BasePathSize;
+ CastExprBits.HasFPFeatures = HasFPFeatures;
assert((CastExprBits.BasePathSize == BasePathSize) &&
"BasePathSize overflow!");
}
+ /// Return a pointer to the trailing FPOptions.
+ /// \pre hasStoredFPFeatures() == true
+ FPOptionsOverride *getTrailingFPFeatures();
+ const FPOptionsOverride *getTrailingFPFeatures() const {
+ return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
+ }
+
public:
CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
void setCastKind(CastKind K) { CastExprBits.Kind = K; }
@@ -3446,6 +3481,28 @@ public:
return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
}
+ bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
+
+ /// Get FPOptionsOverride from trailing storage.
+ FPOptionsOverride getStoredFPFeatures() const {
+ assert(hasStoredFPFeatures());
+ return *getTrailingFPFeatures();
+ }
+
+ // Get the FP features status of this operation. Only meaningful for
+ // operations on floating point types.
+ FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
+ if (hasStoredFPFeatures())
+ return getStoredFPFeatures().applyOverrides(LO);
+ return FPOptions::defaultWithoutTrailingStorage(LO);
+ }
+
+ FPOptionsOverride getFPFeatures() const {
+ if (hasStoredFPFeatures())
+ return getStoredFPFeatures();
+ return FPOptionsOverride();
+ }
+
static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
QualType opType);
static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
@@ -3483,21 +3540,35 @@ public:
/// @endcode
class ImplicitCastExpr final
: public CastExpr,
- private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
+ private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
+ FPOptionsOverride> {
ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
- unsigned BasePathLength, ExprValueKind VK)
- : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { }
+ unsigned BasePathLength, FPOptionsOverride FPO,
+ ExprValueKind VK)
+ : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
+ FPO.requiresTrailingStorage()) {
+ if (hasStoredFPFeatures())
+ *getTrailingFPFeatures() = FPO;
+ }
/// Construct an empty implicit cast.
- explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
- : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
+ explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
+ bool HasFPFeatures)
+ : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
+
+ unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
+ return path_size();
+ }
public:
enum OnStack_t { OnStack };
ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
- ExprValueKind VK)
- : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
+ ExprValueKind VK, FPOptionsOverride FPO)
+ : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
+ FPO.requiresTrailingStorage()) {
+ if (hasStoredFPFeatures())
+ *getTrailingFPFeatures() = FPO;
}
bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
@@ -3508,10 +3579,10 @@ public:
static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
CastKind Kind, Expr *Operand,
const CXXCastPath *BasePath,
- ExprValueKind Cat);
+ ExprValueKind Cat, FPOptionsOverride FPO);
static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
- unsigned PathSize);
+ unsigned PathSize, bool HasFPFeatures);
SourceLocation getBeginLoc() const LLVM_READONLY {
return getSubExpr()->getBeginLoc();
@@ -3552,12 +3623,14 @@ class ExplicitCastExpr : public CastExpr {
protected:
ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
CastKind kind, Expr *op, unsigned PathSize,
- TypeSourceInfo *writtenTy)
- : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
+ bool HasFPFeatures, TypeSourceInfo *writtenTy)
+ : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
+ TInfo(writtenTy) {}
/// Construct an empty explicit cast.
- ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
- : CastExpr(SC, Shell, PathSize) { }
+ ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
+ bool HasFPFeatures)
+ : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
public:
/// getTypeInfoAsWritten - Returns the type source info for the type
@@ -3580,29 +3653,38 @@ public:
/// (Type)expr. For example: @c (int)f.
class CStyleCastExpr final
: public ExplicitCastExpr,
- private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
+ private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
+ FPOptionsOverride> {
SourceLocation LPLoc; // the location of the left paren
SourceLocation RPLoc; // the location of the right paren
CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
- unsigned PathSize, TypeSourceInfo *writtenTy,
- SourceLocation l, SourceLocation r)
- : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
- writtenTy), LPLoc(l), RPLoc(r) {}
+ unsigned PathSize, FPOptionsOverride FPO,
+ TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
+ : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
+ FPO.requiresTrailingStorage(), writtenTy),
+ LPLoc(l), RPLoc(r) {
+ if (hasStoredFPFeatures())
+ *getTrailingFPFeatures() = FPO;
+ }
/// Construct an empty C-style explicit cast.
- explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
- : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
+ explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
+ bool HasFPFeatures)
+ : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
+
+ unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
+ return path_size();
+ }
public:
- static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
- ExprValueKind VK, CastKind K,
- Expr *Op, const CXXCastPath *BasePath,
- TypeSourceInfo *WrittenTy, SourceLocation L,
- SourceLocation R);
+ static CStyleCastExpr *
+ Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
+ Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
+ TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
- unsigned PathSize);
+ unsigned PathSize, bool HasFPFeatures);
SourceLocation getLParenLoc() const { return LPLoc; }
void setLParenLoc(SourceLocation L) { LPLoc = L; }
@@ -4690,6 +4772,13 @@ public:
setDependence(getDependence() | expr->getDependence());
}
+ /// Mark the semantic form of the InitListExpr as error when the semantic
+ /// analysis fails.
+ void markError() {
+ assert(isSemanticForm());
+ setDependence(getDependence() | ExprDependence::ErrorDependent);
+ }
+
/// Reserve space for some number of initializers.
void reserveInits(const ASTContext &C, unsigned NumInits);
@@ -4904,10 +4993,10 @@ public:
uintptr_t NameOrField;
/// The location of the '.' in the designated initializer.
- unsigned DotLoc;
+ SourceLocation DotLoc;
/// The location of the field name in the designated initializer.
- unsigned FieldLoc;
+ SourceLocation FieldLoc;
};
/// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
@@ -4916,12 +5005,12 @@ public:
/// initializer expression's list of subexpressions.
unsigned Index;
/// The location of the '[' starting the array range designator.
- unsigned LBracketLoc;
+ SourceLocation LBracketLoc;
/// The location of the ellipsis separating the start and end
/// indices. Only valid for GNU array-range designators.
- unsigned EllipsisLoc;
+ SourceLocation EllipsisLoc;
/// The location of the ']' terminating the array range designator.
- unsigned RBracketLoc;
+ SourceLocation RBracketLoc;
};
/// Represents a single C99 designator.
@@ -4953,29 +5042,32 @@ public:
Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
SourceLocation FieldLoc)
: Kind(FieldDesignator) {
+ new (&Field) DesignatedInitExpr::FieldDesignator;
Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
- Field.DotLoc = DotLoc.getRawEncoding();
- Field.FieldLoc = FieldLoc.getRawEncoding();
+ Field.DotLoc = DotLoc;
+ Field.FieldLoc = FieldLoc;
}
/// Initializes an array designator.
Designator(unsigned Index, SourceLocation LBracketLoc,
SourceLocation RBracketLoc)
: Kind(ArrayDesignator) {
+ new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
ArrayOrRange.Index = Index;
- ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
- ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
- ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
+ ArrayOrRange.LBracketLoc = LBracketLoc;
+ ArrayOrRange.EllipsisLoc = SourceLocation();
+ ArrayOrRange.RBracketLoc = RBracketLoc;
}
/// Initializes a GNU array-range designator.
Designator(unsigned Index, SourceLocation LBracketLoc,
SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
: Kind(ArrayRangeDesignator) {
+ new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
ArrayOrRange.Index = Index;
- ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
- ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
- ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
+ ArrayOrRange.LBracketLoc = LBracketLoc;
+ ArrayOrRange.EllipsisLoc = EllipsisLoc;
+ ArrayOrRange.RBracketLoc = RBracketLoc;
}
bool isFieldDesignator() const { return Kind == FieldDesignator; }
@@ -4999,30 +5091,30 @@ public:
SourceLocation getDotLoc() const {
assert(Kind == FieldDesignator && "Only valid on a field designator");
- return SourceLocation::getFromRawEncoding(Field.DotLoc);
+ return Field.DotLoc;
}
SourceLocation getFieldLoc() const {
assert(Kind == FieldDesignator && "Only valid on a field designator");
- return SourceLocation::getFromRawEncoding(Field.FieldLoc);
+ return Field.FieldLoc;
}
SourceLocation getLBracketLoc() const {
assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator");
- return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
+ return ArrayOrRange.LBracketLoc;
}
SourceLocation getRBracketLoc() const {
assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
"Only valid on an array or array-range designator");
- return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
+ return ArrayOrRange.RBracketLoc;
}
SourceLocation getEllipsisLoc() const {
assert(Kind == ArrayRangeDesignator &&
"Only valid on an array-range designator");
- return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
+ return ArrayOrRange.EllipsisLoc;
}
unsigned getFirstExprIndex() const {
@@ -6240,9 +6332,6 @@ public:
///
/// One can also reliably suppress all bogus errors on expressions containing
/// recovery expressions by examining results of Expr::containsErrors().
-///
-/// FIXME: RecoveryExpr is currently generated by default in C++ mode only, as
-/// dependence isn't handled properly on several C-only codepaths.
class RecoveryExpr final : public Expr,
private llvm::TrailingObjects<RecoveryExpr, Expr *> {
public:
diff --git a/contrib/llvm-project/clang/include/clang/AST/ExprCXX.h b/contrib/llvm-project/clang/include/clang/AST/ExprCXX.h
index 6f0b68479b9d..fbeeb4004f7d 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ExprCXX.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ExprCXX.h
@@ -84,7 +84,6 @@ class CXXOperatorCallExpr final : public CallExpr {
friend class ASTStmtWriter;
SourceRange Range;
- FPOptionsOverride Overrides;
// CXXOperatorCallExpr has some trailing objects belonging
// to CallExpr. See CallExpr for the details.
@@ -96,7 +95,7 @@ class CXXOperatorCallExpr final : public CallExpr {
SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
ADLCallKind UsesADL);
- CXXOperatorCallExpr(unsigned NumArgs, EmptyShell Empty);
+ CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
public:
static CXXOperatorCallExpr *
@@ -106,7 +105,8 @@ public:
ADLCallKind UsesADL = NotADL);
static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
- unsigned NumArgs, EmptyShell Empty);
+ unsigned NumArgs, bool HasFPFeatures,
+ EmptyShell Empty);
/// Returns the kind of overloaded operator that this expression refers to.
OverloadedOperatorKind getOperator() const {
@@ -164,11 +164,6 @@ public:
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXOperatorCallExprClass;
}
-
- // Set the FPFeatures status of this operator. Only meaningful for
- // operations on floating point types.
- void setFPFeatures(FPOptionsOverride F) { Overrides = F; }
- FPOptionsOverride getFPFeatures() const { return Overrides; }
};
/// Represents a call to a member function that
@@ -184,18 +179,20 @@ class CXXMemberCallExpr final : public CallExpr {
// to CallExpr. See CallExpr for the details.
CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
- ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs);
+ ExprValueKind VK, SourceLocation RP,
+ FPOptionsOverride FPOptions, unsigned MinNumArgs);
- CXXMemberCallExpr(unsigned NumArgs, EmptyShell Empty);
+ CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
public:
static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
ArrayRef<Expr *> Args, QualType Ty,
ExprValueKind VK, SourceLocation RP,
+ FPOptionsOverride FPFeatures,
unsigned MinNumArgs = 0);
static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
- EmptyShell Empty);
+ bool HasFPFeatures, EmptyShell Empty);
/// Retrieve the implicit object argument for the member call.
///
@@ -242,18 +239,21 @@ class CUDAKernelCallExpr final : public CallExpr {
CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
QualType Ty, ExprValueKind VK, SourceLocation RP,
- unsigned MinNumArgs);
+ FPOptionsOverride FPFeatures, unsigned MinNumArgs);
- CUDAKernelCallExpr(unsigned NumArgs, EmptyShell Empty);
+ CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
public:
static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
CallExpr *Config, ArrayRef<Expr *> Args,
QualType Ty, ExprValueKind VK,
- SourceLocation RP, unsigned MinNumArgs = 0);
+ SourceLocation RP,
+ FPOptionsOverride FPFeatures,
+ unsigned MinNumArgs = 0);
static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
- unsigned NumArgs, EmptyShell Empty);
+ unsigned NumArgs, bool HasFPFeatures,
+ EmptyShell Empty);
const CallExpr *getConfig() const {
return cast_or_null<CallExpr>(getPreArg(CONFIG));
@@ -320,6 +320,16 @@ public:
bool isReversed() const { return CXXRewrittenBinaryOperatorBits.IsReversed; }
BinaryOperatorKind getOperator() const { return getDecomposedForm().Opcode; }
+ BinaryOperatorKind getOpcode() const { return getOperator(); }
+ static StringRef getOpcodeStr(BinaryOperatorKind Op) {
+ return BinaryOperator::getOpcodeStr(Op);
+ }
+ StringRef getOpcodeStr() const {
+ return BinaryOperator::getOpcodeStr(getOpcode());
+ }
+ bool isComparisonOp() const { return true; }
+ bool isAssignmentOp() const { return false; }
+
const Expr *getLHS() const { return getDecomposedForm().LHS; }
const Expr *getRHS() const { return getDecomposedForm().RHS; }
@@ -374,16 +384,17 @@ private:
protected:
friend class ASTStmtReader;
- CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
- CastKind kind, Expr *op, unsigned PathSize,
+ CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK, CastKind kind,
+ Expr *op, unsigned PathSize, bool HasFPFeatures,
TypeSourceInfo *writtenTy, SourceLocation l,
- SourceLocation RParenLoc,
- SourceRange AngleBrackets)
- : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
- RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
+ SourceLocation RParenLoc, SourceRange AngleBrackets)
+ : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, HasFPFeatures,
+ writtenTy),
+ Loc(l), RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
- explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
- : ExplicitCastExpr(SC, Shell, PathSize) {}
+ explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
+ bool HasFPFeatures)
+ : ExplicitCastExpr(SC, Shell, PathSize, HasFPFeatures) {}
public:
const char *getCastName() const;
@@ -419,29 +430,39 @@ public:
/// \c static_cast<int>(1.0).
class CXXStaticCastExpr final
: public CXXNamedCastExpr,
- private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *> {
+ private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *,
+ FPOptionsOverride> {
CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
unsigned pathSize, TypeSourceInfo *writtenTy,
- SourceLocation l, SourceLocation RParenLoc,
- SourceRange AngleBrackets)
+ FPOptionsOverride FPO, SourceLocation l,
+ SourceLocation RParenLoc, SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
- writtenTy, l, RParenLoc, AngleBrackets) {}
+ FPO.requiresTrailingStorage(), writtenTy, l, RParenLoc,
+ AngleBrackets) {
+ if (hasStoredFPFeatures())
+ *getTrailingFPFeatures() = FPO;
+ }
+
+ explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize,
+ bool HasFPFeatures)
+ : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize,
+ HasFPFeatures) {}
- explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
- : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) {}
+ unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
+ return path_size();
+ }
public:
friend class CastExpr;
friend TrailingObjects;
- static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
- ExprValueKind VK, CastKind K, Expr *Op,
- const CXXCastPath *Path,
- TypeSourceInfo *Written, SourceLocation L,
- SourceLocation RParenLoc,
- SourceRange AngleBrackets);
+ static CXXStaticCastExpr *
+ Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
+ Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written,
+ FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc,
+ SourceRange AngleBrackets);
static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
- unsigned PathSize);
+ unsigned PathSize, bool hasFPFeatures);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXStaticCastExprClass;
@@ -456,15 +477,17 @@ public:
class CXXDynamicCastExpr final
: public CXXNamedCastExpr,
private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
- CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
- Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
+ CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind, Expr *op,
+ unsigned pathSize, TypeSourceInfo *writtenTy,
SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
- writtenTy, l, RParenLoc, AngleBrackets) {}
+ /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
+ AngleBrackets) {}
explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
- : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) {}
+ : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize,
+ /*HasFPFeatures*/ false) {}
public:
friend class CastExpr;
@@ -499,16 +522,17 @@ class CXXReinterpretCastExpr final
: public CXXNamedCastExpr,
private llvm::TrailingObjects<CXXReinterpretCastExpr,
CXXBaseSpecifier *> {
- CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
- Expr *op, unsigned pathSize,
- TypeSourceInfo *writtenTy, SourceLocation l,
- SourceLocation RParenLoc,
+ CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
+ unsigned pathSize, TypeSourceInfo *writtenTy,
+ SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
- pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
+ pathSize, /*HasFPFeatures*/ false, writtenTy, l,
+ RParenLoc, AngleBrackets) {}
CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
- : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) {}
+ : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize,
+ /*HasFPFeatures*/ false) {}
public:
friend class CastExpr;
@@ -541,11 +565,13 @@ class CXXConstCastExpr final
CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc, SourceRange AngleBrackets)
- : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
- 0, writtenTy, l, RParenLoc, AngleBrackets) {}
+ : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op, 0,
+ /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
+ AngleBrackets) {}
explicit CXXConstCastExpr(EmptyShell Empty)
- : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) {}
+ : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0,
+ /*HasFPFeatures*/ false) {}
public:
friend class CastExpr;
@@ -578,10 +604,12 @@ class CXXAddrspaceCastExpr final
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc, SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXAddrspaceCastExprClass, ty, VK, Kind, op, 0,
- writtenTy, l, RParenLoc, AngleBrackets) {}
+ /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
+ AngleBrackets) {}
explicit CXXAddrspaceCastExpr(EmptyShell Empty)
- : CXXNamedCastExpr(CXXAddrspaceCastExprClass, Empty, 0) {}
+ : CXXNamedCastExpr(CXXAddrspaceCastExprClass, Empty, 0,
+ /*HasFPFeatures*/ false) {}
public:
friend class CastExpr;
@@ -619,18 +647,20 @@ class UserDefinedLiteral final : public CallExpr {
UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
ExprValueKind VK, SourceLocation LitEndLoc,
- SourceLocation SuffixLoc);
+ SourceLocation SuffixLoc, FPOptionsOverride FPFeatures);
- UserDefinedLiteral(unsigned NumArgs, EmptyShell Empty);
+ UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
public:
static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
ArrayRef<Expr *> Args, QualType Ty,
ExprValueKind VK, SourceLocation LitEndLoc,
- SourceLocation SuffixLoc);
+ SourceLocation SuffixLoc,
+ FPOptionsOverride FPFeatures);
static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
- unsigned NumArgs, EmptyShell Empty);
+ unsigned NumArgs, bool HasFPOptions,
+ EmptyShell Empty);
/// The kind of literal operator which is invoked.
enum LiteralOperatorKind {
@@ -838,6 +868,10 @@ public:
/// evaluated, per C++11 [expr.typeid]p3.
bool isPotentiallyEvaluated() const;
+ /// Best-effort check if the expression operand refers to a most derived
+ /// object. This is not a strong guarantee.
+ bool isMostDerived(ASTContext &Context) const;
+
bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
/// Retrieves the type operand of this typeid() expression after
@@ -1691,34 +1725,43 @@ public:
/// \endcode
class CXXFunctionalCastExpr final
: public ExplicitCastExpr,
- private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *> {
+ private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *,
+ FPOptionsOverride> {
SourceLocation LParenLoc;
SourceLocation RParenLoc;
CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
- TypeSourceInfo *writtenTy,
- CastKind kind, Expr *castExpr, unsigned pathSize,
- SourceLocation lParenLoc, SourceLocation rParenLoc)
- : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
- castExpr, pathSize, writtenTy),
- LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
+ TypeSourceInfo *writtenTy, CastKind kind,
+ Expr *castExpr, unsigned pathSize,
+ FPOptionsOverride FPO, SourceLocation lParenLoc,
+ SourceLocation rParenLoc)
+ : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind, castExpr,
+ pathSize, FPO.requiresTrailingStorage(), writtenTy),
+ LParenLoc(lParenLoc), RParenLoc(rParenLoc) {
+ if (hasStoredFPFeatures())
+ *getTrailingFPFeatures() = FPO;
+ }
- explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
- : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) {}
+ explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize,
+ bool HasFPFeatures)
+ : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize,
+ HasFPFeatures) {}
+
+ unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
+ return path_size();
+ }
public:
friend class CastExpr;
friend TrailingObjects;
- static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
- ExprValueKind VK,
- TypeSourceInfo *Written,
- CastKind Kind, Expr *Op,
- const CXXCastPath *Path,
- SourceLocation LPLoc,
- SourceLocation RPLoc);
- static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
- unsigned PathSize);
+ static CXXFunctionalCastExpr *
+ Create(const ASTContext &Context, QualType T, ExprValueKind VK,
+ TypeSourceInfo *Written, CastKind Kind, Expr *Op,
+ const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc,
+ SourceLocation RPLoc);
+ static CXXFunctionalCastExpr *
+ CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures);
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
@@ -1996,6 +2039,9 @@ public:
/// invented by use of an auto parameter).
ArrayRef<NamedDecl *> getExplicitTemplateParameters() const;
+ /// Get the trailing requires clause, if any.
+ Expr *getTrailingRequiresClause() const;
+
/// Whether this is a generic lambda.
bool isGenericLambda() const { return getTemplateParameterList(); }
@@ -3394,17 +3440,18 @@ class CXXUnresolvedConstructExpr final
/// The location of the right parentheses (')').
SourceLocation RParenLoc;
- CXXUnresolvedConstructExpr(TypeSourceInfo *TSI, SourceLocation LParenLoc,
- ArrayRef<Expr *> Args, SourceLocation RParenLoc);
+ CXXUnresolvedConstructExpr(QualType T, TypeSourceInfo *TSI,
+ SourceLocation LParenLoc, ArrayRef<Expr *> Args,
+ SourceLocation RParenLoc);
CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
- : Expr(CXXUnresolvedConstructExprClass, Empty) {
+ : Expr(CXXUnresolvedConstructExprClass, Empty), TSI(nullptr) {
CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
}
public:
static CXXUnresolvedConstructExpr *Create(const ASTContext &Context,
- TypeSourceInfo *Type,
+ QualType T, TypeSourceInfo *TSI,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc);
@@ -3436,43 +3483,43 @@ public:
bool isListInitialization() const { return LParenLoc.isInvalid(); }
/// Retrieve the number of arguments.
- unsigned arg_size() const { return CXXUnresolvedConstructExprBits.NumArgs; }
+ unsigned getNumArgs() const { return CXXUnresolvedConstructExprBits.NumArgs; }
using arg_iterator = Expr **;
using arg_range = llvm::iterator_range<arg_iterator>;
arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
- arg_iterator arg_end() { return arg_begin() + arg_size(); }
+ arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
using const_arg_iterator = const Expr* const *;
using const_arg_range = llvm::iterator_range<const_arg_iterator>;
const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
- const_arg_iterator arg_end() const { return arg_begin() + arg_size(); }
+ const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
const_arg_range arguments() const {
return const_arg_range(arg_begin(), arg_end());
}
Expr *getArg(unsigned I) {
- assert(I < arg_size() && "Argument index out-of-range");
+ assert(I < getNumArgs() && "Argument index out-of-range");
return arg_begin()[I];
}
const Expr *getArg(unsigned I) const {
- assert(I < arg_size() && "Argument index out-of-range");
+ assert(I < getNumArgs() && "Argument index out-of-range");
return arg_begin()[I];
}
void setArg(unsigned I, Expr *E) {
- assert(I < arg_size() && "Argument index out-of-range");
+ assert(I < getNumArgs() && "Argument index out-of-range");
arg_begin()[I] = E;
}
SourceLocation getBeginLoc() const LLVM_READONLY;
SourceLocation getEndLoc() const LLVM_READONLY {
- if (!RParenLoc.isValid() && arg_size() > 0)
- return getArg(arg_size() - 1)->getEndLoc();
+ if (!RParenLoc.isValid() && getNumArgs() > 0)
+ return getArg(getNumArgs() - 1)->getEndLoc();
return RParenLoc;
}
@@ -3483,13 +3530,13 @@ public:
// Iterators
child_range children() {
auto **begin = reinterpret_cast<Stmt **>(arg_begin());
- return child_range(begin, begin + arg_size());
+ return child_range(begin, begin + getNumArgs());
}
const_child_range children() const {
auto **begin = reinterpret_cast<Stmt **>(
const_cast<CXXUnresolvedConstructExpr *>(this)->arg_begin());
- return const_child_range(begin, begin + arg_size());
+ return const_child_range(begin, begin + getNumArgs());
}
};
@@ -4199,8 +4246,10 @@ class SubstNonTypeTemplateParmExpr : public Expr {
friend class ASTReader;
friend class ASTStmtReader;
- /// The replaced parameter.
- NonTypeTemplateParmDecl *Param;
+ /// The replaced parameter and a flag indicating if it was a reference
+ /// parameter. For class NTTPs, we can't determine that based on the value
+ /// category alone.
+ llvm::PointerIntPair<NonTypeTemplateParmDecl*, 1, bool> ParamAndRef;
/// The replacement expression.
Stmt *Replacement;
@@ -4211,10 +4260,10 @@ class SubstNonTypeTemplateParmExpr : public Expr {
public:
SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
SourceLocation Loc,
- NonTypeTemplateParmDecl *Param,
+ NonTypeTemplateParmDecl *Param, bool RefParam,
Expr *Replacement)
: Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary),
- Param(Param), Replacement(Replacement) {
+ ParamAndRef(Param, RefParam), Replacement(Replacement) {
SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
setDependence(computeDependence(this));
}
@@ -4227,7 +4276,14 @@ public:
Expr *getReplacement() const { return cast<Expr>(Replacement); }
- NonTypeTemplateParmDecl *getParameter() const { return Param; }
+ NonTypeTemplateParmDecl *getParameter() const {
+ return ParamAndRef.getPointer();
+ }
+
+ bool isReferenceParameter() const { return ParamAndRef.getInt(); }
+
+ /// Determine the substituted type of the template parameter.
+ QualType getParameterType(const ASTContext &Ctx) const;
static bool classof(const Stmt *s) {
return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
@@ -4476,6 +4532,10 @@ public:
return getValueKind() == VK_LValue;
}
+ /// Determine whether this temporary object is usable in constant
+ /// expressions, as specified in C++20 [expr.const]p4.
+ bool isUsableInConstantExpressions(const ASTContext &Context) const;
+
SourceLocation getBeginLoc() const LLVM_READONLY {
return getSubExpr()->getBeginLoc();
}
@@ -4517,31 +4577,38 @@ class CXXFoldExpr : public Expr {
friend class ASTStmtReader;
friend class ASTStmtWriter;
+ enum SubExpr { Callee, LHS, RHS, Count };
+
SourceLocation LParenLoc;
SourceLocation EllipsisLoc;
SourceLocation RParenLoc;
// When 0, the number of expansions is not known. Otherwise, this is one more
// than the number of expansions.
unsigned NumExpansions;
- Stmt *SubExprs[2];
+ Stmt *SubExprs[SubExpr::Count];
BinaryOperatorKind Opcode;
public:
- CXXFoldExpr(QualType T, SourceLocation LParenLoc, Expr *LHS,
- BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS,
- SourceLocation RParenLoc, Optional<unsigned> NumExpansions)
+ CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,
+ SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode,
+ SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc,
+ Optional<unsigned> NumExpansions)
: Expr(CXXFoldExprClass, T, VK_RValue, OK_Ordinary), LParenLoc(LParenLoc),
EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) {
- SubExprs[0] = LHS;
- SubExprs[1] = RHS;
+ SubExprs[SubExpr::Callee] = Callee;
+ SubExprs[SubExpr::LHS] = LHS;
+ SubExprs[SubExpr::RHS] = RHS;
setDependence(computeDependence(this));
}
CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
- Expr *getLHS() const { return static_cast<Expr*>(SubExprs[0]); }
- Expr *getRHS() const { return static_cast<Expr*>(SubExprs[1]); }
+ UnresolvedLookupExpr *getCallee() const {
+ return static_cast<UnresolvedLookupExpr *>(SubExprs[SubExpr::Callee]);
+ }
+ Expr *getLHS() const { return static_cast<Expr*>(SubExprs[SubExpr::LHS]); }
+ Expr *getRHS() const { return static_cast<Expr*>(SubExprs[SubExpr::RHS]); }
/// Does this produce a right-associated sequence of operators?
bool isRightFold() const {
@@ -4557,6 +4624,8 @@ public:
/// Get the operand that doesn't contain a pack, for a binary fold.
Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
+ SourceLocation getLParenLoc() const { return LParenLoc; }
+ SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
BinaryOperatorKind getOperator() const { return Opcode; }
@@ -4566,19 +4635,33 @@ public:
return None;
}
- SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
+ SourceLocation getBeginLoc() const LLVM_READONLY {
+ if (LParenLoc.isValid())
+ return LParenLoc;
+ if (isLeftFold())
+ return getEllipsisLoc();
+ return getLHS()->getBeginLoc();
+ }
- SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
+ SourceLocation getEndLoc() const LLVM_READONLY {
+ if (RParenLoc.isValid())
+ return RParenLoc;
+ if (isRightFold())
+ return getEllipsisLoc();
+ return getRHS()->getEndLoc();
+ }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXFoldExprClass;
}
// Iterators
- child_range children() { return child_range(SubExprs, SubExprs + 2); }
+ child_range children() {
+ return child_range(SubExprs, SubExprs + SubExpr::Count);
+ }
const_child_range children() const {
- return const_child_range(SubExprs, SubExprs + 2);
+ return const_child_range(SubExprs, SubExprs + SubExpr::Count);
}
};
@@ -4796,7 +4879,7 @@ class BuiltinBitCastExpr final
private llvm::TrailingObjects<BuiltinBitCastExpr, CXXBaseSpecifier *> {
friend class ASTStmtReader;
friend class CastExpr;
- friend class TrailingObjects;
+ friend TrailingObjects;
SourceLocation KWLoc;
SourceLocation RParenLoc;
@@ -4805,11 +4888,11 @@ public:
BuiltinBitCastExpr(QualType T, ExprValueKind VK, CastKind CK, Expr *SrcExpr,
TypeSourceInfo *DstType, SourceLocation KWLoc,
SourceLocation RParenLoc)
- : ExplicitCastExpr(BuiltinBitCastExprClass, T, VK, CK, SrcExpr, 0,
+ : ExplicitCastExpr(BuiltinBitCastExprClass, T, VK, CK, SrcExpr, 0, false,
DstType),
KWLoc(KWLoc), RParenLoc(RParenLoc) {}
BuiltinBitCastExpr(EmptyShell Empty)
- : ExplicitCastExpr(BuiltinBitCastExprClass, Empty, 0) {}
+ : ExplicitCastExpr(BuiltinBitCastExprClass, Empty, 0, false) {}
SourceLocation getBeginLoc() const LLVM_READONLY { return KWLoc; }
SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
diff --git a/contrib/llvm-project/clang/include/clang/AST/ExprConcepts.h b/contrib/llvm-project/clang/include/clang/AST/ExprConcepts.h
index 2a88ed5175d2..1544c498ef66 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ExprConcepts.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ExprConcepts.h
@@ -126,7 +126,11 @@ public:
}
SourceLocation getEndLoc() const LLVM_READONLY {
- return ArgsAsWritten->RAngleLoc;
+ // If the ConceptSpecializationExpr is the ImmediatelyDeclaredConstraint
+ // of a TypeConstraint written syntactically as a constrained-parameter,
+ // there may not be a template argument list.
+ return ArgsAsWritten->RAngleLoc.isValid() ? ArgsAsWritten->RAngleLoc
+ : ConceptName.getEndLoc();
}
// Iterators
diff --git a/contrib/llvm-project/clang/include/clang/AST/ExprObjC.h b/contrib/llvm-project/clang/include/clang/AST/ExprObjC.h
index 4b39d9ab96a6..17eec5172697 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ExprObjC.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ExprObjC.h
@@ -1639,12 +1639,12 @@ public:
CastKind CK, SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo, Expr *Operand)
: ExplicitCastExpr(ObjCBridgedCastExprClass, TSInfo->getType(), VK_RValue,
- CK, Operand, 0, TSInfo),
+ CK, Operand, 0, false, TSInfo),
LParenLoc(LParenLoc), BridgeKeywordLoc(BridgeKeywordLoc), Kind(Kind) {}
/// Construct an empty Objective-C bridged cast.
explicit ObjCBridgedCastExpr(EmptyShell Shell)
- : ExplicitCastExpr(ObjCBridgedCastExprClass, Shell, 0) {}
+ : ExplicitCastExpr(ObjCBridgedCastExprClass, Shell, 0, false) {}
SourceLocation getLParenLoc() const { return LParenLoc; }
diff --git a/contrib/llvm-project/clang/include/clang/AST/ExternalASTSource.h b/contrib/llvm-project/clang/include/clang/AST/ExternalASTSource.h
index def877b91816..caae0770931b 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ExternalASTSource.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ExternalASTSource.h
@@ -161,10 +161,6 @@ public:
/// Retrieve the module that corresponds to the given module ID.
virtual Module *getModule(unsigned ID) { return nullptr; }
- /// Determine whether D comes from a PCH which was built with a corresponding
- /// object file.
- virtual bool DeclIsFromPCHWithObjectFile(const Decl *D) { return false; }
-
/// Return a descriptor for the corresponding module, if one exists.
virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);
diff --git a/contrib/llvm-project/clang/include/clang/AST/GlobalDecl.h b/contrib/llvm-project/clang/include/clang/AST/GlobalDecl.h
index d8ac498be54f..8cb56fb4ae90 100644
--- a/contrib/llvm-project/clang/include/clang/AST/GlobalDecl.h
+++ b/contrib/llvm-project/clang/include/clang/AST/GlobalDecl.h
@@ -32,6 +32,7 @@ enum class DynamicInitKind : unsigned {
NoStub = 0,
Initializer,
AtExit,
+ GlobalArrayDestructor
};
enum class KernelReferenceKind : unsigned {
diff --git a/contrib/llvm-project/clang/include/clang/AST/IgnoreExpr.h b/contrib/llvm-project/clang/include/clang/AST/IgnoreExpr.h
new file mode 100644
index 000000000000..1c2b538e5b63
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/AST/IgnoreExpr.h
@@ -0,0 +1,161 @@
+//===--- IgnoreExpr.h - Ignore intermediate Expressions -----------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines common functions to ignore intermediate expression nodes
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_AST_IGNOREEXPR_H
+#define LLVM_CLANG_AST_IGNOREEXPR_H
+
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+
+namespace clang {
+namespace detail {
+/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
+/// Return Fn_n(...(Fn_1(E)))
+inline Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
+template <typename FnTy, typename... FnTys>
+Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
+ return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
+}
+} // namespace detail
+
+/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
+/// Recursively apply each of the functions to E until reaching a fixed point.
+/// Note that a null E is valid; in this case nothing is done.
+template <typename... FnTys> Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
+ Expr *LastE = nullptr;
+ while (E != LastE) {
+ LastE = E;
+ E = detail::IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
+ }
+ return E;
+}
+
+template <typename... FnTys>
+const Expr *IgnoreExprNodes(const Expr *E, FnTys &&...Fns) {
+ return const_cast<Expr *>(IgnoreExprNodes(E, std::forward<FnTys>(Fns)...));
+}
+
+inline Expr *IgnoreImplicitCastsSingleStep(Expr *E) {
+ if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
+ return ICE->getSubExpr();
+
+ if (auto *FE = dyn_cast<FullExpr>(E))
+ return FE->getSubExpr();
+
+ return E;
+}
+
+inline Expr *IgnoreImplicitCastsExtraSingleStep(Expr *E) {
+ // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
+ // addition to what IgnoreImpCasts() skips to account for the current
+ // behaviour of IgnoreParenImpCasts().
+ Expr *SubE = IgnoreImplicitCastsSingleStep(E);
+ if (SubE != E)
+ return SubE;
+
+ if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
+ return MTE->getSubExpr();
+
+ if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
+ return NTTP->getReplacement();
+
+ return E;
+}
+
+inline Expr *IgnoreCastsSingleStep(Expr *E) {
+ if (auto *CE = dyn_cast<CastExpr>(E))
+ return CE->getSubExpr();
+
+ if (auto *FE = dyn_cast<FullExpr>(E))
+ return FE->getSubExpr();
+
+ if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
+ return MTE->getSubExpr();
+
+ if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
+ return NTTP->getReplacement();
+
+ return E;
+}
+
+inline Expr *IgnoreLValueCastsSingleStep(Expr *E) {
+ // Skip what IgnoreCastsSingleStep skips, except that only
+ // lvalue-to-rvalue casts are skipped.
+ if (auto *CE = dyn_cast<CastExpr>(E))
+ if (CE->getCastKind() != CK_LValueToRValue)
+ return E;
+
+ return IgnoreCastsSingleStep(E);
+}
+
+inline Expr *IgnoreBaseCastsSingleStep(Expr *E) {
+ if (auto *CE = dyn_cast<CastExpr>(E))
+ if (CE->getCastKind() == CK_DerivedToBase ||
+ CE->getCastKind() == CK_UncheckedDerivedToBase ||
+ CE->getCastKind() == CK_NoOp)
+ return CE->getSubExpr();
+
+ return E;
+}
+
+inline Expr *IgnoreImplicitSingleStep(Expr *E) {
+ Expr *SubE = IgnoreImplicitCastsSingleStep(E);
+ if (SubE != E)
+ return SubE;
+
+ if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
+ return MTE->getSubExpr();
+
+ if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
+ return BTE->getSubExpr();
+
+ return E;
+}
+
+inline Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E) {
+ if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
+ return ICE->getSubExprAsWritten();
+
+ return IgnoreImplicitSingleStep(E);
+}
+
+inline Expr *IgnoreParensOnlySingleStep(Expr *E) {
+ if (auto *PE = dyn_cast<ParenExpr>(E))
+ return PE->getSubExpr();
+ return E;
+}
+
+inline Expr *IgnoreParensSingleStep(Expr *E) {
+ if (auto *PE = dyn_cast<ParenExpr>(E))
+ return PE->getSubExpr();
+
+ if (auto *UO = dyn_cast<UnaryOperator>(E)) {
+ if (UO->getOpcode() == UO_Extension)
+ return UO->getSubExpr();
+ }
+
+ else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
+ if (!GSE->isResultDependent())
+ return GSE->getResultExpr();
+ }
+
+ else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
+ if (!CE->isConditionDependent())
+ return CE->getChosenSubExpr();
+ }
+
+ return E;
+}
+
+} // namespace clang
+
+#endif // LLVM_CLANG_AST_IGNOREEXPR_H
diff --git a/contrib/llvm-project/clang/include/clang/AST/Mangle.h b/contrib/llvm-project/clang/include/clang/AST/Mangle.h
index 011d1faab8ea..7b6495d85eb6 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Mangle.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Mangle.h
@@ -96,6 +96,9 @@ public:
virtual bool shouldMangleCXXName(const NamedDecl *D) = 0;
virtual bool shouldMangleStringLiteral(const StringLiteral *SL) = 0;
+ virtual bool isDeviceMangleContext() const { return false; }
+ virtual void setDeviceMangleContext(bool) {}
+
// FIXME: consider replacing raw_ostream & with something like SmallString &.
void mangleName(GlobalDecl GD, raw_ostream &);
virtual void mangleCXXName(GlobalDecl GD, raw_ostream &) = 0;
@@ -123,8 +126,11 @@ public:
void mangleBlock(const DeclContext *DC, const BlockDecl *BD,
raw_ostream &Out);
- void mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD, raw_ostream &);
- void mangleObjCMethodName(const ObjCMethodDecl *MD, raw_ostream &);
+ void mangleObjCMethodName(const ObjCMethodDecl *MD, raw_ostream &OS,
+ bool includePrefixByte = true,
+ bool includeCategoryNamespace = true);
+ void mangleObjCMethodNameAsSourceName(const ObjCMethodDecl *MD,
+ raw_ostream &);
virtual void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) = 0;
@@ -149,14 +155,9 @@ public:
};
class ItaniumMangleContext : public MangleContext {
- bool IsUniqueNameMangler = false;
public:
explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D)
: MangleContext(C, D, MK_Itanium) {}
- explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D,
- bool IsUniqueNameMangler)
- : MangleContext(C, D, MK_Itanium),
- IsUniqueNameMangler(IsUniqueNameMangler) {}
virtual void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) = 0;
virtual void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) = 0;
@@ -177,15 +178,12 @@ public:
virtual void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &) = 0;
- bool isUniqueNameMangler() { return IsUniqueNameMangler; }
-
static bool classof(const MangleContext *C) {
return C->getKind() == MK_Itanium;
}
static ItaniumMangleContext *create(ASTContext &Context,
- DiagnosticsEngine &Diags,
- bool IsUniqueNameMangler = false);
+ DiagnosticsEngine &Diags);
};
class MicrosoftMangleContext : public MangleContext {
diff --git a/contrib/llvm-project/clang/include/clang/AST/MangleNumberingContext.h b/contrib/llvm-project/clang/include/clang/AST/MangleNumberingContext.h
index f1ca6a05dbaf..eb33759682d6 100644
--- a/contrib/llvm-project/clang/include/clang/AST/MangleNumberingContext.h
+++ b/contrib/llvm-project/clang/include/clang/AST/MangleNumberingContext.h
@@ -52,6 +52,11 @@ public:
/// this context.
virtual unsigned getManglingNumber(const TagDecl *TD,
unsigned MSLocalManglingNumber) = 0;
+
+ /// Retrieve the mangling number of a new lambda expression with the
+ /// given call operator within the device context. No device number is
+ /// assigned if there's no device numbering context is associated.
+ virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *) { return 0; }
};
} // end namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h b/contrib/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h
index 540ac3df48fe..8bc3e25c0f4b 100644
--- a/contrib/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h
+++ b/contrib/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h
@@ -17,6 +17,7 @@
#include "clang/AST/DependenceFlags.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Compiler.h"
@@ -518,8 +519,8 @@ public:
/// Insertion operator for diagnostics. This allows sending
/// NestedNameSpecifiers into a diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- NestedNameSpecifier *NNS) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ NestedNameSpecifier *NNS) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(NNS),
DiagnosticsEngine::ak_nestednamespec);
return DB;
@@ -527,4 +528,33 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
} // namespace clang
+namespace llvm {
+
+template <> struct DenseMapInfo<clang::NestedNameSpecifierLoc> {
+ using FirstInfo = DenseMapInfo<clang::NestedNameSpecifier *>;
+ using SecondInfo = DenseMapInfo<void *>;
+
+ static clang::NestedNameSpecifierLoc getEmptyKey() {
+ return clang::NestedNameSpecifierLoc(FirstInfo::getEmptyKey(),
+ SecondInfo::getEmptyKey());
+ }
+
+ static clang::NestedNameSpecifierLoc getTombstoneKey() {
+ return clang::NestedNameSpecifierLoc(FirstInfo::getTombstoneKey(),
+ SecondInfo::getTombstoneKey());
+ }
+
+ static unsigned getHashValue(const clang::NestedNameSpecifierLoc &PairVal) {
+ return hash_combine(
+ FirstInfo::getHashValue(PairVal.getNestedNameSpecifier()),
+ SecondInfo::getHashValue(PairVal.getOpaqueData()));
+ }
+
+ static bool isEqual(const clang::NestedNameSpecifierLoc &LHS,
+ const clang::NestedNameSpecifierLoc &RHS) {
+ return LHS == RHS;
+ }
+};
+} // namespace llvm
+
#endif // LLVM_CLANG_AST_NESTEDNAMESPECIFIER_H
diff --git a/contrib/llvm-project/clang/include/clang/AST/OpenMPClause.h b/contrib/llvm-project/clang/include/clang/AST/OpenMPClause.h
index 6de7b6deb514..877c1d87d8ac 100644
--- a/contrib/llvm-project/clang/include/clang/AST/OpenMPClause.h
+++ b/contrib/llvm-project/clang/include/clang/AST/OpenMPClause.h
@@ -16,6 +16,7 @@
#ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H
#define LLVM_CLANG_AST_OPENMPCLAUSE_H
+#include "clang/AST/ASTFwd.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
@@ -27,6 +28,7 @@
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/iterator_range.h"
@@ -4737,8 +4739,9 @@ public:
/// subscript it may not have any associated declaration. In that case the
/// associated declaration is set to nullptr.
class MappableComponent {
- /// Expression associated with the component.
- Expr *AssociatedExpression = nullptr;
+ /// Pair of Expression and Non-contiguous pair associated with the
+ /// component.
+ llvm::PointerIntPair<Expr *, 1, bool> AssociatedExpressionNonContiguousPr;
/// Declaration associated with the declaration. If the component does
/// not have a declaration (e.g. array subscripts or section), this is set
@@ -4748,14 +4751,22 @@ public:
public:
explicit MappableComponent() = default;
explicit MappableComponent(Expr *AssociatedExpression,
- ValueDecl *AssociatedDeclaration)
- : AssociatedExpression(AssociatedExpression),
+ ValueDecl *AssociatedDeclaration,
+ bool IsNonContiguous)
+ : AssociatedExpressionNonContiguousPr(AssociatedExpression,
+ IsNonContiguous),
AssociatedDeclaration(
AssociatedDeclaration
? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl())
: nullptr) {}
- Expr *getAssociatedExpression() const { return AssociatedExpression; }
+ Expr *getAssociatedExpression() const {
+ return AssociatedExpressionNonContiguousPr.getPointer();
+ }
+
+ bool isNonContiguous() const {
+ return AssociatedExpressionNonContiguousPr.getInt();
+ }
ValueDecl *getAssociatedDeclaration() const {
return AssociatedDeclaration;
@@ -4820,6 +4831,11 @@ class OMPMappableExprListClause : public OMPVarListClause<T>,
/// Total number of components in this clause.
unsigned NumComponents;
+ /// Whether this clause is possible to have user-defined mappers associated.
+ /// It should be true for map, to, and from clauses, and false for
+ /// use_device_ptr and is_device_ptr.
+ const bool SupportsMapper;
+
/// C++ nested name specifier for the associated user-defined mapper.
NestedNameSpecifierLoc MapperQualifierLoc;
@@ -4840,19 +4856,21 @@ protected:
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
+ /// \param SupportsMapper Indicates whether this clause is possible to have
+ /// user-defined mappers associated.
/// \param MapperQualifierLocPtr C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfoPtr The identifier of associated user-defined mapper.
OMPMappableExprListClause(
OpenMPClauseKind K, const OMPVarListLocTy &Locs,
- const OMPMappableExprListSizeTy &Sizes,
+ const OMPMappableExprListSizeTy &Sizes, bool SupportsMapper = false,
NestedNameSpecifierLoc *MapperQualifierLocPtr = nullptr,
DeclarationNameInfo *MapperIdInfoPtr = nullptr)
: OMPVarListClause<T>(K, Locs.StartLoc, Locs.LParenLoc, Locs.EndLoc,
Sizes.NumVars),
NumUniqueDeclarations(Sizes.NumUniqueDeclarations),
NumComponentLists(Sizes.NumComponentLists),
- NumComponents(Sizes.NumComponents) {
+ NumComponents(Sizes.NumComponents), SupportsMapper(SupportsMapper) {
if (MapperQualifierLocPtr)
MapperQualifierLoc = *MapperQualifierLocPtr;
if (MapperIdInfoPtr)
@@ -5051,6 +5069,8 @@ protected:
/// Get the user-defined mapper references that are in the trailing objects of
/// the class.
MutableArrayRef<Expr *> getUDMapperRefs() {
+ assert(SupportsMapper &&
+ "Must be a clause that is possible to have user-defined mappers");
return llvm::makeMutableArrayRef<Expr *>(
static_cast<T *>(this)->template getTrailingObjects<Expr *>() +
OMPVarListClause<T>::varlist_size(),
@@ -5060,8 +5080,10 @@ protected:
/// Get the user-defined mappers references that are in the trailing objects
/// of the class.
ArrayRef<Expr *> getUDMapperRefs() const {
+ assert(SupportsMapper &&
+ "Must be a clause that is possible to have user-defined mappers");
return llvm::makeArrayRef<Expr *>(
- static_cast<T *>(this)->template getTrailingObjects<Expr *>() +
+ static_cast<const T *>(this)->template getTrailingObjects<Expr *>() +
OMPVarListClause<T>::varlist_size(),
OMPVarListClause<T>::varlist_size());
}
@@ -5071,6 +5093,8 @@ protected:
void setUDMapperRefs(ArrayRef<Expr *> DMDs) {
assert(DMDs.size() == OMPVarListClause<T>::varlist_size() &&
"Unexpected number of user-defined mappers.");
+ assert(SupportsMapper &&
+ "Must be a clause that is possible to have user-defined mappers");
std::copy(DMDs.begin(), DMDs.end(), getUDMapperRefs().begin());
}
@@ -5107,6 +5131,12 @@ public:
// The list number associated with the current declaration.
ArrayRef<unsigned>::iterator NumListsCur;
+ // Whether this clause is possible to have user-defined mappers associated.
+ const bool SupportsMapper;
+
+ // The user-defined mapper associated with the current declaration.
+ ArrayRef<Expr *>::iterator MapperCur;
+
// Remaining lists for the current declaration.
unsigned RemainingLists = 0;
@@ -5127,16 +5157,20 @@ public:
explicit const_component_lists_iterator(
ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum,
ArrayRef<unsigned> CumulativeListSizes,
- MappableExprComponentListRef Components)
+ MappableExprComponentListRef Components, bool SupportsMapper,
+ ArrayRef<Expr *> Mappers)
: const_component_lists_iterator::iterator_adaptor_base(
Components.begin()),
DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()),
+ SupportsMapper(SupportsMapper),
ListSizeCur(CumulativeListSizes.begin()),
ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) {
assert(UniqueDecls.size() == DeclsListNum.size() &&
"Inconsistent number of declarations and list sizes!");
if (!DeclsListNum.empty())
RemainingLists = *NumListsCur;
+ if (SupportsMapper)
+ MapperCur = Mappers.begin();
}
/// Construct an iterator that scan lists for a given declaration \a
@@ -5144,9 +5178,11 @@ public:
explicit const_component_lists_iterator(
const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls,
ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes,
- MappableExprComponentListRef Components)
+ MappableExprComponentListRef Components, bool SupportsMapper,
+ ArrayRef<Expr *> Mappers)
: const_component_lists_iterator(UniqueDecls, DeclsListNum,
- CumulativeListSizes, Components) {
+ CumulativeListSizes, Components,
+ SupportsMapper, Mappers) {
// Look for the desired declaration. While we are looking for it, we
// update the state so that we know the component where a given list
// starts.
@@ -5161,6 +5197,9 @@ public:
std::advance(ListSizeCur, *NumListsCur - 1);
PrevListSize = *ListSizeCur;
++ListSizeCur;
+
+ if (SupportsMapper)
+ ++MapperCur;
}
// If we didn't find any declaration, advance the iterator to after the
@@ -5186,14 +5225,20 @@ public:
// Return the array with the current list. The sizes are cumulative, so the
// array size is the difference between the current size and previous one.
- std::pair<const ValueDecl *, MappableExprComponentListRef>
+ std::tuple<const ValueDecl *, MappableExprComponentListRef,
+ const ValueDecl *>
operator*() const {
assert(ListSizeCur != ListSizeEnd && "Invalid iterator!");
- return std::make_pair(
+ const ValueDecl *Mapper = nullptr;
+ if (SupportsMapper && *MapperCur)
+ Mapper = cast<ValueDecl>(cast<DeclRefExpr>(*MapperCur)->getDecl());
+ return std::make_tuple(
*DeclCur,
- MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize));
+ MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize),
+ Mapper);
}
- std::pair<const ValueDecl *, MappableExprComponentListRef>
+ std::tuple<const ValueDecl *, MappableExprComponentListRef,
+ const ValueDecl *>
operator->() const {
return **this;
}
@@ -5216,6 +5261,8 @@ public:
if (!(--RemainingLists)) {
++DeclCur;
++NumListsCur;
+ if (SupportsMapper)
+ ++MapperCur;
RemainingLists = *NumListsCur;
assert(RemainingLists && "No lists in the following declaration??");
}
@@ -5233,13 +5280,15 @@ public:
const_component_lists_iterator component_lists_begin() const {
return const_component_lists_iterator(
getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(),
- getComponentsRef());
+ getComponentsRef(), SupportsMapper,
+ SupportsMapper ? getUDMapperRefs() : llvm::None);
}
const_component_lists_iterator component_lists_end() const {
return const_component_lists_iterator(
ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(),
MappableExprComponentListRef(getComponentsRef().end(),
- getComponentsRef().end()));
+ getComponentsRef().end()),
+ SupportsMapper, llvm::None);
}
const_component_lists_range component_lists() const {
return {component_lists_begin(), component_lists_end()};
@@ -5251,7 +5300,8 @@ public:
decl_component_lists_begin(const ValueDecl *VD) const {
return const_component_lists_iterator(
VD, getUniqueDeclsRef(), getDeclNumListsRef(),
- getComponentListSizesRef(), getComponentsRef());
+ getComponentListSizesRef(), getComponentsRef(), SupportsMapper,
+ SupportsMapper ? getUDMapperRefs() : llvm::None);
}
const_component_lists_iterator decl_component_lists_end() const {
return component_lists_end();
@@ -5354,7 +5404,7 @@ private:
/// Map-type-modifiers for the 'map' clause.
OpenMPMapModifierKind MapTypeModifiers[NumberOfOMPMapClauseModifiers] = {
OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
- OMPC_MAP_MODIFIER_unknown};
+ OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
/// Location of map-type-modifiers for the 'map' clause.
SourceLocation MapTypeModifiersLoc[NumberOfOMPMapClauseModifiers];
@@ -5399,7 +5449,8 @@ private:
SourceLocation MapLoc, const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_map, Locs, Sizes,
- &MapperQualifierLoc, &MapperIdInfo),
+ /*SupportsMapper=*/true, &MapperQualifierLoc,
+ &MapperIdInfo),
MapType(MapType), MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) {
assert(llvm::array_lengthof(MapTypeModifiers) == MapModifiers.size() &&
"Unexpected number of map type modifiers.");
@@ -5419,8 +5470,8 @@ private:
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPMapClause(const OMPMappableExprListSizeTy &Sizes)
- : OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(),
- Sizes) {}
+ : OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(), Sizes,
+ /*SupportsMapper=*/true) {}
/// Set map-type-modifier for the clause.
///
@@ -6289,8 +6340,20 @@ class OMPToClause final : public OMPMappableExprListClause<OMPToClause>,
friend OMPVarListClause;
friend TrailingObjects;
+ /// Motion-modifiers for the 'to' clause.
+ OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = {
+ OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown};
+
+ /// Location of motion-modifiers for the 'to' clause.
+ SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers];
+
+ /// Colon location.
+ SourceLocation ColonLoc;
+
/// Build clause with number of variables \a NumVars.
///
+ /// \param TheMotionModifiers Motion-modifiers.
+ /// \param TheMotionModifiersLoc Locations of motion-modifiers.
/// \param MapperQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfo The identifier of associated user-defined mapper.
@@ -6302,12 +6365,24 @@ class OMPToClause final : public OMPMappableExprListClause<OMPToClause>,
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
- explicit OMPToClause(NestedNameSpecifierLoc MapperQualifierLoc,
+ explicit OMPToClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers,
+ ArrayRef<SourceLocation> TheMotionModifiersLoc,
+ NestedNameSpecifierLoc MapperQualifierLoc,
DeclarationNameInfo MapperIdInfo,
const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_to, Locs, Sizes,
- &MapperQualifierLoc, &MapperIdInfo) {}
+ /*SupportsMapper=*/true, &MapperQualifierLoc,
+ &MapperIdInfo) {
+ assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() &&
+ "Unexpected number of motion modifiers.");
+ llvm::copy(TheMotionModifiers, std::begin(MotionModifiers));
+
+ assert(llvm::array_lengthof(MotionModifiersLoc) ==
+ TheMotionModifiersLoc.size() &&
+ "Unexpected number of motion modifier locations.");
+ llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc));
+ }
/// Build an empty clause.
///
@@ -6317,8 +6392,31 @@ class OMPToClause final : public OMPMappableExprListClause<OMPToClause>,
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPToClause(const OMPMappableExprListSizeTy &Sizes)
- : OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(),
- Sizes) {}
+ : OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(), Sizes,
+ /*SupportsMapper=*/true) {}
+
+ /// Set motion-modifier for the clause.
+ ///
+ /// \param I index for motion-modifier.
+ /// \param T motion-modifier for the clause.
+ void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) {
+ assert(I < NumberOfOMPMotionModifiers &&
+ "Unexpected index to store motion modifier, exceeds array size.");
+ MotionModifiers[I] = T;
+ }
+
+ /// Set location for the motion-modifier.
+ ///
+ /// \param I index for motion-modifier location.
+ /// \param TLoc motion-modifier location.
+ void setMotionModifierLoc(unsigned I, SourceLocation TLoc) {
+ assert(I < NumberOfOMPMotionModifiers &&
+ "Index to store motion modifier location exceeds array size.");
+ MotionModifiersLoc[I] = TLoc;
+ }
+
+ /// Set colon location.
+ void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
@@ -6344,6 +6442,8 @@ public:
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
+ /// \param MotionModifiers Motion-modifiers.
+ /// \param MotionModifiersLoc Location of motion-modifiers.
/// \param UDMapperRefs References to user-defined mappers associated with
/// expressions used in the clause.
/// \param UDMQualifierLoc C++ nested name specifier for the associated
@@ -6354,6 +6454,8 @@ public:
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists,
ArrayRef<Expr *> UDMapperRefs,
+ ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
+ ArrayRef<SourceLocation> MotionModifiersLoc,
NestedNameSpecifierLoc UDMQualifierLoc,
DeclarationNameInfo MapperId);
@@ -6368,6 +6470,38 @@ public:
static OMPToClause *CreateEmpty(const ASTContext &C,
const OMPMappableExprListSizeTy &Sizes);
+ /// Fetches the motion-modifier at 'Cnt' index of array of modifiers.
+ ///
+ /// \param Cnt index for motion-modifier.
+ OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY {
+ assert(Cnt < NumberOfOMPMotionModifiers &&
+ "Requested modifier exceeds the total number of modifiers.");
+ return MotionModifiers[Cnt];
+ }
+
+ /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers'
+ /// locations.
+ ///
+ /// \param Cnt index for motion-modifier location.
+ SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY {
+ assert(Cnt < NumberOfOMPMotionModifiers &&
+ "Requested modifier location exceeds total number of modifiers.");
+ return MotionModifiersLoc[Cnt];
+ }
+
+ /// Fetches ArrayRef of motion-modifiers.
+ ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY {
+ return llvm::makeArrayRef(MotionModifiers);
+ }
+
+ /// Fetches ArrayRef of location of motion-modifiers.
+ ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY {
+ return llvm::makeArrayRef(MotionModifiersLoc);
+ }
+
+ /// Get colon location.
+ SourceLocation getColonLoc() const { return ColonLoc; }
+
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
@@ -6408,8 +6542,20 @@ class OMPFromClause final
friend OMPVarListClause;
friend TrailingObjects;
+ /// Motion-modifiers for the 'from' clause.
+ OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = {
+ OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown};
+
+ /// Location of motion-modifiers for the 'from' clause.
+ SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers];
+
+ /// Colon location.
+ SourceLocation ColonLoc;
+
/// Build clause with number of variables \a NumVars.
///
+ /// \param TheMotionModifiers Motion-modifiers.
+ /// \param TheMotionModifiersLoc Locations of motion-modifiers.
/// \param MapperQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfo The identifier of associated user-defined mapper.
@@ -6421,12 +6567,24 @@ class OMPFromClause final
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
- explicit OMPFromClause(NestedNameSpecifierLoc MapperQualifierLoc,
+ explicit OMPFromClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers,
+ ArrayRef<SourceLocation> TheMotionModifiersLoc,
+ NestedNameSpecifierLoc MapperQualifierLoc,
DeclarationNameInfo MapperIdInfo,
const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_from, Locs, Sizes,
- &MapperQualifierLoc, &MapperIdInfo) {}
+ /*SupportsMapper=*/true, &MapperQualifierLoc,
+ &MapperIdInfo) {
+ assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() &&
+ "Unexpected number of motion modifiers.");
+ llvm::copy(TheMotionModifiers, std::begin(MotionModifiers));
+
+ assert(llvm::array_lengthof(MotionModifiersLoc) ==
+ TheMotionModifiersLoc.size() &&
+ "Unexpected number of motion modifier locations.");
+ llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc));
+ }
/// Build an empty clause.
///
@@ -6437,7 +6595,30 @@ class OMPFromClause final
/// NumComponents: total number of expression components in the clause.
explicit OMPFromClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_from, OMPVarListLocTy(),
- Sizes) {}
+ Sizes, /*SupportsMapper=*/true) {}
+
+ /// Set motion-modifier for the clause.
+ ///
+ /// \param I index for motion-modifier.
+ /// \param T motion-modifier for the clause.
+ void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) {
+ assert(I < NumberOfOMPMotionModifiers &&
+ "Unexpected index to store motion modifier, exceeds array size.");
+ MotionModifiers[I] = T;
+ }
+
+ /// Set location for the motion-modifier.
+ ///
+ /// \param I index for motion-modifier location.
+ /// \param TLoc motion-modifier location.
+ void setMotionModifierLoc(unsigned I, SourceLocation TLoc) {
+ assert(I < NumberOfOMPMotionModifiers &&
+ "Index to store motion modifier location exceeds array size.");
+ MotionModifiersLoc[I] = TLoc;
+ }
+
+ /// Set colon location.
+ void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
@@ -6463,18 +6644,21 @@ public:
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
+ /// \param MotionModifiers Motion-modifiers.
+ /// \param MotionModifiersLoc Location of motion-modifiers.
/// \param UDMapperRefs References to user-defined mappers associated with
/// expressions used in the clause.
/// \param UDMQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperId The identifier of associated user-defined mapper.
- static OMPFromClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs,
- ArrayRef<Expr *> Vars,
- ArrayRef<ValueDecl *> Declarations,
- MappableExprComponentListsRef ComponentLists,
- ArrayRef<Expr *> UDMapperRefs,
- NestedNameSpecifierLoc UDMQualifierLoc,
- DeclarationNameInfo MapperId);
+ static OMPFromClause *
+ Create(const ASTContext &C, const OMPVarListLocTy &Locs,
+ ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations,
+ MappableExprComponentListsRef ComponentLists,
+ ArrayRef<Expr *> UDMapperRefs,
+ ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
+ ArrayRef<SourceLocation> MotionModifiersLoc,
+ NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId);
/// Creates an empty clause with the place for \a NumVars variables.
///
@@ -6487,6 +6671,38 @@ public:
static OMPFromClause *CreateEmpty(const ASTContext &C,
const OMPMappableExprListSizeTy &Sizes);
+ /// Fetches the motion-modifier at 'Cnt' index of array of modifiers.
+ ///
+ /// \param Cnt index for motion-modifier.
+ OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY {
+ assert(Cnt < NumberOfOMPMotionModifiers &&
+ "Requested modifier exceeds the total number of modifiers.");
+ return MotionModifiers[Cnt];
+ }
+
+ /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers'
+ /// locations.
+ ///
+ /// \param Cnt index for motion-modifier location.
+ SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY {
+ assert(Cnt < NumberOfOMPMotionModifiers &&
+ "Requested modifier location exceeds total number of modifiers.");
+ return MotionModifiersLoc[Cnt];
+ }
+
+ /// Fetches ArrayRef of motion-modifiers.
+ ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY {
+ return llvm::makeArrayRef(MotionModifiers);
+ }
+
+ /// Fetches ArrayRef of location of motion-modifiers.
+ ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY {
+ return llvm::makeArrayRef(MotionModifiersLoc);
+ }
+
+ /// Get colon location.
+ SourceLocation getColonLoc() const { return ColonLoc; }
+
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
@@ -7542,22 +7758,22 @@ public:
#define DISPATCH(CLASS) \
return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S))
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
- RetTy Visit ## Class (PTR(Class) S) { DISPATCH(Class); }
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) \
+ RetTy Visit##Class(PTR(Class) S) { DISPATCH(Class); }
+#include "llvm/Frontend/OpenMP/OMP.inc"
RetTy Visit(PTR(OMPClause) S) {
// Top switch clause: visit each OMPClause.
switch (S->getClauseKind()) {
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) \
case llvm::omp::Clause::Enum: \
return Visit##Class(static_cast<PTR(Class)>(S));
-#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
+#define CLAUSE_NO_CLASS(Enum, Str) \
case llvm::omp::Clause::Enum: \
break;
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
- default:
- break;
+#include "llvm/Frontend/OpenMP/OMP.inc"
}
}
// Base case, ignore it. :)
@@ -7581,18 +7797,24 @@ class OMPClausePrinter final : public OMPClauseVisitor<OMPClausePrinter> {
/// Process clauses with list of variables.
template <typename T> void VisitOMPClauseList(T *Node, char StartSym);
+ /// Process motion clauses.
+ template <typename T> void VisitOMPMotionClause(T *Node);
public:
OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy)
: OS(OS), Policy(Policy) {}
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
- void Visit##Class(Class *S);
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
+#include "llvm/Frontend/OpenMP/OMP.inc"
};
struct OMPTraitProperty {
llvm::omp::TraitProperty Kind = llvm::omp::TraitProperty::invalid;
+
+ /// The raw string as we parsed it. This is needed for the `isa` trait set
+ /// (which accepts anything) and (later) extensions.
+ StringRef RawString;
};
struct OMPTraitSelector {
Expr *ScoreOrCondition = nullptr;
@@ -7644,12 +7866,190 @@ public:
/// Return a string representation identifying this context selector.
std::string getMangledName() const;
+ /// Check the extension trait \p TP is active.
+ bool isExtensionActive(llvm::omp::TraitProperty TP) {
+ for (const OMPTraitSet &Set : Sets) {
+ if (Set.Kind != llvm::omp::TraitSet::implementation)
+ continue;
+ for (const OMPTraitSelector &Selector : Set.Selectors) {
+ if (Selector.Kind != llvm::omp::TraitSelector::implementation_extension)
+ continue;
+ for (const OMPTraitProperty &Property : Selector.Properties) {
+ if (Property.Kind == TP)
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
/// Print a human readable representation into \p OS.
void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
};
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI);
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI);
+/// Clang specific specialization of the OMPContext to lookup target features.
+struct TargetOMPContext final : public llvm::omp::OMPContext {
+
+ TargetOMPContext(ASTContext &ASTCtx,
+ std::function<void(StringRef)> &&DiagUnknownTrait,
+ const FunctionDecl *CurrentFunctionDecl);
+ virtual ~TargetOMPContext() = default;
+
+ /// See llvm::omp::OMPContext::matchesISATrait
+ bool matchesISATrait(StringRef RawString) const override;
+
+private:
+ std::function<bool(StringRef)> FeatureValidityCheck;
+ std::function<void(StringRef)> DiagUnknownTrait;
+ llvm::StringMap<bool> FeatureMap;
+};
+
+/// Contains data for OpenMP directives: clauses, children
+/// expressions/statements (helpers for codegen) and associated statement, if
+/// any.
+class OMPChildren final
+ : private llvm::TrailingObjects<OMPChildren, OMPClause *, Stmt *> {
+ friend TrailingObjects;
+ friend class OMPClauseReader;
+ friend class OMPExecutableDirective;
+ template <typename T> friend class OMPDeclarativeDirective;
+
+ /// Numbers of clauses.
+ unsigned NumClauses = 0;
+ /// Number of child expressions/stmts.
+ unsigned NumChildren = 0;
+ /// true if the directive has associated statement.
+ bool HasAssociatedStmt = false;
+
+ /// Define the sizes of each trailing object array except the last one. This
+ /// is required for TrailingObjects to work properly.
+ size_t numTrailingObjects(OverloadToken<OMPClause *>) const {
+ return NumClauses;
+ }
+
+ OMPChildren() = delete;
+
+ OMPChildren(unsigned NumClauses, unsigned NumChildren, bool HasAssociatedStmt)
+ : NumClauses(NumClauses), NumChildren(NumChildren),
+ HasAssociatedStmt(HasAssociatedStmt) {}
+
+ static size_t size(unsigned NumClauses, bool HasAssociatedStmt,
+ unsigned NumChildren);
+
+ static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses);
+ static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses, Stmt *S,
+ unsigned NumChildren = 0);
+ static OMPChildren *CreateEmpty(void *Mem, unsigned NumClauses,
+ bool HasAssociatedStmt = false,
+ unsigned NumChildren = 0);
+
+public:
+ unsigned getNumClauses() const { return NumClauses; }
+ unsigned getNumChildren() const { return NumChildren; }
+ bool hasAssociatedStmt() const { return HasAssociatedStmt; }
+
+ /// Set associated statement.
+ void setAssociatedStmt(Stmt *S) {
+ getTrailingObjects<Stmt *>()[NumChildren] = S;
+ }
+
+ void setChildren(ArrayRef<Stmt *> Children);
+
+ /// Sets the list of variables for this clause.
+ ///
+ /// \param Clauses The list of clauses for the directive.
+ ///
+ void setClauses(ArrayRef<OMPClause *> Clauses);
+
+ /// Returns statement associated with the directive.
+ const Stmt *getAssociatedStmt() const {
+ return const_cast<OMPChildren *>(this)->getAssociatedStmt();
+ }
+ Stmt *getAssociatedStmt() {
+ assert(HasAssociatedStmt &&
+ "Expected directive with the associated statement.");
+ return getTrailingObjects<Stmt *>()[NumChildren];
+ }
+
+ /// Get the clauses storage.
+ MutableArrayRef<OMPClause *> getClauses() {
+ return llvm::makeMutableArrayRef(getTrailingObjects<OMPClause *>(),
+ NumClauses);
+ }
+ ArrayRef<OMPClause *> getClauses() const {
+ return const_cast<OMPChildren *>(this)->getClauses();
+ }
+
+ /// Returns the captured statement associated with the
+ /// component region within the (combined) directive.
+ ///
+ /// \param RegionKind Component region kind.
+ const CapturedStmt *
+ getCapturedStmt(OpenMPDirectiveKind RegionKind,
+ ArrayRef<OpenMPDirectiveKind> CaptureRegions) const {
+ assert(llvm::any_of(
+ CaptureRegions,
+ [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) &&
+ "RegionKind not found in OpenMP CaptureRegions.");
+ auto *CS = cast<CapturedStmt>(getAssociatedStmt());
+ for (auto ThisCaptureRegion : CaptureRegions) {
+ if (ThisCaptureRegion == RegionKind)
+ return CS;
+ CS = cast<CapturedStmt>(CS->getCapturedStmt());
+ }
+ llvm_unreachable("Incorrect RegionKind specified for directive.");
+ }
+
+ /// Get innermost captured statement for the construct.
+ CapturedStmt *
+ getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) {
+ assert(hasAssociatedStmt() && "Must have associated captured statement.");
+ assert(!CaptureRegions.empty() &&
+ "At least one captured statement must be provided.");
+ auto *CS = cast<CapturedStmt>(getAssociatedStmt());
+ for (unsigned Level = CaptureRegions.size(); Level > 1; --Level)
+ CS = cast<CapturedStmt>(CS->getCapturedStmt());
+ return CS;
+ }
+
+ const CapturedStmt *
+ getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) const {
+ return const_cast<OMPChildren *>(this)->getInnermostCapturedStmt(
+ CaptureRegions);
+ }
+
+ MutableArrayRef<Stmt *> getChildren();
+ ArrayRef<Stmt *> getChildren() const {
+ return const_cast<OMPChildren *>(this)->getChildren();
+ }
+
+ Stmt *getRawStmt() {
+ assert(HasAssociatedStmt &&
+ "Expected directive with the associated statement.");
+ if (auto *CS = dyn_cast<CapturedStmt>(getAssociatedStmt())) {
+ Stmt *S = nullptr;
+ do {
+ S = CS->getCapturedStmt();
+ CS = dyn_cast<CapturedStmt>(S);
+ } while (CS);
+ return S;
+ }
+ return getAssociatedStmt();
+ }
+ const Stmt *getRawStmt() const {
+ return const_cast<OMPChildren *>(this)->getRawStmt();
+ }
+
+ Stmt::child_range getAssociatedStmtAsRange() {
+ if (!HasAssociatedStmt)
+ return Stmt::child_range(Stmt::child_iterator(), Stmt::child_iterator());
+ return Stmt::child_range(&getTrailingObjects<Stmt *>()[NumChildren],
+ &getTrailingObjects<Stmt *>()[NumChildren + 1]);
+ }
+};
+
} // namespace clang
#endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
diff --git a/contrib/llvm-project/clang/include/clang/AST/OperationKinds.def b/contrib/llvm-project/clang/include/clang/AST/OperationKinds.def
index f29664e8eb33..7c82ab6e57ef 100644
--- a/contrib/llvm-project/clang/include/clang/AST/OperationKinds.def
+++ b/contrib/llvm-project/clang/include/clang/AST/OperationKinds.def
@@ -77,9 +77,10 @@ CAST_OPERATION(LValueToRValueBitCast)
CAST_OPERATION(LValueToRValue)
/// CK_NoOp - A conversion which does not affect the type other than
-/// (possibly) adding qualifiers.
+/// (possibly) adding qualifiers or removing noexcept.
/// int -> int
/// char** -> const char * const *
+/// void () noexcept -> void ()
CAST_OPERATION(NoOp)
/// CK_BaseToDerived - A conversion from a C++ class pointer/reference
@@ -201,6 +202,14 @@ CAST_OPERATION(IntegralToBoolean)
/// float f = i;
CAST_OPERATION(IntegralToFloating)
+/// CK_FloatingToFixedPoint - Floating to fixed point.
+/// _Accum a = f;
+CAST_OPERATION(FloatingToFixedPoint)
+
+/// CK_FixedPointToFloating - Fixed point to floating.
+/// (float) 2.5k
+CAST_OPERATION(FixedPointToFloating)
+
/// CK_FixedPointCast - Fixed point to fixed point.
/// (_Accum) 0.5r
CAST_OPERATION(FixedPointCast)
diff --git a/contrib/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h b/contrib/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h
index c57199f0fdf1..c9a2d19f4ebc 100644
--- a/contrib/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h
@@ -63,7 +63,7 @@ public:
return *this;
}
- OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
+ OptionalDiagnostic &operator<<(const llvm::APFixedPoint &FX) {
if (Diag) {
SmallVector<char, 32> Buffer;
FX.toString(Buffer);
diff --git a/contrib/llvm-project/clang/include/clang/AST/ParentMap.h b/contrib/llvm-project/clang/include/clang/AST/ParentMap.h
index 1e65d7efd272..86e2f048a344 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ParentMap.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ParentMap.h
@@ -51,9 +51,7 @@ public:
return getParentIgnoreParenCasts(const_cast<Stmt*>(S));
}
- bool hasParent(Stmt* S) const {
- return getParent(S) != nullptr;
- }
+ bool hasParent(const Stmt *S) const { return getParent(S) != nullptr; }
bool isConsumedExpr(Expr *E) const;
diff --git a/contrib/llvm-project/clang/include/clang/AST/ParentMapContext.h b/contrib/llvm-project/clang/include/clang/AST/ParentMapContext.h
index be4d75df7b99..a0412380a864 100644
--- a/contrib/llvm-project/clang/include/clang/AST/ParentMapContext.h
+++ b/contrib/llvm-project/clang/include/clang/AST/ParentMapContext.h
@@ -94,25 +94,24 @@ class DynTypedNodeList {
public:
DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
- new (Storage.buffer) DynTypedNode(N);
+ new (&Storage) DynTypedNode(N);
}
DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
- new (Storage.buffer) ArrayRef<DynTypedNode>(A);
+ new (&Storage) ArrayRef<DynTypedNode>(A);
}
const DynTypedNode *begin() const {
if (!IsSingleNode)
- return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
+ return reinterpret_cast<const ArrayRef<DynTypedNode> *>(&Storage)
->begin();
- return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
+ return reinterpret_cast<const DynTypedNode *>(&Storage);
}
const DynTypedNode *end() const {
if (!IsSingleNode)
- return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
- ->end();
- return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
+ return reinterpret_cast<const ArrayRef<DynTypedNode> *>(&Storage)->end();
+ return reinterpret_cast<const DynTypedNode *>(&Storage) + 1;
}
size_t size() const { return end() - begin(); }
diff --git a/contrib/llvm-project/clang/include/clang/AST/PrettyPrinter.h b/contrib/llvm-project/clang/include/clang/AST/PrettyPrinter.h
index 616647f44430..3baf2b2ba94d 100644
--- a/contrib/llvm-project/clang/include/clang/AST/PrettyPrinter.h
+++ b/contrib/llvm-project/clang/include/clang/AST/PrettyPrinter.h
@@ -18,6 +18,7 @@
namespace clang {
+class DeclContext;
class LangOptions;
class SourceManager;
class Stmt;
@@ -39,6 +40,15 @@ public:
virtual std::string remapPath(StringRef Path) const {
return std::string(Path);
}
+
+ /// When printing type to be inserted into code in specific context, this
+ /// callback can be used to avoid printing the redundant part of the
+ /// qualifier. For example, when inserting code inside namespace foo, we
+ /// should print bar::SomeType instead of foo::bar::SomeType.
+ /// To do this, shouldPrintScope should return true on "foo" NamespaceDecl.
+ /// The printing stops at the first isScopeVisible() == true, so there will
+ /// be no calls with outer scopes.
+ virtual bool isScopeVisible(const DeclContext *DC) const { return false; }
};
/// Describes how types, statements, expressions, and declarations should be
@@ -52,12 +62,13 @@ struct PrintingPolicy {
: Indentation(2), SuppressSpecifiers(false),
SuppressTagKeyword(LO.CPlusPlus), IncludeTagDefinition(false),
SuppressScope(false), SuppressUnwrittenScope(false),
- SuppressInitializers(false), ConstantArraySizeAsWritten(false),
- AnonymousTagLocations(true), SuppressStrongLifetime(false),
- SuppressLifetimeQualifiers(false),
- SuppressTemplateArgsInCXXConstructors(false), Bool(LO.Bool),
- Restrict(LO.C99), Alignof(LO.CPlusPlus11), UnderscoreAlignof(LO.C11),
- UseVoidForZeroParams(!LO.CPlusPlus),
+ SuppressInlineNamespace(true), SuppressInitializers(false),
+ ConstantArraySizeAsWritten(false), AnonymousTagLocations(true),
+ SuppressStrongLifetime(false), SuppressLifetimeQualifiers(false),
+ SuppressTemplateArgsInCXXConstructors(false),
+ SuppressDefaultTemplateArgs(true), Bool(LO.Bool),
+ Nullptr(LO.CPlusPlus11), Restrict(LO.C99), Alignof(LO.CPlusPlus11),
+ UnderscoreAlignof(LO.C11), UseVoidForZeroParams(!LO.CPlusPlus),
SplitTemplateClosers(!LO.CPlusPlus11), TerseOutput(false),
PolishForDeclaration(false), Half(LO.Half),
MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
@@ -117,10 +128,15 @@ struct PrintingPolicy {
/// Suppresses printing of scope specifiers.
unsigned SuppressScope : 1;
- /// Suppress printing parts of scope specifiers that don't need
- /// to be written, e.g., for inline or anonymous namespaces.
+ /// Suppress printing parts of scope specifiers that are never
+ /// written, e.g., for anonymous namespaces.
unsigned SuppressUnwrittenScope : 1;
+ /// Suppress printing parts of scope specifiers that correspond
+ /// to inline namespaces, where the name is unambiguous with the specifier
+ /// removed.
+ unsigned SuppressInlineNamespace : 1;
+
/// Suppress printing of variable initializers.
///
/// This flag is used when printing the loop variable in a for-range
@@ -167,10 +183,18 @@ struct PrintingPolicy {
/// constructors.
unsigned SuppressTemplateArgsInCXXConstructors : 1;
+ /// When true, attempt to suppress template arguments that match the default
+ /// argument for the parameter.
+ unsigned SuppressDefaultTemplateArgs : 1;
+
/// Whether we can use 'bool' rather than '_Bool' (even if the language
/// doesn't actually have 'bool', because, e.g., it is defined as a macro).
unsigned Bool : 1;
+ /// Whether we should use 'nullptr' rather than '0' as a null pointer
+ /// constant.
+ unsigned Nullptr : 1;
+
/// Whether we can use 'restrict' rather than '__restrict'.
unsigned Restrict : 1;
diff --git a/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td b/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td
index ba0f237a3bc3..a087cb406b29 100644
--- a/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td
+++ b/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td
@@ -72,6 +72,8 @@ class CountPropertyType<string typeName = ""> : PropertyType<typeName> {
def APInt : PropertyType<"llvm::APInt"> { let PassByReference = 1; }
def APSInt : PropertyType<"llvm::APSInt"> { let PassByReference = 1; }
+def APValue : PropertyType { let PassByReference = 1; }
+def APValueKind : EnumPropertyType<"APValue::ValueKind">;
def ArraySizeModifier : EnumPropertyType<"ArrayType::ArraySizeModifier">;
def AttrKind : EnumPropertyType<"attr::Kind">;
def AutoTypeKeyword : EnumPropertyType;
@@ -109,7 +111,15 @@ def DeclRef : RefPropertyType<"Decl"> { let ConstWhenWriting = 1; }
SubclassPropertyType<"ValueDecl", DeclRef>;
def ElaboratedTypeKeyword : EnumPropertyType;
def ExtParameterInfo : PropertyType<"FunctionProtoType::ExtParameterInfo">;
+def FixedPointSemantics : PropertyType<"llvm::FixedPointSemantics"> {
+ let PassByReference = 1;
+}
def Identifier : RefPropertyType<"IdentifierInfo"> { let ConstWhenWriting = 1; }
+def LValuePathEntry : PropertyType<"APValue::LValuePathEntry">;
+def LValuePathSerializationHelper :
+ PropertyType<"APValue::LValuePathSerializationHelper"> {
+ let BufferElementTypes = [ LValuePathEntry ];
+}
def NestedNameSpecifier : PropertyType<"NestedNameSpecifier *">;
def NestedNameSpecifierKind :
EnumPropertyType<"NestedNameSpecifier::SpecifierKind">;
@@ -237,6 +247,304 @@ class PropertyTypeCase<PropertyType type, string name> : HasProperties {
string Name = name;
}
+// Type cases for APValue.
+def : PropertyTypeKind<APValue, APValueKind,
+ "node.getKind()">;
+let Class = PropertyTypeCase<APValue, "None"> in {
+ def : Creator<[{ return APValue(); }]>;
+}
+let Class = PropertyTypeCase<APValue, "Indeterminate"> in {
+ def : Creator<[{ return APValue::IndeterminateValue(); }]>;
+}
+let Class = PropertyTypeCase<APValue, "Int"> in {
+ def : Property<"value", APSInt> {
+ let Read = [{ node.getInt() }];
+ }
+ def : Creator<[{ return APValue(value); }]>;
+}
+let Class = PropertyTypeCase<APValue, "Float"> in {
+ def : Property<"semantics", UInt32> {
+ let Read = [{
+ static_cast<uint32_t>(
+ llvm::APFloatBase::SemanticsToEnum(node.getFloat().getSemantics()))
+ }];
+ }
+ def : Property<"value", APInt> {
+ let Read = [{ node.getFloat().bitcastToAPInt() }];
+ }
+ def : Creator<[{
+ const llvm::fltSemantics &floatSema = llvm::APFloatBase::EnumToSemantics(
+ static_cast<llvm::APFloatBase::Semantics>(semantics));
+ return APValue(llvm::APFloat(floatSema, value));
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "FixedPoint"> in {
+ def : Property<"semantics", FixedPointSemantics> {
+ let Read = [{ node.getFixedPoint().getSemantics() }];
+ }
+ def : Property<"value", APSInt> {
+ let Read = [{ node.getFixedPoint().getValue() }];
+ }
+ def : Creator<[{
+ return APValue(llvm::APFixedPoint(std::move(value), semantics));
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "ComplexInt"> in {
+ def : Property<"real", APSInt> {
+ let Read = [{ node.getComplexIntReal() }];
+ }
+ def : Property<"imag", APSInt> {
+ let Read = [{ node.getComplexIntImag() }];
+ }
+ def : Creator<[{ return APValue(real, imag); }]>;
+}
+let Class = PropertyTypeCase<APValue, "ComplexFloat"> in {
+ def : ReadHelper<[{
+ auto sema = llvm::APFloatBase::SemanticsToEnum(
+ node.getComplexFloatReal().getSemantics());
+ assert(sema == llvm::APFloatBase::SemanticsToEnum(
+ node.getComplexFloatImag().getSemantics()));
+ }]>;
+ def : Property<"semantics", UInt32> {
+ let Read = [{ static_cast<uint32_t>(sema) }];
+ }
+ def : Property<"real", APInt> {
+ let Read = [{ node.getComplexFloatReal().bitcastToAPInt() }];
+ }
+ def : Property<"imag", APInt> {
+ let Read = [{ node.getComplexFloatImag().bitcastToAPInt() }];
+ }
+ def : Creator<[{
+ const llvm::fltSemantics &sema = llvm::APFloatBase::EnumToSemantics(
+ static_cast<llvm::APFloatBase::Semantics>(semantics));
+ return APValue(llvm::APFloat(sema, real),
+ llvm::APFloat(sema, imag));
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "Vector"> in {
+ def : ReadHelper<[{
+ SmallVector<APValue, 4> buffer;
+ unsigned len = node.getVectorLength();
+ for (unsigned i = 0; i < len; ++i)
+ buffer.push_back(node.getVectorElt(i));
+ }]>;
+ def : Property<"elements", Array<APValue>> {
+ let Read = [{ buffer }];
+ }
+ def : Creator<[{
+ APValue result;
+ result.MakeVector();
+ unsigned length = elements.size();
+ (void)result.setVectorUninit(length);
+ for (unsigned i = 0; i < length; i++)
+ result.getVectorElt(i) = elements[i];
+ return result;
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "Array"> in {
+ def : ReadHelper<[{
+ SmallVector<APValue, 4> buffer{};
+ unsigned initLength = node.getArrayInitializedElts();
+ for (unsigned i = 0; i < initLength; ++i)
+ buffer.push_back(node.getArrayInitializedElt(i));
+ if (node.hasArrayFiller())
+ buffer.push_back(node.getArrayFiller());
+ }]>;
+ def : Property<"totalLength", UInt32> {
+ let Read = [{ node.getArraySize() }];
+ }
+ def : Property<"hasFiller", Bool> {
+ let Read = [{ node.hasArrayFiller() }];
+ }
+ def : Property<"elements", Array<APValue>> {
+ let Read = [{ buffer }];
+ }
+ def : Creator<[{
+ APValue result;
+ unsigned initLength = elements.size() - (hasFiller ? 1 : 0);
+ result.MakeArray(initLength, totalLength);
+ for (unsigned i = 0; i < initLength; ++i)
+ result.getArrayInitializedElt(i) = elements[i];
+ if (hasFiller)
+ result.getArrayFiller() = elements.back();
+ return result;
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "Struct"> in {
+ def : ReadHelper<[{
+ SmallVector<APValue, 4> structBases;
+ unsigned numBases = node.getStructNumBases();
+ for (unsigned i = 0; i < numBases; ++i)
+ structBases.push_back(node.getStructBase(i));
+ SmallVector<APValue, 4> structFields;
+ unsigned numFields = node.getStructNumFields();
+ for (unsigned i = 0; i < numFields; ++i)
+ structFields.push_back(node.getStructField(i));
+ }]>;
+ def : Property<"bases", Array<APValue>> {
+ let Read = [{ structBases }];
+ }
+ def : Property<"fields", Array<APValue>> {
+ let Read = [{ structFields }];
+ }
+ def : Creator<[{
+ APValue result;
+ result.MakeStruct(bases.size(), fields.size());
+ for (unsigned i = 0; i < bases.size(); ++i)
+ result.getStructBase(i) = bases[i];
+ for (unsigned i = 0; i < fields.size(); ++i)
+ result.getStructField(i) = fields[i];
+ return result;
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "Union"> in {
+ def : Property<"fieldDecl", DeclRef> {
+ let Read = [{ node.getUnionField() }];
+ }
+ def : Property<"value", APValue> {
+ let Read = [{ node.getUnionValue() }];
+ }
+ def : Creator<[{
+ return APValue(cast<clang::FieldDecl>(fieldDecl), std::move(value));
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "AddrLabelDiff"> in {
+ def : Property<"lhs", StmtRef> {
+ let Read = [{ const_cast<AddrLabelExpr *>(node.getAddrLabelDiffLHS()) }];
+ }
+ def : Property<"rhs", StmtRef> {
+ let Read = [{ const_cast<AddrLabelExpr *>(node.getAddrLabelDiffRHS()) }];
+ }
+ def : Creator<[{
+ return APValue(cast<AddrLabelExpr>(lhs), cast<AddrLabelExpr>(rhs));
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "MemberPointer"> in {
+ def : Property<"isDerived", Bool> {
+ let Read = [{ node.isMemberPointerToDerivedMember() }];
+ }
+ def : Property<"member", ValueDeclRef> {
+ let Read = [{ node.getMemberPointerDecl() }];
+ }
+ def : Property<"memberPath", Array<CXXRecordDeclRef>> {
+ let Read = [{ node.getMemberPointerPath() }];
+ }
+ def : Creator<[{
+ APValue result;
+ unsigned pathSize = memberPath.size();
+ const CXXRecordDecl **pathArray =
+ result.setMemberPointerUninit(member, isDerived, pathSize).data();
+ for (unsigned i = 0; i < pathSize; ++i)
+ pathArray[i] = memberPath[i]->getCanonicalDecl();
+ return result;
+ }]>;
+}
+let Class = PropertyTypeCase<APValue, "LValue"> in {
+ def : ReadHelper<[{
+ auto lvalueBase = node.getLValueBase();
+ const Expr *expr =
+ lvalueBase ? lvalueBase.dyn_cast<const Expr *>() : nullptr;
+ bool lvalueBaseIsExpr = (bool) expr;
+ bool lvalueBaseIsTypeInfo = lvalueBase.is<TypeInfoLValue>();
+ QualType elemTy;
+ if (lvalueBase) {
+ if (lvalueBaseIsTypeInfo) {
+ elemTy = lvalueBase.getTypeInfoType();
+ } else if (lvalueBaseIsExpr) {
+ elemTy = expr->getType();
+ } else {
+ elemTy = lvalueBase.get<const ValueDecl *>()->getType();
+ }
+ }
+ }]>;
+ def : Property<"hasLValuePath", Bool> {
+ let Read = [{ node.hasLValuePath() }];
+ }
+ def : Property<"isLValueOnePastTheEnd", Bool> {
+ let Read = [{ node.isLValueOnePastTheEnd() }];
+ }
+ def : Property<"isExpr", Bool> {
+ let Read = [{ lvalueBaseIsExpr }];
+ }
+ def : Property<"isTypeInfo", Bool> {
+ let Read = [{ lvalueBaseIsTypeInfo }];
+ }
+ def : Property<"hasBase", Bool> {
+ let Read = [{ static_cast<bool>(lvalueBase) }];
+ }
+ def : Property<"isNullPtr", Bool> {
+ let Read = [{ node.isNullPointer() }];
+ }
+ def : Property<"typeInfo", QualType> {
+ let Conditional = [{ hasBase && isTypeInfo }];
+ let Read = [{
+ QualType(node.getLValueBase().get<TypeInfoLValue>().getType(), 0)
+ }];
+ }
+ def : Property<"type", QualType> {
+ let Conditional = [{ hasBase && isTypeInfo }];
+ let Read = [{ node.getLValueBase().getTypeInfoType() }];
+ }
+ def : Property<"callIndex", UInt32> {
+ let Conditional = [{ hasBase && !isTypeInfo }];
+ let Read = [{ node.getLValueBase().getCallIndex() }];
+ }
+ def : Property<"version", UInt32> {
+ let Conditional = [{ hasBase && !isTypeInfo }];
+ let Read = [{ node.getLValueBase().getVersion() }];
+ }
+ def : Property<"stmt", StmtRef> {
+ let Conditional = [{ hasBase && !isTypeInfo && isExpr }];
+ let Read = [{ const_cast<Expr *>(expr) }];
+ }
+ def : Property<"decl", DeclRef> {
+ let Conditional = [{ hasBase && !isTypeInfo && !isExpr }];
+ let Read = [{ lvalueBase.get<const ValueDecl *>() }];
+ }
+ def : Property<"offsetQuantity", UInt32> {
+ let Read = [{ node.getLValueOffset().getQuantity() }];
+ }
+ def : Property<"lvaluePath", LValuePathSerializationHelper> {
+ let Conditional = [{ hasLValuePath }];
+ let Read = [{
+ APValue::LValuePathSerializationHelper(node.getLValuePath(), elemTy)
+ }];
+ }
+ def : Creator<[{
+ (void)ctx;
+ APValue::LValueBase base;
+ QualType elemTy;
+ if (hasBase) {
+ if (isTypeInfo) {
+ base = APValue::LValueBase::getTypeInfo(
+ TypeInfoLValue(typeInfo.getValue().getTypePtr()), type.getValue());
+ elemTy = base.getTypeInfoType();
+ } else if (isExpr) {
+ base = APValue::LValueBase(cast<Expr>(stmt.getValue()),
+ callIndex.getValue(), version.getValue());
+ elemTy = base.get<const Expr *>()->getType();
+ } else {
+ base = APValue::LValueBase(cast<ValueDecl>(decl.getValue()),
+ callIndex.getValue(), version.getValue());
+ elemTy = base.get<const ValueDecl *>()->getType();
+ }
+ }
+ CharUnits offset = CharUnits::fromQuantity(offsetQuantity);
+ APValue result;
+ result.MakeLValue();
+ if (!hasLValuePath) {
+ result.setLValue(base, offset, APValue::NoLValuePath{}, isNullPtr);
+ return result;
+ }
+ auto pathLength = lvaluePath->Path.size();
+ APValue::LValuePathEntry *path = result.setLValueUninit(
+ base, offset, pathLength, isLValueOnePastTheEnd, isNullPtr).data();
+ assert(lvaluePath->getType() == elemTy && "Unexpected type reference!");
+ llvm::copy(lvaluePath->Path, path);
+ return result;
+ }]>;
+}
+
// Type cases for DeclarationName.
def : PropertyTypeKind<DeclarationName, DeclarationNameKind,
"node.getNameKind()">;
diff --git a/contrib/llvm-project/clang/include/clang/AST/RecordLayout.h b/contrib/llvm-project/clang/include/clang/AST/RecordLayout.h
index b259791af509..dd18f9c49f84 100644
--- a/contrib/llvm-project/clang/include/clang/AST/RecordLayout.h
+++ b/contrib/llvm-project/clang/include/clang/AST/RecordLayout.h
@@ -70,6 +70,11 @@ private:
// Alignment - Alignment of record in characters.
CharUnits Alignment;
+ // PreferredAlignment - Preferred alignment of record in characters. This
+ // can be different than Alignment in cases where it is beneficial for
+ // performance or backwards compatibility preserving (e.g. AIX-ABI).
+ CharUnits PreferredAlignment;
+
// UnadjustedAlignment - Maximum of the alignments of the record members in
// characters.
CharUnits UnadjustedAlignment;
@@ -91,6 +96,11 @@ private:
/// which is the alignment of the object without virtual bases.
CharUnits NonVirtualAlignment;
+ /// PreferredNVAlignment - The preferred non-virtual alignment (in chars) of
+ /// an object, which is the preferred alignment of the object without
+ /// virtual bases.
+ CharUnits PreferredNVAlignment;
+
/// SizeOfLargestEmptySubobject - The size of the largest empty subobject
/// (either a base or a member). Will be zero if the class doesn't contain
/// any empty subobjects.
@@ -139,30 +149,26 @@ private:
CXXRecordLayoutInfo *CXXInfo = nullptr;
ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment,
- CharUnits unadjustedAlignment,
+ CharUnits preferredAlignment, CharUnits unadjustedAlignment,
CharUnits requiredAlignment, CharUnits datasize,
ArrayRef<uint64_t> fieldoffsets);
using BaseOffsetsMapTy = CXXRecordLayoutInfo::BaseOffsetsMapTy;
// Constructor for C++ records.
- ASTRecordLayout(const ASTContext &Ctx,
- CharUnits size, CharUnits alignment,
- CharUnits unadjustedAlignment,
- CharUnits requiredAlignment,
- bool hasOwnVFPtr, bool hasExtendableVFPtr,
- CharUnits vbptroffset,
- CharUnits datasize,
- ArrayRef<uint64_t> fieldoffsets,
+ ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment,
+ CharUnits preferredAlignment, CharUnits unadjustedAlignment,
+ CharUnits requiredAlignment, bool hasOwnVFPtr,
+ bool hasExtendableVFPtr, CharUnits vbptroffset,
+ CharUnits datasize, ArrayRef<uint64_t> fieldoffsets,
CharUnits nonvirtualsize, CharUnits nonvirtualalignment,
+ CharUnits preferrednvalignment,
CharUnits SizeOfLargestEmptySubobject,
- const CXXRecordDecl *PrimaryBase,
- bool IsPrimaryBaseVirtual,
+ const CXXRecordDecl *PrimaryBase, bool IsPrimaryBaseVirtual,
const CXXRecordDecl *BaseSharingVBPtr,
- bool EndsWithZeroSizedObject,
- bool LeadsWithZeroSizedBase,
- const BaseOffsetsMapTy& BaseOffsets,
- const VBaseOffsetsMapTy& VBaseOffsets);
+ bool EndsWithZeroSizedObject, bool LeadsWithZeroSizedBase,
+ const BaseOffsetsMapTy &BaseOffsets,
+ const VBaseOffsetsMapTy &VBaseOffsets);
~ASTRecordLayout() = default;
@@ -175,6 +181,10 @@ public:
/// getAlignment - Get the record alignment in characters.
CharUnits getAlignment() const { return Alignment; }
+ /// getPreferredFieldAlignment - Get the record preferred alignment in
+ /// characters.
+ CharUnits getPreferredAlignment() const { return PreferredAlignment; }
+
/// getUnadjustedAlignment - Get the record alignment in characters, before
/// alignment adjustement.
CharUnits getUnadjustedAlignment() const { return UnadjustedAlignment; }
@@ -193,9 +203,7 @@ public:
/// getDataSize() - Get the record data size, which is the record size
/// without tail padding, in characters.
- CharUnits getDataSize() const {
- return DataSize;
- }
+ CharUnits getDataSize() const { return DataSize; }
/// getNonVirtualSize - Get the non-virtual size (in chars) of an object,
/// which is the size of the object without virtual bases.
@@ -205,14 +213,23 @@ public:
return CXXInfo->NonVirtualSize;
}
- /// getNonVirtualSize - Get the non-virtual alignment (in chars) of an object,
- /// which is the alignment of the object without virtual bases.
+ /// getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an
+ /// object, which is the alignment of the object without virtual bases.
CharUnits getNonVirtualAlignment() const {
assert(CXXInfo && "Record layout does not have C++ specific info!");
return CXXInfo->NonVirtualAlignment;
}
+ /// getPreferredNVAlignment - Get the preferred non-virtual alignment (in
+ /// chars) of an object, which is the preferred alignment of the object
+ /// without virtual bases.
+ CharUnits getPreferredNVAlignment() const {
+ assert(CXXInfo && "Record layout does not have C++ specific info!");
+
+ return CXXInfo->PreferredNVAlignment;
+ }
+
/// getPrimaryBase - Get the primary base for this record.
const CXXRecordDecl *getPrimaryBase() const {
assert(CXXInfo && "Record layout does not have C++ specific info!");
@@ -231,6 +248,8 @@ public:
/// getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const {
assert(CXXInfo && "Record layout does not have C++ specific info!");
+
+ Base = Base->getDefinition();
assert(CXXInfo->BaseOffsets.count(Base) && "Did not find base!");
return CXXInfo->BaseOffsets[Base];
@@ -239,6 +258,8 @@ public:
/// getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const {
assert(CXXInfo && "Record layout does not have C++ specific info!");
+
+ VBase = VBase->getDefinition();
assert(CXXInfo->VBaseOffsets.count(VBase) && "Did not find base!");
return CXXInfo->VBaseOffsets[VBase].VBaseOffset;
@@ -287,9 +308,7 @@ public:
return !CXXInfo->VBPtrOffset.isNegative();
}
- CharUnits getRequiredAlignment() const {
- return RequiredAlignment;
- }
+ CharUnits getRequiredAlignment() const { return RequiredAlignment; }
bool endsWithZeroSizedObject() const {
return CXXInfo && CXXInfo->EndsWithZeroSizedObject;
diff --git a/contrib/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h b/contrib/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h
index 3dcfc9fee629..7870cea198a7 100644
--- a/contrib/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/contrib/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -186,6 +186,9 @@ public:
/// code, e.g., implicit constructors and destructors.
bool shouldVisitImplicitCode() const { return false; }
+ /// Return whether this visitor should recurse into lambda body
+ bool shouldVisitLambdaBody() const { return true; }
+
/// Return whether this visitor should traverse post-order.
bool shouldTraversePostOrder() const { return false; }
@@ -461,6 +464,15 @@ public:
bool canIgnoreChildDeclWhileTraversingDeclContext(const Decl *Child);
+#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND) \
+ bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
+ DEF_TRAVERSE_TMPL_INST(Class)
+ DEF_TRAVERSE_TMPL_INST(Var)
+ DEF_TRAVERSE_TMPL_INST(Function)
+#undef DEF_TRAVERSE_TMPL_INST
+
+ bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
+
private:
// These are helper methods used by more than one Traverse* method.
bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
@@ -469,12 +481,6 @@ private:
template <typename T>
bool TraverseDeclTemplateParameterLists(T *D);
-#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND) \
- bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
- DEF_TRAVERSE_TMPL_INST(Class)
- DEF_TRAVERSE_TMPL_INST(Var)
- DEF_TRAVERSE_TMPL_INST(Function)
-#undef DEF_TRAVERSE_TMPL_INST
bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
unsigned Count);
bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
@@ -487,15 +493,15 @@ private:
bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
bool TraverseOMPLoopDirective(OMPLoopDirective *S);
bool TraverseOMPClause(OMPClause *C);
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) bool Visit##Class(Class *C);
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) bool Visit##Class(Class *C);
+#include "llvm/Frontend/OpenMP/OMP.inc"
/// Process clauses with list of variables.
template <typename T> bool VisitOMPClauseList(T *Node);
/// Process clauses with pre-initis.
bool VisitOMPClauseWithPreInit(OMPClauseWithPreInit *Node);
bool VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *Node);
- bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
bool PostVisitStmt(Stmt *S);
};
@@ -1777,8 +1783,17 @@ DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
// D is the "T" in something like "template<typename T> class vector;"
if (D->getTypeForDecl())
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
- if (const auto *TC = D->getTypeConstraint())
- TRY_TO(TraverseConceptReference(*TC));
+ if (const auto *TC = D->getTypeConstraint()) {
+ if (Expr *IDC = TC->getImmediatelyDeclaredConstraint()) {
+ TRY_TO(TraverseStmt(IDC));
+ } else {
+ // Avoid traversing the ConceptReference in the TypeCosntraint
+ // if we have an immediately-declared-constraint, otherwise
+ // we'll end up visiting the concept and the arguments in
+ // the TC twice.
+ TRY_TO(TraverseConceptReference(*TC));
+ }
+ }
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
})
@@ -1961,6 +1976,8 @@ DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
DEF_TRAVERSE_DECL(MSGuidDecl, {})
+DEF_TRAVERSE_DECL(TemplateParamObjectDecl, {})
+
DEF_TRAVERSE_DECL(FieldDecl, {
TRY_TO(TraverseDeclaratorHelper(D));
if (D->isBitField())
@@ -2043,6 +2060,15 @@ bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
// by clang.
(!D->isDefaulted() || getDerived().shouldVisitImplicitCode());
+ if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
+ if (const CXXRecordDecl *RD = MD->getParent()) {
+ if (RD->isLambda() &&
+ declaresSameEntity(RD->getLambdaCallOperator(), MD)) {
+ VisitBody = VisitBody && getDerived().shouldVisitLambdaBody();
+ }
+ }
+ }
+
if (VisitBody) {
TRY_TO(TraverseStmt(D->getBody())); // Function body.
}
@@ -2491,17 +2517,12 @@ DEF_TRAVERSE_STMT(LambdaExpr, {
TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
FunctionProtoTypeLoc Proto = TL.getAsAdjusted<FunctionProtoTypeLoc>();
- for (Decl *D : S->getExplicitTemplateParameters()) {
- // Visit explicit template parameters.
- TRY_TO(TraverseDecl(D));
- }
+ TRY_TO(TraverseTemplateParameterListHelper(S->getTemplateParameterList()));
if (S->hasExplicitParameters()) {
// Visit parameters.
for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
TRY_TO(TraverseDecl(Proto.getParam(I)));
}
- if (S->hasExplicitResultType())
- TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
auto *T = Proto.getTypePtr();
for (const auto &E : T->exceptions())
@@ -2510,6 +2531,10 @@ DEF_TRAVERSE_STMT(LambdaExpr, {
if (Expr *NE = T->getNoexceptExpr())
TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(NE);
+ if (S->hasExplicitResultType())
+ TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
+ TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getTrailingRequiresClause());
+
TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getBody());
}
ShouldVisitChildren = false;
@@ -2938,16 +2963,15 @@ bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
if (!C)
return true;
switch (C->getClauseKind()) {
-#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
+#define GEN_CLANG_CLAUSE_CLASS
+#define CLAUSE_CLASS(Enum, Str, Class) \
case llvm::omp::Clause::Enum: \
TRY_TO(Visit##Class(static_cast<Class *>(C))); \
break;
-#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
+#define CLAUSE_NO_CLASS(Enum, Str) \
case llvm::omp::Clause::Enum: \
break;
-#include "llvm/Frontend/OpenMP/OMPKinds.def"
- default:
- break;
+#include "llvm/Frontend/OpenMP/OMP.inc"
}
return true;
}
diff --git a/contrib/llvm-project/clang/include/clang/AST/Redeclarable.h b/contrib/llvm-project/clang/include/clang/AST/Redeclarable.h
index 0975773dd2cb..87252337a0f4 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Redeclarable.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Redeclarable.h
@@ -370,6 +370,7 @@ public:
private:
friend struct llvm::DenseMapInfo<CanonicalDeclPtr<decl_type>>;
+ friend struct llvm::PointerLikeTypeTraits<CanonicalDeclPtr<decl_type>>;
decl_type *Ptr = nullptr;
};
@@ -407,6 +408,20 @@ struct DenseMapInfo<clang::CanonicalDeclPtr<decl_type>> {
}
};
+template <typename decl_type>
+struct PointerLikeTypeTraits<clang::CanonicalDeclPtr<decl_type>> {
+ static inline void *getAsVoidPointer(clang::CanonicalDeclPtr<decl_type> P) {
+ return P.Ptr;
+ }
+ static inline clang::CanonicalDeclPtr<decl_type> getFromVoidPointer(void *P) {
+ clang::CanonicalDeclPtr<decl_type> C;
+ C.Ptr = PointerLikeTypeTraits<decl_type *>::getFromVoidPtr(P);
+ return C;
+ }
+ static constexpr int NumLowBitsAvailable =
+ PointerLikeTypeTraits<decl_type *>::NumLowBitsAvailable;
+};
+
} // namespace llvm
#endif // LLVM_CLANG_AST_REDECLARABLE_H
diff --git a/contrib/llvm-project/clang/include/clang/AST/Stmt.h b/contrib/llvm-project/clang/include/clang/AST/Stmt.h
index d3fad58fcf59..c2e69a91e55d 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Stmt.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Stmt.h
@@ -464,8 +464,11 @@ protected:
/// True if the callee of the call expression was found using ADL.
unsigned UsesADL : 1;
+ /// True if the call expression has some floating-point features.
+ unsigned HasFPFeatures : 1;
+
/// Padding used to align OffsetToTrailingObjects to a byte multiple.
- unsigned : 24 - 2 - NumExprBits;
+ unsigned : 24 - 3 - NumExprBits;
/// The offset in bytes from the this pointer to the start of the
/// trailing objects belonging to CallExpr. Intentionally byte sized
@@ -518,6 +521,9 @@ protected:
unsigned Kind : 6;
unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
+ /// True if the call expression has some floating-point features.
+ unsigned HasFPFeatures : 1;
+
/// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
/// here. ([implimits] Direct and indirect base classes [16384]).
unsigned BasePathSize;
@@ -1095,6 +1101,14 @@ public:
/// de-serialization).
struct EmptyShell {};
+ /// The likelihood of a branch being taken.
+ enum Likelihood {
+ LH_Unlikely = -1, ///< Branch has the [[unlikely]] attribute.
+ LH_None, ///< No attribute set or branches of the IfStmt have
+ ///< the same attribute.
+ LH_Likely ///< Branch has the [[likely]] attribute.
+ };
+
protected:
/// Iterator for iterating over Stmt * arrays that contain only T *.
///
@@ -1163,6 +1177,26 @@ public:
static void EnableStatistics();
static void PrintStats();
+ /// \returns the likelihood of a set of attributes.
+ static Likelihood getLikelihood(ArrayRef<const Attr *> Attrs);
+
+ /// \returns the likelihood of a statement.
+ static Likelihood getLikelihood(const Stmt *S);
+
+ /// \returns the likelihood attribute of a statement.
+ static const Attr *getLikelihoodAttr(const Stmt *S);
+
+ /// \returns the likelihood of the 'then' branch of an 'if' statement. The
+ /// 'else' branch is required to determine whether both branches specify the
+ /// same likelihood, which affects the result.
+ static Likelihood getLikelihood(const Stmt *Then, const Stmt *Else);
+
+ /// \returns whether the likelihood of the branches of an if statement are
+ /// conflicting. When the first element is \c true there's a conflict and
+ /// the Attr's are the conflicting attributes of the Then and Else Stmt.
+ static std::tuple<bool, const Attr *, const Attr *>
+ determineLikelihoodConflict(const Stmt *Then, const Stmt *Else);
+
/// Dumps the specified AST fragment and all subtrees to
/// \c llvm::errs().
void dump() const;
@@ -1892,6 +1926,8 @@ class IfStmt final
// Present if and only if hasElseStorage().
enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
enum { NumMandatoryStmtPtr = 2 };
+ SourceLocation LParenLoc;
+ SourceLocation RParenLoc;
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
@@ -1912,7 +1948,8 @@ class IfStmt final
/// Build an if/then/else statement.
IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init,
- VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL, Stmt *Else);
+ VarDecl *Var, Expr *Cond, SourceLocation LParenLoc,
+ SourceLocation RParenLoc, Stmt *Then, SourceLocation EL, Stmt *Else);
/// Build an empty if/then/else statement.
explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
@@ -1921,7 +1958,8 @@ public:
/// Create an IfStmt.
static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
- Stmt *Then, SourceLocation EL = SourceLocation(),
+ SourceLocation LPL, SourceLocation RPL, Stmt *Then,
+ SourceLocation EL = SourceLocation(),
Stmt *Else = nullptr);
/// Create an empty IfStmt optionally with storage for an else statement,
@@ -2051,6 +2089,10 @@ public:
return getElse()->getEndLoc();
return getThen()->getEndLoc();
}
+ SourceLocation getLParenLoc() const { return LParenLoc; }
+ void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+ SourceLocation getRParenLoc() const { return RParenLoc; }
+ void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
// Iterators over subexpressions. The iterators will include iterating
// over the initialization expression referenced by the condition variable.
@@ -2098,6 +2140,8 @@ class SwitchStmt final : public Stmt,
// Always present.
enum { InitOffset = 0, BodyOffsetFromCond = 1 };
enum { NumMandatoryStmtPtr = 2 };
+ SourceLocation LParenLoc;
+ SourceLocation RParenLoc;
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
@@ -2111,7 +2155,8 @@ class SwitchStmt final : public Stmt,
unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
/// Build a switch statement.
- SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
+ SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond,
+ SourceLocation LParenLoc, SourceLocation RParenLoc);
/// Build a empty switch statement.
explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
@@ -2119,7 +2164,8 @@ class SwitchStmt final : public Stmt,
public:
/// Create a switch statement.
static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
- Expr *Cond);
+ Expr *Cond, SourceLocation LParenLoc,
+ SourceLocation RParenLoc);
/// Create an empty switch statement optionally with storage for
/// an init expression and a condition variable.
@@ -2207,6 +2253,10 @@ public:
SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
+ SourceLocation getLParenLoc() const { return LParenLoc; }
+ void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+ SourceLocation getRParenLoc() const { return RParenLoc; }
+ void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
void setBody(Stmt *S, SourceLocation SL) {
setBody(S);
diff --git a/contrib/llvm-project/clang/include/clang/AST/StmtIterator.h b/contrib/llvm-project/clang/include/clang/AST/StmtIterator.h
index 911205347aad..bcdb0df829fb 100644
--- a/contrib/llvm-project/clang/include/clang/AST/StmtIterator.h
+++ b/contrib/llvm-project/clang/include/clang/AST/StmtIterator.h
@@ -104,12 +104,13 @@ public:
return tmp;
}
- bool operator==(const DERIVED& RHS) const {
- return stmt == RHS.stmt && DGI == RHS.DGI && RawVAPtr == RHS.RawVAPtr;
+ friend bool operator==(const DERIVED &LHS, const DERIVED &RHS) {
+ return LHS.stmt == RHS.stmt && LHS.DGI == RHS.DGI &&
+ LHS.RawVAPtr == RHS.RawVAPtr;
}
- bool operator!=(const DERIVED& RHS) const {
- return stmt != RHS.stmt || DGI != RHS.DGI || RawVAPtr != RHS.RawVAPtr;
+ friend bool operator!=(const DERIVED &LHS, const DERIVED &RHS) {
+ return !(LHS == RHS);
}
REFERENCE operator*() const {
diff --git a/contrib/llvm-project/clang/include/clang/AST/StmtOpenMP.h b/contrib/llvm-project/clang/include/clang/AST/StmtOpenMP.h
index bd87eafc9034..b7bbf15949a0 100644
--- a/contrib/llvm-project/clang/include/clang/AST/StmtOpenMP.h
+++ b/contrib/llvm-project/clang/include/clang/AST/StmtOpenMP.h
@@ -14,6 +14,7 @@
#ifndef LLVM_CLANG_AST_STMTOPENMP_H
#define LLVM_CLANG_AST_STMTOPENMP_H
+#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Stmt.h"
@@ -32,30 +33,26 @@ namespace clang {
///
class OMPExecutableDirective : public Stmt {
friend class ASTStmtReader;
+ friend class ASTStmtWriter;
+
/// Kind of the directive.
- OpenMPDirectiveKind Kind;
+ OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
/// Starting location of the directive (directive keyword).
SourceLocation StartLoc;
/// Ending location of the directive.
SourceLocation EndLoc;
- /// Numbers of clauses.
- const unsigned NumClauses;
- /// Number of child expressions/stmts.
- const unsigned NumChildren;
- /// Offset from this to the start of clauses.
- /// There are NumClauses pointers to clauses, they are followed by
- /// NumChildren pointers to child stmts/exprs (if the directive type
- /// requires an associated stmt, then it has to be the first of them).
- const unsigned ClausesOffset;
/// Get the clauses storage.
MutableArrayRef<OMPClause *> getClauses() {
- OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>(
- reinterpret_cast<char *>(this) + ClausesOffset);
- return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses);
+ if (!Data)
+ return llvm::None;
+ return Data->getClauses();
}
protected:
+ /// Data, associated with the directive.
+ OMPChildren *Data = nullptr;
+
/// Build instance of directive of class \a K.
///
/// \param SC Statement class.
@@ -63,28 +60,57 @@ protected:
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
///
- template <typename T>
- OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K,
- SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses, unsigned NumChildren)
+ OMPExecutableDirective(StmtClass SC, OpenMPDirectiveKind K,
+ SourceLocation StartLoc, SourceLocation EndLoc)
: Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)),
- EndLoc(std::move(EndLoc)), NumClauses(NumClauses),
- NumChildren(NumChildren),
- ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {}
-
- /// Sets the list of variables for this clause.
- ///
- /// \param Clauses The list of clauses for the directive.
- ///
- void setClauses(ArrayRef<OMPClause *> Clauses);
+ EndLoc(std::move(EndLoc)) {}
+
+ template <typename T, typename... Params>
+ static T *createDirective(const ASTContext &C, ArrayRef<OMPClause *> Clauses,
+ Stmt *AssociatedStmt, unsigned NumChildren,
+ Params &&... P) {
+ void *Mem =
+ C.Allocate(sizeof(T) + OMPChildren::size(Clauses.size(), AssociatedStmt,
+ NumChildren),
+ alignof(T));
+
+ auto *Data = OMPChildren::Create(reinterpret_cast<T *>(Mem) + 1, Clauses,
+ AssociatedStmt, NumChildren);
+ auto *Inst = new (Mem) T(std::forward<Params>(P)...);
+ Inst->Data = Data;
+ return Inst;
+ }
+
+ template <typename T, typename... Params>
+ static T *createEmptyDirective(const ASTContext &C, unsigned NumClauses,
+ bool HasAssociatedStmt, unsigned NumChildren,
+ Params &&... P) {
+ void *Mem =
+ C.Allocate(sizeof(T) + OMPChildren::size(NumClauses, HasAssociatedStmt,
+ NumChildren),
+ alignof(T));
+ auto *Data =
+ OMPChildren::CreateEmpty(reinterpret_cast<T *>(Mem) + 1, NumClauses,
+ HasAssociatedStmt, NumChildren);
+ auto *Inst = new (Mem) T(std::forward<Params>(P)...);
+ Inst->Data = Data;
+ return Inst;
+ }
- /// Set the associated statement for the directive.
- ///
- /// /param S Associated statement.
- ///
- void setAssociatedStmt(Stmt *S) {
- assert(hasAssociatedStmt() && "no associated statement.");
- *child_begin() = S;
+ template <typename T>
+ static T *createEmptyDirective(const ASTContext &C, unsigned NumClauses,
+ bool HasAssociatedStmt = false,
+ unsigned NumChildren = 0) {
+ void *Mem =
+ C.Allocate(sizeof(T) + OMPChildren::size(NumClauses, HasAssociatedStmt,
+ NumChildren),
+ alignof(T));
+ auto *Data =
+ OMPChildren::CreateEmpty(reinterpret_cast<T *>(Mem) + 1, NumClauses,
+ HasAssociatedStmt, NumChildren);
+ auto *Inst = new (Mem) T;
+ Inst->Data = Data;
+ return Inst;
}
public:
@@ -238,59 +264,50 @@ public:
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// Get number of clauses.
- unsigned getNumClauses() const { return NumClauses; }
+ unsigned getNumClauses() const {
+ if (!Data)
+ return 0;
+ return Data->getNumClauses();
+ }
/// Returns specified clause.
///
- /// \param i Number of clause.
+ /// \param I Number of clause.
///
- OMPClause *getClause(unsigned i) const { return clauses()[i]; }
+ OMPClause *getClause(unsigned I) const { return clauses()[I]; }
/// Returns true if directive has associated statement.
- bool hasAssociatedStmt() const { return NumChildren > 0; }
+ bool hasAssociatedStmt() const { return Data && Data->hasAssociatedStmt(); }
/// Returns statement associated with the directive.
const Stmt *getAssociatedStmt() const {
- assert(hasAssociatedStmt() && "no associated statement.");
- return *child_begin();
+ return const_cast<OMPExecutableDirective *>(this)->getAssociatedStmt();
}
Stmt *getAssociatedStmt() {
- assert(hasAssociatedStmt() && "no associated statement.");
- return *child_begin();
+ assert(hasAssociatedStmt() &&
+ "Expected directive with the associated statement.");
+ return Data->getAssociatedStmt();
}
/// Returns the captured statement associated with the
/// component region within the (combined) directive.
- //
- // \param RegionKind Component region kind.
+ ///
+ /// \param RegionKind Component region kind.
const CapturedStmt *getCapturedStmt(OpenMPDirectiveKind RegionKind) const {
+ assert(hasAssociatedStmt() &&
+ "Expected directive with the associated statement.");
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
- assert(std::any_of(
- CaptureRegions.begin(), CaptureRegions.end(),
- [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) &&
- "RegionKind not found in OpenMP CaptureRegions.");
- auto *CS = cast<CapturedStmt>(getAssociatedStmt());
- for (auto ThisCaptureRegion : CaptureRegions) {
- if (ThisCaptureRegion == RegionKind)
- return CS;
- CS = cast<CapturedStmt>(CS->getCapturedStmt());
- }
- llvm_unreachable("Incorrect RegionKind specified for directive.");
+ return Data->getCapturedStmt(RegionKind, CaptureRegions);
}
/// Get innermost captured statement for the construct.
CapturedStmt *getInnermostCapturedStmt() {
- assert(hasAssociatedStmt() && getAssociatedStmt() &&
- "Must have associated statement.");
+ assert(hasAssociatedStmt() &&
+ "Expected directive with the associated statement.");
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
- assert(!CaptureRegions.empty() &&
- "At least one captured statement must be provided.");
- auto *CS = cast<CapturedStmt>(getAssociatedStmt());
- for (unsigned Level = CaptureRegions.size(); Level > 1; --Level)
- CS = cast<CapturedStmt>(CS->getCapturedStmt());
- return CS;
+ return Data->getInnermostCapturedStmt(CaptureRegions);
}
const CapturedStmt *getInnermostCapturedStmt() const {
@@ -306,26 +323,19 @@ public:
}
child_range children() {
- if (!hasAssociatedStmt())
+ if (!Data)
return child_range(child_iterator(), child_iterator());
- Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end());
- /// Do not mark all the special expression/statements as children, except
- /// for the associated statement.
- return child_range(ChildStorage, ChildStorage + 1);
+ return Data->getAssociatedStmtAsRange();
}
const_child_range children() const {
- if (!hasAssociatedStmt())
- return const_child_range(const_child_iterator(), const_child_iterator());
- Stmt **ChildStorage = reinterpret_cast<Stmt **>(
- const_cast<OMPExecutableDirective *>(this)->getClauses().end());
- return const_child_range(ChildStorage, ChildStorage + 1);
+ return const_cast<OMPExecutableDirective *>(this)->children();
}
- ArrayRef<OMPClause *> clauses() { return getClauses(); }
-
ArrayRef<OMPClause *> clauses() const {
- return const_cast<OMPExecutableDirective *>(this)->getClauses();
+ if (!Data)
+ return llvm::None;
+ return Data->getClauses();
}
/// Returns whether or not this is a Standalone directive.
@@ -337,11 +347,18 @@ public:
/// Returns the AST node representing OpenMP structured-block of this
/// OpenMP executable directive,
/// Prerequisite: Executable Directive must not be Standalone directive.
- const Stmt *getStructuredBlock() const;
+ const Stmt *getStructuredBlock() const {
+ return const_cast<OMPExecutableDirective *>(this)->getStructuredBlock();
+ }
+ Stmt *getStructuredBlock();
- Stmt *getStructuredBlock() {
- return const_cast<Stmt *>(
- const_cast<const OMPExecutableDirective *>(this)->getStructuredBlock());
+ const Stmt *getRawStmt() const {
+ return const_cast<OMPExecutableDirective *>(this)->getRawStmt();
+ }
+ Stmt *getRawStmt() {
+ assert(hasAssociatedStmt() &&
+ "Expected directive with the associated statement.");
+ return Data->getRawStmt();
}
};
@@ -356,36 +373,28 @@ public:
///
class OMPParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending Location of the directive.
///
- OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelDirectiveClass,
- llvm::omp::OMPD_parallel, StartLoc, EndLoc,
- NumClauses, 1),
- HasCancel(false) {}
+ OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPParallelDirectiveClass,
+ llvm::omp::OMPD_parallel, StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPParallelDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelDirectiveClass,
+ explicit OMPParallelDirective()
+ : OMPExecutableDirective(OMPParallelDirectiveClass,
llvm::omp::OMPD_parallel, SourceLocation(),
- SourceLocation(), NumClauses, 1),
- HasCancel(false) {}
+ SourceLocation()) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) { Data->getChildren()[0] = E; }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -416,8 +425,12 @@ public:
unsigned NumClauses, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPParallelDirective *>(this)->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -433,7 +446,7 @@ public:
class OMPLoopDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Number of collapsed loops as specified by 'collapse' clause.
- unsigned CollapsedNum;
+ unsigned CollapsedNum = 0;
/// Offsets to the stored exprs.
/// This enumeration contains offsets to all the pointers to children
@@ -452,110 +465,110 @@ class OMPLoopDirective : public OMPExecutableDirective {
/// (e.g. 'distribute parallel for')
///
enum {
- AssociatedStmtOffset = 0,
- IterationVariableOffset = 1,
- LastIterationOffset = 2,
- CalcLastIterationOffset = 3,
- PreConditionOffset = 4,
- CondOffset = 5,
- InitOffset = 6,
- IncOffset = 7,
- PreInitsOffset = 8,
+ IterationVariableOffset = 0,
+ LastIterationOffset = 1,
+ CalcLastIterationOffset = 2,
+ PreConditionOffset = 3,
+ CondOffset = 4,
+ InitOffset = 5,
+ IncOffset = 6,
+ PreInitsOffset = 7,
// The '...End' enumerators do not correspond to child expressions - they
// specify the offset to the end (and start of the following counters/
// updates/finals/dependent_counters/dependent_inits/finals_conditions
// arrays).
- DefaultEnd = 9,
+ DefaultEnd = 8,
// The following 8 exprs are used by worksharing and distribute loops only.
- IsLastIterVariableOffset = 9,
- LowerBoundVariableOffset = 10,
- UpperBoundVariableOffset = 11,
- StrideVariableOffset = 12,
- EnsureUpperBoundOffset = 13,
- NextLowerBoundOffset = 14,
- NextUpperBoundOffset = 15,
- NumIterationsOffset = 16,
+ IsLastIterVariableOffset = 8,
+ LowerBoundVariableOffset = 9,
+ UpperBoundVariableOffset = 10,
+ StrideVariableOffset = 11,
+ EnsureUpperBoundOffset = 12,
+ NextLowerBoundOffset = 13,
+ NextUpperBoundOffset = 14,
+ NumIterationsOffset = 15,
// Offset to the end for worksharing loop directives.
- WorksharingEnd = 17,
- PrevLowerBoundVariableOffset = 17,
- PrevUpperBoundVariableOffset = 18,
- DistIncOffset = 19,
- PrevEnsureUpperBoundOffset = 20,
- CombinedLowerBoundVariableOffset = 21,
- CombinedUpperBoundVariableOffset = 22,
- CombinedEnsureUpperBoundOffset = 23,
- CombinedInitOffset = 24,
- CombinedConditionOffset = 25,
- CombinedNextLowerBoundOffset = 26,
- CombinedNextUpperBoundOffset = 27,
- CombinedDistConditionOffset = 28,
- CombinedParForInDistConditionOffset = 29,
+ WorksharingEnd = 16,
+ PrevLowerBoundVariableOffset = 16,
+ PrevUpperBoundVariableOffset = 17,
+ DistIncOffset = 18,
+ PrevEnsureUpperBoundOffset = 19,
+ CombinedLowerBoundVariableOffset = 20,
+ CombinedUpperBoundVariableOffset = 21,
+ CombinedEnsureUpperBoundOffset = 22,
+ CombinedInitOffset = 23,
+ CombinedConditionOffset = 24,
+ CombinedNextLowerBoundOffset = 25,
+ CombinedNextUpperBoundOffset = 26,
+ CombinedDistConditionOffset = 27,
+ CombinedParForInDistConditionOffset = 28,
// Offset to the end (and start of the following
// counters/updates/finals/dependent_counters/dependent_inits/finals_conditions
// arrays) for combined distribute loop directives.
- CombinedDistributeEnd = 30,
+ CombinedDistributeEnd = 29,
};
/// Get the counters storage.
MutableArrayRef<Expr *> getCounters() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &(*(std::next(child_begin(), getArraysOffset(getDirectiveKind())))));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind())]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the private counters storage.
MutableArrayRef<Expr *> getPrivateCounters() {
- Expr **Storage = reinterpret_cast<Expr **>(&*std::next(
- child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getInits() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 2 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getUpdates() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 3 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the final counter updates storage.
MutableArrayRef<Expr *> getFinals() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 4 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the dependent counters storage.
MutableArrayRef<Expr *> getDependentCounters() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 5 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 5 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the dependent inits storage.
MutableArrayRef<Expr *> getDependentInits() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 6 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 6 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
/// Get the finals conditions storage.
MutableArrayRef<Expr *> getFinalsConditions() {
- Expr **Storage = reinterpret_cast<Expr **>(
- &*std::next(child_begin(),
- getArraysOffset(getDirectiveKind()) + 7 * CollapsedNum));
- return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+ auto **Storage = reinterpret_cast<Expr **>(
+ &Data->getChildren()[getArraysOffset(getDirectiveKind()) +
+ 7 * CollapsedNum]);
+ return llvm::makeMutableArrayRef(Storage, CollapsedNum);
}
protected:
@@ -566,17 +579,11 @@ protected:
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed loops from 'collapse' clause.
- /// \param NumClauses Number of clauses.
- /// \param NumSpecialChildren Number of additional directive-specific stmts.
///
- template <typename T>
- OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind,
+ OMPLoopDirective(StmtClass SC, OpenMPDirectiveKind Kind,
SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses,
- unsigned NumSpecialChildren = 0)
- : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses,
- numLoopChildren(CollapsedNum, Kind) +
- NumSpecialChildren),
+ unsigned CollapsedNum)
+ : OMPExecutableDirective(SC, Kind, StartLoc, EndLoc),
CollapsedNum(CollapsedNum) {}
/// Offset to the start of children expression arrays.
@@ -599,146 +606,142 @@ protected:
}
void setIterationVariable(Expr *IV) {
- *std::next(child_begin(), IterationVariableOffset) = IV;
+ Data->getChildren()[IterationVariableOffset] = IV;
}
void setLastIteration(Expr *LI) {
- *std::next(child_begin(), LastIterationOffset) = LI;
+ Data->getChildren()[LastIterationOffset] = LI;
}
void setCalcLastIteration(Expr *CLI) {
- *std::next(child_begin(), CalcLastIterationOffset) = CLI;
- }
- void setPreCond(Expr *PC) {
- *std::next(child_begin(), PreConditionOffset) = PC;
+ Data->getChildren()[CalcLastIterationOffset] = CLI;
}
- void setCond(Expr *Cond) {
- *std::next(child_begin(), CondOffset) = Cond;
- }
- void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
- void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
+ void setPreCond(Expr *PC) { Data->getChildren()[PreConditionOffset] = PC; }
+ void setCond(Expr *Cond) { Data->getChildren()[CondOffset] = Cond; }
+ void setInit(Expr *Init) { Data->getChildren()[InitOffset] = Init; }
+ void setInc(Expr *Inc) { Data->getChildren()[IncOffset] = Inc; }
void setPreInits(Stmt *PreInits) {
- *std::next(child_begin(), PreInitsOffset) = PreInits;
+ Data->getChildren()[PreInitsOffset] = PreInits;
}
void setIsLastIterVariable(Expr *IL) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), IsLastIterVariableOffset) = IL;
+ Data->getChildren()[IsLastIterVariableOffset] = IL;
}
void setLowerBoundVariable(Expr *LB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), LowerBoundVariableOffset) = LB;
+ Data->getChildren()[LowerBoundVariableOffset] = LB;
}
void setUpperBoundVariable(Expr *UB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), UpperBoundVariableOffset) = UB;
+ Data->getChildren()[UpperBoundVariableOffset] = UB;
}
void setStrideVariable(Expr *ST) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), StrideVariableOffset) = ST;
+ Data->getChildren()[StrideVariableOffset] = ST;
}
void setEnsureUpperBound(Expr *EUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), EnsureUpperBoundOffset) = EUB;
+ Data->getChildren()[EnsureUpperBoundOffset] = EUB;
}
void setNextLowerBound(Expr *NLB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), NextLowerBoundOffset) = NLB;
+ Data->getChildren()[NextLowerBoundOffset] = NLB;
}
void setNextUpperBound(Expr *NUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), NextUpperBoundOffset) = NUB;
+ Data->getChildren()[NextUpperBoundOffset] = NUB;
}
void setNumIterations(Expr *NI) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- *std::next(child_begin(), NumIterationsOffset) = NI;
+ Data->getChildren()[NumIterationsOffset] = NI;
}
void setPrevLowerBoundVariable(Expr *PrevLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB;
+ Data->getChildren()[PrevLowerBoundVariableOffset] = PrevLB;
}
void setPrevUpperBoundVariable(Expr *PrevUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB;
+ Data->getChildren()[PrevUpperBoundVariableOffset] = PrevUB;
}
void setDistInc(Expr *DistInc) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), DistIncOffset) = DistInc;
+ Data->getChildren()[DistIncOffset] = DistInc;
}
void setPrevEnsureUpperBound(Expr *PrevEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), PrevEnsureUpperBoundOffset) = PrevEUB;
+ Data->getChildren()[PrevEnsureUpperBoundOffset] = PrevEUB;
}
void setCombinedLowerBoundVariable(Expr *CombLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedLowerBoundVariableOffset) = CombLB;
+ Data->getChildren()[CombinedLowerBoundVariableOffset] = CombLB;
}
void setCombinedUpperBoundVariable(Expr *CombUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedUpperBoundVariableOffset) = CombUB;
+ Data->getChildren()[CombinedUpperBoundVariableOffset] = CombUB;
}
void setCombinedEnsureUpperBound(Expr *CombEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedEnsureUpperBoundOffset) = CombEUB;
+ Data->getChildren()[CombinedEnsureUpperBoundOffset] = CombEUB;
}
void setCombinedInit(Expr *CombInit) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedInitOffset) = CombInit;
+ Data->getChildren()[CombinedInitOffset] = CombInit;
}
void setCombinedCond(Expr *CombCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedConditionOffset) = CombCond;
+ Data->getChildren()[CombinedConditionOffset] = CombCond;
}
void setCombinedNextLowerBound(Expr *CombNLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedNextLowerBoundOffset) = CombNLB;
+ Data->getChildren()[CombinedNextLowerBoundOffset] = CombNLB;
}
void setCombinedNextUpperBound(Expr *CombNUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- *std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB;
+ Data->getChildren()[CombinedNextUpperBoundOffset] = CombNUB;
}
void setCombinedDistCond(Expr *CombDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
- *std::next(child_begin(), CombinedDistConditionOffset) = CombDistCond;
+ Data->getChildren()[CombinedDistConditionOffset] = CombDistCond;
}
void setCombinedParForInDistCond(Expr *CombParForInDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
- *std::next(child_begin(),
- CombinedParForInDistConditionOffset) = CombParForInDistCond;
+ Data->getChildren()[CombinedParForInDistConditionOffset] =
+ CombParForInDistCond;
}
void setCounters(ArrayRef<Expr *> A);
void setPrivateCounters(ArrayRef<Expr *> A);
@@ -925,178 +928,144 @@ public:
unsigned getCollapsedNumber() const { return CollapsedNum; }
Expr *getIterationVariable() const {
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), IterationVariableOffset)));
+ return cast<Expr>(Data->getChildren()[IterationVariableOffset]);
}
Expr *getLastIteration() const {
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), LastIterationOffset)));
+ return cast<Expr>(Data->getChildren()[LastIterationOffset]);
}
Expr *getCalcLastIteration() const {
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CalcLastIterationOffset)));
+ return cast<Expr>(Data->getChildren()[CalcLastIterationOffset]);
}
Expr *getPreCond() const {
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), PreConditionOffset)));
- }
- Expr *getCond() const {
- return const_cast<Expr *>(
- reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset)));
- }
- Expr *getInit() const {
- return const_cast<Expr *>(
- reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset)));
- }
- Expr *getInc() const {
- return const_cast<Expr *>(
- reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset)));
+ return cast<Expr>(Data->getChildren()[PreConditionOffset]);
}
+ Expr *getCond() const { return cast<Expr>(Data->getChildren()[CondOffset]); }
+ Expr *getInit() const { return cast<Expr>(Data->getChildren()[InitOffset]); }
+ Expr *getInc() const { return cast<Expr>(Data->getChildren()[IncOffset]); }
const Stmt *getPreInits() const {
- return *std::next(child_begin(), PreInitsOffset);
+ return Data->getChildren()[PreInitsOffset];
}
- Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); }
+ Stmt *getPreInits() { return Data->getChildren()[PreInitsOffset]; }
Expr *getIsLastIterVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), IsLastIterVariableOffset)));
+ return cast<Expr>(Data->getChildren()[IsLastIterVariableOffset]);
}
Expr *getLowerBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), LowerBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[LowerBoundVariableOffset]);
}
Expr *getUpperBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), UpperBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[UpperBoundVariableOffset]);
}
Expr *getStrideVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), StrideVariableOffset)));
+ return cast<Expr>(Data->getChildren()[StrideVariableOffset]);
}
Expr *getEnsureUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), EnsureUpperBoundOffset)));
+ return cast<Expr>(Data->getChildren()[EnsureUpperBoundOffset]);
}
Expr *getNextLowerBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), NextLowerBoundOffset)));
+ return cast<Expr>(Data->getChildren()[NextLowerBoundOffset]);
}
Expr *getNextUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), NextUpperBoundOffset)));
+ return cast<Expr>(Data->getChildren()[NextUpperBoundOffset]);
}
Expr *getNumIterations() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), NumIterationsOffset)));
+ return cast<Expr>(Data->getChildren()[NumIterationsOffset]);
}
Expr *getPrevLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), PrevLowerBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[PrevLowerBoundVariableOffset]);
}
Expr *getPrevUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), PrevUpperBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[PrevUpperBoundVariableOffset]);
}
Expr *getDistInc() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), DistIncOffset)));
+ return cast<Expr>(Data->getChildren()[DistIncOffset]);
}
Expr *getPrevEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), PrevEnsureUpperBoundOffset)));
+ return cast<Expr>(Data->getChildren()[PrevEnsureUpperBoundOffset]);
}
Expr *getCombinedLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedLowerBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedLowerBoundVariableOffset]);
}
Expr *getCombinedUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedUpperBoundVariableOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedUpperBoundVariableOffset]);
}
Expr *getCombinedEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedEnsureUpperBoundOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedEnsureUpperBoundOffset]);
}
Expr *getCombinedInit() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedInitOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedInitOffset]);
}
Expr *getCombinedCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedConditionOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedConditionOffset]);
}
Expr *getCombinedNextLowerBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedNextLowerBoundOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedNextLowerBoundOffset]);
}
Expr *getCombinedNextUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedNextUpperBoundOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedNextUpperBoundOffset]);
}
Expr *getCombinedDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedDistConditionOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedDistConditionOffset]);
}
Expr *getCombinedParForInDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(), CombinedParForInDistConditionOffset)));
+ return cast<Expr>(Data->getChildren()[CombinedParForInDistConditionOffset]);
}
/// Try to find the next loop sub-statement in the specified statement \p
/// CurStmt.
@@ -1206,27 +1175,25 @@ public:
///
class OMPSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPSimdDirectiveClass, llvm::omp::OMPD_simd,
- StartLoc, EndLoc, CollapsedNum, NumClauses) {}
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPSimdDirectiveClass, llvm::omp::OMPD_simd, StartLoc,
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPSimdDirectiveClass, llvm::omp::OMPD_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ explicit OMPSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPSimdDirectiveClass, llvm::omp::OMPD_simd,
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -1271,38 +1238,34 @@ public:
///
class OMPForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if current directive has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPForDirectiveClass, llvm::omp::OMPD_for,
- StartLoc, EndLoc, CollapsedNum, NumClauses),
- HasCancel(false) {}
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPForDirectiveClass, llvm::omp::OMPD_for, StartLoc,
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPForDirectiveClass, llvm::omp::OMPD_for,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses),
- HasCancel(false) {}
+ explicit OMPForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPForDirectiveClass, llvm::omp::OMPD_for,
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(getCollapsedNumber(),
+ llvm::omp::OMPD_for)] = E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -1338,8 +1301,13 @@ public:
unsigned CollapsedNum, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPForDirective *>(this)->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -1360,28 +1328,25 @@ public:
///
class OMPForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPForSimdDirectiveClass,
- llvm::omp::OMPD_for_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPForSimdDirectiveClass, llvm::omp::OMPD_for_simd,
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPForSimdDirectiveClass,
- llvm::omp::OMPD_for_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ explicit OMPForSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPForSimdDirectiveClass, llvm::omp::OMPD_for_simd,
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -1426,38 +1391,29 @@ public:
///
class OMPSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
/// true if current directive has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPSectionsDirectiveClass,
- llvm::omp::OMPD_sections, StartLoc, EndLoc,
- NumClauses, 1),
- HasCancel(false) {}
+ OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPSectionsDirectiveClass,
+ llvm::omp::OMPD_sections, StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPSectionsDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPSectionsDirectiveClass,
+ explicit OMPSectionsDirective()
+ : OMPExecutableDirective(OMPSectionsDirectiveClass,
llvm::omp::OMPD_sections, SourceLocation(),
- SourceLocation(), NumClauses, 1),
- HasCancel(false) {}
+ SourceLocation()) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) { Data->getChildren()[0] = E; }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -1489,8 +1445,12 @@ public:
unsigned NumClauses, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPSectionsDirective *>(this)->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -1508,9 +1468,10 @@ public:
///
class OMPSectionDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// true if current directive has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
@@ -1518,17 +1479,15 @@ class OMPSectionDirective : public OMPExecutableDirective {
/// \param EndLoc Ending location of the directive.
///
OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPSectionDirectiveClass,
- llvm::omp::OMPD_section, StartLoc, EndLoc, 0, 1),
- HasCancel(false) {}
+ : OMPExecutableDirective(OMPSectionDirectiveClass,
+ llvm::omp::OMPD_section, StartLoc, EndLoc) {}
/// Build an empty directive.
///
explicit OMPSectionDirective()
- : OMPExecutableDirective(this, OMPSectionDirectiveClass,
+ : OMPExecutableDirective(OMPSectionDirectiveClass,
llvm::omp::OMPD_section, SourceLocation(),
- SourceLocation(), 0, 1),
- HasCancel(false) {}
+ SourceLocation()) {}
public:
/// Creates directive.
@@ -1571,26 +1530,21 @@ public:
///
class OMPSingleDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPSingleDirectiveClass,
- llvm::omp::OMPD_single, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPSingleDirectiveClass, llvm::omp::OMPD_single,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPSingleDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPSingleDirectiveClass,
- llvm::omp::OMPD_single, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ explicit OMPSingleDirective()
+ : OMPExecutableDirective(OMPSingleDirectiveClass, llvm::omp::OMPD_single,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -1627,22 +1581,21 @@ public:
///
class OMPMasterDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPMasterDirectiveClass,
- llvm::omp::OMPD_master, StartLoc, EndLoc, 0, 1) {
- }
+ : OMPExecutableDirective(OMPMasterDirectiveClass, llvm::omp::OMPD_master,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
explicit OMPMasterDirective()
- : OMPExecutableDirective(this, OMPMasterDirectiveClass,
- llvm::omp::OMPD_master, SourceLocation(),
- SourceLocation(), 0, 1) {}
+ : OMPExecutableDirective(OMPMasterDirectiveClass, llvm::omp::OMPD_master,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive.
@@ -1676,6 +1629,7 @@ public:
///
class OMPCriticalDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Name of the directive.
DeclarationNameInfo DirName;
/// Build directive with the given start and end location.
@@ -1683,24 +1637,19 @@ class OMPCriticalDirective : public OMPExecutableDirective {
/// \param Name Name of the directive.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc,
- SourceLocation EndLoc, unsigned NumClauses)
- : OMPExecutableDirective(this, OMPCriticalDirectiveClass,
- llvm::omp::OMPD_critical, StartLoc, EndLoc,
- NumClauses, 1),
+ SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPCriticalDirectiveClass,
+ llvm::omp::OMPD_critical, StartLoc, EndLoc),
DirName(Name) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPCriticalDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPCriticalDirectiveClass,
+ explicit OMPCriticalDirective()
+ : OMPExecutableDirective(OMPCriticalDirectiveClass,
llvm::omp::OMPD_critical, SourceLocation(),
- SourceLocation(), NumClauses, 1),
- DirName() {}
+ SourceLocation()) {}
/// Set name of the directive.
///
@@ -1751,40 +1700,37 @@ public:
///
class OMPParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
/// true if current region has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelForDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelForDirectiveClass,
llvm::omp::OMPD_parallel_for, StartLoc, EndLoc,
- CollapsedNum, NumClauses),
- HasCancel(false) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelForDirectiveClass,
+ explicit OMPParallelForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelForDirectiveClass,
llvm::omp::OMPD_parallel_for, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses),
- HasCancel(false) {}
+ SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(getCollapsedNumber(),
+ llvm::omp::OMPD_parallel_for)] = E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -1822,8 +1768,14 @@ public:
EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_parallel_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPParallelForDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -1845,29 +1797,27 @@ public:
///
class OMPParallelForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelForSimdDirectiveClass,
llvm::omp::OMPD_parallel_for_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPParallelForSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
+ explicit OMPParallelForSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelForSimdDirectiveClass,
llvm::omp::OMPD_parallel_for_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -1912,25 +1862,20 @@ public:
///
class OMPParallelMasterDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
-
- OMPParallelMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelMasterDirectiveClass,
+ OMPParallelMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPParallelMasterDirectiveClass,
llvm::omp::OMPD_parallel_master, StartLoc,
- EndLoc, NumClauses, 1) {}
+ EndLoc) {}
- explicit OMPParallelMasterDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelMasterDirectiveClass,
+ explicit OMPParallelMasterDirective()
+ : OMPExecutableDirective(OMPParallelMasterDirectiveClass,
llvm::omp::OMPD_parallel_master,
- SourceLocation(), SourceLocation(), NumClauses,
- 1) {}
+ SourceLocation(), SourceLocation()) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) { Data->getChildren()[0] = E; }
public:
/// Creates directive with a list of \a Clauses.
@@ -1957,8 +1902,13 @@ public:
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPParallelMasterDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelMasterDirectiveClass;
@@ -1976,39 +1926,30 @@ public:
///
class OMPParallelSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
/// true if current directive has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
+ OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPParallelSectionsDirectiveClass,
llvm::omp::OMPD_parallel_sections, StartLoc,
- EndLoc, NumClauses, 1),
- HasCancel(false) {}
+ EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPParallelSectionsDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
+ explicit OMPParallelSectionsDirective()
+ : OMPExecutableDirective(OMPParallelSectionsDirectiveClass,
llvm::omp::OMPD_parallel_sections,
- SourceLocation(), SourceLocation(), NumClauses,
- 1),
- HasCancel(false) {}
+ SourceLocation(), SourceLocation()) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) { Data->getChildren()[0] = E; }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -2040,8 +1981,13 @@ public:
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPParallelSectionsDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -2061,31 +2007,24 @@ public:
///
class OMPTaskDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// true if this directive has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTaskDirectiveClass,
- llvm::omp::OMPD_task, StartLoc, EndLoc,
- NumClauses, 1),
- HasCancel(false) {}
+ OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTaskDirectiveClass, llvm::omp::OMPD_task,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTaskDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTaskDirectiveClass,
- llvm::omp::OMPD_task, SourceLocation(),
- SourceLocation(), NumClauses, 1),
- HasCancel(false) {}
+ explicit OMPTaskDirective()
+ : OMPExecutableDirective(OMPTaskDirectiveClass, llvm::omp::OMPD_task,
+ SourceLocation(), SourceLocation()) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -2130,22 +2069,22 @@ public:
///
class OMPTaskyieldDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass,
- llvm::omp::OMPD_taskyield, StartLoc, EndLoc, 0,
- 0) {}
+ : OMPExecutableDirective(OMPTaskyieldDirectiveClass,
+ llvm::omp::OMPD_taskyield, StartLoc, EndLoc) {}
/// Build an empty directive.
///
explicit OMPTaskyieldDirective()
- : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass,
+ : OMPExecutableDirective(OMPTaskyieldDirectiveClass,
llvm::omp::OMPD_taskyield, SourceLocation(),
- SourceLocation(), 0, 0) {}
+ SourceLocation()) {}
public:
/// Creates directive.
@@ -2176,22 +2115,22 @@ public:
///
class OMPBarrierDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPBarrierDirectiveClass,
- llvm::omp::OMPD_barrier, StartLoc, EndLoc, 0,
- 0) {}
+ : OMPExecutableDirective(OMPBarrierDirectiveClass,
+ llvm::omp::OMPD_barrier, StartLoc, EndLoc) {}
/// Build an empty directive.
///
explicit OMPBarrierDirective()
- : OMPExecutableDirective(this, OMPBarrierDirectiveClass,
+ : OMPExecutableDirective(OMPBarrierDirectiveClass,
llvm::omp::OMPD_barrier, SourceLocation(),
- SourceLocation(), 0, 0) {}
+ SourceLocation()) {}
public:
/// Creates directive.
@@ -2222,22 +2161,22 @@ public:
///
class OMPTaskwaitDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass,
- llvm::omp::OMPD_taskwait, StartLoc, EndLoc, 0,
- 0) {}
+ : OMPExecutableDirective(OMPTaskwaitDirectiveClass,
+ llvm::omp::OMPD_taskwait, StartLoc, EndLoc) {}
/// Build an empty directive.
///
explicit OMPTaskwaitDirective()
- : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass,
+ : OMPExecutableDirective(OMPTaskwaitDirectiveClass,
llvm::omp::OMPD_taskwait, SourceLocation(),
- SourceLocation(), 0, 0) {}
+ SourceLocation()) {}
public:
/// Creates directive.
@@ -2268,30 +2207,25 @@ public:
///
class OMPTaskgroupDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass,
- llvm::omp::OMPD_taskgroup, StartLoc, EndLoc,
- NumClauses, 2) {}
+ OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTaskgroupDirectiveClass,
+ llvm::omp::OMPD_taskgroup, StartLoc, EndLoc) {}
/// Build an empty directive.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTaskgroupDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass,
+ explicit OMPTaskgroupDirective()
+ : OMPExecutableDirective(OMPTaskgroupDirectiveClass,
llvm::omp::OMPD_taskgroup, SourceLocation(),
- SourceLocation(), NumClauses, 2) {}
+ SourceLocation()) {}
/// Sets the task_reduction return variable.
- void setReductionRef(Expr *RR) {
- *std::next(child_begin(), 1) = RR;
- }
+ void setReductionRef(Expr *RR) { Data->getChildren()[0] = RR; }
public:
/// Creates directive.
@@ -2319,11 +2253,9 @@ public:
/// Returns reference to the task_reduction return variable.
const Expr *getReductionRef() const {
- return static_cast<const Expr *>(*std::next(child_begin(), 1));
- }
- Expr *getReductionRef() {
- return static_cast<Expr *>(*std::next(child_begin(), 1));
+ return const_cast<OMPTaskgroupDirective *>(this)->getReductionRef();
}
+ Expr *getReductionRef() { return cast_or_null<Expr>(Data->getChildren()[0]); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskgroupDirectiveClass;
@@ -2342,26 +2274,21 @@ public:
/// FlushClause.
class OMPFlushDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPFlushDirectiveClass,
- llvm::omp::OMPD_flush, StartLoc, EndLoc,
- NumClauses, 0) {}
+ OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPFlushDirectiveClass, llvm::omp::OMPD_flush,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPFlushDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPFlushDirectiveClass,
- llvm::omp::OMPD_flush, SourceLocation(),
- SourceLocation(), NumClauses, 0) {}
+ explicit OMPFlushDirective()
+ : OMPExecutableDirective(OMPFlushDirectiveClass, llvm::omp::OMPD_flush,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2399,27 +2326,22 @@ public:
/// 'a' with dependence type 'in' and a list with 'x' and 'y' locators.
class OMPDepobjDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPDepobjDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPDepobjDirectiveClass,
- llvm::omp::OMPD_depobj, StartLoc, EndLoc,
- NumClauses, 0) {}
+ OMPDepobjDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPDepobjDirectiveClass, llvm::omp::OMPD_depobj,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPDepobjDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPDepobjDirectiveClass,
- llvm::omp::OMPD_depobj, SourceLocation(),
- SourceLocation(), NumClauses, 0) {}
+ explicit OMPDepobjDirective()
+ : OMPExecutableDirective(OMPDepobjDirectiveClass, llvm::omp::OMPD_depobj,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2456,26 +2378,22 @@ public:
///
class OMPOrderedDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPOrderedDirectiveClass,
- llvm::omp::OMPD_ordered, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPOrderedDirectiveClass,
+ llvm::omp::OMPD_ordered, StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPOrderedDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPOrderedDirectiveClass,
+ explicit OMPOrderedDirective()
+ : OMPExecutableDirective(OMPOrderedDirectiveClass,
llvm::omp::OMPD_ordered, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ SourceLocation()) {}
public:
/// Creates directive.
@@ -2494,9 +2412,11 @@ public:
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
+ /// \param IsStandalone true, if the the standalone directive is created.
///
static OMPOrderedDirective *CreateEmpty(const ASTContext &C,
- unsigned NumClauses, EmptyShell);
+ unsigned NumClauses,
+ bool IsStandalone, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPOrderedDirectiveClass;
@@ -2512,6 +2432,7 @@ public:
///
class OMPAtomicDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
@@ -2521,7 +2442,7 @@ class OMPAtomicDirective : public OMPExecutableDirective {
/// This field is true for the first form of the expression and false for the
/// second. Required for correct codegen of non-associative operations (like
/// << or >>).
- bool IsXLHSInRHSPart;
+ bool IsXLHSInRHSPart = false;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
@@ -2530,41 +2451,33 @@ class OMPAtomicDirective : public OMPExecutableDirective {
/// \endcode
/// This field is true for the first(postfix) form of the expression and false
/// otherwise.
- bool IsPostfixUpdate;
+ bool IsPostfixUpdate = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPAtomicDirectiveClass,
- llvm::omp::OMPD_atomic, StartLoc, EndLoc,
- NumClauses, 5),
- IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
+ OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPAtomicDirectiveClass, llvm::omp::OMPD_atomic,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPAtomicDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPAtomicDirectiveClass,
- llvm::omp::OMPD_atomic, SourceLocation(),
- SourceLocation(), NumClauses, 5),
- IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
+ explicit OMPAtomicDirective()
+ : OMPExecutableDirective(OMPAtomicDirectiveClass, llvm::omp::OMPD_atomic,
+ SourceLocation(), SourceLocation()) {}
/// Set 'x' part of the associated expression/statement.
- void setX(Expr *X) { *std::next(child_begin()) = X; }
+ void setX(Expr *X) { Data->getChildren()[0] = X; }
/// Set helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
- void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; }
+ void setUpdateExpr(Expr *UE) { Data->getChildren()[1] = UE; }
/// Set 'v' part of the associated expression/statement.
- void setV(Expr *V) { *std::next(child_begin(), 3) = V; }
+ void setV(Expr *V) { Data->getChildren()[2] = V; }
/// Set 'expr' part of the associated expression/statement.
- void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; }
+ void setExpr(Expr *E) { Data->getChildren()[3] = E; }
public:
/// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr'
@@ -2601,18 +2514,16 @@ public:
unsigned NumClauses, EmptyShell);
/// Get 'x' part of the associated expression/statement.
- Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); }
+ Expr *getX() { return cast_or_null<Expr>(Data->getChildren()[0]); }
const Expr *getX() const {
- return cast_or_null<Expr>(*std::next(child_begin()));
+ return cast_or_null<Expr>(Data->getChildren()[0]);
}
/// Get helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
- Expr *getUpdateExpr() {
- return cast_or_null<Expr>(*std::next(child_begin(), 2));
- }
+ Expr *getUpdateExpr() { return cast_or_null<Expr>(Data->getChildren()[1]); }
const Expr *getUpdateExpr() const {
- return cast_or_null<Expr>(*std::next(child_begin(), 2));
+ return cast_or_null<Expr>(Data->getChildren()[1]);
}
/// Return true if helper update expression has form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form
@@ -2622,14 +2533,14 @@ public:
/// 'x', false if 'v' must be updated to the new value of 'x'.
bool isPostfixUpdate() const { return IsPostfixUpdate; }
/// Get 'v' part of the associated expression/statement.
- Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); }
+ Expr *getV() { return cast_or_null<Expr>(Data->getChildren()[2]); }
const Expr *getV() const {
- return cast_or_null<Expr>(*std::next(child_begin(), 3));
+ return cast_or_null<Expr>(Data->getChildren()[2]);
}
/// Get 'expr' part of the associated expression/statement.
- Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); }
+ Expr *getExpr() { return cast_or_null<Expr>(Data->getChildren()[3]); }
const Expr *getExpr() const {
- return cast_or_null<Expr>(*std::next(child_begin(), 4));
+ return cast_or_null<Expr>(Data->getChildren()[3]);
}
static bool classof(const Stmt *T) {
@@ -2647,26 +2558,21 @@ public:
///
class OMPTargetDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetDirectiveClass,
- llvm::omp::OMPD_target, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetDirectiveClass, llvm::omp::OMPD_target,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetDirectiveClass,
- llvm::omp::OMPD_target, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ explicit OMPTargetDirective()
+ : OMPExecutableDirective(OMPTargetDirectiveClass, llvm::omp::OMPD_target,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2706,26 +2612,22 @@ public:
///
class OMPTargetDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
- /// \param NumClauses The number of clauses.
///
- OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
- llvm::omp::OMPD_target_data, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetDataDirectiveClass,
+ llvm::omp::OMPD_target_data, StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetDataDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
+ explicit OMPTargetDataDirective()
+ : OMPExecutableDirective(OMPTargetDataDirectiveClass,
llvm::omp::OMPD_target_data, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2764,27 +2666,23 @@ public:
///
class OMPTargetEnterDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
- /// \param NumClauses The number of clauses.
///
- OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
+ OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetEnterDataDirectiveClass,
llvm::omp::OMPD_target_enter_data, StartLoc,
- EndLoc, NumClauses, /*NumChildren=*/1) {}
+ EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetEnterDataDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
+ explicit OMPTargetEnterDataDirective()
+ : OMPExecutableDirective(OMPTargetEnterDataDirectiveClass,
llvm::omp::OMPD_target_enter_data,
- SourceLocation(), SourceLocation(), NumClauses,
- /*NumChildren=*/1) {}
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2823,27 +2721,23 @@ public:
///
class OMPTargetExitDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
- /// \param NumClauses The number of clauses.
///
- OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
+ OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetExitDataDirectiveClass,
llvm::omp::OMPD_target_exit_data, StartLoc,
- EndLoc, NumClauses, /*NumChildren=*/1) {}
+ EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetExitDataDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
+ explicit OMPTargetExitDataDirective()
+ : OMPExecutableDirective(OMPTargetExitDataDirectiveClass,
llvm::omp::OMPD_target_exit_data,
- SourceLocation(), SourceLocation(), NumClauses,
- /*NumChildren=*/1) {}
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -2881,9 +2775,7 @@ public:
///
class OMPTargetParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
@@ -2891,26 +2783,21 @@ class OMPTargetParallelDirective : public OMPExecutableDirective {
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
+ OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetParallelDirectiveClass,
llvm::omp::OMPD_target_parallel, StartLoc,
- EndLoc, NumClauses, /*NumChildren=*/1) {}
+ EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetParallelDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
+ explicit OMPTargetParallelDirective()
+ : OMPExecutableDirective(OMPTargetParallelDirectiveClass,
llvm::omp::OMPD_target_parallel,
- SourceLocation(), SourceLocation(), NumClauses,
- /*NumChildren=*/1) {}
+ SourceLocation(), SourceLocation()) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) { Data->getChildren()[0] = E; }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -2941,8 +2828,13 @@ public:
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[0]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPTargetParallelDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -2963,41 +2855,37 @@ public:
///
class OMPTargetParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
/// true if current region has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetParallelForDirectiveClass,
llvm::omp::OMPD_target_parallel_for, StartLoc, EndLoc,
- CollapsedNum, NumClauses),
- HasCancel(false) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetParallelForDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
+ explicit OMPTargetParallelForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetParallelForDirectiveClass,
llvm::omp::OMPD_target_parallel_for, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses),
- HasCancel(false) {}
+ SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_target_parallel_for)] = E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -3035,8 +2923,14 @@ public:
EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_target_parallel_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPTargetParallelForDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -3056,26 +2950,21 @@ public:
///
class OMPTeamsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTeamsDirectiveClass,
- llvm::omp::OMPD_teams, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTeamsDirectiveClass, llvm::omp::OMPD_teams,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTeamsDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTeamsDirectiveClass,
- llvm::omp::OMPD_teams, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ explicit OMPTeamsDirective()
+ : OMPExecutableDirective(OMPTeamsDirectiveClass, llvm::omp::OMPD_teams,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -3114,25 +3003,24 @@ public:
/// In this example a cancellation point is created for innermost 'for' region.
class OMPCancellationPointDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
- OpenMPDirectiveKind CancelRegion;
+ friend class OMPExecutableDirective;
+ OpenMPDirectiveKind CancelRegion = llvm::omp::OMPD_unknown;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
+ /// statements and child expressions.
///
OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc)
- : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
+ : OMPExecutableDirective(OMPCancellationPointDirectiveClass,
llvm::omp::OMPD_cancellation_point, StartLoc,
- EndLoc, 0, 0),
- CancelRegion(llvm::omp::OMPD_unknown) {}
+ EndLoc) {}
/// Build an empty directive.
- ///
explicit OMPCancellationPointDirective()
- : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
+ : OMPExecutableDirective(OMPCancellationPointDirectiveClass,
llvm::omp::OMPD_cancellation_point,
- SourceLocation(), SourceLocation(), 0, 0),
- CancelRegion(llvm::omp::OMPD_unknown) {}
+ SourceLocation(), SourceLocation()) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
@@ -3173,28 +3061,22 @@ public:
/// In this example a cancel is created for innermost 'for' region.
class OMPCancelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
- OpenMPDirectiveKind CancelRegion;
+ friend class OMPExecutableDirective;
+ OpenMPDirectiveKind CancelRegion = llvm::omp::OMPD_unknown;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPCancelDirectiveClass,
- llvm::omp::OMPD_cancel, StartLoc, EndLoc,
- NumClauses, 0),
- CancelRegion(llvm::omp::OMPD_unknown) {}
+ OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPCancelDirectiveClass, llvm::omp::OMPD_cancel,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- explicit OMPCancelDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPCancelDirectiveClass,
- llvm::omp::OMPD_cancel, SourceLocation(),
- SourceLocation(), NumClauses, 0),
- CancelRegion(llvm::omp::OMPD_unknown) {}
+ explicit OMPCancelDirective()
+ : OMPExecutableDirective(OMPCancelDirectiveClass, llvm::omp::OMPD_cancel,
+ SourceLocation(), SourceLocation()) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
@@ -3239,33 +3121,28 @@ public:
///
class OMPTaskLoopDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTaskLoopDirectiveClass,
- llvm::omp::OMPD_taskloop, StartLoc, EndLoc,
- CollapsedNum, NumClauses),
- HasCancel(false) {}
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTaskLoopDirectiveClass, llvm::omp::OMPD_taskloop,
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTaskLoopDirectiveClass,
- llvm::omp::OMPD_taskloop, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses),
- HasCancel(false) {}
+ explicit OMPTaskLoopDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTaskLoopDirectiveClass, llvm::omp::OMPD_taskloop,
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -3317,28 +3194,27 @@ public:
///
class OMPTaskLoopSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_taskloop_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
+ explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_taskloop_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -3384,34 +3260,30 @@ public:
///
class OMPMasterTaskLoopDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPMasterTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPMasterTaskLoopDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPMasterTaskLoopDirectiveClass,
llvm::omp::OMPD_master_taskloop, StartLoc, EndLoc,
- CollapsedNum, NumClauses),
- HasCancel(false) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPMasterTaskLoopDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPMasterTaskLoopDirectiveClass,
+ explicit OMPMasterTaskLoopDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPMasterTaskLoopDirectiveClass,
llvm::omp::OMPD_master_taskloop, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses),
- HasCancel(false) {}
+ SourceLocation(), CollapsedNum) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -3464,29 +3336,27 @@ public:
///
class OMPMasterTaskLoopSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPMasterTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPMasterTaskLoopSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPMasterTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_master_taskloop_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPMasterTaskLoopSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPMasterTaskLoopSimdDirectiveClass,
+ explicit OMPMasterTaskLoopSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPMasterTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_master_taskloop_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \p Clauses.
@@ -3532,36 +3402,31 @@ public:
///
class OMPParallelMasterTaskLoopDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
- bool HasCancel;
+ bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPParallelMasterTaskLoopDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelMasterTaskLoopDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelMasterTaskLoopDirectiveClass,
llvm::omp::OMPD_parallel_master_taskloop, StartLoc,
- EndLoc, CollapsedNum, NumClauses),
- HasCancel(false) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPParallelMasterTaskLoopDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelMasterTaskLoopDirectiveClass,
+ explicit OMPParallelMasterTaskLoopDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelMasterTaskLoopDirectiveClass,
llvm::omp::OMPD_parallel_master_taskloop,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses),
- HasCancel(false) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -3615,32 +3480,28 @@ public:
///
class OMPParallelMasterTaskLoopSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPParallelMasterTaskLoopSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelMasterTaskLoopSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelMasterTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_parallel_master_taskloop_simd,
- StartLoc, EndLoc, CollapsedNum, NumClauses) {}
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPParallelMasterTaskLoopSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPParallelMasterTaskLoopSimdDirectiveClass,
+ explicit OMPParallelMasterTaskLoopSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPParallelMasterTaskLoopSimdDirectiveClass,
llvm::omp::OMPD_parallel_master_taskloop_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \p Clauses.
@@ -3684,29 +3545,28 @@ public:
///
class OMPDistributeDirective : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeDirectiveClass,
llvm::omp::OMPD_distribute, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeDirectiveClass,
+ explicit OMPDistributeDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeDirectiveClass,
llvm::omp::OMPD_distribute, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -3751,26 +3611,23 @@ public:
///
class OMPTargetUpdateDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
- /// \param NumClauses The number of clauses.
///
- OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
- llvm::omp::OMPD_target_update, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetUpdateDirectiveClass,
+ llvm::omp::OMPD_target_update, StartLoc,
+ EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetUpdateDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
+ explicit OMPTargetUpdateDirective()
+ : OMPExecutableDirective(OMPTargetUpdateDirectiveClass,
llvm::omp::OMPD_target_update, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -3810,9 +3667,7 @@ public:
///
class OMPDistributeParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
@@ -3821,31 +3676,28 @@ class OMPDistributeParallelForDirective : public OMPLoopDirective {
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeParallelForDirectiveClass,
llvm::omp::OMPD_distribute_parallel_for, StartLoc,
- EndLoc, CollapsedNum, NumClauses),
- HasCancel(false) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPDistributeParallelForDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
+ explicit OMPDistributeParallelForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeParallelForDirectiveClass,
llvm::omp::OMPD_distribute_parallel_for,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses),
- HasCancel(false) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_distribute_parallel_for)] = E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -3883,8 +3735,14 @@ public:
EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_distribute_parallel_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPDistributeParallelForDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -3905,33 +3763,29 @@ public:
///
class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_distribute_parallel_for_simd, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
+ explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_distribute_parallel_for_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -3974,30 +3828,28 @@ public:
///
class OMPDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeSimdDirectiveClass,
llvm::omp::OMPD_distribute_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPDistributeSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
+ explicit OMPDistributeSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPDistributeSimdDirectiveClass,
llvm::omp::OMPD_distribute_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4042,32 +3894,29 @@ public:
///
class OMPTargetParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetParallelForSimdDirectiveClass,
llvm::omp::OMPD_target_parallel_for_simd, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
+ explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetParallelForSimdDirectiveClass,
llvm::omp::OMPD_target_parallel_for_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4112,29 +3961,28 @@ public:
///
class OMPTargetSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetSimdDirectiveClass,
llvm::omp::OMPD_target_simd, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetSimdDirectiveClass,
+ explicit OMPTargetSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetSimdDirectiveClass,
llvm::omp::OMPD_target_simd, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4178,30 +4026,28 @@ public:
///
class OMPTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeDirectiveClass,
llvm::omp::OMPD_teams_distribute, StartLoc, EndLoc,
- CollapsedNum, NumClauses) {}
+ CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTeamsDistributeDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
+ explicit OMPTeamsDistributeDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeDirectiveClass,
llvm::omp::OMPD_teams_distribute, SourceLocation(),
- SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4246,32 +4092,28 @@ public:
///
class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTeamsDistributeSimdDirective(SourceLocation StartLoc,
- SourceLocation EndLoc, unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
+ SourceLocation EndLoc, unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeSimdDirectiveClass,
llvm::omp::OMPD_teams_distribute_simd, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
+ explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeSimdDirectiveClass,
llvm::omp::OMPD_teams_distribute_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4318,33 +4160,29 @@ public:
class OMPTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_teams_distribute_parallel_for_simd,
- StartLoc, EndLoc, CollapsedNum, NumClauses) {}
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
+ explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_teams_distribute_parallel_for_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4388,9 +4226,7 @@ public:
///
class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
@@ -4399,32 +4235,29 @@ class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective {
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeParallelForDirectiveClass,
llvm::omp::OMPD_teams_distribute_parallel_for,
- StartLoc, EndLoc, CollapsedNum, NumClauses),
- HasCancel(false) {}
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
+ explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTeamsDistributeParallelForDirectiveClass,
llvm::omp::OMPD_teams_distribute_parallel_for,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses),
- HasCancel(false) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_teams_distribute_parallel_for)] =
+ E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -4460,8 +4293,14 @@ public:
EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(), llvm::omp::OMPD_teams_distribute_parallel_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPTeamsDistributeParallelForDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -4481,26 +4320,23 @@ public:
///
class OMPTargetTeamsDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
- llvm::omp::OMPD_target_teams, StartLoc, EndLoc,
- NumClauses, 1) {}
+ OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPTargetTeamsDirectiveClass,
+ llvm::omp::OMPD_target_teams, StartLoc, EndLoc) {
+ }
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPTargetTeamsDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
+ explicit OMPTargetTeamsDirective()
+ : OMPExecutableDirective(OMPTargetTeamsDirectiveClass,
llvm::omp::OMPD_target_teams, SourceLocation(),
- SourceLocation(), NumClauses, 1) {}
+ SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4540,32 +4376,29 @@ public:
///
class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum, unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeDirectiveClass,
llvm::omp::OMPD_target_teams_distribute, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
+ explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeDirectiveClass,
llvm::omp::OMPD_target_teams_distribute,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4610,9 +4443,7 @@ public:
class OMPTargetTeamsDistributeParallelForDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
- /// Special reference expression for handling task reduction. Used to store
- /// the taskgroup descriptor returned by the runtime functions.
- Expr *TaskRedRef = nullptr;
+ friend class OMPExecutableDirective;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
@@ -4621,33 +4452,29 @@ class OMPTargetTeamsDistributeParallelForDirective final
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this,
- OMPTargetTeamsDistributeParallelForDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeParallelForDirectiveClass,
llvm::omp::OMPD_target_teams_distribute_parallel_for,
- StartLoc, EndLoc, CollapsedNum, NumClauses),
- HasCancel(false) {}
+ StartLoc, EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(
- this, OMPTargetTeamsDistributeParallelForDirectiveClass,
- llvm::omp::OMPD_target_teams_distribute_parallel_for,
- SourceLocation(), SourceLocation(), CollapsedNum, NumClauses),
- HasCancel(false) {}
+ explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeParallelForDirectiveClass,
+ llvm::omp::OMPD_target_teams_distribute_parallel_for,
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
/// Sets special task reduction descriptor.
- void setTaskReductionRefExpr(Expr *E) { TaskRedRef = E; }
+ void setTaskReductionRefExpr(Expr *E) {
+ Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(),
+ llvm::omp::OMPD_target_teams_distribute_parallel_for)] = E;
+ }
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
@@ -4683,8 +4510,15 @@ public:
EmptyShell);
/// Returns special task reduction reference expression.
- Expr *getTaskReductionRefExpr() { return TaskRedRef; }
- const Expr *getTaskReductionRefExpr() const { return TaskRedRef; }
+ Expr *getTaskReductionRefExpr() {
+ return cast_or_null<Expr>(Data->getChildren()[numLoopChildren(
+ getCollapsedNumber(),
+ llvm::omp::OMPD_target_teams_distribute_parallel_for)]);
+ }
+ const Expr *getTaskReductionRefExpr() const {
+ return const_cast<OMPTargetTeamsDistributeParallelForDirective *>(this)
+ ->getTaskReductionRefExpr();
+ }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
@@ -4707,34 +4541,32 @@ public:
class OMPTargetTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
+ unsigned CollapsedNum)
: OMPLoopDirective(
- this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
+ OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_target_teams_distribute_parallel_for_simd, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeParallelForSimdDirective(
- unsigned CollapsedNum, unsigned NumClauses)
+ unsigned CollapsedNum)
: OMPLoopDirective(
- this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
+ OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
llvm::omp::OMPD_target_teams_distribute_parallel_for_simd,
- SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4779,33 +4611,29 @@ public:
///
class OMPTargetTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
- unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
+ unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeSimdDirectiveClass,
llvm::omp::OMPD_target_teams_distribute_simd, StartLoc,
- EndLoc, CollapsedNum, NumClauses) {}
+ EndLoc, CollapsedNum) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
- /// \param NumClauses Number of clauses.
///
- explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum,
- unsigned NumClauses)
- : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
+ explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum)
+ : OMPLoopDirective(OMPTargetTeamsDistributeSimdDirectiveClass,
llvm::omp::OMPD_target_teams_distribute_simd,
- SourceLocation(), SourceLocation(), CollapsedNum,
- NumClauses) {}
+ SourceLocation(), SourceLocation(), CollapsedNum) {}
public:
/// Creates directive with a list of \a Clauses.
@@ -4847,26 +4675,21 @@ public:
/// list item 'a'.
class OMPScanDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
+ friend class OMPExecutableDirective;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
- /// \param NumClauses Number of clauses.
///
- OMPScanDirective(SourceLocation StartLoc, SourceLocation EndLoc,
- unsigned NumClauses)
- : OMPExecutableDirective(this, OMPScanDirectiveClass,
- llvm::omp::OMPD_scan, StartLoc, EndLoc,
- NumClauses, 0) {}
+ OMPScanDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(OMPScanDirectiveClass, llvm::omp::OMPD_scan,
+ StartLoc, EndLoc) {}
/// Build an empty directive.
///
- /// \param NumClauses Number of clauses.
- ///
- explicit OMPScanDirective(unsigned NumClauses)
- : OMPExecutableDirective(this, OMPScanDirectiveClass,
- llvm::omp::OMPD_scan, SourceLocation(),
- SourceLocation(), NumClauses, 0) {}
+ explicit OMPScanDirective()
+ : OMPExecutableDirective(OMPScanDirectiveClass, llvm::omp::OMPD_scan,
+ SourceLocation(), SourceLocation()) {}
public:
/// Creates directive with a list of \a Clauses.
diff --git a/contrib/llvm-project/clang/include/clang/AST/TemplateBase.h b/contrib/llvm-project/clang/include/clang/AST/TemplateBase.h
index 51fd8ba51034..1671637521e2 100644
--- a/contrib/llvm-project/clang/include/clang/AST/TemplateBase.h
+++ b/contrib/llvm-project/clang/include/clang/AST/TemplateBase.h
@@ -36,6 +36,17 @@ namespace llvm {
class FoldingSetNodeID;
+// Provide PointerLikeTypeTraits for clang::Expr*, this default one requires a
+// full definition of Expr, but this file only sees a forward del because of
+// the dependency.
+template <> struct PointerLikeTypeTraits<clang::Expr *> {
+ static inline void *getAsVoidPointer(clang::Expr *P) { return P; }
+ static inline clang::Expr *getFromVoidPointer(void *P) {
+ return static_cast<clang::Expr *>(P);
+ }
+ static constexpr int NumLowBitsAvailable = 2;
+};
+
} // namespace llvm
namespace clang {
@@ -393,56 +404,51 @@ public:
/// Location information for a TemplateArgument.
struct TemplateArgumentLocInfo {
private:
- struct T {
+ struct TemplateTemplateArgLocInfo {
// FIXME: We'd like to just use the qualifier in the TemplateName,
// but template arguments get canonicalized too quickly.
NestedNameSpecifier *Qualifier;
void *QualifierLocData;
- unsigned TemplateNameLoc;
- unsigned EllipsisLoc;
- };
-
- union {
- struct T Template;
- Expr *Expression;
- TypeSourceInfo *Declarator;
+ SourceLocation TemplateNameLoc;
+ SourceLocation EllipsisLoc;
};
-public:
- constexpr TemplateArgumentLocInfo() : Template({nullptr, nullptr, 0, 0}) {}
+ llvm::PointerUnion<TemplateTemplateArgLocInfo *, Expr *, TypeSourceInfo *>
+ Pointer;
- TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {}
+ TemplateTemplateArgLocInfo *getTemplate() const {
+ return Pointer.get<TemplateTemplateArgLocInfo *>();
+ }
- TemplateArgumentLocInfo(Expr *E) : Expression(E) {}
+public:
+ TemplateArgumentLocInfo() {}
+ TemplateArgumentLocInfo(TypeSourceInfo *Declarator) { Pointer = Declarator; }
- TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc,
+ TemplateArgumentLocInfo(Expr *E) { Pointer = E; }
+ // Ctx is used for allocation -- this case is unusually large and also rare,
+ // so we store the payload out-of-line.
+ TemplateArgumentLocInfo(ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateNameLoc,
- SourceLocation EllipsisLoc) {
- Template.Qualifier = QualifierLoc.getNestedNameSpecifier();
- Template.QualifierLocData = QualifierLoc.getOpaqueData();
- Template.TemplateNameLoc = TemplateNameLoc.getRawEncoding();
- Template.EllipsisLoc = EllipsisLoc.getRawEncoding();
- }
+ SourceLocation EllipsisLoc);
TypeSourceInfo *getAsTypeSourceInfo() const {
- return Declarator;
+ return Pointer.get<TypeSourceInfo *>();
}
- Expr *getAsExpr() const {
- return Expression;
- }
+ Expr *getAsExpr() const { return Pointer.get<Expr *>(); }
NestedNameSpecifierLoc getTemplateQualifierLoc() const {
- return NestedNameSpecifierLoc(Template.Qualifier,
- Template.QualifierLocData);
+ const auto *Template = getTemplate();
+ return NestedNameSpecifierLoc(Template->Qualifier,
+ Template->QualifierLocData);
}
SourceLocation getTemplateNameLoc() const {
- return SourceLocation::getFromRawEncoding(Template.TemplateNameLoc);
+ return getTemplate()->TemplateNameLoc;
}
SourceLocation getTemplateEllipsisLoc() const {
- return SourceLocation::getFromRawEncoding(Template.EllipsisLoc);
+ return getTemplate()->EllipsisLoc;
}
};
@@ -453,7 +459,7 @@ class TemplateArgumentLoc {
TemplateArgumentLocInfo LocInfo;
public:
- constexpr TemplateArgumentLoc() {}
+ TemplateArgumentLoc() {}
TemplateArgumentLoc(const TemplateArgument &Argument,
TemplateArgumentLocInfo Opaque)
@@ -475,12 +481,12 @@ public:
Argument.getKind() == TemplateArgument::Expression);
}
- TemplateArgumentLoc(const TemplateArgument &Argument,
+ TemplateArgumentLoc(ASTContext &Ctx, const TemplateArgument &Argument,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateNameLoc,
SourceLocation EllipsisLoc = SourceLocation())
: Argument(Argument),
- LocInfo(QualifierLoc, TemplateNameLoc, EllipsisLoc) {
+ LocInfo(Ctx, QualifierLoc, TemplateNameLoc, EllipsisLoc) {
assert(Argument.getKind() == TemplateArgument::Template ||
Argument.getKind() == TemplateArgument::TemplateExpansion);
}
@@ -681,8 +687,8 @@ struct alignas(void *) ASTTemplateKWAndArgsInfo {
TemplateArgumentListInfo &List) const;
};
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const TemplateArgument &Arg);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const TemplateArgument &Arg);
inline TemplateSpecializationType::iterator
TemplateSpecializationType::end() const {
diff --git a/contrib/llvm-project/clang/include/clang/AST/TemplateName.h b/contrib/llvm-project/clang/include/clang/AST/TemplateName.h
index 9bcf2838dcf1..010b813dc525 100644
--- a/contrib/llvm-project/clang/include/clang/AST/TemplateName.h
+++ b/contrib/llvm-project/clang/include/clang/AST/TemplateName.h
@@ -342,10 +342,8 @@ public:
/// Insertion operator for diagnostics. This allows sending TemplateName's
/// into a diagnostic with <<.
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- TemplateName N);
-const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- TemplateName N);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ TemplateName N);
/// A structure for storing the information associated with a
/// substituted template template parameter.
diff --git a/contrib/llvm-project/clang/include/clang/AST/TextNodeDumper.h b/contrib/llvm-project/clang/include/clang/AST/TextNodeDumper.h
index b4cfb5a380d1..15ca348f4766 100644
--- a/contrib/llvm-project/clang/include/clang/AST/TextNodeDumper.h
+++ b/contrib/llvm-project/clang/include/clang/AST/TextNodeDumper.h
@@ -155,6 +155,7 @@ class TextNodeDumper
const comments::CommandTraits *Traits = nullptr;
const char *getCommandName(unsigned CommandID);
+ void printFPOptions(FPOptionsOverride FPO);
void dumpAPValueChildren(const APValue &Value, QualType Ty,
const APValue &(*IdxToChildFun)(const APValue &,
@@ -269,6 +270,7 @@ public:
void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
void VisitCXXThisExpr(const CXXThisExpr *Node);
void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node);
+ void VisitCXXStaticCastExpr(const CXXStaticCastExpr *Node);
void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *Node);
void VisitCXXConstructExpr(const CXXConstructExpr *Node);
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
@@ -294,6 +296,7 @@ public:
void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node);
void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node);
void VisitOMPIteratorExpr(const OMPIteratorExpr *Node);
+ void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *Node);
void VisitRValueReferenceType(const ReferenceType *T);
void VisitArrayType(const ArrayType *T);
diff --git a/contrib/llvm-project/clang/include/clang/AST/Type.h b/contrib/llvm-project/clang/include/clang/AST/Type.h
index 74e4a578cb55..95b38da01b01 100644
--- a/contrib/llvm-project/clang/include/clang/AST/Type.h
+++ b/contrib/llvm-project/clang/include/clang/AST/Type.h
@@ -61,6 +61,7 @@ class ExtQuals;
class QualType;
class ConceptDecl;
class TagDecl;
+class TemplateParameterList;
class Type;
enum {
@@ -480,6 +481,11 @@ public:
// Otherwise in OpenCLC v2.0 s6.5.5: every address space except
// for __constant can be used as __generic.
(A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
+ // We also define global_device and global_host address spaces,
+ // to distinguish global pointers allocated on host from pointers
+ // allocated on device, which are a subset of __global.
+ (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
+ B == LangAS::opencl_global_host)) ||
// Consider pointer size address spaces to be equivalent to default.
((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
(isPtrSizeAddressSpace(B) || B == LangAS::Default));
@@ -1675,19 +1681,6 @@ protected:
uint32_t NumElements;
};
- class ConstantMatrixTypeBitfields {
- friend class ConstantMatrixType;
-
- unsigned : NumTypeBits;
-
- /// Number of rows and columns. Using 20 bits allows supporting very large
- /// matrixes, while keeping 24 bits to accommodate NumTypeBits.
- unsigned NumRows : 20;
- unsigned NumColumns : 20;
-
- static constexpr uint32_t MaxElementsPerDimension = (1 << 20) - 1;
- };
-
class AttributedTypeBitfields {
friend class AttributedType;
@@ -1797,7 +1790,6 @@ protected:
TypeWithKeywordBitfields TypeWithKeywordBits;
ElaboratedTypeBitfields ElaboratedTypeBits;
VectorTypeBitfields VectorTypeBits;
- ConstantMatrixTypeBitfields ConstantMatrixTypeBits;
SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
DependentTemplateSpecializationTypeBitfields
@@ -1853,6 +1845,10 @@ protected:
Type(TypeClass tc, QualType canon, TypeDependence Dependence)
: ExtQualsTypeCommonBase(this,
canon.isNull() ? QualType(this_(), 0) : canon) {
+ static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
+ "changing bitfields changed sizeof(Type)!");
+ static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
+ "Insufficient alignment!");
TypeBits.TC = tc;
TypeBits.Dependence = static_cast<unsigned>(Dependence);
TypeBits.CacheValid = false;
@@ -1925,6 +1921,16 @@ public:
bool isSizelessType() const;
bool isSizelessBuiltinType() const;
+ /// Determines if this is a sizeless type supported by the
+ /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
+ /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
+ bool isVLSTBuiltinType() const;
+
+ /// Returns the representative type for the element of an SVE builtin type.
+ /// This is used to represent fixed-length SVE vectors created with the
+ /// 'arm_sve_vector_bits' type attribute as VectorType.
+ QualType getSveEltType(const ASTContext &Ctx) const;
+
/// Types are partitioned into 3 broad categories (C99 6.2.5p1):
/// object types, function types, and incomplete types.
@@ -1956,6 +1962,9 @@ public:
/// (C++11 [basic.types]p10)
bool isLiteralType(const ASTContext &Ctx) const;
+ /// Determine if this type is a structural type, per C++20 [temp.param]p7.
+ bool isStructuralType() const;
+
/// Test if this type is a standard-layout type.
/// (C++0x [basic.type]p9)
bool isStandardLayoutType() const;
@@ -2118,6 +2127,7 @@ public:
bool isAtomicType() const; // C11 _Atomic()
bool isUndeducedAutoType() const; // C++11 auto or
// C++14 decltype(auto)
+ bool isTypedefNameType() const; // typedef or alias template
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
bool is##Id##Type() const;
@@ -2513,6 +2523,9 @@ public:
// SVE Types
#define SVE_TYPE(Name, Id, SingletonId) Id,
#include "clang/Basic/AArch64SVEACLETypes.def"
+// PPC MMA Types
+#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
+#include "clang/Basic/PPCTypes.def"
// All other builtin types
#define BUILTIN_TYPE(Id, SingletonId) Id,
#define LAST_BUILTIN_TYPE(Id) LastKind = Id
@@ -3250,7 +3263,13 @@ public:
NeonVector,
/// is ARM Neon polynomial vector
- NeonPolyVector
+ NeonPolyVector,
+
+ /// is AArch64 SVE fixed-length data vector
+ SveFixedLengthDataVector,
+
+ /// is AArch64 SVE fixed-length predicate vector
+ SveFixedLengthPredicateVector
};
protected:
@@ -3456,8 +3475,15 @@ protected:
friend class ASTContext;
/// The element type of the matrix.
+ // FIXME: Appears to be unused? There is also MatrixType::ElementType...
QualType ElementType;
+ /// Number of rows and columns.
+ unsigned NumRows;
+ unsigned NumColumns;
+
+ static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
+
ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
unsigned NColumns, QualType CanonElementType);
@@ -3466,25 +3492,24 @@ protected:
public:
/// Returns the number of rows in the matrix.
- unsigned getNumRows() const { return ConstantMatrixTypeBits.NumRows; }
+ unsigned getNumRows() const { return NumRows; }
/// Returns the number of columns in the matrix.
- unsigned getNumColumns() const { return ConstantMatrixTypeBits.NumColumns; }
+ unsigned getNumColumns() const { return NumColumns; }
/// Returns the number of elements required to embed the matrix into a vector.
unsigned getNumElementsFlattened() const {
- return ConstantMatrixTypeBits.NumRows * ConstantMatrixTypeBits.NumColumns;
+ return getNumRows() * getNumColumns();
}
/// Returns true if \p NumElements is a valid matrix dimension.
- static bool isDimensionValid(uint64_t NumElements) {
- return NumElements > 0 &&
- NumElements <= ConstantMatrixTypeBitfields::MaxElementsPerDimension;
+ static constexpr bool isDimensionValid(size_t NumElements) {
+ return NumElements > 0 && NumElements <= MaxElementsPerDimension;
}
/// Returns the maximum number of elements per dimension.
- static unsigned getMaxElementsPerDimension() {
- return ConstantMatrixTypeBitfields::MaxElementsPerDimension;
+ static constexpr unsigned getMaxElementsPerDimension() {
+ return MaxElementsPerDimension;
}
void Profile(llvm::FoldingSetNodeID &ID) {
@@ -4372,10 +4397,11 @@ public:
class TypedefType : public Type {
TypedefNameDecl *Decl;
-protected:
+private:
friend class ASTContext; // ASTContext creates these.
- TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can);
+ TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
+ QualType can);
public:
TypedefNameDecl *getDecl() const { return Decl; }
@@ -4726,6 +4752,9 @@ public:
case NullabilityKind::Nullable:
return attr::TypeNullable;
+ case NullabilityKind::NullableResult:
+ return attr::TypeNullableResult;
+
case NullabilityKind::Unspecified:
return attr::TypeNullUnspecified;
}
@@ -5118,11 +5147,24 @@ class alignas(8) TemplateSpecializationType
public:
/// Determine whether any of the given template arguments are dependent.
- static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
- bool &InstantiationDependent);
-
- static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
- bool &InstantiationDependent);
+ ///
+ /// The converted arguments should be supplied when known; whether an
+ /// argument is dependent can depend on the conversions performed on it
+ /// (for example, a 'const int' passed as a template argument might be
+ /// dependent if the parameter is a reference but non-dependent if the
+ /// parameter is an int).
+ ///
+ /// Note that the \p Args parameter is unused: this is intentional, to remind
+ /// the caller that they need to pass in the converted arguments, not the
+ /// specified arguments.
+ static bool
+ anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
+ ArrayRef<TemplateArgument> Converted);
+ static bool
+ anyDependentTemplateArguments(const TemplateArgumentListInfo &,
+ ArrayRef<TemplateArgument> Converted);
+ static bool anyInstantiationDependentTemplateArguments(
+ ArrayRef<TemplateArgumentLoc> Args);
/// True if this template specialization type matches a current
/// instantiation in the context in which it is found.
@@ -5207,15 +5249,18 @@ public:
/// enclosing the template arguments.
void printTemplateArgumentList(raw_ostream &OS,
ArrayRef<TemplateArgument> Args,
- const PrintingPolicy &Policy);
+ const PrintingPolicy &Policy,
+ const TemplateParameterList *TPL = nullptr);
void printTemplateArgumentList(raw_ostream &OS,
ArrayRef<TemplateArgumentLoc> Args,
- const PrintingPolicy &Policy);
+ const PrintingPolicy &Policy,
+ const TemplateParameterList *TPL = nullptr);
void printTemplateArgumentList(raw_ostream &OS,
const TemplateArgumentListInfo &Args,
- const PrintingPolicy &Policy);
+ const PrintingPolicy &Policy,
+ const TemplateParameterList *TPL = nullptr);
/// The injected class name of a C++ class template or class
/// template partial specialization. Used to record that a type was
@@ -5401,7 +5446,9 @@ class ElaboratedType final
ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
: TypeWithKeyword(Keyword, Elaborated, CanonType,
- NamedType->getDependence()),
+ NamedType->getDependence() |
+ (NNS ? toTypeDependence(NNS->getDependence())
+ : TypeDependence::None)),
NNS(NNS), NamedType(NamedType) {
ElaboratedTypeBits.HasOwnedTagDecl = false;
if (OwnedTagDecl) {
@@ -7056,6 +7103,15 @@ inline bool Type::isOverloadableType() const {
return isDependentType() || isRecordType() || isEnumeralType();
}
+/// Determines whether this type is written as a typedef-name.
+inline bool Type::isTypedefNameType() const {
+ if (getAs<TypedefType>())
+ return true;
+ if (auto *TST = getAs<TemplateSpecializationType>())
+ return TST->isTypeAlias();
+ return false;
+}
+
/// Determines whether this type can decay to a pointer type.
inline bool Type::canDecayToPointerType() const {
return isFunctionType() || isArrayType();
@@ -7085,55 +7141,28 @@ inline const Type *Type::getPointeeOrArrayElementType() const {
return type->getBaseElementTypeUnsafe();
return type;
}
-/// Insertion operator for diagnostics. This allows sending address spaces into
-/// a diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- LangAS AS) {
- DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
- DiagnosticsEngine::ArgumentKind::ak_addrspace);
- return DB;
-}
-
/// Insertion operator for partial diagnostics. This allows sending adress
/// spaces into a diagnostic with <<.
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- LangAS AS) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
+ LangAS AS) {
PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
DiagnosticsEngine::ArgumentKind::ak_addrspace);
return PD;
}
-/// Insertion operator for diagnostics. This allows sending Qualifiers into a
-/// diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- Qualifiers Q) {
- DB.AddTaggedVal(Q.getAsOpaqueValue(),
- DiagnosticsEngine::ArgumentKind::ak_qual);
- return DB;
-}
-
/// Insertion operator for partial diagnostics. This allows sending Qualifiers
/// into a diagnostic with <<.
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- Qualifiers Q) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
+ Qualifiers Q) {
PD.AddTaggedVal(Q.getAsOpaqueValue(),
DiagnosticsEngine::ArgumentKind::ak_qual);
return PD;
}
-/// Insertion operator for diagnostics. This allows sending QualType's into a
-/// diagnostic with <<.
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- QualType T) {
- DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
- DiagnosticsEngine::ak_qualtype);
- return DB;
-}
-
/// Insertion operator for partial diagnostics. This allows sending QualType's
/// into a diagnostic with <<.
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- QualType T) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
+ QualType T) {
PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
DiagnosticsEngine::ak_qualtype);
return PD;
diff --git a/contrib/llvm-project/clang/include/clang/AST/TypeLoc.h b/contrib/llvm-project/clang/include/clang/AST/TypeLoc.h
index 72cc8ef098e7..65e95d52c303 100644
--- a/contrib/llvm-project/clang/include/clang/AST/TypeLoc.h
+++ b/contrib/llvm-project/clang/include/clang/AST/TypeLoc.h
@@ -603,32 +603,32 @@ public:
if (needsExtraLocalData())
return static_cast<TypeSpecifierSign>(getWrittenBuiltinSpecs().Sign);
else
- return TSS_unspecified;
+ return TypeSpecifierSign::Unspecified;
}
bool hasWrittenSignSpec() const {
- return getWrittenSignSpec() != TSS_unspecified;
+ return getWrittenSignSpec() != TypeSpecifierSign::Unspecified;
}
void setWrittenSignSpec(TypeSpecifierSign written) {
if (needsExtraLocalData())
- getWrittenBuiltinSpecs().Sign = written;
+ getWrittenBuiltinSpecs().Sign = static_cast<unsigned>(written);
}
TypeSpecifierWidth getWrittenWidthSpec() const {
if (needsExtraLocalData())
return static_cast<TypeSpecifierWidth>(getWrittenBuiltinSpecs().Width);
else
- return TSW_unspecified;
+ return TypeSpecifierWidth::Unspecified;
}
bool hasWrittenWidthSpec() const {
- return getWrittenWidthSpec() != TSW_unspecified;
+ return getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified;
}
void setWrittenWidthSpec(TypeSpecifierWidth written) {
if (needsExtraLocalData())
- getWrittenBuiltinSpecs().Width = written;
+ getWrittenBuiltinSpecs().Width = static_cast<unsigned>(written);
}
TypeSpecifierType getWrittenTypeSpec() const;
@@ -658,8 +658,8 @@ public:
setBuiltinLoc(Loc);
if (needsExtraLocalData()) {
WrittenBuiltinSpecs &wbs = getWrittenBuiltinSpecs();
- wbs.Sign = TSS_unspecified;
- wbs.Width = TSW_unspecified;
+ wbs.Sign = static_cast<unsigned>(TypeSpecifierSign::Unspecified);
+ wbs.Width = static_cast<unsigned>(TypeSpecifierWidth::Unspecified);
wbs.Type = TST_unspecified;
wbs.ModeAttr = false;
}
@@ -1749,30 +1749,79 @@ public:
// FIXME: size expression and attribute locations (or keyword if we
// ever fully support altivec syntax).
-class VectorTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
- VectorTypeLoc,
- VectorType> {
+struct VectorTypeLocInfo {
+ SourceLocation NameLoc;
+};
+
+class VectorTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, VectorTypeLoc,
+ VectorType, VectorTypeLocInfo> {
+public:
+ SourceLocation getNameLoc() const { return this->getLocalData()->NameLoc; }
+
+ void setNameLoc(SourceLocation Loc) { this->getLocalData()->NameLoc = Loc; }
+
+ SourceRange getLocalSourceRange() const {
+ return SourceRange(getNameLoc(), getNameLoc());
+ }
+
+ void initializeLocal(ASTContext &Context, SourceLocation Loc) {
+ setNameLoc(Loc);
+ }
+
+ TypeLoc getElementLoc() const { return getInnerTypeLoc(); }
+
+ QualType getInnerType() const { return this->getTypePtr()->getElementType(); }
};
// FIXME: size expression and attribute locations (or keyword if we
// ever fully support altivec syntax).
class DependentVectorTypeLoc
- : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
- DependentVectorTypeLoc,
- DependentVectorType> {};
+ : public ConcreteTypeLoc<UnqualTypeLoc, DependentVectorTypeLoc,
+ DependentVectorType, VectorTypeLocInfo> {
+public:
+ SourceLocation getNameLoc() const { return this->getLocalData()->NameLoc; }
-// FIXME: size expression and attribute locations.
-class ExtVectorTypeLoc : public InheritingConcreteTypeLoc<VectorTypeLoc,
- ExtVectorTypeLoc,
- ExtVectorType> {
+ void setNameLoc(SourceLocation Loc) { this->getLocalData()->NameLoc = Loc; }
+
+ SourceRange getLocalSourceRange() const {
+ return SourceRange(getNameLoc(), getNameLoc());
+ }
+
+ void initializeLocal(ASTContext &Context, SourceLocation Loc) {
+ setNameLoc(Loc);
+ }
+
+ TypeLoc getElementLoc() const { return getInnerTypeLoc(); }
+
+ QualType getInnerType() const { return this->getTypePtr()->getElementType(); }
};
+// FIXME: size expression and attribute locations.
+class ExtVectorTypeLoc
+ : public InheritingConcreteTypeLoc<VectorTypeLoc, ExtVectorTypeLoc,
+ ExtVectorType> {};
+
// FIXME: attribute locations.
// For some reason, this isn't a subtype of VectorType.
-class DependentSizedExtVectorTypeLoc :
- public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
- DependentSizedExtVectorTypeLoc,
- DependentSizedExtVectorType> {
+class DependentSizedExtVectorTypeLoc
+ : public ConcreteTypeLoc<UnqualTypeLoc, DependentSizedExtVectorTypeLoc,
+ DependentSizedExtVectorType, VectorTypeLocInfo> {
+public:
+ SourceLocation getNameLoc() const { return this->getLocalData()->NameLoc; }
+
+ void setNameLoc(SourceLocation Loc) { this->getLocalData()->NameLoc = Loc; }
+
+ SourceRange getLocalSourceRange() const {
+ return SourceRange(getNameLoc(), getNameLoc());
+ }
+
+ void initializeLocal(ASTContext &Context, SourceLocation Loc) {
+ setNameLoc(Loc);
+ }
+
+ TypeLoc getElementLoc() const { return getInnerTypeLoc(); }
+
+ QualType getInnerType() const { return this->getTypePtr()->getElementType(); }
};
struct MatrixTypeLocInfo {
diff --git a/contrib/llvm-project/clang/include/clang/AST/TypeProperties.td b/contrib/llvm-project/clang/include/clang/AST/TypeProperties.td
index ed91670829b8..ffcc8290938f 100644
--- a/contrib/llvm-project/clang/include/clang/AST/TypeProperties.td
+++ b/contrib/llvm-project/clang/include/clang/AST/TypeProperties.td
@@ -484,8 +484,12 @@ let Class = TagType in {
let Read = [{ node->isDependentType() }];
}
def : Property<"declaration", DeclRef> {
- // Serializing a reference to the canonical declaration is apparently
- // necessary to make module-merging work.
+ // We don't know which declaration was originally referenced here, and we
+ // cannot reference a declaration that follows the use (because that can
+ // introduce deserialization cycles), so conservatively generate a
+ // reference to the first declaration.
+ // FIXME: If this is a reference to a class template specialization, that
+ // can still introduce a deserialization cycle.
let Read = [{ node->getDecl()->getCanonicalDecl() }];
}
}
@@ -761,6 +765,10 @@ let Class = BuiltinType in {
case BuiltinType::ID: return ctx.SINGLETON_ID;
#include "clang/Basic/AArch64SVEACLETypes.def"
+#define PPC_VECTOR_TYPE(NAME, ID, SIZE) \
+ case BuiltinType::ID: return ctx.ID##Ty;
+#include "clang/Basic/PPCTypes.def"
+
#define BUILTIN_TYPE(ID, SINGLETON_ID) \
case BuiltinType::ID: return ctx.SINGLETON_ID;
#include "clang/AST/BuiltinTypes.def"
diff --git a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h
index 0af98438ab52..81125ad8d96d 100644
--- a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -159,6 +159,8 @@ public:
MatchCallback *Action);
void addMatcher(const CXXCtorInitializerMatcher &NodeMatch,
MatchCallback *Action);
+ void addMatcher(const TemplateArgumentLocMatcher &NodeMatch,
+ MatchCallback *Action);
/// @}
/// Adds a matcher to execute when running over the AST.
@@ -209,6 +211,8 @@ public:
NestedNameSpecifierLoc;
std::vector<std::pair<TypeLocMatcher, MatchCallback *>> TypeLoc;
std::vector<std::pair<CXXCtorInitializerMatcher, MatchCallback *>> CtorInit;
+ std::vector<std::pair<TemplateArgumentLocMatcher, MatchCallback *>>
+ TemplateArgumentLoc;
/// All the callbacks in one container to simplify iteration.
llvm::SmallPtrSet<MatchCallback *, 16> AllCallbacks;
};
diff --git a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
index 643419743a11..031fa4682c3a 100644
--- a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -145,6 +145,8 @@ using TypeLocMatcher = internal::Matcher<TypeLoc>;
using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
+using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
+using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
/// @}
/// Matches any node.
@@ -306,10 +308,9 @@ AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
/// Does not match if only part of the statement is expanded from that macro or
/// if different parts of the the statement are expanded from different
/// appearances of the macro.
-///
-/// FIXME: Change to be a polymorphic matcher that works on any syntactic
-/// node. There's nothing `Stmt`-specific about it.
-AST_MATCHER_P(Stmt, isExpandedFromMacro, llvm::StringRef, MacroName) {
+AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
+ std::string, MacroName) {
// Verifies that the statement' beginning and ending are both expanded from
// the same instance of the given macro.
auto& Context = Finder->getASTContext();
@@ -333,6 +334,19 @@ AST_MATCHER_P(Stmt, isExpandedFromMacro, llvm::StringRef, MacroName) {
/// \endcode
extern const internal::VariadicAllOfMatcher<Decl> decl;
+/// Matches decomposition-declarations.
+///
+/// Examples matches the declaration node with \c foo and \c bar, but not
+/// \c number.
+/// (matcher = declStmt(has(decompositionDecl())))
+///
+/// \code
+/// int number = 42;
+/// auto [foo, bar] = std::make_pair{42, 42};
+/// \endcode
+extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
+ decompositionDecl;
+
/// Matches a declaration of a linkage specification.
///
/// Given
@@ -515,6 +529,18 @@ extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
/// matches 'int' in C<int>.
extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
+/// Matches template arguments (with location info).
+///
+/// Given
+/// \code
+/// template <typename T> struct C {};
+/// C<int> c;
+/// \endcode
+/// templateArgumentLoc()
+/// matches 'int' in C<int>.
+extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
+ templateArgumentLoc;
+
/// Matches template name.
///
/// Given
@@ -549,6 +575,18 @@ extern const internal::VariadicDynCastAllOfMatcher<Decl,
extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
templateTypeParmDecl;
+/// Matches template template parameter declarations.
+///
+/// Given
+/// \code
+/// template <template <typename> class Z, int N> struct C {};
+/// \endcode
+/// templateTypeParmDecl()
+/// matches 'Z', but not 'N'.
+extern const internal::VariadicDynCastAllOfMatcher<Decl,
+ TemplateTemplateParmDecl>
+ templateTemplateParmDecl;
+
/// Matches public C++ declarations and C++ base specifers that specify public
/// inheritance.
///
@@ -730,7 +768,7 @@ AST_POLYMORPHIC_MATCHER_P(
ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
- Builder);
+ Builder) != List.end();
}
/// Causes all nested matchers to be matched with the specified traversal kind.
@@ -744,7 +782,7 @@ AST_POLYMORPHIC_MATCHER_P(
/// \endcode
/// The matcher
/// \code
-/// traverse(TK_IgnoreImplicitCastsAndParentheses,
+/// traverse(TK_IgnoreUnlessSpelledInSource,
/// varDecl(hasInitializer(floatLiteral().bind("init")))
/// )
/// \endcode
@@ -809,6 +847,12 @@ traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
TK, InnerMatcher);
}
+template <typename... T>
+internal::Matcher<typename internal::GetClade<T...>::Type>
+traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
+ return traverse(TK, InnerMatcher.with());
+}
+
/// Matches expressions that match InnerMatcher after any implicit AST
/// nodes are stripped off.
///
@@ -1124,7 +1168,7 @@ AST_MATCHER(TemplateArgument, isIntegral) {
return Node.getKind() == TemplateArgument::Integral;
}
-/// Matches a TemplateArgument that referes to an integral type.
+/// Matches a TemplateArgument that refers to an integral type.
///
/// Given
/// \code
@@ -1927,9 +1971,32 @@ extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
/// ostream &o; int b = 1, c = 1;
/// o << b << c;
/// \endcode
+/// See also the binaryOperation() matcher for more-general matching of binary
+/// uses of this AST node.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
cxxOperatorCallExpr;
+/// Matches rewritten binary operators
+///
+/// Example matches use of "<":
+/// \code
+/// #include <compare>
+/// struct HasSpaceshipMem {
+/// int a;
+/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
+/// };
+/// void compare() {
+/// HasSpaceshipMem hs1, hs2;
+/// if (hs1 < hs2)
+/// return;
+/// }
+/// \endcode
+/// See also the binaryOperation() matcher for more-general matching
+/// of this AST node.
+extern const internal::VariadicDynCastAllOfMatcher<Stmt,
+ CXXRewrittenBinaryOperator>
+ cxxRewrittenBinaryOperator;
+
/// Matches expressions.
///
/// Example matches x()
@@ -2324,6 +2391,10 @@ extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
gnuNullExpr;
+/// Matches C11 _Generic expression.
+extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
+ genericSelectionExpr;
+
/// Matches atomic builtins.
/// Example matches __atomic_load_n(ptr, 1)
/// \code
@@ -2345,6 +2416,7 @@ extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
/// \code
/// !(a || b)
/// \endcode
+/// See also the binaryOperation() matcher for more-general matching.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
binaryOperator;
@@ -2651,6 +2723,112 @@ extern const internal::VariadicDynCastAllOfMatcher<Stmt,
UnaryExprOrTypeTraitExpr>
unaryExprOrTypeTraitExpr;
+/// Matches any of the \p NodeMatchers with InnerMatchers nested within
+///
+/// Given
+/// \code
+/// if (true);
+/// for (; true; );
+/// \endcode
+/// with the matcher
+/// \code
+/// mapAnyOf(ifStmt, forStmt).with(
+/// hasCondition(cxxBoolLiteralExpr(equals(true)))
+/// ).bind("trueCond")
+/// \endcode
+/// matches the \c if and the \c for. It is equivalent to:
+/// \code
+/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
+/// anyOf(
+/// ifStmt(trueCond).bind("trueCond"),
+/// forStmt(trueCond).bind("trueCond")
+/// );
+/// \endcode
+///
+/// The with() chain-call accepts zero or more matchers which are combined
+/// as-if with allOf() in each of the node matchers.
+/// Usable as: Any Matcher
+template <typename T, typename... U>
+auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
+ return internal::MapAnyOfHelper<U...>();
+}
+
+/// Matches nodes which can be used with binary operators.
+///
+/// The code
+/// \code
+/// var1 != var2;
+/// \endcode
+/// might be represented in the clang AST as a binaryOperator, a
+/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
+///
+/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
+/// least one is a class type (cxxOperatorCallExpr)
+/// * whether the code appears in a template declaration, if at least one of the
+/// vars is a dependent-type (binaryOperator)
+/// * whether the code relies on a rewritten binary operator, such as a
+/// spaceship operator or an inverted equality operator
+/// (cxxRewrittenBinaryOperator)
+///
+/// This matcher elides details in places where the matchers for the nodes are
+/// compatible.
+///
+/// Given
+/// \code
+/// binaryOperation(
+/// hasOperatorName("!="),
+/// hasLHS(expr().bind("lhs")),
+/// hasRHS(expr().bind("rhs"))
+/// )
+/// \endcode
+/// matches each use of "!=" in:
+/// \code
+/// struct S{
+/// bool operator!=(const S&) const;
+/// };
+///
+/// void foo()
+/// {
+/// 1 != 2;
+/// S() != S();
+/// }
+///
+/// template<typename T>
+/// void templ()
+/// {
+/// 1 != 2;
+/// T() != S();
+/// }
+/// struct HasOpEq
+/// {
+/// bool operator==(const HasOpEq &) const;
+/// };
+///
+/// void inverse()
+/// {
+/// HasOpEq s1;
+/// HasOpEq s2;
+/// if (s1 != s2)
+/// return;
+/// }
+///
+/// struct HasSpaceship
+/// {
+/// bool operator<=>(const HasOpEq &) const;
+/// };
+///
+/// void use_spaceship()
+/// {
+/// HasSpaceship s1;
+/// HasSpaceship s2;
+/// if (s1 != s2)
+/// return;
+/// }
+/// \endcode
+extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator>
+ binaryOperation;
+
/// Matches unary expressions that have a specific type of argument.
///
/// Given
@@ -2787,7 +2965,7 @@ hasOverloadedOperatorName(StringRef Name) {
/// Matches overloaded operator names specified in strings without the
/// "operator" prefix: e.g. "<<".
///
-/// hasAnyOverloadesOperatorName("+", "-")
+/// hasAnyOverloadedOperatorName("+", "-")
/// Is equivalent to
/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
extern const internal::VariadicFunction<
@@ -2797,6 +2975,80 @@ extern const internal::VariadicFunction<
StringRef, internal::hasAnyOverloadedOperatorNameFunc>
hasAnyOverloadedOperatorName;
+/// Matches template-dependent, but known, member names.
+///
+/// In template declarations, dependent members are not resolved and so can
+/// not be matched to particular named declarations.
+///
+/// This matcher allows to match on the known name of members.
+///
+/// Given
+/// \code
+/// template <typename T>
+/// struct S {
+/// void mem();
+/// };
+/// template <typename T>
+/// void x() {
+/// S<T> s;
+/// s.mem();
+/// }
+/// \endcode
+/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
+AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
+ return Node.getMember().getAsString() == N;
+}
+
+/// Matches template-dependent, but known, member names against an already-bound
+/// node
+///
+/// In template declarations, dependent members are not resolved and so can
+/// not be matched to particular named declarations.
+///
+/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
+/// and CXXMethodDecl nodes.
+///
+/// Given
+/// \code
+/// template <typename T>
+/// struct S {
+/// void mem();
+/// };
+/// template <typename T>
+/// void x() {
+/// S<T> s;
+/// s.mem();
+/// }
+/// \endcode
+/// The matcher
+/// @code
+/// \c cxxDependentScopeMemberExpr(
+/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
+/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
+/// cxxMethodDecl(hasName("mem")).bind("templMem")
+/// )))))
+/// )))),
+/// memberHasSameNameAsBoundNode("templMem")
+/// )
+/// @endcode
+/// first matches and binds the @c mem member of the @c S template, then
+/// compares its name to the usage in @c s.mem() in the @c x function template
+AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
+ std::string, BindingID) {
+ auto MemberName = Node.getMember().getAsString();
+
+ return Builder->removeBindings(
+ [this, MemberName](const BoundNodesMap &Nodes) {
+ const auto &BN = Nodes.getNode(this->BindingID);
+ if (const auto *ND = BN.get<NamedDecl>()) {
+ if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
+ return true;
+ return ND->getName() != MemberName;
+ }
+ return true;
+ });
+}
+
/// Matches C++ classes that are directly or indirectly derived from a class
/// matching \c Base, or Objective-C classes that directly or indirectly
/// subclass a class matching \c Base.
@@ -2994,8 +3246,16 @@ AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
/// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
InnerMatcher) {
- return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
- Node.method_end(), Finder, Builder);
+ BoundNodesTreeBuilder Result(*Builder);
+ auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
+ Node.method_end(), Finder, &Result);
+ if (MatchIt == Node.method_end())
+ return false;
+
+ if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
+ return false;
+ *Builder = std::move(Result);
+ return true;
}
/// Matches the generated class of lambda expressions.
@@ -3771,7 +4031,8 @@ AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
- Node.decls_end(), Finder, Builder);
+ Node.decls_end(), Finder,
+ Builder) != Node.decls_end();
}
/// Matches the Decl of a DeclStmt which has a single declaration.
@@ -3926,11 +4187,19 @@ AST_MATCHER(VarDecl, isExceptionVariable) {
/// f(0, 0);
/// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
- AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
- CXXConstructExpr,
- ObjCMessageExpr),
+ AST_POLYMORPHIC_SUPPORTED_TYPES(
+ CallExpr, CXXConstructExpr,
+ CXXUnresolvedConstructExpr, ObjCMessageExpr),
unsigned, N) {
- return Node.getNumArgs() == N;
+ unsigned NumArgs = Node.getNumArgs();
+ if (!Finder->isTraversalIgnoringImplicitNodes())
+ return NumArgs == N;
+ while (NumArgs) {
+ if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
+ break;
+ --NumArgs;
+ }
+ return NumArgs == N;
}
/// Matches the n'th argument of a call expression or a constructor
@@ -3942,13 +4211,16 @@ AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
/// void x(int) { int y; x(y); }
/// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,
- AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
- CXXConstructExpr,
- ObjCMessageExpr),
+ AST_POLYMORPHIC_SUPPORTED_TYPES(
+ CallExpr, CXXConstructExpr,
+ CXXUnresolvedConstructExpr, ObjCMessageExpr),
unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
- return (N < Node.getNumArgs() &&
- InnerMatcher.matches(
- *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
+ if (N >= Node.getNumArgs())
+ return false;
+ const Expr *Arg = Node.getArg(N);
+ if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
+ return false;
+ return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
}
/// Matches the n'th item of an initializer list expression.
@@ -4040,8 +4312,11 @@ AST_MATCHER(CXXCatchStmt, isCatchAll) {
/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
- return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
- Node.init_end(), Finder, Builder);
+ auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
+ Node.init_end(), Finder, Builder);
+ if (MatchIt == Node.init_end())
+ return false;
+ return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
}
/// Matches the field declaration of a constructor initializer.
@@ -4166,6 +4441,9 @@ AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
CXXUnresolvedConstructExpr, ObjCMessageExpr),
internal::Matcher<Expr>, InnerMatcher) {
for (const Expr *Arg : Node.arguments()) {
+ if (Finder->isTraversalIgnoringImplicitNodes() &&
+ isa<CXXDefaultArgExpr>(Arg))
+ break;
BoundNodesTreeBuilder Result(*Builder);
if (InnerMatcher.matches(*Arg, Finder, &Result)) {
*Builder = std::move(Result);
@@ -4324,6 +4602,103 @@ AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
return Matched;
}
+/// Matches all arguments and their respective types for a \c CallExpr or
+/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
+/// it works on calls through function pointers as well.
+///
+/// The difference is, that function pointers do not provide access to a
+/// \c ParmVarDecl, but only the \c QualType for each argument.
+///
+/// Given
+/// \code
+/// void f(int i);
+/// int y;
+/// f(y);
+/// void (*f_ptr)(int) = f;
+/// f_ptr(y);
+/// \endcode
+/// callExpr(
+/// forEachArgumentWithParamType(
+/// declRefExpr(to(varDecl(hasName("y")))),
+/// qualType(isInteger()).bind("type)
+/// ))
+/// matches f(y) and f_ptr(y)
+/// with declRefExpr(...)
+/// matching int y
+/// and qualType(...)
+/// matching int
+AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
+ CXXConstructExpr),
+ internal::Matcher<Expr>, ArgMatcher,
+ internal::Matcher<QualType>, ParamMatcher) {
+ BoundNodesTreeBuilder Result;
+ // The first argument of an overloaded member operator is the implicit object
+ // argument of the method which should not be matched against a parameter, so
+ // we skip over it here.
+ BoundNodesTreeBuilder Matches;
+ unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
+ .matches(Node, Finder, &Matches)
+ ? 1
+ : 0;
+
+ const FunctionProtoType *FProto = nullptr;
+
+ if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
+ if (const auto *Value =
+ dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
+ QualType QT = Value->getType().getCanonicalType();
+
+ // This does not necessarily lead to a `FunctionProtoType`,
+ // e.g. K&R functions do not have a function prototype.
+ if (QT->isFunctionPointerType())
+ FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
+
+ if (QT->isMemberFunctionPointerType()) {
+ const auto *MP = QT->getAs<MemberPointerType>();
+ assert(MP && "Must be member-pointer if its a memberfunctionpointer");
+ FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
+ assert(FProto &&
+ "The call must have happened through a member function "
+ "pointer");
+ }
+ }
+ }
+
+ int ParamIndex = 0;
+ bool Matched = false;
+
+ for (; ArgIndex < Node.getNumArgs(); ++ArgIndex, ++ParamIndex) {
+ BoundNodesTreeBuilder ArgMatches(*Builder);
+ if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
+ &ArgMatches)) {
+ BoundNodesTreeBuilder ParamMatches(ArgMatches);
+
+ // This test is cheaper compared to the big matcher in the next if.
+ // Therefore, please keep this order.
+ if (FProto) {
+ QualType ParamType = FProto->getParamType(ParamIndex);
+ if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
+ Result.addMatch(ParamMatches);
+ Matched = true;
+ continue;
+ }
+ }
+ if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
+ hasParameter(ParamIndex, hasType(ParamMatcher))))),
+ callExpr(callee(functionDecl(
+ hasParameter(ParamIndex, hasType(ParamMatcher)))))))
+ .matches(Node, Finder, &ParamMatches)) {
+ Result.addMatch(ParamMatches);
+ Matched = true;
+ continue;
+ }
+ }
+ }
+ *Builder = std::move(Result);
+ return Matched;
+}
+
/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
/// list. The parameter list could be that of either a block, function, or
/// objc-method.
@@ -4390,7 +4765,8 @@ AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
internal::Matcher<ParmVarDecl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
- Node.param_end(), Finder, Builder);
+ Node.param_end(), Finder,
+ Builder) != Node.param_end();
}
/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
@@ -4512,6 +4888,17 @@ AST_MATCHER(FunctionDecl, isDefaulted) {
return Node.isDefaulted();
}
+/// Matches weak function declarations.
+///
+/// Given:
+/// \code
+/// void foo() __attribute__((__weakref__("__foo")));
+/// void bar();
+/// \endcode
+/// functionDecl(isWeak())
+/// matches the weak declaration "foo", but not "bar".
+AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
+
/// Matches functions that have a dynamic exception specification.
///
/// Given:
@@ -4744,7 +5131,9 @@ AST_MATCHER_P(ArraySubscriptExpr, hasBase,
}
/// Matches a 'for', 'while', 'do while' statement or a function
-/// definition that has a given body.
+/// definition that has a given body. Note that in case of functions
+/// this matcher only matches the definition itself and not the other
+/// declarations of the same function.
///
/// Given
/// \code
@@ -4754,17 +5143,55 @@ AST_MATCHER_P(ArraySubscriptExpr, hasBase,
/// matches 'for (;;) {}'
/// with compoundStmt()
/// matching '{}'
+///
+/// Given
+/// \code
+/// void f();
+/// void f() {}
+/// \endcode
+/// hasBody(functionDecl())
+/// matches 'void f() {}'
+/// with compoundStmt()
+/// matching '{}'
+/// but does not match 'void f();'
+
AST_POLYMORPHIC_MATCHER_P(hasBody,
AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
WhileStmt,
CXXForRangeStmt,
FunctionDecl),
internal::Matcher<Stmt>, InnerMatcher) {
+ if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
+ return false;
const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
return (Statement != nullptr &&
InnerMatcher.matches(*Statement, Finder, Builder));
}
+/// Matches a function declaration that has a given body present in the AST.
+/// Note that this matcher matches all the declarations of a function whose
+/// body is present in the AST.
+///
+/// Given
+/// \code
+/// void f();
+/// void f() {}
+/// void g();
+/// \endcode
+/// hasAnyBody(functionDecl())
+/// matches both 'void f();'
+/// and 'void f() {}'
+/// with compoundStmt()
+/// matching '{}'
+/// but does not match 'void g();'
+AST_MATCHER_P(FunctionDecl, hasAnyBody,
+ internal::Matcher<Stmt>, InnerMatcher) {
+ const Stmt *const Statement = Node.getBody();
+ return (Statement != nullptr &&
+ InnerMatcher.matches(*Statement, Finder, Builder));
+}
+
+
/// Matches compound statements where at least one substatement matches
/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
///
@@ -4782,7 +5209,8 @@ AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
internal::Matcher<Stmt>, InnerMatcher) {
const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
- CS->body_end(), Finder, Builder);
+ CS->body_end(), Finder,
+ Builder) != CS->body_end();
}
/// Checks that a compound statement contains a specific number of
@@ -4867,11 +5295,14 @@ AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
/// \code
/// !(a || b)
/// \endcode
-AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
- UnaryOperator),
- std::string, Name) {
- return Name == Node.getOpcodeStr(Node.getOpcode());
+AST_POLYMORPHIC_MATCHER_P(
+ hasOperatorName,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator, UnaryOperator),
+ std::string, Name) {
+ if (Optional<StringRef> OpName = internal::getOpName(Node))
+ return *OpName == Name;
+ return false;
}
/// Matches operator expressions (binary or unary) that have any of the
@@ -4883,7 +5314,9 @@ AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
extern const internal::VariadicFunction<
internal::PolymorphicMatcherWithParam1<
internal::HasAnyOperatorNameMatcher, std::vector<std::string>,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, UnaryOperator)>,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator,
+ UnaryOperator)>,
StringRef, internal::hasAnyOperatorNameFunc>
hasAnyOperatorName;
@@ -4901,9 +5334,10 @@ extern const internal::VariadicFunction<
/// struct S { S& operator=(const S&); };
/// void x() { S s1, s2; s1 = s2; }
/// \endcode
-AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
- CXXOperatorCallExpr)) {
+AST_POLYMORPHIC_MATCHER(
+ isAssignmentOperator,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator)) {
return Node.isAssignmentOp();
}
@@ -4921,9 +5355,10 @@ AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
/// struct S { bool operator<(const S& other); };
/// void x(S s1, S s2) { bool b1 = s1 < s2; }
/// \endcode
-AST_POLYMORPHIC_MATCHER(isComparisonOperator,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
- CXXOperatorCallExpr)) {
+AST_POLYMORPHIC_MATCHER(
+ isComparisonOperator,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator)) {
return Node.isComparisonOp();
}
@@ -4934,10 +5369,11 @@ AST_POLYMORPHIC_MATCHER(isComparisonOperator,
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
- ArraySubscriptExpr),
+ AST_POLYMORPHIC_SUPPORTED_TYPES(
+ BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator, ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
- const Expr *LeftHandSide = Node.getLHS();
+ const Expr *LeftHandSide = internal::getLHS(Node);
return (LeftHandSide != nullptr &&
InnerMatcher.matches(*LeftHandSide, Finder, Builder));
}
@@ -4949,19 +5385,25 @@ AST_POLYMORPHIC_MATCHER_P(hasLHS,
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,
- AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
- ArraySubscriptExpr),
+ AST_POLYMORPHIC_SUPPORTED_TYPES(
+ BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator, ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
- const Expr *RightHandSide = Node.getRHS();
+ const Expr *RightHandSide = internal::getRHS(Node);
return (RightHandSide != nullptr &&
InnerMatcher.matches(*RightHandSide, Finder, Builder));
}
/// Matches if either the left hand side or the right hand side of a
/// binary operator matches.
-inline internal::Matcher<BinaryOperator> hasEitherOperand(
- const internal::Matcher<Expr> &InnerMatcher) {
- return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
+AST_POLYMORPHIC_MATCHER_P(
+ hasEitherOperand,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator),
+ internal::Matcher<Expr>, InnerMatcher) {
+ return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
+ anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
+ .matches(Node, Finder, Builder);
}
/// Matches if both matchers match with opposite sides of the binary operator.
@@ -4974,11 +5416,15 @@ inline internal::Matcher<BinaryOperator> hasEitherOperand(
/// 1 + 1 // No match
/// 2 + 2 // No match
/// \endcode
-inline internal::Matcher<BinaryOperator>
-hasOperands(const internal::Matcher<Expr> &Matcher1,
- const internal::Matcher<Expr> &Matcher2) {
- return anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
- allOf(hasLHS(Matcher2), hasRHS(Matcher1)));
+AST_POLYMORPHIC_MATCHER_P2(
+ hasOperands,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator),
+ internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
+ return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
+ anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
+ allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
+ .matches(Node, Finder, Builder);
}
/// Matches if the operand of a unary operator matches.
@@ -4988,9 +5434,11 @@ hasOperands(const internal::Matcher<Expr> &Matcher1,
/// \code
/// !true
/// \endcode
-AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
- internal::Matcher<Expr>, InnerMatcher) {
- const Expr * const Operand = Node.getSubExpr();
+AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
+ CXXOperatorCallExpr),
+ internal::Matcher<Expr>, InnerMatcher) {
+ const Expr *const Operand = internal::getSubExpr(Node);
return (Operand != nullptr &&
InnerMatcher.matches(*Operand, Finder, Builder));
}
@@ -5198,6 +5646,9 @@ AST_MATCHER(FunctionDecl, isVariadic) {
/// \endcode
AST_MATCHER_P(CXXMethodDecl, ofClass,
internal::Matcher<CXXRecordDecl>, InnerMatcher) {
+
+ ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
+
const CXXRecordDecl *Parent = Node.getParent();
return (Parent != nullptr &&
InnerMatcher.matches(*Parent, Finder, Builder));
@@ -5624,7 +6075,8 @@ AST_POLYMORPHIC_MATCHER_P(
AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
internal::Matcher<UsingShadowDecl>, InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
- Node.shadow_end(), Finder, Builder);
+ Node.shadow_end(), Finder,
+ Builder) != Node.shadow_end();
}
/// Matches a using shadow declaration where the target declaration is
@@ -6399,7 +6851,7 @@ extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
/// \endcode
extern const AstTypeMatcher<DecayedType> decayedType;
-/// Matches the decayed type, whos decayed type matches \c InnerMatcher
+/// Matches the decayed type, whoes decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
InnerType) {
return InnerType.matches(Node.getDecayedType(), Finder, Builder);
@@ -6616,6 +7068,8 @@ AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
BoundNodesTreeBuilder Result;
bool Matched = false;
for (const auto *I : Node.inits()) {
+ if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
+ continue;
BoundNodesTreeBuilder InitBuilder(*Builder);
if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
Matched = true;
@@ -6742,6 +7196,9 @@ AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
if (!ES.getExpr())
return false;
+
+ ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
+
return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
}
@@ -7180,7 +7637,8 @@ AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
internal::Matcher<OMPClause>, InnerMatcher) {
ArrayRef<OMPClause *> Clauses = Node.clauses();
return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
- Clauses.end(), Finder, Builder);
+ Clauses.end(), Finder,
+ Builder) != Clauses.end();
}
/// Matches OpenMP ``default`` clause.
diff --git a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
index 3992850c992d..2af4e6e88109 100644
--- a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -586,6 +586,10 @@ public:
return this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder,
Builder);
}
+
+ llvm::Optional<clang::TraversalKind> TraversalKind() const override {
+ return this->InnerMatcher.getTraversalKind();
+ }
};
private:
@@ -615,6 +619,149 @@ inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
return Matcher<T>(Implementation);
}
+/// Interface that allows matchers to traverse the AST.
+/// FIXME: Find a better name.
+///
+/// This provides three entry methods for each base node type in the AST:
+/// - \c matchesChildOf:
+/// Matches a matcher on every child node of the given node. Returns true
+/// if at least one child node could be matched.
+/// - \c matchesDescendantOf:
+/// Matches a matcher on all descendant nodes of the given node. Returns true
+/// if at least one descendant matched.
+/// - \c matchesAncestorOf:
+/// Matches a matcher on all ancestors of the given node. Returns true if
+/// at least one ancestor matched.
+///
+/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
+/// In the future, we want to implement this for all nodes for which it makes
+/// sense. In the case of matchesAncestorOf, we'll want to implement it for
+/// all nodes, as all nodes have ancestors.
+class ASTMatchFinder {
+public:
+ /// Defines how bindings are processed on recursive matches.
+ enum BindKind {
+ /// Stop at the first match and only bind the first match.
+ BK_First,
+
+ /// Create results for all combinations of bindings that match.
+ BK_All
+ };
+
+ /// Defines which ancestors are considered for a match.
+ enum AncestorMatchMode {
+ /// All ancestors.
+ AMM_All,
+
+ /// Direct parent only.
+ AMM_ParentOnly
+ };
+
+ virtual ~ASTMatchFinder() = default;
+
+ /// Returns true if the given C++ class is directly or indirectly derived
+ /// from a base type matching \c base.
+ ///
+ /// A class is not considered to be derived from itself.
+ virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
+ const Matcher<NamedDecl> &Base,
+ BoundNodesTreeBuilder *Builder,
+ bool Directly) = 0;
+
+ /// Returns true if the given Objective-C class is directly or indirectly
+ /// derived from a base class matching \c base.
+ ///
+ /// A class is not considered to be derived from itself.
+ virtual bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
+ const Matcher<NamedDecl> &Base,
+ BoundNodesTreeBuilder *Builder,
+ bool Directly) = 0;
+
+ template <typename T>
+ bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder, BindKind Bind) {
+ static_assert(std::is_base_of<Decl, T>::value ||
+ std::is_base_of<Stmt, T>::value ||
+ std::is_base_of<NestedNameSpecifier, T>::value ||
+ std::is_base_of<NestedNameSpecifierLoc, T>::value ||
+ std::is_base_of<TypeLoc, T>::value ||
+ std::is_base_of<QualType, T>::value,
+ "unsupported type for recursive matching");
+ return matchesChildOf(DynTypedNode::create(Node), getASTContext(), Matcher,
+ Builder, Bind);
+ }
+
+ template <typename T>
+ bool matchesDescendantOf(const T &Node, const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder, BindKind Bind) {
+ static_assert(std::is_base_of<Decl, T>::value ||
+ std::is_base_of<Stmt, T>::value ||
+ std::is_base_of<NestedNameSpecifier, T>::value ||
+ std::is_base_of<NestedNameSpecifierLoc, T>::value ||
+ std::is_base_of<TypeLoc, T>::value ||
+ std::is_base_of<QualType, T>::value,
+ "unsupported type for recursive matching");
+ return matchesDescendantOf(DynTypedNode::create(Node), getASTContext(),
+ Matcher, Builder, Bind);
+ }
+
+ // FIXME: Implement support for BindKind.
+ template <typename T>
+ bool matchesAncestorOf(const T &Node, const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder,
+ AncestorMatchMode MatchMode) {
+ static_assert(std::is_base_of<Decl, T>::value ||
+ std::is_base_of<NestedNameSpecifierLoc, T>::value ||
+ std::is_base_of<Stmt, T>::value ||
+ std::is_base_of<TypeLoc, T>::value,
+ "type not allowed for recursive matching");
+ return matchesAncestorOf(DynTypedNode::create(Node), getASTContext(),
+ Matcher, Builder, MatchMode);
+ }
+
+ virtual ASTContext &getASTContext() const = 0;
+
+ virtual bool IsMatchingInASTNodeNotSpelledInSource() const = 0;
+
+ virtual bool IsMatchingInASTNodeNotAsIs() const = 0;
+
+ bool isTraversalIgnoringImplicitNodes() const;
+
+protected:
+ virtual bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
+ const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder,
+ BindKind Bind) = 0;
+
+ virtual bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
+ const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder,
+ BindKind Bind) = 0;
+
+ virtual bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
+ const DynTypedMatcher &Matcher,
+ BoundNodesTreeBuilder *Builder,
+ AncestorMatchMode MatchMode) = 0;
+private:
+ friend struct ASTChildrenNotSpelledInSourceScope;
+ virtual bool isMatchingChildrenNotSpelledInSource() const = 0;
+ virtual void setMatchingChildrenNotSpelledInSource(bool Set) = 0;
+};
+
+struct ASTChildrenNotSpelledInSourceScope {
+ ASTChildrenNotSpelledInSourceScope(ASTMatchFinder *V, bool B)
+ : MV(V), MB(V->isMatchingChildrenNotSpelledInSource()) {
+ V->setMatchingChildrenNotSpelledInSource(B);
+ }
+ ~ASTChildrenNotSpelledInSourceScope() {
+ MV->setMatchingChildrenNotSpelledInSource(MB);
+ }
+
+private:
+ ASTMatchFinder *MV;
+ bool MB;
+};
+
/// Specialization of the conversion functions for QualType.
///
/// This specialization provides the Matcher<Type>->Matcher<QualType>
@@ -632,34 +779,43 @@ inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
/// Finds the first node in a range that matches the given matcher.
template <typename MatcherT, typename IteratorT>
-bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
- IteratorT End, ASTMatchFinder *Finder,
- BoundNodesTreeBuilder *Builder) {
+IteratorT matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
+ IteratorT End, ASTMatchFinder *Finder,
+ BoundNodesTreeBuilder *Builder) {
for (IteratorT I = Start; I != End; ++I) {
BoundNodesTreeBuilder Result(*Builder);
if (Matcher.matches(*I, Finder, &Result)) {
*Builder = std::move(Result);
- return true;
+ return I;
}
}
- return false;
+ return End;
}
/// Finds the first node in a pointer range that matches the given
/// matcher.
template <typename MatcherT, typename IteratorT>
-bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
- IteratorT End, ASTMatchFinder *Finder,
- BoundNodesTreeBuilder *Builder) {
+IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
+ IteratorT End, ASTMatchFinder *Finder,
+ BoundNodesTreeBuilder *Builder) {
for (IteratorT I = Start; I != End; ++I) {
BoundNodesTreeBuilder Result(*Builder);
if (Matcher.matches(**I, Finder, &Result)) {
*Builder = std::move(Result);
- return true;
+ return I;
}
}
+ return End;
+}
+
+template <typename T, std::enable_if_t<!std::is_base_of<FunctionDecl, T>::value>
+ * = nullptr>
+inline bool isDefaultedHelper(const T *) {
return false;
}
+inline bool isDefaultedHelper(const FunctionDecl *FD) {
+ return FD->isDefaulted();
+}
// Metafunction to determine if type T has a member called getDecl.
template <typename Ty>
@@ -928,8 +1084,11 @@ private:
/// is \c NULL.
bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
BoundNodesTreeBuilder *Builder) const {
- return Node != nullptr && this->InnerMatcher.matches(
- DynTypedNode::create(*Node), Finder, Builder);
+ return Node != nullptr &&
+ !(Finder->isTraversalIgnoringImplicitNodes() &&
+ Node->isImplicit()) &&
+ this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder,
+ Builder);
}
};
@@ -938,142 +1097,17 @@ private:
template <typename T>
struct IsBaseType {
static const bool value =
- std::is_same<T, Decl>::value ||
- std::is_same<T, Stmt>::value ||
- std::is_same<T, QualType>::value ||
- std::is_same<T, Type>::value ||
+ std::is_same<T, Decl>::value || std::is_same<T, Stmt>::value ||
+ std::is_same<T, QualType>::value || std::is_same<T, Type>::value ||
std::is_same<T, TypeLoc>::value ||
std::is_same<T, NestedNameSpecifier>::value ||
std::is_same<T, NestedNameSpecifierLoc>::value ||
- std::is_same<T, CXXCtorInitializer>::value;
+ std::is_same<T, CXXCtorInitializer>::value ||
+ std::is_same<T, TemplateArgumentLoc>::value;
};
template <typename T>
const bool IsBaseType<T>::value;
-/// Interface that allows matchers to traverse the AST.
-/// FIXME: Find a better name.
-///
-/// This provides three entry methods for each base node type in the AST:
-/// - \c matchesChildOf:
-/// Matches a matcher on every child node of the given node. Returns true
-/// if at least one child node could be matched.
-/// - \c matchesDescendantOf:
-/// Matches a matcher on all descendant nodes of the given node. Returns true
-/// if at least one descendant matched.
-/// - \c matchesAncestorOf:
-/// Matches a matcher on all ancestors of the given node. Returns true if
-/// at least one ancestor matched.
-///
-/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
-/// In the future, we want to implement this for all nodes for which it makes
-/// sense. In the case of matchesAncestorOf, we'll want to implement it for
-/// all nodes, as all nodes have ancestors.
-class ASTMatchFinder {
-public:
-
- /// Defines how bindings are processed on recursive matches.
- enum BindKind {
- /// Stop at the first match and only bind the first match.
- BK_First,
-
- /// Create results for all combinations of bindings that match.
- BK_All
- };
-
- /// Defines which ancestors are considered for a match.
- enum AncestorMatchMode {
- /// All ancestors.
- AMM_All,
-
- /// Direct parent only.
- AMM_ParentOnly
- };
-
- virtual ~ASTMatchFinder() = default;
-
- /// Returns true if the given C++ class is directly or indirectly derived
- /// from a base type matching \c base.
- ///
- /// A class is not considered to be derived from itself.
- virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
- const Matcher<NamedDecl> &Base,
- BoundNodesTreeBuilder *Builder,
- bool Directly) = 0;
-
- /// Returns true if the given Objective-C class is directly or indirectly
- /// derived from a base class matching \c base.
- ///
- /// A class is not considered to be derived from itself.
- virtual bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
- const Matcher<NamedDecl> &Base,
- BoundNodesTreeBuilder *Builder,
- bool Directly) = 0;
-
- template <typename T>
- bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder, TraversalKind Traverse,
- BindKind Bind) {
- static_assert(std::is_base_of<Decl, T>::value ||
- std::is_base_of<Stmt, T>::value ||
- std::is_base_of<NestedNameSpecifier, T>::value ||
- std::is_base_of<NestedNameSpecifierLoc, T>::value ||
- std::is_base_of<TypeLoc, T>::value ||
- std::is_base_of<QualType, T>::value,
- "unsupported type for recursive matching");
- return matchesChildOf(DynTypedNode::create(Node), getASTContext(), Matcher,
- Builder, Traverse, Bind);
- }
-
- template <typename T>
- bool matchesDescendantOf(const T &Node,
- const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder,
- BindKind Bind) {
- static_assert(std::is_base_of<Decl, T>::value ||
- std::is_base_of<Stmt, T>::value ||
- std::is_base_of<NestedNameSpecifier, T>::value ||
- std::is_base_of<NestedNameSpecifierLoc, T>::value ||
- std::is_base_of<TypeLoc, T>::value ||
- std::is_base_of<QualType, T>::value,
- "unsupported type for recursive matching");
- return matchesDescendantOf(DynTypedNode::create(Node), getASTContext(),
- Matcher, Builder, Bind);
- }
-
- // FIXME: Implement support for BindKind.
- template <typename T>
- bool matchesAncestorOf(const T &Node,
- const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder,
- AncestorMatchMode MatchMode) {
- static_assert(std::is_base_of<Decl, T>::value ||
- std::is_base_of<NestedNameSpecifierLoc, T>::value ||
- std::is_base_of<Stmt, T>::value ||
- std::is_base_of<TypeLoc, T>::value,
- "type not allowed for recursive matching");
- return matchesAncestorOf(DynTypedNode::create(Node), getASTContext(),
- Matcher, Builder, MatchMode);
- }
-
- virtual ASTContext &getASTContext() const = 0;
-
-protected:
- virtual bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
- const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder,
- TraversalKind Traverse, BindKind Bind) = 0;
-
- virtual bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
- const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder,
- BindKind Bind) = 0;
-
- virtual bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
- const DynTypedMatcher &Matcher,
- BoundNodesTreeBuilder *Builder,
- AncestorMatchMode MatchMode) = 0;
-};
-
/// A type-list implementation.
///
/// A "linked list" of types, accessible by using the ::head and ::tail
@@ -1137,6 +1171,232 @@ using HasDeclarationSupportedTypes =
TemplateSpecializationType, TemplateTypeParmType, TypedefType,
UnresolvedUsingType, ObjCIvarRefExpr>;
+/// A Matcher that allows binding the node it matches to an id.
+///
+/// BindableMatcher provides a \a bind() method that allows binding the
+/// matched node to an id if the match was successful.
+template <typename T> class BindableMatcher : public Matcher<T> {
+public:
+ explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
+ explicit BindableMatcher(MatcherInterface<T> *Implementation)
+ : Matcher<T>(Implementation) {}
+
+ /// Returns a matcher that will bind the matched node on a match.
+ ///
+ /// The returned matcher is equivalent to this matcher, but will
+ /// bind the matched node on a match.
+ Matcher<T> bind(StringRef ID) const {
+ return DynTypedMatcher(*this)
+ .tryBind(ID)
+ ->template unconditionalConvertTo<T>();
+ }
+
+ /// Same as Matcher<T>'s conversion operator, but enables binding on
+ /// the returned matcher.
+ operator DynTypedMatcher() const {
+ DynTypedMatcher Result = static_cast<const Matcher<T> &>(*this);
+ Result.setAllowBind(true);
+ return Result;
+ }
+};
+
+/// Matches any instance of the given NodeType.
+///
+/// This is useful when a matcher syntactically requires a child matcher,
+/// but the context doesn't care. See for example: anything().
+class TrueMatcher {
+public:
+ using ReturnTypes = AllNodeBaseTypes;
+
+ template <typename T> operator Matcher<T>() const {
+ return DynTypedMatcher::trueMatcher(ASTNodeKind::getFromNodeKind<T>())
+ .template unconditionalConvertTo<T>();
+ }
+};
+
+/// Creates a Matcher<T> that matches if all inner matchers match.
+template <typename T>
+BindableMatcher<T>
+makeAllOfComposite(ArrayRef<const Matcher<T> *> InnerMatchers) {
+ // For the size() == 0 case, we return a "true" matcher.
+ if (InnerMatchers.empty()) {
+ return BindableMatcher<T>(TrueMatcher());
+ }
+ // For the size() == 1 case, we simply return that one matcher.
+ // No need to wrap it in a variadic operation.
+ if (InnerMatchers.size() == 1) {
+ return BindableMatcher<T>(*InnerMatchers[0]);
+ }
+
+ using PI = llvm::pointee_iterator<const Matcher<T> *const *>;
+
+ std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
+ PI(InnerMatchers.end()));
+ return BindableMatcher<T>(
+ DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
+ ASTNodeKind::getFromNodeKind<T>(),
+ std::move(DynMatchers))
+ .template unconditionalConvertTo<T>());
+}
+
+/// Creates a Matcher<T> that matches if
+/// T is dyn_cast'able into InnerT and all inner matchers match.
+///
+/// Returns BindableMatcher, as matchers that use dyn_cast have
+/// the same object both to match on and to run submatchers on,
+/// so there is no ambiguity with what gets bound.
+template <typename T, typename InnerT>
+BindableMatcher<T>
+makeDynCastAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
+ return BindableMatcher<T>(
+ makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
+}
+
+/// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
+/// variadic functor that takes a number of Matcher<TargetT> and returns a
+/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
+/// given matchers, if SourceT can be dynamically casted into TargetT.
+///
+/// For example:
+/// const VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> record;
+/// Creates a functor record(...) that creates a Matcher<Decl> given
+/// a variable number of arguments of type Matcher<CXXRecordDecl>.
+/// The returned matcher matches if the given Decl can by dynamically
+/// casted to CXXRecordDecl and all given matchers match.
+template <typename SourceT, typename TargetT>
+class VariadicDynCastAllOfMatcher
+ : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
+ makeDynCastAllOfComposite<SourceT, TargetT>> {
+public:
+ VariadicDynCastAllOfMatcher() {}
+};
+
+/// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
+/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
+/// nodes that are matched by all of the given matchers.
+///
+/// For example:
+/// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
+/// Creates a functor nestedNameSpecifier(...) that creates a
+/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
+/// \c Matcher<NestedNameSpecifier>.
+/// The returned matcher matches if all given matchers match.
+template <typename T>
+class VariadicAllOfMatcher
+ : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
+ makeAllOfComposite<T>> {
+public:
+ VariadicAllOfMatcher() {}
+};
+
+/// VariadicOperatorMatcher related types.
+/// @{
+
+/// Polymorphic matcher object that uses a \c
+/// DynTypedMatcher::VariadicOperator operator.
+///
+/// Input matchers can have any type (including other polymorphic matcher
+/// types), and the actual Matcher<T> is generated on demand with an implicit
+/// conversion operator.
+template <typename... Ps> class VariadicOperatorMatcher {
+public:
+ VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
+ : Op(Op), Params(std::forward<Ps>(Params)...) {}
+
+ template <typename T> operator Matcher<T>() const {
+ return DynTypedMatcher::constructVariadic(
+ Op, ASTNodeKind::getFromNodeKind<T>(),
+ getMatchers<T>(std::index_sequence_for<Ps...>()))
+ .template unconditionalConvertTo<T>();
+ }
+
+private:
+ // Helper method to unpack the tuple into a vector.
+ template <typename T, std::size_t... Is>
+ std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) const {
+ return {Matcher<T>(std::get<Is>(Params))...};
+ }
+
+ const DynTypedMatcher::VariadicOperator Op;
+ std::tuple<Ps...> Params;
+};
+
+/// Overloaded function object to generate VariadicOperatorMatcher
+/// objects from arbitrary matchers.
+template <unsigned MinCount, unsigned MaxCount>
+struct VariadicOperatorMatcherFunc {
+ DynTypedMatcher::VariadicOperator Op;
+
+ template <typename... Ms>
+ VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
+ static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
+ "invalid number of parameters for variadic matcher");
+ return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
+ }
+};
+
+template <typename F, typename Tuple, std::size_t... I>
+constexpr auto applyMatcherImpl(F &&f, Tuple &&args,
+ std::index_sequence<I...>) {
+ return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(args))...);
+}
+
+template <typename F, typename Tuple>
+constexpr auto applyMatcher(F &&f, Tuple &&args) {
+ return applyMatcherImpl(
+ std::forward<F>(f), std::forward<Tuple>(args),
+ std::make_index_sequence<
+ std::tuple_size<typename std::decay<Tuple>::type>::value>());
+}
+
+template <typename T, bool IsBaseOf, typename Head, typename Tail>
+struct GetCladeImpl {
+ using Type = Head;
+};
+template <typename T, typename Head, typename Tail>
+struct GetCladeImpl<T, false, Head, Tail>
+ : GetCladeImpl<T, std::is_base_of<typename Tail::head, T>::value,
+ typename Tail::head, typename Tail::tail> {};
+
+template <typename T, typename... U>
+struct GetClade : GetCladeImpl<T, false, T, AllNodeBaseTypes> {};
+
+template <typename CladeType, typename... MatcherTypes>
+struct MapAnyOfMatcherImpl {
+
+ template <typename... InnerMatchers>
+ BindableMatcher<CladeType>
+ operator()(InnerMatchers &&... InnerMatcher) const {
+ // TODO: Use std::apply from c++17
+ return VariadicAllOfMatcher<CladeType>()(applyMatcher(
+ internal::VariadicOperatorMatcherFunc<
+ 0, std::numeric_limits<unsigned>::max()>{
+ internal::DynTypedMatcher::VO_AnyOf},
+ applyMatcher(
+ [&](auto... Matcher) {
+ return std::make_tuple(Matcher(
+ std::forward<decltype(InnerMatcher)>(InnerMatcher)...)...);
+ },
+ std::tuple<
+ VariadicDynCastAllOfMatcher<CladeType, MatcherTypes>...>())));
+ }
+};
+
+template <typename... MatcherTypes>
+using MapAnyOfMatcher =
+ MapAnyOfMatcherImpl<typename GetClade<MatcherTypes...>::Type,
+ MatcherTypes...>;
+
+template <typename... MatcherTypes> struct MapAnyOfHelper {
+ using CladeType = typename GetClade<MatcherTypes...>::Type;
+
+ MapAnyOfMatcher<MatcherTypes...> with;
+
+ operator BindableMatcher<CladeType>() const { return with(); }
+
+ Matcher<CladeType> bind(StringRef ID) const { return with().bind(ID); }
+};
+
template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
typename T, typename ToTypes>
class ArgumentAdaptingMatcherFuncAdaptor {
@@ -1183,6 +1443,13 @@ struct ArgumentAdaptingMatcherFunc {
operator()(const Matcher<T> &InnerMatcher) const {
return create(InnerMatcher);
}
+
+ template <typename... T>
+ ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT,
+ typename GetClade<T...>::Type, ToTypes>
+ operator()(const MapAnyOfHelper<T...> &InnerMatcher) const {
+ return create(InnerMatcher.with());
+ }
};
template <typename T> class TraversalMatcher : public MatcherInterface<T> {
@@ -1201,6 +1468,8 @@ public:
}
llvm::Optional<clang::TraversalKind> TraversalKind() const override {
+ if (auto NestedKind = this->InnerMatcher.getTraversalKind())
+ return NestedKind;
return Traversal;
}
};
@@ -1291,51 +1560,6 @@ private:
const P2 Param2;
};
-/// Matches any instance of the given NodeType.
-///
-/// This is useful when a matcher syntactically requires a child matcher,
-/// but the context doesn't care. See for example: anything().
-class TrueMatcher {
-public:
- using ReturnTypes = AllNodeBaseTypes;
-
- template <typename T>
- operator Matcher<T>() const {
- return DynTypedMatcher::trueMatcher(ASTNodeKind::getFromNodeKind<T>())
- .template unconditionalConvertTo<T>();
- }
-};
-
-/// A Matcher that allows binding the node it matches to an id.
-///
-/// BindableMatcher provides a \a bind() method that allows binding the
-/// matched node to an id if the match was successful.
-template <typename T>
-class BindableMatcher : public Matcher<T> {
-public:
- explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
- explicit BindableMatcher(MatcherInterface<T> *Implementation)
- : Matcher<T>(Implementation) {}
-
- /// Returns a matcher that will bind the matched node on a match.
- ///
- /// The returned matcher is equivalent to this matcher, but will
- /// bind the matched node on a match.
- Matcher<T> bind(StringRef ID) const {
- return DynTypedMatcher(*this)
- .tryBind(ID)
- ->template unconditionalConvertTo<T>();
- }
-
- /// Same as Matcher<T>'s conversion operator, but enables binding on
- /// the returned matcher.
- operator DynTypedMatcher() const {
- DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
- Result.setAllowBind(true);
- return Result;
- }
-};
-
/// Matches nodes of type T that have child nodes of type ChildT for
/// which a specified child matcher matches.
///
@@ -1351,7 +1575,6 @@ public:
bool matches(const T &Node, ASTMatchFinder *Finder,
BoundNodesTreeBuilder *Builder) const override {
return Finder->matchesChildOf(Node, this->InnerMatcher, Builder,
- TraversalKind::TK_AsIs,
ASTMatchFinder::BK_First);
}
};
@@ -1376,57 +1599,10 @@ public:
BoundNodesTreeBuilder *Builder) const override {
return Finder->matchesChildOf(
Node, this->InnerMatcher, Builder,
- TraversalKind::TK_IgnoreImplicitCastsAndParentheses,
ASTMatchFinder::BK_All);
}
};
-/// VariadicOperatorMatcher related types.
-/// @{
-
-/// Polymorphic matcher object that uses a \c
-/// DynTypedMatcher::VariadicOperator operator.
-///
-/// Input matchers can have any type (including other polymorphic matcher
-/// types), and the actual Matcher<T> is generated on demand with an implicit
-/// conversion operator.
-template <typename... Ps> class VariadicOperatorMatcher {
-public:
- VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
- : Op(Op), Params(std::forward<Ps>(Params)...) {}
-
- template <typename T> operator Matcher<T>() const {
- return DynTypedMatcher::constructVariadic(
- Op, ASTNodeKind::getFromNodeKind<T>(),
- getMatchers<T>(std::index_sequence_for<Ps...>()))
- .template unconditionalConvertTo<T>();
- }
-
-private:
- // Helper method to unpack the tuple into a vector.
- template <typename T, std::size_t... Is>
- std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) const {
- return {Matcher<T>(std::get<Is>(Params))...};
- }
-
- const DynTypedMatcher::VariadicOperator Op;
- std::tuple<Ps...> Params;
-};
-
-/// Overloaded function object to generate VariadicOperatorMatcher
-/// objects from arbitrary matchers.
-template <unsigned MinCount, unsigned MaxCount>
-struct VariadicOperatorMatcherFunc {
- DynTypedMatcher::VariadicOperator Op;
-
- template <typename... Ms>
- VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
- static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
- "invalid number of parameters for variadic matcher");
- return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
- }
-};
-
/// @}
template <typename T>
@@ -1434,44 +1610,6 @@ inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
return Matcher<T>(*this);
}
-/// Creates a Matcher<T> that matches if all inner matchers match.
-template<typename T>
-BindableMatcher<T> makeAllOfComposite(
- ArrayRef<const Matcher<T> *> InnerMatchers) {
- // For the size() == 0 case, we return a "true" matcher.
- if (InnerMatchers.empty()) {
- return BindableMatcher<T>(TrueMatcher());
- }
- // For the size() == 1 case, we simply return that one matcher.
- // No need to wrap it in a variadic operation.
- if (InnerMatchers.size() == 1) {
- return BindableMatcher<T>(*InnerMatchers[0]);
- }
-
- using PI = llvm::pointee_iterator<const Matcher<T> *const *>;
-
- std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
- PI(InnerMatchers.end()));
- return BindableMatcher<T>(
- DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
- ASTNodeKind::getFromNodeKind<T>(),
- std::move(DynMatchers))
- .template unconditionalConvertTo<T>());
-}
-
-/// Creates a Matcher<T> that matches if
-/// T is dyn_cast'able into InnerT and all inner matchers match.
-///
-/// Returns BindableMatcher, as matchers that use dyn_cast have
-/// the same object both to match on and to run submatchers on,
-/// so there is no ambiguity with what gets bound.
-template<typename T, typename InnerT>
-BindableMatcher<T> makeDynCastAllOfComposite(
- ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
- return BindableMatcher<T>(
- makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
-}
-
/// Matches nodes of type T that have at least one descendant node of
/// type DescendantT for which the given inner matcher matches.
///
@@ -1611,43 +1749,6 @@ inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
}
-/// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
-/// variadic functor that takes a number of Matcher<TargetT> and returns a
-/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
-/// given matchers, if SourceT can be dynamically casted into TargetT.
-///
-/// For example:
-/// const VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> record;
-/// Creates a functor record(...) that creates a Matcher<Decl> given
-/// a variable number of arguments of type Matcher<CXXRecordDecl>.
-/// The returned matcher matches if the given Decl can by dynamically
-/// casted to CXXRecordDecl and all given matchers match.
-template <typename SourceT, typename TargetT>
-class VariadicDynCastAllOfMatcher
- : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
- makeDynCastAllOfComposite<SourceT, TargetT>> {
-public:
- VariadicDynCastAllOfMatcher() {}
-};
-
-/// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
-/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
-/// nodes that are matched by all of the given matchers.
-///
-/// For example:
-/// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
-/// Creates a functor nestedNameSpecifier(...) that creates a
-/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
-/// \c Matcher<NestedNameSpecifier>.
-/// The returned matcher matches if all given matchers match.
-template <typename T>
-class VariadicAllOfMatcher
- : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
- makeAllOfComposite<T>> {
-public:
- VariadicAllOfMatcher() {}
-};
-
/// Matches nodes of type \c TLoc for which the inner
/// \c Matcher<T> matches.
template <typename TLoc, typename T>
@@ -1836,16 +1937,170 @@ struct NotEqualsBoundNodePredicate {
DynTypedNode Node;
};
+template <typename Ty, typename Enable = void> struct GetBodyMatcher {
+ static const Stmt *get(const Ty &Node) { return Node.getBody(); }
+};
+
template <typename Ty>
-struct GetBodyMatcher {
+struct GetBodyMatcher<Ty, typename std::enable_if<
+ std::is_base_of<FunctionDecl, Ty>::value>::type> {
static const Stmt *get(const Ty &Node) {
- return Node.getBody();
+ return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
}
};
+template <typename NodeType>
+inline Optional<BinaryOperatorKind>
+equivalentBinaryOperator(const NodeType &Node) {
+ return Node.getOpcode();
+}
+
+template <>
+inline Optional<BinaryOperatorKind>
+equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
+ if (Node.getNumArgs() != 2)
+ return None;
+ switch (Node.getOperator()) {
+ default:
+ return None;
+ case OO_ArrowStar:
+ return BO_PtrMemI;
+ case OO_Star:
+ return BO_Mul;
+ case OO_Slash:
+ return BO_Div;
+ case OO_Percent:
+ return BO_Rem;
+ case OO_Plus:
+ return BO_Add;
+ case OO_Minus:
+ return BO_Sub;
+ case OO_LessLess:
+ return BO_Shl;
+ case OO_GreaterGreater:
+ return BO_Shr;
+ case OO_Spaceship:
+ return BO_Cmp;
+ case OO_Less:
+ return BO_LT;
+ case OO_Greater:
+ return BO_GT;
+ case OO_LessEqual:
+ return BO_LE;
+ case OO_GreaterEqual:
+ return BO_GE;
+ case OO_EqualEqual:
+ return BO_EQ;
+ case OO_ExclaimEqual:
+ return BO_NE;
+ case OO_Amp:
+ return BO_And;
+ case OO_Caret:
+ return BO_Xor;
+ case OO_Pipe:
+ return BO_Or;
+ case OO_AmpAmp:
+ return BO_LAnd;
+ case OO_PipePipe:
+ return BO_LOr;
+ case OO_Equal:
+ return BO_Assign;
+ case OO_StarEqual:
+ return BO_MulAssign;
+ case OO_SlashEqual:
+ return BO_DivAssign;
+ case OO_PercentEqual:
+ return BO_RemAssign;
+ case OO_PlusEqual:
+ return BO_AddAssign;
+ case OO_MinusEqual:
+ return BO_SubAssign;
+ case OO_LessLessEqual:
+ return BO_ShlAssign;
+ case OO_GreaterGreaterEqual:
+ return BO_ShrAssign;
+ case OO_AmpEqual:
+ return BO_AndAssign;
+ case OO_CaretEqual:
+ return BO_XorAssign;
+ case OO_PipeEqual:
+ return BO_OrAssign;
+ case OO_Comma:
+ return BO_Comma;
+ }
+}
+
+template <typename NodeType>
+inline Optional<UnaryOperatorKind>
+equivalentUnaryOperator(const NodeType &Node) {
+ return Node.getOpcode();
+}
+
+template <>
+inline Optional<UnaryOperatorKind>
+equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
+ if (Node.getNumArgs() != 1)
+ return None;
+ switch (Node.getOperator()) {
+ default:
+ return None;
+ case OO_Plus:
+ return UO_Plus;
+ case OO_Minus:
+ return UO_Minus;
+ case OO_Amp:
+ return UO_AddrOf;
+ case OO_Tilde:
+ return UO_Not;
+ case OO_Exclaim:
+ return UO_LNot;
+ case OO_PlusPlus: {
+ const auto *FD = Node.getDirectCallee();
+ if (!FD)
+ return None;
+ return FD->getNumParams() > 0 ? UO_PostInc : UO_PreInc;
+ }
+ case OO_MinusMinus: {
+ const auto *FD = Node.getDirectCallee();
+ if (!FD)
+ return None;
+ return FD->getNumParams() > 0 ? UO_PostDec : UO_PreDec;
+ }
+ case OO_Coawait:
+ return UO_Coawait;
+ }
+}
+
+template <typename NodeType> inline const Expr *getLHS(const NodeType &Node) {
+ return Node.getLHS();
+}
+template <>
+inline const Expr *
+getLHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
+ if (!internal::equivalentBinaryOperator(Node))
+ return nullptr;
+ return Node.getArg(0);
+}
+template <typename NodeType> inline const Expr *getRHS(const NodeType &Node) {
+ return Node.getRHS();
+}
template <>
-inline const Stmt *GetBodyMatcher<FunctionDecl>::get(const FunctionDecl &Node) {
- return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
+inline const Expr *
+getRHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
+ if (!internal::equivalentBinaryOperator(Node))
+ return nullptr;
+ return Node.getArg(1);
+}
+template <typename NodeType>
+inline const Expr *getSubExpr(const NodeType &Node) {
+ return Node.getSubExpr();
+}
+template <>
+inline const Expr *
+getSubExpr<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
+ if (!internal::equivalentUnaryOperator(Node))
+ return nullptr;
+ return Node.getArg(0);
}
template <typename Ty>
@@ -1895,6 +2150,26 @@ llvm::Optional<SourceLocation>
getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc,
const ASTContext &Context);
+inline Optional<StringRef> getOpName(const UnaryOperator &Node) {
+ return Node.getOpcodeStr(Node.getOpcode());
+}
+inline 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) {
+ auto optBinaryOpcode = equivalentBinaryOperator(Node);
+ if (!optBinaryOpcode) {
+ auto optUnaryOpcode = equivalentUnaryOperator(Node);
+ if (!optUnaryOpcode)
+ return None;
+ return UnaryOperator::getOpcodeStr(*optUnaryOpcode);
+ }
+ return BinaryOperator::getOpcodeStr(*optBinaryOpcode);
+}
+
/// Matches overloaded operators with a specific name.
///
/// The type argument ArgT is not used by this matcher but is used by
@@ -1902,8 +2177,11 @@ getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc,
template <typename T, typename ArgT = std::vector<std::string>>
class HasAnyOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
static_assert(std::is_same<T, BinaryOperator>::value ||
+ std::is_same<T, CXXOperatorCallExpr>::value ||
+ std::is_same<T, CXXRewrittenBinaryOperator>::value ||
std::is_same<T, UnaryOperator>::value,
- "Matcher only supports `BinaryOperator` and `UnaryOperator`");
+ "Matcher only supports `BinaryOperator`, `UnaryOperator`, "
+ "`CXXOperatorCallExpr` and `CXXRewrittenBinaryOperator`");
static_assert(std::is_same<ArgT, std::vector<std::string>>::value,
"Matcher ArgT must be std::vector<std::string>");
@@ -1912,26 +2190,42 @@ public:
: SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
bool matchesNode(const T &Node) const override {
- StringRef OpName = getOpName(Node);
- return llvm::any_of(
- Names, [&](const std::string &Name) { return Name == OpName; });
+ Optional<StringRef> OptOpName = getOpName(Node);
+ if (!OptOpName)
+ return false;
+ return llvm::any_of(Names, [OpName = *OptOpName](const std::string &Name) {
+ return Name == OpName;
+ });
}
private:
- static StringRef getOpName(const UnaryOperator &Node) {
+ static Optional<StringRef> getOpName(const UnaryOperator &Node) {
return Node.getOpcodeStr(Node.getOpcode());
}
- static StringRef getOpName(const BinaryOperator &Node) {
+ static 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) {
+ auto optBinaryOpcode = equivalentBinaryOperator(Node);
+ if (!optBinaryOpcode) {
+ auto optUnaryOpcode = equivalentUnaryOperator(Node);
+ if (!optUnaryOpcode)
+ return None;
+ return UnaryOperator::getOpcodeStr(*optUnaryOpcode);
+ }
+ return BinaryOperator::getOpcodeStr(*optBinaryOpcode);
+ }
const std::vector<std::string> Names;
};
-using HasOpNameMatcher =
- PolymorphicMatcherWithParam1<HasAnyOperatorNameMatcher,
- std::vector<std::string>,
- void(TypeList<BinaryOperator, UnaryOperator>)>;
+using HasOpNameMatcher = PolymorphicMatcherWithParam1<
+ HasAnyOperatorNameMatcher, std::vector<std::string>,
+ void(TypeList<BinaryOperator, CXXOperatorCallExpr,
+ CXXRewrittenBinaryOperator, UnaryOperator>)>;
HasOpNameMatcher hasAnyOperatorNameFunc(ArrayRef<const StringRef *> NameRefs);
diff --git a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
index 45e8b1a88b81..7e01ab0c6ee9 100644
--- a/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
+++ b/contrib/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
@@ -134,8 +134,9 @@
class matcher_##DefineMatcher##OverloadId##Matcher \
: public ::clang::ast_matchers::internal::MatcherInterface<Type> { \
public: \
- explicit matcher_##DefineMatcher##OverloadId##Matcher(ParamType A##Param) \
- : Param(std::move(A##Param)) {} \
+ explicit matcher_##DefineMatcher##OverloadId##Matcher( \
+ ParamType const &A##Param) \
+ : Param(A##Param) {} \
bool matches(const Type &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
::clang::ast_matchers::internal::BoundNodesTreeBuilder \
@@ -146,13 +147,12 @@
}; \
} \
inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \
- ParamType Param) { \
+ ParamType const &Param) { \
return ::clang::ast_matchers::internal::makeMatcher( \
- new internal::matcher_##DefineMatcher##OverloadId##Matcher( \
- std::move(Param))); \
+ new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param)); \
} \
- typedef ::clang::ast_matchers::internal::Matcher<Type> ( \
- &DefineMatcher##_Type##OverloadId)(ParamType Param); \
+ typedef ::clang::ast_matchers::internal::Matcher<Type>( \
+ &DefineMatcher##_Type##OverloadId)(ParamType const &Param); \
inline bool internal::matcher_##DefineMatcher##OverloadId##Matcher::matches( \
const Type &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
@@ -183,9 +183,9 @@
class matcher_##DefineMatcher##OverloadId##Matcher \
: public ::clang::ast_matchers::internal::MatcherInterface<Type> { \
public: \
- matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 A##Param1, \
- ParamType2 A##Param2) \
- : Param1(std::move(A##Param1)), Param2(std::move(A##Param2)) {} \
+ matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \
+ ParamType2 const &A##Param2) \
+ : Param1(A##Param1), Param2(A##Param2) {} \
bool matches(const Type &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
::clang::ast_matchers::internal::BoundNodesTreeBuilder \
@@ -197,14 +197,14 @@
}; \
} \
inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \
- ParamType1 Param1, ParamType2 Param2) { \
+ ParamType1 const &Param1, ParamType2 const &Param2) { \
return ::clang::ast_matchers::internal::makeMatcher( \
- new internal::matcher_##DefineMatcher##OverloadId##Matcher( \
- std::move(Param1), std::move(Param2))); \
+ new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param1, \
+ Param2)); \
} \
- typedef ::clang::ast_matchers::internal::Matcher<Type> ( \
- &DefineMatcher##_Type##OverloadId)(ParamType1 Param1, \
- ParamType2 Param2); \
+ typedef ::clang::ast_matchers::internal::Matcher<Type>( \
+ &DefineMatcher##_Type##OverloadId)(ParamType1 const &Param1, \
+ ParamType2 const &Param2); \
inline bool internal::matcher_##DefineMatcher##OverloadId##Matcher::matches( \
const Type &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
@@ -272,8 +272,9 @@
class matcher_##DefineMatcher##OverloadId##Matcher \
: public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \
public: \
- explicit matcher_##DefineMatcher##OverloadId##Matcher(ParamType A##Param) \
- : Param(std::move(A##Param)) {} \
+ explicit matcher_##DefineMatcher##OverloadId##Matcher( \
+ ParamType const &A##Param) \
+ : Param(A##Param) {} \
bool matches(const NodeType &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
::clang::ast_matchers::internal::BoundNodesTreeBuilder \
@@ -286,14 +287,15 @@
inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
ReturnTypesF> \
- DefineMatcher(ParamType Param) { \
+ DefineMatcher(ParamType const &Param) { \
return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
- ReturnTypesF>(std::move(Param)); \
+ ReturnTypesF>(Param); \
} \
typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
- ReturnTypesF> (&DefineMatcher##_Type##OverloadId)(ParamType Param); \
+ ReturnTypesF>(&DefineMatcher##_Type##OverloadId)( \
+ ParamType const &Param); \
template <typename NodeType, typename ParamT> \
bool internal:: \
matcher_##DefineMatcher##OverloadId##Matcher<NodeType, ParamT>::matches( \
@@ -323,9 +325,9 @@
class matcher_##DefineMatcher##OverloadId##Matcher \
: public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \
public: \
- matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 A##Param1, \
- ParamType2 A##Param2) \
- : Param1(std::move(A##Param1)), Param2(std::move(A##Param2)) {} \
+ matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \
+ ParamType2 const &A##Param2) \
+ : Param1(A##Param1), Param2(A##Param2) {} \
bool matches(const NodeType &Node, \
::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
::clang::ast_matchers::internal::BoundNodesTreeBuilder \
@@ -339,15 +341,15 @@
inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
ParamType2, ReturnTypesF> \
- DefineMatcher(ParamType1 Param1, ParamType2 Param2) { \
+ DefineMatcher(ParamType1 const &Param1, ParamType2 const &Param2) { \
return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
- ParamType2, ReturnTypesF>(std::move(Param1), std::move(Param2)); \
+ ParamType2, ReturnTypesF>(Param1, Param2); \
} \
typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
- ParamType2, ReturnTypesF> (&DefineMatcher##_Type##OverloadId)( \
- ParamType1 Param1, ParamType2 Param2); \
+ ParamType2, ReturnTypesF>(&DefineMatcher##_Type##OverloadId)( \
+ ParamType1 const &Param1, ParamType2 const &Param2); \
template <typename NodeType, typename ParamT1, typename ParamT2> \
bool internal::matcher_##DefineMatcher##OverloadId##Matcher< \
NodeType, ParamT1, ParamT2>:: \
diff --git a/contrib/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h b/contrib/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index e47b42a4f38c..fa033f49bc90 100644
--- a/contrib/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/contrib/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -100,8 +100,7 @@ class VariantMatcher {
/// Convert \p Matcher the destination type and return it as a new
/// DynTypedMatcher.
- virtual DynTypedMatcher
- convertMatcher(const DynTypedMatcher &Matcher) const = 0;
+ DynTypedMatcher convertMatcher(const DynTypedMatcher &Matcher) const;
/// Constructs a variadic typed matcher from \p InnerMatchers.
/// Will try to convert each inner matcher to the destination type and
@@ -110,9 +109,6 @@ class VariantMatcher {
constructVariadicOperator(DynTypedMatcher::VariadicOperator Op,
ArrayRef<VariantMatcher> InnerMatchers) const;
- protected:
- ~MatcherOps() = default;
-
private:
ASTNodeKind NodeKind;
};
@@ -174,8 +170,12 @@ public:
/// that can, the result would be ambiguous and false is returned.
template <class T>
bool hasTypedMatcher() const {
+ return hasTypedMatcher(ASTNodeKind::getFromNodeKind<T>());
+ }
+
+ bool hasTypedMatcher(ASTNodeKind NK) const {
if (!Value) return false;
- return Value->getTypedMatcher(TypedMatcherOps<T>()).hasValue();
+ return Value->getTypedMatcher(MatcherOps(NK)).hasValue();
}
/// Determines if the contained matcher can be converted to \p Kind.
@@ -197,10 +197,15 @@ public:
template <class T>
ast_matchers::internal::Matcher<T> getTypedMatcher() const {
assert(hasTypedMatcher<T>() && "hasTypedMatcher<T>() == false");
- return Value->getTypedMatcher(TypedMatcherOps<T>())
+ return Value->getTypedMatcher(MatcherOps(ASTNodeKind::getFromNodeKind<T>()))
->template convertTo<T>();
}
+ DynTypedMatcher getTypedMatcher(ASTNodeKind NK) const {
+ assert(hasTypedMatcher(NK) && "hasTypedMatcher(NK) == false");
+ return *Value->getTypedMatcher(MatcherOps(NK));
+ }
+
/// String representation of the type of the value.
///
/// If the underlying matcher is a polymorphic one, the string will show all
@@ -211,7 +216,6 @@ private:
explicit VariantMatcher(std::shared_ptr<Payload> Value)
: Value(std::move(Value)) {}
- template <typename T> struct TypedMatcherOps;
class SinglePayload;
class PolymorphicPayload;
@@ -220,17 +224,6 @@ private:
std::shared_ptr<const Payload> Value;
};
-template <typename T>
-struct VariantMatcher::TypedMatcherOps final : VariantMatcher::MatcherOps {
- TypedMatcherOps() : MatcherOps(ASTNodeKind::getFromNodeKind<T>()) {}
- typedef ast_matchers::internal::Matcher<T> MatcherT;
-
- DynTypedMatcher
- convertMatcher(const DynTypedMatcher &Matcher) const override {
- return DynTypedMatcher(Matcher.convertTo<T>());
- }
-};
-
/// Variant value class.
///
/// Basically, a tagged union with value type semantics.
@@ -258,6 +251,7 @@ public:
VariantValue(double Double);
VariantValue(unsigned Unsigned);
VariantValue(StringRef String);
+ VariantValue(ASTNodeKind NodeKind);
VariantValue(const VariantMatcher &Matchers);
/// Constructs an \c unsigned value (disambiguation from bool).
@@ -287,6 +281,10 @@ public:
const std::string &getString() const;
void setString(StringRef String);
+ bool isNodeKind() const;
+ const ASTNodeKind &getNodeKind() const;
+ void setNodeKind(ASTNodeKind NodeKind);
+
/// Matcher value functions.
bool isMatcher() const;
const VariantMatcher &getMatcher() const;
@@ -323,7 +321,8 @@ private:
VT_Double,
VT_Unsigned,
VT_String,
- VT_Matcher
+ VT_Matcher,
+ VT_NodeKind
};
/// All supported value types.
@@ -333,6 +332,7 @@ private:
bool Boolean;
std::string *String;
VariantMatcher *Matcher;
+ ASTNodeKind *NodeKind;
};
ValueType Type;
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
new file mode 100644
index 000000000000..fc574c680a44
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
@@ -0,0 +1,112 @@
+//===- CalledOnceCheck.h - Check 'called once' parameters -------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a check for function-like parameters that should be
+// called exactly one time.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_CALLEDONCECHECK_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_CALLEDONCECHECK_H
+
+namespace clang {
+
+class AnalysisDeclContext;
+class CFG;
+class Decl;
+class DeclContext;
+class Expr;
+class ParmVarDecl;
+class Stmt;
+
+/// Classification of situations when parameter is not called on every path.
+/// \enum IfThen -- then branch of the if statement has no call.
+/// \enum IfElse -- else branch of the if statement has no call.
+/// \enum Switch -- one of the switch cases doesn't have a call.
+/// \enum SwitchSkipped -- there is no call if none of the cases appies.
+/// \enum LoopEntered -- no call when the loop is entered.
+/// \enum LoopSkipped -- no call when the loop is not entered.
+/// \enum FallbackReason -- fallback case when we were not able to figure out
+/// the reason.
+enum class NeverCalledReason {
+ IfThen,
+ IfElse,
+ Switch,
+ SwitchSkipped,
+ LoopEntered,
+ LoopSkipped,
+ FallbackReason,
+ LARGEST_VALUE = FallbackReason
+};
+
+class CalledOnceCheckHandler {
+public:
+ CalledOnceCheckHandler() = default;
+ virtual ~CalledOnceCheckHandler() = default;
+
+ /// Called when parameter is called twice.
+ /// \param Parameter -- parameter that should be called once.
+ /// \param Call -- call to report the warning.
+ /// \param PrevCall -- previous call.
+ /// \param IsCompletionHandler -- true, if parameter is a completion handler.
+ /// \param Poised -- true, if the second call is guaranteed to happen after
+ /// the first call.
+ virtual void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call,
+ const Expr *PrevCall, bool IsCompletionHandler,
+ bool Poised) {}
+
+ /// Called when parameter is not called at all.
+ /// \param Parameter -- parameter that should be called once.
+ /// \param IsCompletionHandler -- true, if parameter is a completion handler.
+ virtual void handleNeverCalled(const ParmVarDecl *Parameter,
+ bool IsCompletionHandler) {}
+
+ /// Called when captured parameter is not called at all.
+ /// \param Parameter -- parameter that should be called once.
+ /// \param Where -- declaration that captures \p Parameter
+ /// \param IsCompletionHandler -- true, if parameter is a completion handler.
+ virtual void handleCapturedNeverCalled(const ParmVarDecl *Parameter,
+ const Decl *Where,
+ bool IsCompletionHandler) {}
+
+ /// Called when parameter is not called on one of the paths.
+ /// Usually we try to find a statement that is the least common ancestor of
+ /// the path containing the call and not containing the call. This helps us
+ /// to pinpoint a bad path for the user.
+ /// \param Parameter -- parameter that should be called once.
+ /// \param Where -- the least common ancestor statement.
+ /// \param Reason -- a reason describing the path without a call.
+ /// \param IsCalledDirectly -- true, if parameter actually gets called on
+ /// the other path. It is opposed to be used in some other way (added to some
+ /// collection, passed as a parameter, etc.).
+ /// \param IsCompletionHandler -- true, if parameter is a completion handler.
+ virtual void handleNeverCalled(const ParmVarDecl *Parameter,
+ const Stmt *Where, NeverCalledReason Reason,
+ bool IsCalledDirectly,
+ bool IsCompletionHandler) {}
+};
+
+/// Check given CFG for 'called once' parameter violations.
+///
+/// It traverses the function and tracks how such parameters are used.
+/// It detects two main violations:
+/// * parameter is called twice
+/// * parameter is not called
+///
+/// \param AC -- context.
+/// \param Handler -- a handler for found violations.
+/// \param CheckConventionalParameters -- true, if we want to check parameters
+/// not explicitly marked as 'called once', but having the same requirements
+/// according to conventions.
+void checkCalledOnceParameters(AnalysisDeclContext &AC,
+ CalledOnceCheckHandler &Handler,
+ bool CheckConventionalParameters);
+
+} // end namespace clang
+
+#endif /* LLVM_CLANG_ANALYSIS_ANALYSES_CALLEDONCECHECK_H */
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h
index 95a661138df4..25a5ba9d83fe 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h
@@ -273,76 +273,6 @@ public:
namespace llvm {
-/// Clang's CFG contains nullpointers for unreachable succesors, e.g. when an
-/// if statement's condition is always false, it's 'then' branch is represented
-/// with a nullptr. This however will result in a nullpointer derefernece for
-/// dominator tree calculation.
-///
-/// To circumvent this, let's just crudely specialize the children getters
-/// used in LLVM's dominator tree builder.
-namespace DomTreeBuilder {
-
-using ClangCFGDomChildrenGetter =
-SemiNCAInfo<clang::CFGDomTree::DominatorTreeBase>::ChildrenGetter<
- /*Inverse=*/false>;
-
-template <>
-template <>
-inline ClangCFGDomChildrenGetter::ResultTy ClangCFGDomChildrenGetter::Get(
- clang::CFGBlock *N, std::integral_constant<bool, /*Inverse=*/false>) {
- auto RChildren = reverse(children<NodePtr>(N));
- ResultTy Ret(RChildren.begin(), RChildren.end());
- Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
- return Ret;
-}
-
-using ClangCFGDomReverseChildrenGetter =
-SemiNCAInfo<clang::CFGDomTree::DominatorTreeBase>::ChildrenGetter<
- /*Inverse=*/true>;
-
-template <>
-template <>
-inline ClangCFGDomReverseChildrenGetter::ResultTy
-ClangCFGDomReverseChildrenGetter::Get(
- clang::CFGBlock *N, std::integral_constant<bool, /*Inverse=*/true>) {
- auto IChildren = inverse_children<NodePtr>(N);
- ResultTy Ret(IChildren.begin(), IChildren.end());
- Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
- return Ret;
-}
-
-using ClangCFGPostDomChildrenGetter =
-SemiNCAInfo<clang::CFGPostDomTree::DominatorTreeBase>::ChildrenGetter<
- /*Inverse=*/false>;
-
-template <>
-template <>
-inline ClangCFGPostDomChildrenGetter::ResultTy
-ClangCFGPostDomChildrenGetter::Get(
- clang::CFGBlock *N, std::integral_constant<bool, /*Inverse=*/false>) {
- auto RChildren = reverse(children<NodePtr>(N));
- ResultTy Ret(RChildren.begin(), RChildren.end());
- Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
- return Ret;
-}
-
-using ClangCFGPostDomReverseChildrenGetter =
-SemiNCAInfo<clang::CFGPostDomTree::DominatorTreeBase>::ChildrenGetter<
- /*Inverse=*/true>;
-
-template <>
-template <>
-inline ClangCFGPostDomReverseChildrenGetter::ResultTy
-ClangCFGPostDomReverseChildrenGetter::Get(
- clang::CFGBlock *N, std::integral_constant<bool, /*Inverse=*/true>) {
- auto IChildren = inverse_children<NodePtr>(N);
- ResultTy Ret(IChildren.begin(), IChildren.end());
- Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
- return Ret;
-}
-
-} // end of namespace DomTreeBuilder
-
//===-------------------------------------
/// DominatorTree GraphTraits specialization so the DominatorTree can be
/// iterable by generic graph iterators.
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h
index 2e7dd5d81678..8a3dd0c35e64 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h
@@ -30,22 +30,22 @@ public:
class LivenessValues {
public:
- llvm::ImmutableSet<const Stmt *> liveStmts;
+ llvm::ImmutableSet<const Expr *> liveExprs;
llvm::ImmutableSet<const VarDecl *> liveDecls;
llvm::ImmutableSet<const BindingDecl *> liveBindings;
bool equals(const LivenessValues &V) const;
LivenessValues()
- : liveStmts(nullptr), liveDecls(nullptr), liveBindings(nullptr) {}
+ : liveExprs(nullptr), liveDecls(nullptr), liveBindings(nullptr) {}
- LivenessValues(llvm::ImmutableSet<const Stmt *> LiveStmts,
+ LivenessValues(llvm::ImmutableSet<const Expr *> liveExprs,
llvm::ImmutableSet<const VarDecl *> LiveDecls,
llvm::ImmutableSet<const BindingDecl *> LiveBindings)
- : liveStmts(LiveStmts), liveDecls(LiveDecls),
+ : liveExprs(liveExprs), liveDecls(LiveDecls),
liveBindings(LiveBindings) {}
- bool isLive(const Stmt *S) const;
+ bool isLive(const Expr *E) const;
bool isLive(const VarDecl *D) const;
friend class LiveVariables;
@@ -83,17 +83,17 @@ public:
/// only returns liveness information for block-level expressions.
bool isLive(const Stmt *S, const VarDecl *D);
- /// Returns true the block-level expression "value" is live
+ /// Returns true the block-level expression value is live
/// before the given block-level expression (see runOnAllBlocks).
- bool isLive(const Stmt *Loc, const Stmt *StmtVal);
+ bool isLive(const Stmt *Loc, const Expr *Val);
/// Print to stderr the variable liveness information associated with
/// each basic block.
void dumpBlockLiveness(const SourceManager &M);
- /// Print to stderr the statement liveness information associated with
+ /// Print to stderr the expression liveness information associated with
/// each basic block.
- void dumpStmtLiveness(const SourceManager &M);
+ void dumpExprLiveness(const SourceManager &M);
void runOnAllBlocks(Observer &obs);
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h
index 0d3dda1256fb..bfa9870a1e1f 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h
@@ -202,6 +202,14 @@ public:
virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
SourceLocation Loc) {}
+ /// Warn when calling a function that a negative capability is not held.
+ /// \param D -- The decl for the function requiring the negative capability.
+ /// \param LockName -- The name for the lock expression, to be printed in the
+ /// diagnostic.
+ /// \param Loc -- The location of the protected operation.
+ virtual void handleNegativeNotHeld(const NamedDecl *D, Name LockName,
+ SourceLocation Loc) {}
+
/// Warn when a function is called while an excluded mutex is locked. For
/// example, the mutex may be locked inside the function.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
index c26d2ed99dd2..77a800c28754 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -634,7 +634,9 @@ typename V::R_SExpr Literal::traverse(V &Vs, typename V::R_Ctx Ctx) {
/// At compile time, pointer literals are represented by symbolic names.
class LiteralPtr : public SExpr {
public:
- LiteralPtr(const ValueDecl *D) : SExpr(COP_LiteralPtr), Cvdecl(D) {}
+ LiteralPtr(const ValueDecl *D) : SExpr(COP_LiteralPtr), Cvdecl(D) {
+ assert(D && "ValueDecl must not be null");
+ }
LiteralPtr(const LiteralPtr &) = default;
static bool classof(const SExpr *E) { return E->opcode() == COP_LiteralPtr; }
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/CallGraph.h b/contrib/llvm-project/clang/include/clang/Analysis/CallGraph.h
index 6f7159330f5d..999ac5da8acb 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/CallGraph.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/CallGraph.h
@@ -91,8 +91,8 @@ public:
/// Get the number of nodes in the graph.
unsigned size() const { return FunctionMap.size(); }
- /// \ brief Get the virtual root of the graph, all the functions available
- /// externally are represented as callees of the node.
+ /// Get the virtual root of the graph, all the functions available externally
+ /// are represented as callees of the node.
CallGraphNode *getRoot() const { return Root; }
/// Iterators through all the nodes of the graph that have no parent. These
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/IssueHash.h b/contrib/llvm-project/clang/include/clang/Analysis/IssueHash.h
new file mode 100644
index 000000000000..9c02b79f58f9
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Analysis/IssueHash.h
@@ -0,0 +1,49 @@
+//===---------- IssueHash.h - Generate identification hashes ----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_ISSUE_HASH_H
+#define LLVM_CLANG_STATICANALYZER_CORE_ISSUE_HASH_H
+
+#include "llvm/ADT/SmallString.h"
+
+namespace clang {
+class Decl;
+class FullSourceLoc;
+class LangOptions;
+
+/// Returns an opaque identifier for a diagnostic.
+///
+/// This opaque identifier is intended to be stable even when the source code
+/// is changed. It allows to track diagnostics in the long term, for example,
+/// find which diagnostics are "new", maintain a database of suppressed
+/// diagnostics etc.
+///
+/// We may introduce more variants of issue hashes in the future
+/// but older variants will still be available for compatibility.
+///
+/// This hash is based on the following information:
+/// - Name of the checker that emitted the diagnostic.
+/// - Warning message.
+/// - Name of the enclosing declaration.
+/// - Contents of the line of code with the issue, excluding whitespace.
+/// - Column number (but not the line number! - which makes it stable).
+llvm::SmallString<32> getIssueHash(const FullSourceLoc &IssueLoc,
+ llvm::StringRef CheckerName,
+ llvm::StringRef WarningMessage,
+ const Decl *IssueDecl,
+ const LangOptions &LangOpts);
+
+/// Get the unhashed string representation of the V1 issue hash.
+/// When hashed, it becomes the actual issue hash. Useful for testing.
+/// See GetIssueHashV1() for more information.
+std::string getIssueString(const FullSourceLoc &IssueLoc,
+ llvm::StringRef CheckerName,
+ llvm::StringRef WarningMessage,
+ const Decl *IssueDecl, const LangOptions &LangOpts);
+} // namespace clang
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h b/contrib/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h
index c4b042a51bb5..539aa20b8168 100644
--- a/contrib/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h
@@ -58,6 +58,45 @@ namespace ento {
class PathDiagnostic;
+/// These options tweak the behavior of path diangostic consumers.
+/// Most of these options are currently supported by very few consumers.
+struct PathDiagnosticConsumerOptions {
+ /// Run-line of the tool that produced the diagnostic.
+ /// It can be included with the diagnostic for debugging purposes.
+ std::string ToolInvocation;
+
+ /// Whether to include additional information about macro expansions
+ /// with the diagnostics, because otherwise they can be hard to obtain
+ /// without re-compiling the program under analysis.
+ bool ShouldDisplayMacroExpansions = false;
+
+ /// Whether to include LLVM statistics of the process in the diagnostic.
+ /// Useful for profiling the tool on large real-world codebases.
+ bool ShouldSerializeStats = false;
+
+ /// If the consumer intends to produce multiple output files, should it
+ /// use randomly generated file names for these files (with the tiny risk of
+ /// having random collisions) or deterministic human-readable file names
+ /// (with a larger risk of deterministic collisions or invalid characters
+ /// in the file name). We should not really give this choice to the users
+ /// because deterministic mode is always superior when done right, but
+ /// for some consumers this mode is experimental and needs to be
+ /// off by default.
+ bool ShouldWriteStableReportFilename = false;
+
+ /// Whether the consumer should treat consumed diagnostics as hard errors.
+ /// Useful for breaking your build when issues are found.
+ bool ShouldDisplayWarningsAsErrors = false;
+
+ /// Whether the consumer should attempt to rewrite the source file
+ /// with fix-it hints attached to the diagnostics it consumes.
+ bool ShouldApplyFixIts = false;
+
+ /// Whether the consumer should present the name of the entity that emitted
+ /// the diagnostic (eg., a checker) so that the user knew how to disable it.
+ bool ShouldDisplayDiagnosticName = false;
+};
+
class PathDiagnosticConsumer {
public:
class PDFileEntry : public llvm::FoldingSetNode {
diff --git a/contrib/llvm-project/clang/include/clang/Basic/AddressSpaces.h b/contrib/llvm-project/clang/include/clang/Basic/AddressSpaces.h
index faf7f303aa2d..a9db52dfcc9c 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/AddressSpaces.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/AddressSpaces.h
@@ -36,6 +36,8 @@ enum class LangAS : unsigned {
opencl_constant,
opencl_private,
opencl_generic,
+ opencl_global_device,
+ opencl_global_host,
// CUDA specific address spaces.
cuda_device,
diff --git a/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h b/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h
index 88410c5cb51f..ab9f19da5d59 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h
@@ -33,6 +33,8 @@ inline llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS) {
return llvm::VersionTuple(11U);
case llvm::Triple::WatchOS: // Earliest supporting version is 4.0.0.
return llvm::VersionTuple(4U);
+ case llvm::Triple::ZOS:
+ return llvm::VersionTuple(); // All z/OS versions have no support.
}
llvm_unreachable("Unexpected OS");
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Attr.td b/contrib/llvm-project/clang/include/clang/Basic/Attr.td
index 60eaee7839e2..bfd50f6a6779 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Attr.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/Attr.td
@@ -126,6 +126,9 @@ def FunctionTmpl
FunctionDecl::TK_FunctionTemplate}],
"function templates">;
+def ClassTmpl : SubsetSubject<CXXRecord, [{S->getDescribedClassTemplate()}],
+ "class templates">;
+
// FIXME: this hack is needed because DeclNodes.td defines the base Decl node
// type to be a class, not a definition. This makes it impossible to create an
// attribute subject which accepts a Decl. Normally, this is not a problem,
@@ -267,8 +270,10 @@ class CXX11<string namespace, string name, int version = 1>
string Namespace = namespace;
int Version = version;
}
-class C2x<string namespace, string name> : Spelling<name, "C2x"> {
+class C2x<string namespace, string name, int version = 1>
+ : Spelling<name, "C2x"> {
string Namespace = namespace;
+ int Version = version;
}
class Keyword<string name> : Spelling<name, "Keyword">;
@@ -319,6 +324,7 @@ class LangOpt<string name, code customCode = [{}]> {
def MicrosoftExt : LangOpt<"MicrosoftExt">;
def Borland : LangOpt<"Borland">;
def CUDA : LangOpt<"CUDA">;
+def HIP : LangOpt<"HIP">;
def SYCL : LangOpt<"SYCLIsDevice">;
def COnly : LangOpt<"", "!LangOpts.CPlusPlus">;
def CPlusPlus : LangOpt<"CPlusPlus">;
@@ -366,8 +372,8 @@ def TargetRISCV : TargetArch<["riscv32", "riscv64"]>;
def TargetX86 : TargetArch<["x86"]>;
def TargetAnyX86 : TargetArch<["x86", "x86_64"]>;
def TargetWebAssembly : TargetArch<["wasm32", "wasm64"]>;
-def TargetWindows : TargetArch<["x86", "x86_64", "arm", "thumb", "aarch64"]> {
- let OSes = ["Win32"];
+def TargetHasDLLImportExport : TargetSpec {
+ let CustomCode = [{ Target.getTriple().hasDLLImportExport() }];
}
def TargetItaniumCXXABI : TargetSpec {
let CustomCode = [{ Target.getCXXABI().isItaniumFamily() }];
@@ -379,6 +385,9 @@ def TargetELF : TargetSpec {
let ObjectFormats = ["ELF"];
}
+def TargetSupportsInitPriority : TargetSpec {
+ let CustomCode = [{ !Target.getTriple().isOSzOS() }];
+}
// Attribute subject match rules that are used for #pragma clang attribute.
//
// A instance of AttrSubjectMatcherRule represents an individual match rule.
@@ -562,6 +571,9 @@ class InheritableAttr : Attr {
/// attributes, but have historically been written on declarations.
class DeclOrTypeAttr : InheritableAttr;
+/// A attribute is either a declaration attribute or a statement attribute.
+class DeclOrStmtAttr : InheritableAttr;
+
/// A target-specific attribute. This class is meant to be used as a mixin
/// with InheritableAttr or Attr depending on the attribute's needs.
class TargetSpecificAttr<TargetSpec target> {
@@ -670,10 +682,17 @@ def AlignMac68k : InheritableAttr {
let Documentation = [Undocumented];
}
+def AlignNatural : InheritableAttr {
+ // This attribute has no spellings as it is only ever created implicitly.
+ let Spellings = [];
+ let SemaHandler = 0;
+ let Documentation = [Undocumented];
+}
+
def AlwaysInline : InheritableAttr {
let Spellings = [GCC<"always_inline">, Keyword<"__forceinline">];
let Subjects = SubjectList<[Function]>;
- let Documentation = [Undocumented];
+ let Documentation = [AlwaysInlineDocs];
}
def Artificial : InheritableAttr {
@@ -735,9 +754,19 @@ def AnalyzerNoReturn : InheritableAttr {
def Annotate : InheritableParamAttr {
let Spellings = [Clang<"annotate">];
- let Args = [StringArgument<"Annotation">];
+ let Args = [StringArgument<"Annotation">, VariadicExprArgument<"Args">];
// Ensure that the annotate attribute can be used with
// '#pragma clang attribute' even though it has no subject list.
+ let AdditionalMembers = [{
+ static AnnotateAttr *Create(ASTContext &Ctx, llvm::StringRef Annotation, \
+ const AttributeCommonInfo &CommonInfo) {
+ return AnnotateAttr::Create(Ctx, Annotation, nullptr, 0, CommonInfo);
+ }
+ static AnnotateAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Annotation, \
+ const AttributeCommonInfo &CommonInfo = {SourceRange{}}) {
+ return AnnotateAttr::CreateImplicit(Ctx, Annotation, nullptr, 0, CommonInfo);
+ }
+ }];
let PragmaAttributeSupport = 1;
let Documentation = [Undocumented];
}
@@ -823,6 +852,7 @@ static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) {
.Case("macos_app_extension", "macOSApplicationExtension")
.Case("tvos_app_extension", "tvOSApplicationExtension")
.Case("watchos_app_extension", "watchOSApplicationExtension")
+ .Case("zos", "z/OS")
.Default(Platform);
}
static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) {
@@ -1060,6 +1090,7 @@ def CUDADeviceBuiltinSurfaceType : InheritableAttr {
let LangOpts = [CUDA];
let Subjects = SubjectList<[CXXRecord]>;
let Documentation = [CUDADeviceBuiltinSurfaceTypeDocs];
+ let MeaningfulToClassTemplateDefinition = 1;
}
def CUDADeviceBuiltinTextureType : InheritableAttr {
@@ -1068,6 +1099,7 @@ def CUDADeviceBuiltinTextureType : InheritableAttr {
let LangOpts = [CUDA];
let Subjects = SubjectList<[CXXRecord]>;
let Documentation = [CUDADeviceBuiltinTextureTypeDocs];
+ let MeaningfulToClassTemplateDefinition = 1;
}
def CUDAGlobal : InheritableAttr {
@@ -1084,6 +1116,13 @@ def CUDAHost : InheritableAttr {
let Documentation = [Undocumented];
}
+def HIPManaged : InheritableAttr {
+ let Spellings = [GNU<"managed">, Declspec<"__managed__">];
+ let Subjects = SubjectList<[Var]>;
+ let LangOpts = [HIP];
+ let Documentation = [HIPManagedAttrDocs];
+}
+
def CUDAInvalidTarget : InheritableAttr {
let Spellings = [];
let Subjects = SubjectList<[Function]>;
@@ -1178,6 +1217,16 @@ def OpenCLGlobalAddressSpace : TypeAttr {
let Documentation = [OpenCLAddressSpaceGlobalDocs];
}
+def OpenCLGlobalDeviceAddressSpace : TypeAttr {
+ let Spellings = [Clang<"opencl_global_device">];
+ let Documentation = [OpenCLAddressSpaceGlobalExtDocs];
+}
+
+def OpenCLGlobalHostAddressSpace : TypeAttr {
+ let Spellings = [Clang<"opencl_global_host">];
+ let Documentation = [OpenCLAddressSpaceGlobalExtDocs];
+}
+
def OpenCLLocalAddressSpace : TypeAttr {
let Spellings = [Keyword<"__local">, Keyword<"local">, Clang<"opencl_local">];
let Documentation = [OpenCLAddressSpaceLocalDocs];
@@ -1211,7 +1260,8 @@ def RenderScriptKernel : Attr {
def Deprecated : InheritableAttr {
let Spellings = [GCC<"deprecated">, Declspec<"deprecated">,
- CXX11<"","deprecated", 201309>, C2x<"", "deprecated">];
+ CXX11<"","deprecated", 201309>,
+ C2x<"", "deprecated", 201904>];
let Args = [StringArgument<"Message", 1>,
// An optional string argument that enables us to provide a
// Fix-It.
@@ -1268,15 +1318,29 @@ def ExtVectorType : Attr {
}
def FallThrough : StmtAttr {
- let Spellings = [CXX11<"", "fallthrough", 201603>, C2x<"", "fallthrough">,
+ let Spellings = [CXX11<"", "fallthrough", 201603>,
+ C2x<"", "fallthrough", 201904>,
CXX11<"clang", "fallthrough">, GCC<"fallthrough">];
// let Subjects = [NullStmt];
let Documentation = [FallthroughDocs];
}
-def NoMerge : StmtAttr {
+def Likely : StmtAttr {
+ let Spellings = [CXX11<"", "likely", 201803>, C2x<"clang", "likely">];
+ let Documentation = [LikelihoodDocs];
+}
+
+def Unlikely : StmtAttr {
+ let Spellings = [CXX11<"", "unlikely", 201803>, C2x<"clang", "unlikely">];
+ let Documentation = [LikelihoodDocs];
+}
+
+def NoMerge : DeclOrStmtAttr {
let Spellings = [Clang<"nomerge">];
let Documentation = [NoMergeDocs];
+ let InheritEvenIfAlreadyPresent = 1;
+ let Subjects = SubjectList<[Function], ErrorDiag, "functions and statements">;
+ let SimpleHandler = 1;
}
def FastCall : DeclOrTypeAttr {
@@ -1405,6 +1469,13 @@ def LayoutVersion : InheritableAttr, TargetSpecificAttr<TargetMicrosoftCXXABI> {
let Documentation = [LayoutVersionDocs];
}
+def Leaf : InheritableAttr {
+ let Spellings = [GCC<"leaf">];
+ let Subjects = SubjectList<[Function]>;
+ let Documentation = [LeafDocs];
+ let SimpleHandler = 1;
+}
+
def LifetimeBound : DeclOrTypeAttr {
let Spellings = [Clang<"lifetimebound", 0>];
let Subjects = SubjectList<[ParmVar, ImplicitObjectParameter], ErrorDiag>;
@@ -1532,6 +1603,16 @@ def NeonVectorType : TypeAttr {
let ASTNode = 0;
}
+def ArmSveVectorBits : TypeAttr {
+ let Spellings = [GNU<"arm_sve_vector_bits">];
+ let Subjects = SubjectList<[TypedefName], ErrorDiag>;
+ let Args = [UnsignedArgument<"NumBits">];
+ let Documentation = [ArmSveVectorBitsDocs];
+ let PragmaAttributeSupport = 0;
+ // Represented as VectorType instead.
+ let ASTNode = 0;
+}
+
def ArmMveStrictPolymorphism : TypeAttr, TargetSpecificAttr<TargetARM> {
let Spellings = [Clang<"__clang_arm_mve_strict_polymorphism">];
let Documentation = [ArmMveStrictPolymorphismDocs];
@@ -1732,6 +1813,13 @@ def ReturnsNonNull : InheritableAttr {
let Documentation = [ReturnsNonNullDocs];
}
+def CalledOnce : Attr {
+ let Spellings = [Clang<"called_once">];
+ let Subjects = SubjectList<[ParmVar]>;
+ let LangOpts = [ObjC];
+ let Documentation = [CalledOnceDocs];
+}
+
// pass_object_size(N) indicates that the parameter should have
// __builtin_object_size with Type=N evaluated on the parameter at the callsite.
def PassObjectSize : InheritableParamAttr {
@@ -1754,6 +1842,11 @@ def TypeNullable : TypeAttr {
let Documentation = [TypeNullableDocs];
}
+def TypeNullableResult : TypeAttr {
+ let Spellings = [Keyword<"_Nullable_result">];
+ let Documentation = [TypeNullableResultDocs];
+}
+
def TypeNullUnspecified : TypeAttr {
let Spellings = [Keyword<"_Null_unspecified">];
let Documentation = [TypeNullUnspecifiedDocs];
@@ -1856,6 +1949,13 @@ def ObjCBridgeRelated : InheritableAttr {
let Documentation = [Undocumented];
}
+def NSErrorDomain : InheritableAttr {
+ let Spellings = [GNU<"ns_error_domain">];
+ let Subjects = SubjectList<[Enum], ErrorDiag>;
+ let Args = [DeclArgument<Var, "ErrorDomain">];
+ let Documentation = [NSErrorDomainDocs];
+}
+
def NSReturnsRetained : DeclOrTypeAttr {
let Spellings = [Clang<"ns_returns_retained">];
// let Subjects = SubjectList<[ObjCMethod, ObjCProperty, Function]>;
@@ -1980,6 +2080,13 @@ def ObjCDirectMembers : Attr {
let Documentation = [ObjCDirectMembersDocs];
}
+def ObjCNonRuntimeProtocol : Attr {
+ let Spellings = [Clang<"objc_non_runtime_protocol">];
+ let Subjects = SubjectList<[ObjCProtocol], ErrorDiag>;
+ let LangOpts = [ObjC];
+ let Documentation = [ObjCNonRuntimeProtocolDocs];
+}
+
def ObjCRuntimeName : Attr {
let Spellings = [Clang<"objc_runtime_name">];
let Subjects = SubjectList<[ObjCInterface, ObjCProtocol], ErrorDiag>;
@@ -2087,6 +2194,70 @@ def Regparm : TypeAttr {
let ASTNode = 0;
}
+def SwiftAsyncName : InheritableAttr {
+ let Spellings = [GNU<"swift_async_name">];
+ let Args = [StringArgument<"Name">];
+ let Subjects = SubjectList<[ObjCMethod, Function], ErrorDiag>;
+ let Documentation = [SwiftAsyncNameDocs];
+}
+
+def SwiftAttr : InheritableAttr {
+ let Spellings = [GNU<"swift_attr">];
+ let Args = [StringArgument<"Attribute">];
+ let Documentation = [SwiftAttrDocs];
+}
+
+def SwiftBridge : InheritableAttr {
+ let Spellings = [GNU<"swift_bridge">];
+ let Args = [StringArgument<"SwiftType">];
+ let Subjects = SubjectList<[Tag, TypedefName, ObjCInterface, ObjCProtocol],
+ ErrorDiag>;
+ let Documentation = [SwiftBridgeDocs];
+}
+
+def SwiftBridgedTypedef : InheritableAttr {
+ let Spellings = [GNU<"swift_bridged_typedef">];
+ let Subjects = SubjectList<[TypedefName], ErrorDiag>;
+ let Documentation = [SwiftBridgedTypedefDocs];
+}
+
+def SwiftObjCMembers : Attr {
+ let Spellings = [GNU<"swift_objc_members">];
+ let Subjects = SubjectList<[ObjCInterface], ErrorDiag>;
+ let Documentation = [SwiftObjCMembersDocs];
+}
+
+def SwiftError : InheritableAttr {
+ let Spellings = [GNU<"swift_error">];
+ let Args = [
+ EnumArgument<"Convention", "ConventionKind",
+ ["none", "nonnull_error", "null_result", "zero_result", "nonzero_result"],
+ ["None", "NonNullError", "NullResult", "ZeroResult", "NonZeroResult"]>
+ ];
+ let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
+ let Documentation = [SwiftErrorDocs];
+}
+
+def SwiftName : InheritableAttr {
+ let Spellings = [GNU<"swift_name">];
+ let Args = [StringArgument<"Name">];
+ let Documentation = [SwiftNameDocs];
+}
+
+def SwiftNewType : InheritableAttr {
+ let Spellings = [GNU<"swift_newtype">, GNU<"swift_wrapper">];
+ let Args = [EnumArgument<"NewtypeKind", "NewtypeKind",
+ ["struct", "enum"], ["NK_Struct", "NK_Enum"]>];
+ let Subjects = SubjectList<[TypedefName], ErrorDiag>;
+ let Documentation = [SwiftNewTypeDocs];
+ let HasCustomParsing = 1;
+}
+
+def SwiftPrivate : InheritableAttr {
+ let Spellings = [GNU<"swift_private">];
+ let Documentation = [SwiftPrivateDocs];
+}
+
def NoDeref : TypeAttr {
let Spellings = [Clang<"noderef">];
let Documentation = [NoDerefDocs];
@@ -2111,7 +2282,7 @@ def WorkGroupSizeHint : InheritableAttr {
let Documentation = [Undocumented];
}
-def InitPriority : InheritableAttr {
+def InitPriority : InheritableAttr, TargetSpecificAttr<TargetSupportsInitPriority> {
let Spellings = [GCC<"init_priority", /*AllowInC*/0>];
let Args = [UnsignedArgument<"Priority">];
let Subjects = SubjectList<[Var], ErrorDiag>;
@@ -2167,6 +2338,14 @@ def PragmaClangRelroSection : InheritableAttr {
let Documentation = [Undocumented];
}
+def StrictFP : InheritableAttr {
+ // This attribute has no spellings as it is only ever created implicitly.
+ // Function uses strict floating point operations.
+ let Spellings = [];
+ let Subjects = SubjectList<[Function]>;
+ let Documentation = [Undocumented];
+}
+
def PragmaClangTextSection : InheritableAttr {
// This attribute has no spellings as it is only ever created implicitly.
let Spellings = [];
@@ -2210,6 +2389,16 @@ def SwiftIndirectResult : ParameterABIAttr {
let Documentation = [SwiftIndirectResultDocs];
}
+def SwiftAsync : InheritableAttr {
+ let Spellings = [Clang<"swift_async">];
+ let Subjects = SubjectList<[Function, ObjCMethod]>;
+ let Args = [EnumArgument<"Kind", "Kind",
+ ["none", "swift_private", "not_swift_private"],
+ ["None", "SwiftPrivate", "NotSwiftPrivate"]>,
+ ParamIdxArgument<"CompletionHandlerIndex", /*opt=*/1>];
+ let Documentation = [SwiftAsyncDocs];
+}
+
def Suppress : StmtAttr {
let Spellings = [CXX11<"gsl", "suppress">];
let Args = [VariadicStringArgument<"DiagnosticIdentifiers">];
@@ -2242,6 +2431,16 @@ def Pascal : DeclOrTypeAttr {
let Documentation = [Undocumented];
}
+def PreferredName : InheritableAttr {
+ let Spellings = [Clang<"preferred_name", /*AllowInC*/0>];
+ let Subjects = SubjectList<[ClassTmpl]>;
+ let Args = [TypeArgument<"TypedefType">];
+ let Documentation = [PreferredNameDocs];
+ let InheritEvenIfAlreadyPresent = 1;
+ let MeaningfulToClassTemplateDefinition = 1;
+ let TemplateDependent = 1;
+}
+
def PreserveMost : DeclOrTypeAttr {
let Spellings = [Clang<"preserve_most">];
let Documentation = [PreserveMostDocs];
@@ -2317,11 +2516,10 @@ def Target : InheritableAttr {
// accepting it weirdly.
Feature = Feature.trim();
- // We don't support cpu tuning this way currently.
// TODO: Support the fpmath option. It will require checking
// overall feature validity for the function with the rest of the
// attributes on the function.
- if (Feature.startswith("fpmath=") || Feature.startswith("tune="))
+ if (Feature.startswith("fpmath="))
continue;
if (Feature.startswith("branch-protection=")) {
@@ -2335,6 +2533,11 @@ def Target : InheritableAttr {
Ret.DuplicateArchitecture = true;
else
Ret.Architecture = Feature.split("=").second.trim();
+ } else if (Feature.startswith("tune=")) {
+ if (!Ret.Tune.empty())
+ Ret.DuplicateTune = true;
+ else
+ Ret.Tune = Feature.split("=").second.trim();
} else if (Feature.startswith("no-"))
Ret.Features.push_back("-" + Feature.split("-").second.str());
else
@@ -2424,7 +2627,7 @@ def ObjCRequiresPropertyDefs : InheritableAttr {
def Unused : InheritableAttr {
let Spellings = [CXX11<"", "maybe_unused", 201603>, GCC<"unused">,
- C2x<"", "maybe_unused">];
+ C2x<"", "maybe_unused", 201904>];
let Subjects = SubjectList<[Var, ObjCIvar, Type, Enum, EnumConstant, Label,
Field, ObjCMethod, FunctionLike]>;
let Documentation = [WarnMaybeUnusedDocs];
@@ -2510,7 +2713,8 @@ def WarnUnused : InheritableAttr {
}
def WarnUnusedResult : InheritableAttr {
- let Spellings = [CXX11<"", "nodiscard", 201907>, C2x<"", "nodiscard">,
+ let Spellings = [CXX11<"", "nodiscard", 201907>,
+ C2x<"", "nodiscard", 201904>,
CXX11<"clang", "warn_unused_result">,
GCC<"warn_unused_result">];
let Subjects = SubjectList<[ObjCMethod, Enum, Record, FunctionLike]>;
@@ -3031,24 +3235,24 @@ def MSStruct : InheritableAttr {
let SimpleHandler = 1;
}
-def DLLExport : InheritableAttr, TargetSpecificAttr<TargetWindows> {
+def DLLExport : InheritableAttr, TargetSpecificAttr<TargetHasDLLImportExport> {
let Spellings = [Declspec<"dllexport">, GCC<"dllexport">];
let Subjects = SubjectList<[Function, Var, CXXRecord, ObjCInterface]>;
let Documentation = [DLLExportDocs];
}
-def DLLExportStaticLocal : InheritableAttr, TargetSpecificAttr<TargetWindows> {
+def DLLExportStaticLocal : InheritableAttr, TargetSpecificAttr<TargetHasDLLImportExport> {
// This attribute is used internally only when -fno-dllexport-inlines is
- // passed. This attribute is added to inline function of class having
- // dllexport attribute. And if the function has static local variables, this
- // attribute is used to whether the variables are exported or not. Also if
- // function has local static variables, the function is dllexported too.
+ // passed. This attribute is added to inline functions of a class having the
+ // dllexport attribute. If the function has static local variables, this
+ // attribute is used to determine whether the variables are exported or not. If
+ // the function has local static variables, the function is dllexported too.
let Spellings = [];
let Subjects = SubjectList<[Function]>;
let Documentation = [Undocumented];
}
-def DLLImport : InheritableAttr, TargetSpecificAttr<TargetWindows> {
+def DLLImport : InheritableAttr, TargetSpecificAttr<TargetHasDLLImportExport> {
let Spellings = [Declspec<"dllimport">, GCC<"dllimport">];
let Subjects = SubjectList<[Function, Var, CXXRecord, ObjCInterface]>;
let Documentation = [DLLImportDocs];
@@ -3064,11 +3268,11 @@ public:
}];
}
-def DLLImportStaticLocal : InheritableAttr, TargetSpecificAttr<TargetWindows> {
+def DLLImportStaticLocal : InheritableAttr, TargetSpecificAttr<TargetHasDLLImportExport> {
// This attribute is used internally only when -fno-dllexport-inlines is
- // passed. This attribute is added to inline function of class having
- // dllimport attribute. And if the function has static local variables, this
- // attribute is used to whether the variables are imported or not.
+ // passed. This attribute is added to inline functions of a class having the
+ // dllimport attribute. If the function has static local variables, this
+ // attribute is used to determine whether the variables are imported or not.
let Spellings = [];
let Subjects = SubjectList<[Function]>;
let Documentation = [Undocumented];
@@ -3186,8 +3390,10 @@ def LoopHint : Attr {
"PipelineDisabled", "PipelineInitiationInterval", "Distribute",
"VectorizePredicate"]>,
EnumArgument<"State", "LoopHintState",
- ["enable", "disable", "numeric", "assume_safety", "full"],
- ["Enable", "Disable", "Numeric", "AssumeSafety", "Full"]>,
+ ["enable", "disable", "numeric", "fixed_width",
+ "scalable_width", "assume_safety", "full"],
+ ["Enable", "Disable", "Numeric", "FixedWidth",
+ "ScalableWidth", "AssumeSafety", "Full"]>,
ExprArgument<"Value">];
let AdditionalMembers = [{
@@ -3296,13 +3502,15 @@ def OMPDeclareTargetDecl : InheritableAttr {
[ "MT_To", "MT_Link" ]>,
EnumArgument<"DevType", "DevTypeTy",
[ "host", "nohost", "any" ],
- [ "DT_Host", "DT_NoHost", "DT_Any" ]>
+ [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
+ UnsignedArgument<"Level">
];
let AdditionalMembers = [{
void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const;
static llvm::Optional<MapTypeTy>
isDeclareTargetDeclaration(const ValueDecl *VD);
static llvm::Optional<DevTypeTy> getDeviceType(const ValueDecl *VD);
+ static llvm::Optional<SourceLocation> getLocation(const ValueDecl *VD);
}];
}
@@ -3349,6 +3557,14 @@ def OMPDeclareVariant : InheritableAttr {
}];
}
+def Assumption : InheritableAttr {
+ let Spellings = [Clang<"assume">];
+ let Subjects = SubjectList<[Function, ObjCMethod]>;
+ let InheritEvenIfAlreadyPresent = 1;
+ let Documentation = [AssumptionDocs];
+ let Args = [StringArgument<"Assumption">];
+}
+
def InternalLinkage : InheritableAttr {
let Spellings = [Clang<"internal_linkage">];
let Subjects = SubjectList<[Var, Function, CXXRecord]>;
@@ -3452,3 +3668,19 @@ def Builtin : InheritableAttr {
let SemaHandler = 0;
let Documentation = [Undocumented];
}
+
+def EnforceTCB : InheritableAttr {
+ let Spellings = [Clang<"enforce_tcb">];
+ let Subjects = SubjectList<[Function]>;
+ let Args = [StringArgument<"TCBName">];
+ let Documentation = [EnforceTCBDocs];
+ bit InheritEvenIfAlreadyPresent = 1;
+}
+
+def EnforceTCBLeaf : InheritableAttr {
+ let Spellings = [Clang<"enforce_tcb_leaf">];
+ let Subjects = SubjectList<[Function]>;
+ let Args = [StringArgument<"TCBName">];
+ let Documentation = [EnforceTCBLeafDocs];
+ bit InheritEvenIfAlreadyPresent = 1;
+}
diff --git a/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td b/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td
index 833127ed44eb..170a0fe3d4c4 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td
@@ -75,11 +75,11 @@ relative ordering of values is important. For example:
__attribute__((init_priority(200))) SomeType Obj1;
__attribute__((init_priority(101))) SomeType Obj2;
-``Obj1`` will be initialized *before* ``Obj2`` despite the usual order of
+``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
initialization being the opposite.
This attribute is only supported for C++ and Objective-C++ and is ignored in
-other language modes.
+other language modes. Currently, this attribute is not implemented on z/OS.
}];
}
@@ -87,12 +87,12 @@ def InitSegDocs : Documentation {
let Category = DocCatVariable;
let Content = [{
The attribute applied by ``pragma init_seg()`` controls the section into
-which global initialization function pointers are emitted. It is only
-available with ``-fms-extensions``. Typically, this function pointer is
-emitted into ``.CRT$XCU`` on Windows. The user can change the order of
+which global initialization function pointers are emitted. It is only
+available with ``-fms-extensions``. Typically, this function pointer is
+emitted into ``.CRT$XCU`` on Windows. The user can change the order of
initialization by using a different section name with the same
``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
-after the standard ``.CRT$XCU`` sections. See the init_seg_
+after the standard ``.CRT$XCU`` sections. See the init_seg_
documentation on MSDN for more information.
.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
@@ -118,10 +118,10 @@ def DLLExportDocs : Documentation {
let Category = DocCatVariable;
let Content = [{
The ``__declspec(dllexport)`` attribute declares a variable, function, or
-Objective-C interface to be exported from the module. It is available under the
-``-fdeclspec`` flag for compatibility with various compilers. The primary use
+Objective-C interface to be exported from the module. It is available under the
+``-fdeclspec`` flag for compatibility with various compilers. The primary use
is for COFF object files which explicitly specify what interfaces are available
-for external use. See the dllexport_ documentation on MSDN for more
+for external use. See the dllexport_ documentation on MSDN for more
information.
.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
@@ -132,10 +132,10 @@ def DLLImportDocs : Documentation {
let Category = DocCatVariable;
let Content = [{
The ``__declspec(dllimport)`` attribute declares a variable, function, or
-Objective-C interface to be imported from an external module. It is available
-under the ``-fdeclspec`` flag for compatibility with various compilers. The
+Objective-C interface to be imported from an external module. It is available
+under the ``-fdeclspec`` flag for compatibility with various compilers. The
primary use is for COFF object files which explicitly specify what interfaces
-are imported from external modules. See the dllimport_ documentation on MSDN
+are imported from external modules. See the dllimport_ documentation on MSDN
for more information.
.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
@@ -146,14 +146,14 @@ def ThreadDocs : Documentation {
let Category = DocCatVariable;
let Content = [{
The ``__declspec(thread)`` attribute declares a variable with thread local
-storage. It is available under the ``-fms-extensions`` flag for MSVC
-compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
+storage. It is available under the ``-fms-extensions`` flag for MSVC
+compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
-GNU ``__thread`` keyword. The variable must not have a destructor and must have
-a constant initializer, if any. The attribute only applies to variables
+GNU ``__thread`` keyword. The variable must not have a destructor and must have
+a constant initializer, if any. The attribute only applies to variables
declared with static storage duration, such as globals, class static data
members, and static locals.
}];
@@ -305,7 +305,7 @@ outlining job:
A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
A SYCL kernel defines the entry point to the "device part" of the code. The
compiler will emit all symbols accessible from a "kernel". In this code
-example, the compiler will emit "foo" function. More details about the
+example, the compiler will emit "foo" function. More details about the
compilation of functions for the device part can be found in the SYCL 1.2.1
specification Section 6.4.
To show to the compiler entry point to the "device part" of the code, the SYCL
@@ -377,16 +377,20 @@ that appears to be capable of returning to its caller.
}
def NoMergeDocs : Documentation {
- let Category = DocCatFunction;
+ let Category = DocCatStmt;
let Content = [{
-If a statement is marked ``nomerge`` and contains call experessions, those call
+If a statement is marked ``nomerge`` and contains call expressions, those call
expressions inside the statement will not be merged during optimization. This
attribute can be used to prevent the optimizer from obscuring the source
location of certain calls. For example, it will prevent tail merging otherwise
identical code sequences that raise an exception or terminate the program. Tail
merging normally reduces the precision of source location information, making
stack traces less useful for debugging. This attribute gives the user control
-over the tradeoff between code size and debug information precision.
+over the tradeoff between code size and debug information precision.
+
+``nomerge`` attribute can also be used as function attribute to prevent all
+calls to the specified function from merging. It has no effect on indirect
+calls.
}];
}
@@ -524,7 +528,7 @@ parameter.
Note that this attribute merely informs the compiler that a function always
returns a sufficiently aligned pointer. It does not cause the compiler to
-emit code to enforce that alignment. The behavior is undefined if the returned
+emit code to enforce that alignment. The behavior is undefined if the returned
pointer is not sufficiently aligned.
}];
}
@@ -833,8 +837,8 @@ read more about ``__builtin_dynamic_object_size`` `here
def OverloadableDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
-Clang provides support for C++ function overloading in C. Function overloading
-in C is introduced using the ``overloadable`` attribute. For example, one
+Clang provides support for C++ function overloading in C. Function overloading
+in C is introduced using the ``overloadable`` attribute. For example, one
might provide several overloaded versions of a ``tgsin`` function that invokes
the appropriate standard function computing the sine of a value with ``float``,
``double``, or ``long double`` precision:
@@ -848,7 +852,7 @@ the appropriate standard function computing the sine of a value with ``float``,
Given these declarations, one can call ``tgsin`` with a ``float`` value to
receive a ``float`` result, with a ``double`` to receive a ``double`` result,
-etc. Function overloading in C follows the rules of C++ function overloading
+etc. Function overloading in C follows the rules of C++ function overloading
to pick the best overload given the call arguments, with a few C-specific
semantics:
@@ -861,7 +865,7 @@ semantics:
compatible types.
* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
- and ``U`` are compatible types. This conversion is given "conversion" rank.
+ and ``U`` are compatible types. This conversion is given "conversion" rank.
* If no viable candidates are otherwise available, we allow a conversion from a
pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
@@ -870,10 +874,10 @@ semantics:
for ``T`` and ``U`` to be incompatible.
The declaration of ``overloadable`` functions is restricted to function
-declarations and definitions. If a function is marked with the ``overloadable``
+declarations and definitions. If a function is marked with the ``overloadable``
attribute, then all declarations and definitions of functions with that name,
except for at most one (see the note below about unmarked overloads), must have
-the ``overloadable`` attribute. In addition, redeclarations of a function with
+the ``overloadable`` attribute. In addition, redeclarations of a function with
the ``overloadable`` attribute must have the ``overloadable`` attribute, and
redeclarations of a function without the ``overloadable`` attribute must *not*
have the ``overloadable`` attribute. e.g.,
@@ -891,7 +895,7 @@ have the ``overloadable`` attribute. e.g.,
int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
// have the "overloadable" attribute
-Functions marked ``overloadable`` must have prototypes. Therefore, the
+Functions marked ``overloadable`` must have prototypes. Therefore, the
following code is ill-formed:
.. code-block:: c
@@ -899,7 +903,7 @@ following code is ill-formed:
int h() __attribute__((overloadable)); // error: h does not have a prototype
However, ``overloadable`` functions are allowed to use a ellipsis even if there
-are no named parameters (as is permitted in C++). This feature is particularly
+are no named parameters (as is permitted in C++). This feature is particularly
useful when combined with the ``unavailable`` attribute:
.. code-block:: c++
@@ -907,13 +911,13 @@ useful when combined with the ``unavailable`` attribute:
void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
Functions declared with the ``overloadable`` attribute have their names mangled
-according to the same rules as C++ function names. For example, the three
+according to the same rules as C++ function names. For example, the three
``tgsin`` functions in our motivating example get the mangled names
-``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
+``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
caveats to this use of name mangling:
* Future versions of Clang may change the name mangling of functions overloaded
- in C, so you should not depend on an specific mangling. To be completely
+ in C, so you should not depend on an specific mangling. To be completely
safe, we strongly urge the use of ``static inline`` with ``overloadable``
functions.
@@ -959,7 +963,7 @@ use cases, we provide an attribute to specifically describe the "method family"
that a method belongs to.
**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
-``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
+``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
attribute can only be placed at the end of a method declaration:
.. code-block:: objc
@@ -983,7 +987,7 @@ The behavior of a function with respect to reference counting for Foundation
convention (e.g. functions starting with "get" are assumed to return at
``+0``).
-It can be overridden using a family of the following attributes. In
+It can be overridden using a family of the following attributes. In
Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
a function communicates that the object is returned at ``+1``, and the caller
is responsible for freeing it.
@@ -1110,6 +1114,7 @@ not made control-dependent on any additional values, e.g., unrolling a loop
executed by all work items.
Sample usage:
+
.. code-block:: c
void convfunc(void) __attribute__((convergent));
@@ -1163,7 +1168,7 @@ method in the parent class. For these cases, we provide an attribute to
designate that a method requires a "call to ``super``" in the overriding
method in the subclass.
-**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
+**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
be placed at the end of a method declaration:
.. code-block:: objc
@@ -1171,9 +1176,9 @@ be placed at the end of a method declaration:
- (void)foo __attribute__((objc_requires_super));
This attribute can only be applied the method declarations within a class, and
-not a protocol. Currently this attribute does not enforce any placement of
+not a protocol. Currently this attribute does not enforce any placement of
where the call occurs in the overriding method (such as in the case of
-``-dealloc`` where the call must appear at the end). It checks only that it
+``-dealloc`` where the call must appear at the end). It checks only that it
exists.
Note that on both OS X and iOS that the Foundation framework provides a
@@ -1185,11 +1190,11 @@ attribute:
- (void)foo NS_REQUIRES_SUPER;
This macro is conditionally defined depending on the compiler's support for
-this attribute. If the compiler does not support the attribute the macro
+this attribute. If the compiler does not support the attribute the macro
expands to nothing.
Operationally, when a method has this annotation the compiler will warn if the
-implementation of an override in a subclass does not call super. For example:
+implementation of an override in a subclass does not call super. For example:
.. code-block:: objc
@@ -1208,7 +1213,7 @@ attribute allows annotated interfaces or protocols to use the
specified string argument in the object's metadata name instead of the
default name.
-**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
+**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
can only be placed before an @protocol or @interface declaration:
.. code-block:: objc
@@ -1281,7 +1286,7 @@ def AvailabilityDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
The ``availability`` attribute can be placed on declarations to describe the
-lifecycle of that declaration relative to operating system versions. Consider
+lifecycle of that declaration relative to operating system versions. Consider
the function declaration for a hypothetical function ``f``:
.. code-block:: c++
@@ -1289,17 +1294,17 @@ the function declaration for a hypothetical function ``f``:
void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
The availability attribute states that ``f`` was introduced in macOS 10.4,
-deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
+deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
is used by Clang to determine when it is safe to use ``f``: for example, if
Clang is instructed to compile code for macOS 10.5, a call to ``f()``
-succeeds. If Clang is instructed to compile code for macOS 10.6, the call
+succeeds. If Clang is instructed to compile code for macOS 10.6, the call
succeeds but Clang emits a warning specifying that the function is deprecated.
Finally, if Clang is instructed to compile code for macOS 10.7, the call
fails because ``f()`` is no longer available.
The availability attribute is a comma-separated list starting with the
platform name and then including clauses specifying important milestones in the
-declaration's lifetime (in any order) along with additional information. Those
+declaration's lifetime (in any order) along with additional information. Those
clauses can be:
introduced=\ *version*
@@ -1318,7 +1323,7 @@ unavailable
message=\ *string-literal*
Additional message text that Clang will provide when emitting a warning or
- error about use of a deprecated or obsoleted declaration. Useful to direct
+ error about use of a deprecated or obsoleted declaration. Useful to direct
users to replacement APIs.
replacement=\ *string-literal*
@@ -1337,35 +1342,35 @@ specifies availability for the current target platform, the availability
attributes are ignored. Supported platforms are:
``ios``
- Apple's iOS operating system. The minimum deployment target is specified by
+ Apple's iOS operating system. The minimum deployment target is specified by
the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
command-line arguments.
``macos``
- Apple's macOS operating system. The minimum deployment target is
+ Apple's macOS operating system. The minimum deployment target is
specified by the ``-mmacosx-version-min=*version*`` command-line argument.
``macosx`` is supported for backward-compatibility reasons, but it is
deprecated.
``tvos``
- Apple's tvOS operating system. The minimum deployment target is specified by
+ Apple's tvOS operating system. The minimum deployment target is specified by
the ``-mtvos-version-min=*version*`` command-line argument.
``watchos``
- Apple's watchOS operating system. The minimum deployment target is specified by
+ Apple's watchOS operating system. The minimum deployment target is specified by
the ``-mwatchos-version-min=*version*`` command-line argument.
A declaration can typically be used even when deploying back to a platform
-version prior to when the declaration was introduced. When this happens, the
+version prior to when the declaration was introduced. When this happens, the
declaration is `weakly linked
<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
-as if the ``weak_import`` attribute were added to the declaration. A
+as if the ``weak_import`` attribute were added to the declaration. A
weakly-linked declaration may or may not be present a run-time, and a program
can determine whether the declaration is present by checking whether the
address of that declaration is non-NULL.
The flag ``strict`` disallows using API when deploying back to a
-platform version prior to when the declaration was introduced. An
+platform version prior to when the declaration was introduced. An
attempt to use such API before its introduction causes a hard error.
Weakly-linking is almost always a better API choice, since it allows
users to query availability at runtime.
@@ -1663,12 +1668,12 @@ def FallthroughDocs : Documentation {
let Content = [{
The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
to annotate intentional fall-through
-between switch labels. It can only be applied to a null statement placed at a
-point of execution between any statement and the next switch label. It is
+between switch labels. It can only be applied to a null statement placed at a
+point of execution between any statement and the next switch label. It is
common to mark these places with a specific comment, but this attribute is
meant to replace comments with a more strict annotation, which can be checked
-by the compiler. This attribute doesn't change semantics of the code and can
-be used wherever an intended fall-through occurs. It is designed to mimic
+by the compiler. This attribute doesn't change semantics of the code and can
+be used wherever an intended fall-through occurs. It is designed to mimic
control-flow statements like ``break;``, so it can be placed in most places
where ``break;`` can, but only if there are no statements on the execution path
between it and the next switch label.
@@ -1709,6 +1714,166 @@ Here is an example:
}];
}
+def LikelihoodDocs : Documentation {
+ let Category = DocCatStmt;
+ let Heading = "likely and unlikely";
+ let Content = [{
+The ``likely`` and ``unlikely`` attributes are used as compiler hints.
+The attributes are used to aid the compiler to determine which branch is
+likely or unlikely to be taken. This is done by marking the branch substatement
+with one of the two attributes.
+
+It isn't allowed to annotate a single statement with both ``likely`` and
+``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
+statement with the same likelihood attribute will result in a diagnostic and
+the attributes are ignored on both branches.
+
+In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
+or the ``default`` label with the same likelihood attribute. This makes
+* all labels without an attribute have a neutral likelihood,
+* all labels marked ``[[likely]]`` have an equally positive likelihood, and
+* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
+The neutral likelihood is the more likely of path execution than the negative
+likelihood. The positive likelihood is the more likely of path of execution
+than the neutral likelihood.
+
+These attributes have no effect on the generated code when using
+PGO (Profile-Guided Optimization) or at optimization level 0.
+
+In Clang, the attributes will be ignored if they're not placed on
+* the ``case`` or ``default`` label of a ``switch`` statement,
+* or on the substatement of an ``if`` or ``else`` statement,
+* or on the substatement of an ``for`` or ``while`` statement.
+The C++ Standard recommends to honor them on every statement in the
+path of execution, but that can be confusing:
+
+.. code-block:: c++
+
+ if (b) {
+ [[unlikely]] --b; // In the path of execution,
+ // this branch is considered unlikely.
+ }
+
+ if (b) {
+ --b;
+ if(b)
+ return;
+ [[unlikely]] --b; // Not in the path of execution,
+ } // the branch has no likelihood information.
+
+ if (b) {
+ --b;
+ foo(b);
+ // Whether or not the next statement is in the path of execution depends
+ // on the declaration of foo():
+ // In the path of execution: void foo(int);
+ // Not in the path of execution: [[noreturn]] void foo(int);
+ // This means the likelihood of the branch depends on the declaration
+ // of foo().
+ [[unlikely]] --b;
+ }
+
+
+Below are some example usages of the likelihood attributes and their effects:
+
+.. code-block:: c++
+
+ if (b) [[likely]] { // Placement on the first statement in the branch.
+ // The compiler will optimize to execute the code here.
+ } else {
+ }
+
+ if (b)
+ [[unlikely]] b++; // Placement on the first statement in the branch.
+ else {
+ // The compiler will optimize to execute the code here.
+ }
+
+ if (b) {
+ [[unlikely]] b++; // Placement on the second statement in the branch.
+ } // The attribute will be ignored.
+
+ if (b) [[likely]] {
+ [[unlikely]] b++; // No contradiction since the second attribute
+ } // is ignored.
+
+ if (b)
+ ;
+ else [[likely]] {
+ // The compiler will optimize to execute the code here.
+ }
+
+ if (b)
+ ;
+ else
+ // The compiler will optimize to execute the next statement.
+ [[likely]] b = f();
+
+ if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
+ else [[likely]]; // and the attributes are ignored.
+
+ if (b)
+ [[likely]] int i = 5; // Issues a diagnostic since the attribute
+ // isn't allowed on a declaration.
+
+ switch (i) {
+ [[likely]] case 1: // This value is likely
+ ...
+ break;
+
+ [[unlikely]] case 2: // This value is unlikely
+ ...
+ [[fallthrough]];
+
+ case 3: // No likelihood attribute
+ ...
+ [[likely]] break; // No effect
+
+ case 4: [[likely]] { // attribute on substatement has no effect
+ ...
+ break;
+ }
+
+ [[unlikely]] default: // All other values are unlikely
+ ...
+ break;
+ }
+
+ switch (i) {
+ [[likely]] case 0: // This value and code path is likely
+ ...
+ [[fallthrough]];
+
+ case 1: // No likelihood attribute, code path is neutral
+ break; // falling through has no effect on the likelihood
+
+ case 2: // No likelihood attribute, code path is neutral
+ [[fallthrough]];
+
+ [[unlikely]] default: // This value and code path are both unlikely
+ break;
+ }
+
+ for(int i = 0; i != size; ++i) [[likely]] {
+ ... // The loop is the likely path of execution
+ }
+
+ for(const auto &E : Elements) [[likely]] {
+ ... // The loop is the likely path of execution
+ }
+
+ while(i != size) [[unlikely]] {
+ ... // The loop is the unlikely path of execution
+ } // The generated code will optimize to skip the loop body
+
+ while(true) [[unlikely]] {
+ ... // The attribute has no effect
+ } // Clang elides the comparison and generates an infinite
+ // loop
+
+ }];
+}
+
def ARMInterruptDocs : Documentation {
let Category = DocCatFunction;
let Heading = "interrupt (ARM)";
@@ -1758,7 +1923,7 @@ Clang supports the ``__attribute__((preserve_access_index))``
attribute for the BPF target. This attribute may be attached to a
struct or union declaration, where if -g is specified, it enables
preserving struct or union member access debuginfo indices of this
-struct or union, similar to clang ``__builtin_preserve_acceess_index()``.
+struct or union, similar to clang ``__builtin_preserve_access_index()``.
}];
}
@@ -1826,7 +1991,7 @@ only be added to function declarations and change the code generated
by the compiler when directly calling the function. The ``near`` attribute
allows calls to the function to be made using the ``jal`` instruction, which
requires the function to be located in the same naturally aligned 256MB
-segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
+segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
and require the use of a different call sequence that works regardless
of the distance between the functions.
@@ -1848,7 +2013,7 @@ and change the code generated by the compiler when directly calling
the function. The ``short_call`` and ``near`` attributes are synonyms and
allow calls to the function to be made using the ``jal`` instruction, which
requires the function to be located in the same naturally aligned 256MB segment
-as the caller. The ``long_call`` and ``far`` attributes are synonyms and
+as the caller. The ``long_call`` and ``far`` attributes are synonyms and
require the use of a different call sequence that works regardless
of the distance between the functions.
@@ -1923,6 +2088,9 @@ the target with or without a "-mno-" in front corresponding to the absence
of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
for the function.
+For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
+code for the given CPU without changing the available instructions.
+
For AArch64, the attribute also allows the "branch-protection=<args>" option,
where the permissible arguments and their effect on code generation are the same
as for the command-line option ``-mbranch-protection``.
@@ -1936,7 +2104,7 @@ x86/x86-64 targets, which can be used to create multiple implementations of the
same function that will be resolved at runtime based on the priority of their
``target`` attribute strings. A function is considered a multiversioned function
if either two declarations of the function have different ``target`` attribute
-strings, or if it has a ``target`` attribute string of ``default``. For
+strings, or if it has a ``target`` attribute string of ``default``. For
example:
.. code-block:: c++
@@ -2160,7 +2328,7 @@ On 32-bit x86 targets, this attribute changes the calling convention of a
function to clear parameters off of the stack on return. This convention does
not support variadic calls or unprototyped functions in C, and has no effect on
x86_64 targets. This calling convention is used widely by the Windows API and
-COM applications. See the documentation for `__stdcall`_ on MSDN.
+COM applications. See the documentation for `__stdcall`_ on MSDN.
.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
}];
@@ -2175,7 +2343,7 @@ the stack on return. This convention does not support variadic calls or
unprototyped functions in C, and has no effect on x86_64 targets. This calling
convention is supported primarily for compatibility with existing code. Users
seeking register parameters should use the ``regparm`` attribute, which does
-not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
+not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
}];
@@ -2215,7 +2383,7 @@ convention of a function to pass vector parameters in SSE registers.
On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
The first two integer parameters are passed in ECX and EDX. Subsequent integer
-parameters are passed in memory, and callee clears the stack. On x86_64
+parameters are passed in memory, and callee clears the stack. On x86_64
targets, the callee does *not* clear the stack, and integer parameters are
passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
convention.
@@ -2246,7 +2414,7 @@ def SetTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Annotate methods that transition an object into a new state with
-``__attribute__((set_typestate(new_state)))``. The new state must be
+``__attribute__((set_typestate(new_state)))``. The new state must be
unconsumed, consumed, or unknown.
}];
}
@@ -2255,8 +2423,8 @@ def CallableWhenDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Use ``__attribute__((callable_when(...)))`` to indicate what states a method
-may be called in. Valid states are unconsumed, consumed, or unknown. Each
-argument to this attribute must be a quoted string. E.g.:
+may be called in. Valid states are unconsumed, consumed, or unknown. Each
+argument to this attribute must be a quoted string. E.g.:
``__attribute__((callable_when("unconsumed", "unknown")))``
}];
@@ -2273,9 +2441,9 @@ returns true if the object is in the specified state..
def ParamTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
-This attribute specifies expectations about function parameters. Calls to an
+This attribute specifies expectations about function parameters. Calls to an
function with annotated parameters will issue a warning if the corresponding
-argument isn't in the expected state. The attribute is also used to set the
+argument isn't in the expected state. The attribute is also used to set the
initial state of the parameter when analyzing the function's body.
}];
}
@@ -2285,12 +2453,12 @@ def ReturnTypestateDocs : Documentation {
let Content = [{
The ``return_typestate`` attribute can be applied to functions or parameters.
When applied to a function the attribute specifies the state of the returned
-value. The function's body is checked to ensure that it always returns a value
-in the specified state. On the caller side, values returned by the annotated
+value. The function's body is checked to ensure that it always returns a value
+in the specified state. On the caller side, values returned by the annotated
function are initialized to the given state.
When applied to a function parameter it modifies the state of an argument after
-a call to the function returns. The function's body is checked to ensure that
+a call to the function returns. The function's body is checked to ensure that
the parameter is in the expected state before returning.
}];
}
@@ -2299,7 +2467,7 @@ def ConsumableDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Each ``class`` that uses any of the typestate annotations must first be marked
-using the ``consumable`` attribute. Failure to do so will result in a warning.
+using the ``consumable`` attribute. Failure to do so will result in a warning.
This attribute accepts a single parameter that must be one of the following:
``unknown``, ``consumed``, or ``unconsumed``.
@@ -2387,7 +2555,7 @@ checks, ensure that -Wtype-safety is enabled. Use cases include:
* checking types of variadic functions' arguments for functions like
``fcntl()`` and ``ioctl()``.
-You can detect support for these attributes with ``__has_attribute()``. For
+You can detect support for these attributes with ``__has_attribute()``. For
example:
.. code-block:: c++
@@ -2397,7 +2565,7 @@ example:
__has_attribute(pointer_with_type_tag) && \
__has_attribute(type_tag_for_datatype)
# define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
- /* ... other macros ... */
+ /* ... other macros ... */
# endif
#endif
@@ -2552,14 +2720,14 @@ values for this optional third argument:
/* In user code */
struct my_pair { double a; int b; };
struct my_pair *buffer;
- MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
+ MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
// layout of my_pair is
// compatible with that of
// internal_mpi_double_int
struct my_int_pair { int a; int b; }
struct my_int_pair *buffer2;
- MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
+ MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
// layout of my_int_pair
// does not match that of
// internal_mpi_double_int
@@ -2584,7 +2752,7 @@ values for this optional third argument:
/* In user code */
struct my_pair { double a; int b; };
struct my_pair *buffer;
- MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
+ MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
// was specified but buffer
// is not a null pointer
}];
@@ -2615,18 +2783,18 @@ Clang implements two kinds of checks with this attribute.
#. Clang checks that the function with the ``format`` attribute is called with
a format string that uses format specifiers that are allowed, and that
- arguments match the format string. This is the ``-Wformat`` warning, it is
+ arguments match the format string. This is the ``-Wformat`` warning, it is
on by default.
-#. Clang checks that the format string argument is a literal string. This is
+#. Clang checks that the format string argument is a literal string. This is
the ``-Wformat-nonliteral`` warning, it is off by default.
Clang implements this mostly the same way as GCC, but there is a difference
for functions that accept a ``va_list`` argument (for example, ``vprintf``).
GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
- functions. Clang does not warn if the format string comes from a function
+ functions. Clang does not warn if the format string comes from a function
parameter, where the function is annotated with a compatible attribute,
- otherwise it warns. For example:
+ otherwise it warns. For example:
.. code-block:: c
@@ -2657,7 +2825,7 @@ Clang implements two kinds of checks with this attribute.
}
In this case Clang does not warn because the format string ``s`` and
- the corresponding arguments are annotated. If the arguments are
+ the corresponding arguments are annotated. If the arguments are
incorrect, the caller of ``foo`` will receive a warning.
}];
}
@@ -2697,7 +2865,14 @@ def AsmLabelDocs : Documentation {
let Content = [{
This attribute can be used on a function or variable to specify its symbol name.
-On some targets, all C symbols are prefixed by default with a single character, typically ``_``. This was done historically to distinguish them from symbols used by other languages. (This prefix is also added to the standard Itanium C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true symbol name for a C++ variable declared as ``int cppvar;`` would be ``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the symbol names specified by the ``asm`` attribute; programmers wishing to match a C symbol name must compensate for this.
+On some targets, all C symbols are prefixed by default with a single character,
+typically ``_``. This was done historically to distinguish them from symbols
+used by other languages. (This prefix is also added to the standard Itanium
+C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
+symbol name for a C++ variable declared as ``int cppvar;`` would be
+``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
+symbol names specified by the ``asm`` attribute; programmers wishing to match a
+C symbol name must compensate for this.
For example, consider the following C code:
@@ -2712,7 +2887,11 @@ For example, consider the following C code:
Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
-While it is possible to use this attribute to name a special symbol used internally by the compiler, such as an LLVM intrinsic, this is neither recommended nor supported and may cause the compiler to crash or miscompile. Users who wish to gain access to intrinsic behavior are strongly encouraged to request new builtin functions.
+While it is possible to use this attribute to name a special symbol used
+internally by the compiler, such as an LLVM intrinsic, this is neither
+recommended nor supported and may cause the compiler to crash or miscompile.
+Users who wish to gain access to intrinsic behavior are strongly encouraged to
+request new builtin functions.
}];
}
@@ -2838,7 +3017,8 @@ Attribute ``trivial_abi`` has no effect in the following cases:
- The class directly declares a virtual base or virtual methods.
- Copy constructors and move constructors of the class are all deleted.
- The class has a base class that is non-trivial for the purposes of calls.
-- The class has a non-static data member whose type is non-trivial for the purposes of calls, which includes:
+- The class has a non-static data member whose type is non-trivial for the
+ purposes of calls, which includes:
- classes that are non-trivial for the purposes of calls
- __weak-qualified types in Objective-C++
@@ -2858,7 +3038,7 @@ varies in size and alignment depending on the definition of the underlying
class.
However, this is problematic when a forward declaration is only available and
-no definition has been made yet. In such cases, Clang is forced to utilize the
+no definition has been made yet. In such cases, Clang is forced to utilize the
most general representation that is available to it.
These keywords make it possible to use a pointer-to-member representation other
@@ -2907,9 +3087,9 @@ def OptnoneDocs : Documentation {
let Content = [{
The ``optnone`` attribute suppresses essentially all optimizations
on a function or method, regardless of the optimization level applied to
-the compilation unit as a whole. This is particularly useful when you
+the compilation unit as a whole. This is particularly useful when you
need to debug a particular function, but it is infeasible to build the
-entire application without optimization. Avoiding optimization on the
+entire application without optimization. Avoiding optimization on the
specified function can improve the quality of the debugging information
for that function.
@@ -2954,7 +3134,7 @@ time:
}
Specifying the optional parameter, ``#pragma unroll _value_``, directs the
-unroller to unroll the loop ``_value_`` times. The parameter may optionally be
+unroller to unroll the loop ``_value_`` times. The parameter may optionally be
enclosed in parentheses:
.. code-block:: c++
@@ -2981,7 +3161,7 @@ Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
``#pragma clang loop unroll(full)`` and
``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
-is equivalent to ``#pragma clang loop unroll(disable)``. See
+is equivalent to ``#pragma clang loop unroll(disable)``. See
`language extensions
<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
for further details including limitations of the unroll hints.
@@ -3149,6 +3329,31 @@ scope) variables and static local variable as well.
}];
}
+def OpenCLAddressSpaceGlobalExtDocs : Documentation {
+ let Category = DocOpenCLAddressSpaces;
+ let Heading = "[[clang::opencl_global_device]], [[clang::opencl_global_host]]";
+ let Content = [{
+The ``global_device`` and ``global_host`` address space attributes specify that
+an object is allocated in global memory on the device/host. It helps to
+distinguish USM (Unified Shared Memory) pointers that access global device
+memory from those that access global host memory. These new address spaces are
+a subset of the ``__global/opencl_global`` address space, the full address space
+set model for OpenCL 2.0 with the extension looks as follows:
+
+ | generic->global->host
+ | ->device
+ | ->private
+ | ->local
+ | constant
+
+As ``global_device`` and ``global_host`` are a subset of
+``__global/opencl_global`` address spaces it is allowed to convert
+``global_device`` and ``global_host`` address spaces to
+``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
+"Address space nesting and rules for pointers").
+ }];
+}
+
def OpenCLAddressSpaceLocalDocs : Documentation {
let Category = DocOpenCLAddressSpaces;
let Heading = "__local, local, [[clang::opencl_local]]";
@@ -3226,9 +3431,25 @@ extended when converted to a 64-bit pointer.
def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
let Content = [{
-Whether a particular pointer may be "null" is an important concern when working with pointers in the C family of languages. The various nullability attributes indicate whether a particular pointer can be null or not, which makes APIs more expressive and can help static analysis tools identify bugs involving null pointers. Clang supports several kinds of nullability attributes: the ``nonnull`` and ``returns_nonnull`` attributes indicate which function or method parameters and result types can never be null, while nullability type qualifiers indicate which pointer types can be null (``_Nullable``) or cannot be null (``_Nonnull``).
-
-The nullability (type) qualifiers express whether a value of a given pointer type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning for null (the ``_Nonnull`` qualifier), or for which the purpose of null is unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers are expressed within the type system, they are more general than the ``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for example) a nullable pointer to an array of nonnull pointers. Nullability qualifiers are written to the right of the pointer to which they apply. For example:
+Whether a particular pointer may be "null" is an important concern when working
+with pointers in the C family of languages. The various nullability attributes
+indicate whether a particular pointer can be null or not, which makes APIs more
+expressive and can help static analysis tools identify bugs involving null
+pointers. Clang supports several kinds of nullability attributes: the
+``nonnull`` and ``returns_nonnull`` attributes indicate which function or
+method parameters and result types can never be null, while nullability type
+qualifiers indicate which pointer types can be null (``_Nullable``) or cannot
+be null (``_Nonnull``).
+
+The nullability (type) qualifiers express whether a value of a given pointer
+type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning
+for null (the ``_Nonnull`` qualifier), or for which the purpose of null is
+unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers
+are expressed within the type system, they are more general than the
+``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for
+example) a nullable pointer to an array of nonnull pointers. Nullability
+qualifiers are written to the right of the pointer to which they apply. For
+example:
.. code-block:: c
@@ -3243,7 +3464,9 @@ The nullability (type) qualifiers express whether a value of a given pointer typ
// A nullable pointer to non-null pointers to const characters.
const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
-In Objective-C, there is an alternate spelling for the nullability qualifiers that can be used in Objective-C methods and properties using context-sensitive, non-underscored keywords. For example:
+In Objective-C, there is an alternate spelling for the nullability qualifiers
+that can be used in Objective-C methods and properties using context-sensitive,
+non-underscored keywords. For example:
.. code-block:: objective-c
@@ -3258,20 +3481,28 @@ In Objective-C, there is an alternate spelling for the nullability qualifiers th
def TypeNonNullDocs : Documentation {
let Category = NullabilityDocs;
let Content = [{
-The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful value for a value of the ``_Nonnull`` pointer type. For example, given a declaration such as:
+The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
+value for a value of the ``_Nonnull`` pointer type. For example, given a
+declaration such as:
.. code-block:: c
int fetch(int * _Nonnull ptr);
-a caller of ``fetch`` should not provide a null value, and the compiler will produce a warning if it sees a literal null value passed to ``fetch``. Note that, unlike the declaration attribute ``nonnull``, the presence of ``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` is free to consider null undefined behavior or (perhaps for backward-compatibility reasons) defensively handle null.
+a caller of ``fetch`` should not provide a null value, and the compiler will
+produce a warning if it sees a literal null value passed to ``fetch``. Note
+that, unlike the declaration attribute ``nonnull``, the presence of
+``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
+is free to consider null undefined behavior or (perhaps for
+backward-compatibility reasons) defensively handle null.
}];
}
def TypeNullableDocs : Documentation {
let Category = NullabilityDocs;
let Content = [{
-The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
+The ``_Nullable`` nullability qualifier indicates that a value of the
+``_Nullable`` pointer type can be null. For example, given:
.. code-block:: c
@@ -3281,17 +3512,48 @@ a caller of ``fetch_or_zero`` can provide null.
}];
}
+def TypeNullableResultDocs : Documentation {
+ let Category = NullabilityDocs;
+ let Content = [{
+The ``_Nullable_result`` nullability qualifier means that a value of the
+``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
+attribute differs from ``_Nullable`` is when it's used on a parameter to a
+completion handler in a Swift async method. For instance, here:
+
+ .. code-block:: objc
+
+ -(void)fetchSomeDataWithID:(int)identifier
+ completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
+
+This method asynchronously calls ``completionHandler`` when the data is
+available, or calls it with an error. ``_Nullable_result`` indicates to the
+Swift importer that this is the uncommon case where ``result`` can get ``nil``
+even if no error has occured, and will therefore import it as a Swift optional
+type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
+importer will assume that ``result`` will always be non-nil unless an error
+occured.
+}];
+}
+
def TypeNullUnspecifiedDocs : Documentation {
let Category = NullabilityDocs;
let Content = [{
-The ``_Null_unspecified`` nullability qualifier indicates that neither the ``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer type. It is used primarily to indicate that the role of null with specific pointers in a nullability-annotated header is unclear, e.g., due to overly-complex implementations or historical factors with a long-lived API.
+The ``_Null_unspecified`` nullability qualifier indicates that neither the
+``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
+type. It is used primarily to indicate that the role of null with specific
+pointers in a nullability-annotated header is unclear, e.g., due to
+overly-complex implementations or historical factors with a long-lived API.
}];
}
def NonNullDocs : Documentation {
let Category = NullabilityDocs;
let Content = [{
-The ``nonnull`` attribute indicates that some function parameters must not be null, and can be used in several different ways. It's original usage (`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) is as a function (or Objective-C method) attribute that specifies which parameters of the function are nonnull in a comma-separated list. For example:
+The ``nonnull`` attribute indicates that some function parameters must not be
+null, and can be used in several different ways. It's original usage
+(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
+is as a function (or Objective-C method) attribute that specifies which
+parameters of the function are nonnull in a comma-separated list. For example:
.. code-block:: c
@@ -3299,34 +3561,48 @@ The ``nonnull`` attribute indicates that some function parameters must not be nu
__attribute__((nonnull (1, 2)));
Here, the ``nonnull`` attribute indicates that parameters 1 and 2
-cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
+cannot have a null value. Omitting the parenthesized list of parameter indices
+means that all parameters of pointer type cannot be null:
.. code-block:: c
extern void * my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull));
-Clang also allows the ``nonnull`` attribute to be placed directly on a function (or Objective-C method) parameter, eliminating the need to specify the parameter index ahead of type. For example:
+Clang also allows the ``nonnull`` attribute to be placed directly on a function
+(or Objective-C method) parameter, eliminating the need to specify the
+parameter index ahead of type. For example:
.. code-block:: c
extern void * my_memcpy (void *dest __attribute__((nonnull)),
const void *src __attribute__((nonnull)), size_t len);
-Note that the ``nonnull`` attribute indicates that passing null to a non-null parameter is undefined behavior, which the optimizer may take advantage of to, e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable.
+Note that the ``nonnull`` attribute indicates that passing null to a non-null
+parameter is undefined behavior, which the optimizer may take advantage of to,
+e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
+pointer cannot be null in a more general manner (because it is part of the type
+system) and does not imply undefined behavior, making it more widely applicable.
}];
}
def ReturnsNonNullDocs : Documentation {
let Category = NullabilityDocs;
let Content = [{
-The ``returns_nonnull`` attribute indicates that a particular function (or Objective-C method) always returns a non-null pointer. For example, a particular system ``malloc`` might be defined to terminate a process when memory is not available rather than returning a null pointer:
+The ``returns_nonnull`` attribute indicates that a particular function (or
+Objective-C method) always returns a non-null pointer. For example, a
+particular system ``malloc`` might be defined to terminate a process when
+memory is not available rather than returning a null pointer:
.. code-block:: c
extern void * malloc (size_t size) __attribute__((returns_nonnull));
-The ``returns_nonnull`` attribute implies that returning a null pointer is undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable
+The ``returns_nonnull`` attribute implies that returning a null pointer is
+undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
+type qualifier indicates that a pointer cannot be null in a more general manner
+(because it is part of the type system) and does not imply undefined behavior,
+making it more widely applicable
}];
}
@@ -3339,6 +3615,243 @@ arguments, with arbitrary offsets.
}];
}
+def NSErrorDomainDocs : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+In Cocoa frameworks in Objective-C, one can group related error codes in enums
+and categorize these enums with error domains.
+
+The ``ns_error_domain`` attribute indicates a global ``NSString`` or
+``CFString`` constant representing the error domain that an error code belongs
+to. For pointer uniqueness and code size this is a constant symbol, not a
+literal.
+
+The domain and error code need to be used together. The ``ns_error_domain``
+attribute links error codes to their domain at the source level.
+
+This metadata is useful for documentation purposes, for static analysis, and for
+improving interoperability between Objective-C and Swift. It is not used for
+code generation in Objective-C.
+
+For example:
+
+ .. code-block:: objc
+
+ #define NS_ERROR_ENUM(_type, _name, _domain) \
+ enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
+
+ extern NSString *const MyErrorDomain;
+ typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
+ MyErrFirst,
+ MyErrSecond,
+ };
+ }];
+}
+
+def SwiftDocs : DocumentationCategory<"Customizing Swift Import"> {
+ let Content = [{
+Clang supports additional attributes for customizing how APIs are imported into
+Swift.
+ }];
+}
+
+def SwiftAsyncNameDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_async_name";
+ let Content = [{
+The ``swift_async_name`` attribute provides the name of the ``async`` overload for
+the given declaration in Swift. If this attribute is absent, the name is
+transformed according to the algorithm built into the Swift compiler.
+
+The argument is a string literal that contains the Swift name of the function or
+method. The name may be a compound Swift name. The function or method with such
+an attribute must have more than zero parameters, as its last parameter is
+assumed to be a callback that's eliminated in the Swift ``async`` name.
+
+ .. code-block:: objc
+
+ @interface URL
+ + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
+ @end
+ }];
+}
+
+def SwiftAttrDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_attr";
+ let Content = [{
+The ``swift_attr`` provides a Swift-specific annotation for the declaration
+to which the attribute appertains to. It can be used on any declaration
+in Clang. This kind of annotation is ignored by Clang as it doesn't have any
+semantic meaning in languages supported by Clang. The Swift compiler can
+interpret these annotations according to its own rules when importing C or
+Objective-C declarations.
+}];
+}
+
+def SwiftBridgeDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_bridge";
+ let Content = [{
+The ``swift_bridge`` attribute indicates that the declaration to which the
+attribute appertains is bridged to the named Swift type.
+
+ .. code-block:: objc
+
+ __attribute__((__objc_root__))
+ @interface Base
+ - (instancetype)init;
+ @end
+
+ __attribute__((__swift_bridge__("BridgedI")))
+ @interface I : Base
+ @end
+
+In this example, the Objective-C interface ``I`` will be made available to Swift
+with the name ``BridgedI``. It would be possible for the compiler to refer to
+``I`` still in order to bridge the type back to Objective-C.
+ }];
+}
+
+def SwiftBridgedTypedefDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_bridged";
+ let Content = [{
+The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
+the attribute appertains is imported into Swift, it should refer to the bridged
+Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
+(e.g. ``NSString``).
+
+ .. code-block:: objc
+
+ @interface NSString;
+ typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
+
+ extern void acceptsAliasedString(AliasedString _Nonnull parameter);
+
+In this case, the function ``acceptsAliasedString`` will be imported into Swift
+as a function which accepts a ``String`` type parameter.
+ }];
+}
+
+def SwiftObjCMembersDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_objc_members";
+ let Content = [{
+This attribute indicates that Swift subclasses and members of Swift extensions
+of this class will be implicitly marked with the ``@objcMembers`` Swift
+attribute, exposing them back to Objective-C.
+ }];
+}
+
+def SwiftErrorDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_error";
+ let Content = [{
+The ``swift_error`` attribute controls whether a particular function (or
+Objective-C method) is imported into Swift as a throwing function, and if so,
+which dynamic convention it uses.
+
+All of these conventions except ``none`` require the function to have an error
+parameter. Currently, the error parameter is always the last parameter of type
+``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
+the imported API. When calling the API, Swift will always pass a valid address
+initialized to a null pointer.
+
+* ``swift_error(none)`` means that the function should not be imported as
+ throwing. The error parameter and result type will be imported normally.
+
+* ``swift_error(null_result)`` means that calls to the function should be
+ considered to have thrown if they return a null value. The return type must be
+ a pointer type, and it will be imported into Swift with a non-optional type.
+ This is the default error convention for Objective-C methods that return
+ pointers.
+
+* ``swift_error(zero_result)`` means that calls to the function should be
+ considered to have thrown if they return a zero result. The return type must be
+ an integral type. If the return type would have been imported as ``Bool``, it
+ is instead imported as ``Void``. This is the default error convention for
+ Objective-C methods that return a type that would be imported as ``Bool``.
+
+* ``swift_error(nonzero_result)`` means that calls to the function should be
+ considered to have thrown if they return a non-zero result. The return type must
+ be an integral type. If the return type would have been imported as ``Bool``,
+ it is instead imported as ``Void``.
+
+* ``swift_error(nonnull_error)`` means that calls to the function should be
+ considered to have thrown if they leave a non-null error in the error parameter.
+ The return type is left unmodified.
+
+ }];
+}
+
+def SwiftNameDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_name";
+ let Content = [{
+The ``swift_name`` attribute provides the name of the declaration in Swift. If
+this attribute is absent, the name is transformed according to the algorithm
+built into the Swift compiler.
+
+The argument is a string literal that contains the Swift name of the function,
+variable, or type. When renaming a function, the name may be a compound Swift
+name. For a type, enum constant, property, or variable declaration, the name
+must be a simple or qualified identifier.
+
+ .. code-block:: objc
+
+ @interface URL
+ - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
+ @end
+
+ void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
+ }
+ }];
+}
+
+def SwiftNewTypeDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_newtype";
+ let Content = [{
+The ``swift_newtype`` attribute indicates that the typedef to which the
+attribute appertains is imported as a new Swift type of the typedef's name.
+Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
+the attribute is identical with either spelling, ``swift_wrapper`` is
+deprecated, only exists for compatibility purposes, and should not be used in
+new code.
+
+* ``swift_newtype(struct)`` means that a Swift struct will be created for this
+ typedef.
+
+* ``swift_newtype(enum)`` means that a Swift enum will be created for this
+ typedef.
+
+ .. code-block:: c
+
+ // Import UIFontTextStyle as an enum type, with enumerated values being
+ // constants.
+ typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
+
+ // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
+ // values being members of the type structure.
+ typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
+
+ }];
+}
+
+def SwiftPrivateDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_private";
+ let Content = [{
+Declarations marked with the ``swift_private`` attribute are hidden from the
+framework client but are still made available for use within the framework or
+Swift SDK overlay.
+
+The purpose of this attribute is to permit a more idomatic implementation of
+declarations in Swift while hiding the non-idiomatic one.
+ }];
+}
+
def OMPDeclareSimdDocs : Documentation {
let Category = DocCatFunction;
let Heading = "#pragma omp declare simd";
@@ -3445,16 +3958,79 @@ Clang provides the following context selector extensions, used via
match_all
match_any
match_none
+ disable_implicit_base
+ allow_templates
The match extensions change when the *entire* context selector is considered a
match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
selector is allowed to be in the OpenMP context, with ``any`` a single trait in
both the selector and OpenMP context is sufficient. Only a single match
extension trait is allowed per context selector.
+The disable extensions remove default effects of the ``begin declare variant``
+applied to a definition. If ``disable_implicit_base`` is given, we will not
+introduce an implicit base function for a variant if no base function was
+found. The variant is still generated but will never be called, due to the
+absence of a base function and consequently calls to a base function.
+The allow extensions change when the ``begin declare variant`` effect is
+applied to a definition. If ``allow_templates`` is given, template function
+definitions are considered as specializations of existing or assumed template
+declarations with the same name. The template parameters for the base functions
+are used to instantiate the specialization.
}];
}
+def LeafDocs : Documentation {
+ let Category = DocCatVariable;
+ let Content = [{
+
+The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
+in library functions. Functions marked with the ``leaf`` attribute are not allowed
+to jump back into the caller's translation unit, whether through invoking a
+callback function, an external function call, use of ``longjmp``, or other means.
+Therefore, they cannot use or modify any data that does not escape the caller function's
+compilation unit.
+
+For more information see
+`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`
+}];
+}
+
+def AssumptionDocs : Documentation {
+ let Category = DocCatFunction;
+ let Heading = "assume";
+ let Content = [{
+Clang supports the ``__attribute__((assume("assumption")))`` attribute to
+provide additional information to the optimizer. The string-literal, here
+"assumption", will be attached to the function declaration such that later
+analysis and optimization passes can assume the "assumption" to hold.
+This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
+instead of an expression that can be assumed to be non-zero, the assumption is
+expressed as a string and it holds for the entire function.
+
+A function can have multiple assume attributes and they propagate from prior
+declarations to later definitions. Multiple assumptions are aggregated into a
+single comma separated string. Thus, one can provide multiple assumptions via
+a comma separated string, i.a.,
+``__attribute__((assume("assumption1,assumption2")))``.
+
+While LLVM plugins might provide more assumption strings, the default LLVM
+optimization passes are aware of the following assumptions:
+
+ .. code-block:: none
+
+ "omp_no_openmp"
+ "omp_no_openmp_routines"
+ "omp_no_parallelism"
+
+The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
+spelled "XYZ" in the `OpenMP 5.1 Standard`_).
+
+.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2
+
+}];
+}
+
def NoStackProtectorDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
@@ -3480,7 +4056,10 @@ option.
def NotTailCalledDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
-The ``not_tail_called`` attribute prevents tail-call optimization on statically bound calls. It has no effect on indirect calls. Virtual functions, objective-c methods, and functions marked as ``always_inline`` cannot be marked as ``not_tail_called``.
+The ``not_tail_called`` attribute prevents tail-call optimization on statically
+bound calls. It has no effect on indirect calls. Virtual functions, objective-c
+methods, and functions marked as ``always_inline`` cannot be marked as
+``not_tail_called``.
For example, it prevents tail-call optimization in the following case:
@@ -3501,8 +4080,8 @@ However, it doesn't prevent tail-call optimization in this case:
int foo2(int a) {
int (*fn)(int) = &foo1;
- // not_tail_called has no effect on an indirect call even if the call can be
- // resolved at compile time.
+ // not_tail_called has no effect on an indirect call even if the call can
+ // be resolved at compile time.
return (*fn)(a);
}
@@ -3546,10 +4125,12 @@ guaranteed to not throw an exception.
def InternalLinkageDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
-The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
-This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
-this attribute affects all methods and static data members of that class.
-This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
+The ``internal_linkage`` attribute changes the linkage type of the declaration
+to internal. This is similar to C-style ``static``, but can be used on classes
+and class methods. When applied to a class definition, this attribute affects
+all methods and static data members of that class. This can be used to contain
+the ABI of a C++ library by excluding unwanted class methods from the export
+tables.
}];
}
@@ -3618,7 +4199,8 @@ templates.
def DisableTailCallsDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
-The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
+The ``disable_tail_calls`` attribute instructs the backend to not perform tail
+call optimization inside the marked function.
For example:
@@ -3736,13 +4318,13 @@ The ``swiftcall`` attribute indicates that a function should be called
using the Swift calling convention for a function or function pointer.
The lowering for the Swift calling convention, as described by the Swift
-ABI documentation, occurs in multiple phases. The first, "high-level"
+ABI documentation, occurs in multiple phases. The first, "high-level"
phase breaks down the formal parameters and results into innately direct
and indirect components, adds implicit parameters for the generic
signature, and assigns the context and error ABI treatments to parameters
-where applicable. The second phase breaks down the direct parameters
+where applicable. The second phase breaks down the direct parameters
and results from the first phase and assigns them to registers or the
-stack. The ``swiftcall`` convention only handles this second phase of
+stack. The ``swiftcall`` convention only handles this second phase of
lowering; the C function type must accurately reflect the results
of the first phase, as follows:
@@ -3782,12 +4364,12 @@ of the first phase, as follows:
The parameter ABI treatment attributes are aspects of the function type.
A function type which applies an ABI treatment attribute to a
parameter is a different type from an otherwise-identical function type
-that does not. A single parameter may not have multiple ABI treatment
+that does not. A single parameter may not have multiple ABI treatment
attributes.
Support for this feature is target-dependent, although it should be
-supported on every target that Swift supports. Query for this support
-with ``__has_attribute(swiftcall)``. This implies support for the
+supported on every target that Swift supports. Query for this support
+with ``__has_attribute(swiftcall)``. This implies support for the
``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
attributes.
}];
@@ -3825,16 +4407,16 @@ This is modeled in C by pretending that the register is addressable memory:
the call; if the call returns normally, the value is copied back into the
variable.
-- The callee appears to receive the address of a variable. This address
+- The callee appears to receive the address of a variable. This address
is actually a hidden location in its own stack, initialized with the
- value of the register upon entry. When the function returns normally,
+ value of the register upon entry. When the function returns normally,
the value in that hidden location is written back to the register.
A ``swift_error_result`` parameter must be the last parameter, and it must be
preceded by a ``swift_context`` parameter.
A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
-type T. Note that no qualifiers are permitted on the intermediate level.
+type T. Note that no qualifiers are permitted on the intermediate level.
It is undefined behavior if the caller does not pass a pointer or
reference to a valid object.
@@ -3853,8 +4435,8 @@ function as having the special indirect-result ABI treatment.
This treatment gives the parameter the target's normal indirect-result
ABI treatment, which may involve passing it differently from an ordinary
-parameter. However, only the first indirect result will receive this
-treatment. Furthermore, low-level lowering may decide that a direct result
+parameter. However, only the first indirect result will receive this
+treatment. Furthermore, low-level lowering may decide that a direct result
must be returned indirectly; if so, this will take priority over the
``swift_indirect_result`` parameters.
@@ -3862,7 +4444,7 @@ A ``swift_indirect_result`` parameter must either be the first parameter or
follow another ``swift_indirect_result`` parameter.
A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
-some object type ``T``. If ``T`` is a complete type at the point of
+some object type ``T``. If ``T`` is a complete type at the point of
definition of a function, it is undefined behavior if the argument
value does not point to storage of adequate size and alignment for a
value of type ``T``.
@@ -3873,6 +4455,37 @@ optimizations like C++'s named return value optimization (NRVO).
}];
}
+def SwiftAsyncDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_async";
+ let Content = [{
+The ``swift_async`` attribute specifies if and how a particular function or
+Objective-C method is imported into a swift async method. For instance:
+
+.. code-block:: objc
+
+ @interface MyClass : NSObject
+ -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
+ __attribute__((swift_async(none)));
+
+ -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
+ __attribute__((swift_async(swift_private, 1)));
+ @end
+
+Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
+``async`` (because it's last parameter's selector piece is
+``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
+Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
+``async`` if not for the ``swift_async`` attribute because it doesn't match the
+naming convention.
+
+When using ``swift_async`` to enable importing, the first argument to the
+attribute is either ``swift_private`` or ``not_swift_private`` to indicate
+whether the function/method is private to the current framework, and the second
+argument is the index of the completion handler parameter.
+ }];
+}
+
def SuppressDocs : Documentation {
let Category = DocCatStmt;
let Content = [{
@@ -3913,6 +4526,30 @@ the old mangled name and the new code will use the new mangled name with tags.
}];
}
+def PreferredNameDocs : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+The ``preferred_name`` attribute can be applied to a class template, and
+specifies a preferred way of naming a specialization of the template. The
+preferred name will be used whenever the corresponding template specialization
+would otherwise be printed in a diagnostic or similar context.
+
+The preferred name must be a typedef or type alias declaration that refers to a
+specialization of the class template (not including any type qualifiers). In
+general this requires the template to be declared at least twice. For example:
+
+.. code-block:: c++
+
+ template<typename T> struct basic_string;
+ using string = basic_string<char>;
+ using wstring = basic_string<wchar_t>;
+ template<typename T> struct [[clang::preferred_name(string),
+ clang::preferred_name(wstring)]] basic_string {
+ // ...
+ };
+ }];
+}
+
def PreserveMostDocs : Documentation {
let Category = DocCatCallingConvs;
let Content = [{
@@ -4004,13 +4641,23 @@ string argument which is the message to display when emitting the warning.
def IFuncDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
-``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
+``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
+declaration should be resolved at runtime by calling a resolver function.
-The symbol name of the resolver function is given in quotes. A function with this name (after mangling) must be defined in the current translation unit; it may be ``static``. The resolver function should return a pointer.
+The symbol name of the resolver function is given in quotes. A function with
+this name (after mangling) must be defined in the current translation unit; it
+may be ``static``. The resolver function should return a pointer.
-The ``ifunc`` attribute may only be used on a function declaration. A function declaration with an ``ifunc`` attribute is considered to be a definition of the declared entity. The entity must not have weak linkage; for example, in C++, it cannot be applied to a declaration if a definition at that location would be considered inline.
+The ``ifunc`` attribute may only be used on a function declaration. A function
+declaration with an ``ifunc`` attribute is considered to be a definition of the
+declared entity. The entity must not have weak linkage; for example, in C++,
+it cannot be applied to a declaration if a definition at that location would be
+considered inline.
-Not all targets support this attribute. ELF target support depends on both the linker and runtime linker, and is available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. Non-ELF targets currently do not support this attribute.
+Not all targets support this attribute. ELF target support depends on both the
+linker and runtime linker, and is available in at least lld 4.0 and later,
+binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later.
+Non-ELF targets currently do not support this attribute.
}];
}
@@ -4028,7 +4675,7 @@ def RenderScriptKernelAttributeDocs : Documentation {
RenderScript.
In RenderScript, ``kernel`` functions are used to express data-parallel
-computations. The RenderScript runtime efficiently parallelizes ``kernel``
+computations. The RenderScript runtime efficiently parallelizes ``kernel``
functions to run on computational resources such as multi-core CPUs and GPUs.
See the RenderScript_ documentation for more information.
@@ -4040,13 +4687,23 @@ def XRayDocs : Documentation {
let Category = DocCatFunction;
let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args";
let Content = [{
-``__attribute__((xray_always_instrument))`` or ``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), methods (in Objective C), and free functions (in C, C++, and Objective C) to be instrumented with XRay. This will cause the function to always have space at the beginning and exit points to allow for runtime patching.
+``__attribute__((xray_always_instrument))`` or
+``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
+methods (in Objective C), and free functions (in C, C++, and Objective C) to be
+instrumented with XRay. This will cause the function to always have space at
+the beginning and exit points to allow for runtime patching.
-Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
+Conversely, ``__attribute__((xray_never_instrument))`` or
+``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
+instrumentation points.
-If a function has neither of these attributes, they become subject to the XRay heuristics used to determine whether a function should be instrumented or otherwise.
+If a function has neither of these attributes, they become subject to the XRay
+heuristics used to determine whether a function should be instrumented or
+otherwise.
-``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is used to preserve N function arguments for the logging function. Currently, only N==1 is supported.
+``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
+used to preserve N function arguments for the logging function. Currently,
+only N==1 is supported.
}];
}
@@ -4104,8 +4761,8 @@ def ObjCDirectDocs : Documentation {
let Category = DocCatDecl;
let Content = [{
The ``objc_direct`` attribute can be used to mark an Objective-C method as
-being *direct*. A direct method is treated statically like an ordinary method,
-but dynamically it behaves more like a C function. This lowers some of the costs
+being *direct*. A direct method is treated statically like an ordinary method,
+but dynamically it behaves more like a C function. This lowers some of the costs
associated with the method but also sacrifices some of the ordinary capabilities
of Objective-C methods.
@@ -4152,7 +4809,7 @@ It is an error to do any of the following:
If any of these rules would be violated if every method defined in an
``@implementation`` within a single linkage unit were declared in an
appropriate class interface, the program is ill-formed with no diagnostic
-required. If a violation of this rule is not diagnosed, behavior remains
+required. If a violation of this rule is not diagnosed, behavior remains
well-defined; this paragraph is simply reserving the right to diagnose such
conflicts in the future, not to treat them as undefined behavior.
@@ -4164,11 +4821,11 @@ For the purpose of these rules, a "class interface" includes a class's primary
and all the class interfaces of its superclasses.
An Objective-C property can be declared with the ``direct`` property
-attribute. If a direct property declaration causes an implicit declaration of
+attribute. If a direct property declaration causes an implicit declaration of
a getter or setter method (that is, if the given method is not explicitly
declared elsewhere), the method is declared to be direct.
-Some programmers may wish to make many methods direct at once. In order
+Some programmers may wish to make many methods direct at once. In order
to simplify this, the ``objc_direct_members`` attribute is provided; see its
documentation for more information.
}];
@@ -4179,12 +4836,12 @@ def ObjCDirectMembersDocs : Documentation {
let Content = [{
The ``objc_direct_members`` attribute can be placed on an Objective-C
``@interface`` or ``@implementation`` to mark that methods declared
-therein should be considered direct by default. See the documentation
+therein should be considered direct by default. See the documentation
for ``objc_direct`` for more information about direct methods.
When ``objc_direct_members`` is placed on an ``@interface`` block, every
-method in the block is considered to be declared as direct. This includes any
-implicit method declarations introduced by property declarations. If the method
+method in the block is considered to be declared as direct. This includes any
+implicit method declarations introduced by property declarations. If the method
redeclares a non-direct method, the declaration is ill-formed, exactly as if the
method was annotated with the ``objc_direct`` attribute.
@@ -4196,6 +4853,22 @@ properties, including auto-synthesized properties.
}];
}
+def ObjCNonRuntimeProtocolDocs : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+The ``objc_non_runtime_protocol`` attribute can be used to mark that an
+Objective-C protocol is only used during static type-checking and doesn't need
+to be represented dynamically. This avoids several small code-size and run-time
+overheads associated with handling the protocol's metadata. A non-runtime
+protocol cannot be used as the operand of a ``@protocol`` expression, and
+dynamic attempts to find it with ``objc_getProtocol`` will fail.
+
+If a non-runtime protocol inherits from any ordinary protocols, classes and
+derived protocols that declare conformance to the non-runtime protocol will
+dynamically list their conformance to those bare protocols.
+ }];
+}
+
def SelectAnyDocs : Documentation {
let Category = DocCatDecl;
let Content = [{
@@ -4311,8 +4984,8 @@ accessed. The following are examples of valid expressions where may not be diagn
p = &s->a;
p = &(*s).a;
-``noderef`` is currently only supported for pointers and arrays and not usable for
-references or Objective-C object pointers.
+``noderef`` is currently only supported for pointers and arrays and not usable
+for references or Objective-C object pointers.
.. code-block: c++
@@ -4489,6 +5162,59 @@ in the future.
}];
}
+def CalledOnceDocs : Documentation {
+ let Category = DocCatVariable;
+ let Content = [{
+The ``called_once`` attribute specifies that the annotated function or method
+parameter is invoked exactly once on all execution paths. It only applies
+to parameters with function-like types, i.e. function pointers or blocks. This
+concept is particularly useful for asynchronous programs.
+
+Clang implements a check for ``called_once`` parameters,
+``-Wcalled-once-parameter``. It is on by default and finds the following
+violations:
+
+* Parameter is not called at all.
+
+* Parameter is called more than once.
+
+* Parameter is not called on one of the execution paths.
+
+In the latter case, Clang pinpoints the path where parameter is not invoked
+by showing the control-flow statement where the path diverges.
+
+.. code-block:: objc
+
+ void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
+ if (somePredicate()) {
+ ...
+ callback();
+ } esle {
+ callback(); // OK: callback is called on every path
+ }
+ }
+
+ void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
+ if (somePredicate()) {
+ ...
+ callback(); // note: previous call is here
+ }
+ callback(); // warning: callback is called twice
+ }
+
+ void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
+ if (somePredicate()) { // warning: callback is not called when condition is false
+ ...
+ callback();
+ }
+ }
+
+This attribute is useful for API developers who want to double-check if they
+implemented their method correctly.
+
+ }];
+}
+
def GnuInlineDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
@@ -4693,6 +5419,17 @@ unbind runtime APIs.
}];
}
+def HIPManagedAttrDocs : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
+A managed variable is emitted as an undefined global symbol in the device binary and is
+registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
+managed memory and uses it to define the symbol when loading the device binary.
+A managed variable can be accessed in both device and host code.
+ }];
+}
+
def LifetimeOwnerDocs : Documentation {
let Category = DocCatDecl;
let Content = [{
@@ -4881,6 +5618,39 @@ close the handle. It is also assumed to require an open handle to work with.
}];
}
+def ArmSveVectorBitsDocs : Documentation {
+ let Category = DocCatType;
+ let Content = [{
+The ``arm_sve_vector_bits(N)`` attribute is defined by the Arm C Language
+Extensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants of
+sizeless types (VLAT).
+
+For example:
+
+.. code-block:: c
+
+ #include <arm_sve.h>
+
+ #if __ARM_FEATURE_SVE_BITS==512
+ typedef svint32_t fixed_svint32_t __attribute__((arm_sve_vector_bits(512)));
+ #endif
+
+Creates a type ``fixed_svint32_t`` that is a fixed-length variant of
+``svint32_t`` that contains exactly 512-bits. Unlike ``svint32_t``, this type
+can be used in globals, structs, unions, and arrays, all of which are
+unsupported for sizeless types.
+
+The attribute can be attached to a single SVE vector (such as ``svint32_t``) or
+to the SVE predicate type ``svbool_t``, this excludes tuple types such as
+``svint32x4_t``. The behavior of the attribute is undefined unless
+``N==__ARM_FEATURE_SVE_BITS``, the implementation defined feature macro that is
+enabled under the ``-msve-vector-bits`` flag.
+
+For more information See `Arm C Language Extensions for SVE
+<https://developer.arm.com/documentation/100987/latest>`_ for more information.
+}];
+}
+
def ArmMveStrictPolymorphismDocs : Documentation {
let Category = DocCatType;
let Content = [{
@@ -4926,7 +5696,7 @@ other than overloading.
def ArmCmseNSCallDocs : Documentation {
let Category = DocCatType;
let Content = [{
-This attribute declares a non-secure function type. When compiling for secure
+This attribute declares a non-secure function type. When compiling for secure
state, a call to such a function would switch from secure to non-secure state.
All non-secure function calls must happen only through a function pointer, and
a non-secure function type should only be used as a base type of a pointer.
@@ -4947,3 +5717,47 @@ Requirements on Development Tools - Engineering Specification Documentation
<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.
}];
}
+
+def AlwaysInlineDocs : Documentation {
+ let Category = DocCatFunction;
+ let Content = [{
+Inlining heuristics are disabled and inlining is always attempted regardless of
+optimization level.
+
+Does not guarantee that inline substitution actually occurs.
+
+See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
+Attribute docs`_, and `the GCC Inline docs`_.
+
+.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
+.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
+.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
+
+}];
+ let Heading = "always_inline, __force_inline";
+}
+
+def EnforceTCBDocs : Documentation {
+ let Category = DocCatFunction;
+ let Content = [{
+ The ``enforce_tcb`` attribute can be placed on functions to enforce that a
+ trusted compute base (TCB) does not call out of the TCB. This generates a
+ warning every time a function not marked with an ``enforce_tcb`` attribute is
+ called from a function with the ``enforce_tcb`` attribute. A function may be a
+ part of multiple TCBs. Invocations through function pointers are currently
+ not checked. Builtins are considered to a part of every TCB.
+
+ - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``
+ }];
+}
+
+def EnforceTCBLeafDocs : Documentation {
+ let Category = DocCatFunction;
+ let Content = [{
+ The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
+ ``enforce_tcb`` for the marked function to be in the named TCB but does not
+ continue to check the functions called from within the leaf function.
+
+ - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``
+ }];
+}
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Builtins.def b/contrib/llvm-project/clang/include/clang/Basic/Builtins.def
index 5463b7dfc18c..ab1b5866c8a7 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Builtins.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/Builtins.def
@@ -115,6 +115,7 @@
BUILTIN(__builtin_atan2 , "ddd" , "Fne")
BUILTIN(__builtin_atan2f, "fff" , "Fne")
BUILTIN(__builtin_atan2l, "LdLdLd", "Fne")
+BUILTIN(__builtin_atan2f128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_abs , "ii" , "ncF")
BUILTIN(__builtin_copysign, "ddd", "ncF")
BUILTIN(__builtin_copysignf, "fff", "ncF")
@@ -130,9 +131,11 @@ BUILTIN(__builtin_fmod , "ddd" , "Fne")
BUILTIN(__builtin_fmodf, "fff" , "Fne")
BUILTIN(__builtin_fmodf16, "hhh" , "Fne")
BUILTIN(__builtin_fmodl, "LdLdLd", "Fne")
+BUILTIN(__builtin_fmodf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_frexp , "ddi*" , "Fn")
BUILTIN(__builtin_frexpf, "ffi*" , "Fn")
BUILTIN(__builtin_frexpl, "LdLdi*", "Fn")
+BUILTIN(__builtin_frexpf128, "LLdLLdi*", "Fn")
BUILTIN(__builtin_huge_val, "d", "nc")
BUILTIN(__builtin_huge_valf, "f", "nc")
BUILTIN(__builtin_huge_vall, "Ld", "nc")
@@ -146,9 +149,11 @@ BUILTIN(__builtin_llabs, "LLiLLi", "Fnc")
BUILTIN(__builtin_ldexp , "ddi" , "Fne")
BUILTIN(__builtin_ldexpf, "ffi" , "Fne")
BUILTIN(__builtin_ldexpl, "LdLdi", "Fne")
+BUILTIN(__builtin_ldexpf128, "LLdLLdi", "Fne")
BUILTIN(__builtin_modf , "ddd*" , "Fn")
BUILTIN(__builtin_modff, "fff*" , "Fn")
BUILTIN(__builtin_modfl, "LdLdLd*", "Fn")
+BUILTIN(__builtin_modff128, "LLdLLdLLd*", "Fn")
BUILTIN(__builtin_nan, "dcC*" , "FnU")
BUILTIN(__builtin_nanf, "fcC*" , "FnU")
BUILTIN(__builtin_nanl, "LdcC*", "FnU")
@@ -164,167 +169,216 @@ BUILTIN(__builtin_pow , "ddd" , "Fne")
BUILTIN(__builtin_powf, "fff" , "Fne")
BUILTIN(__builtin_powf16, "hhh" , "Fne")
BUILTIN(__builtin_powl, "LdLdLd", "Fne")
+BUILTIN(__builtin_powf128, "LLdLLdLLd", "Fne")
// Standard unary libc/libm functions with double/float/long double variants:
BUILTIN(__builtin_acos , "dd" , "Fne")
BUILTIN(__builtin_acosf, "ff" , "Fne")
BUILTIN(__builtin_acosl, "LdLd", "Fne")
+BUILTIN(__builtin_acosf128, "LLdLLd", "Fne")
BUILTIN(__builtin_acosh , "dd" , "Fne")
BUILTIN(__builtin_acoshf, "ff" , "Fne")
BUILTIN(__builtin_acoshl, "LdLd", "Fne")
+BUILTIN(__builtin_acoshf128, "LLdLLd", "Fne")
BUILTIN(__builtin_asin , "dd" , "Fne")
BUILTIN(__builtin_asinf, "ff" , "Fne")
BUILTIN(__builtin_asinl, "LdLd", "Fne")
+BUILTIN(__builtin_asinf128, "LLdLLd", "Fne")
BUILTIN(__builtin_asinh , "dd" , "Fne")
BUILTIN(__builtin_asinhf, "ff" , "Fne")
BUILTIN(__builtin_asinhl, "LdLd", "Fne")
+BUILTIN(__builtin_asinhf128, "LLdLLd", "Fne")
BUILTIN(__builtin_atan , "dd" , "Fne")
BUILTIN(__builtin_atanf, "ff" , "Fne")
BUILTIN(__builtin_atanl, "LdLd", "Fne")
+BUILTIN(__builtin_atanf128, "LLdLLd", "Fne")
BUILTIN(__builtin_atanh , "dd", "Fne")
BUILTIN(__builtin_atanhf, "ff", "Fne")
BUILTIN(__builtin_atanhl, "LdLd", "Fne")
+BUILTIN(__builtin_atanhf128, "LLdLLd", "Fne")
BUILTIN(__builtin_cbrt , "dd", "Fnc")
BUILTIN(__builtin_cbrtf, "ff", "Fnc")
BUILTIN(__builtin_cbrtl, "LdLd", "Fnc")
+BUILTIN(__builtin_cbrtf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_ceil , "dd" , "Fnc")
BUILTIN(__builtin_ceilf, "ff" , "Fnc")
BUILTIN(__builtin_ceilf16, "hh" , "Fnc")
BUILTIN(__builtin_ceill, "LdLd", "Fnc")
+BUILTIN(__builtin_ceilf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_cos , "dd" , "Fne")
BUILTIN(__builtin_cosf, "ff" , "Fne")
BUILTIN(__builtin_cosf16, "hh" , "Fne")
BUILTIN(__builtin_cosh , "dd" , "Fne")
BUILTIN(__builtin_coshf, "ff" , "Fne")
BUILTIN(__builtin_coshl, "LdLd", "Fne")
+BUILTIN(__builtin_coshf128, "LLdLLd", "Fne")
BUILTIN(__builtin_cosl, "LdLd", "Fne")
+BUILTIN(__builtin_cosf128, "LLdLLd" , "Fne")
BUILTIN(__builtin_erf , "dd", "Fne")
BUILTIN(__builtin_erff, "ff", "Fne")
BUILTIN(__builtin_erfl, "LdLd", "Fne")
+BUILTIN(__builtin_erff128, "LLdLLd", "Fne")
BUILTIN(__builtin_erfc , "dd", "Fne")
BUILTIN(__builtin_erfcf, "ff", "Fne")
BUILTIN(__builtin_erfcl, "LdLd", "Fne")
+BUILTIN(__builtin_erfcf128, "LLdLLd", "Fne")
BUILTIN(__builtin_exp , "dd" , "Fne")
BUILTIN(__builtin_expf, "ff" , "Fne")
BUILTIN(__builtin_expf16, "hh" , "Fne")
BUILTIN(__builtin_expl, "LdLd", "Fne")
+BUILTIN(__builtin_expf128, "LLdLLd", "Fne")
BUILTIN(__builtin_exp2 , "dd" , "Fne")
BUILTIN(__builtin_exp2f, "ff" , "Fne")
BUILTIN(__builtin_exp2f16, "hh" , "Fne")
BUILTIN(__builtin_exp2l, "LdLd", "Fne")
+BUILTIN(__builtin_exp2f128, "LLdLLd" , "Fne")
BUILTIN(__builtin_expm1 , "dd", "Fne")
BUILTIN(__builtin_expm1f, "ff", "Fne")
BUILTIN(__builtin_expm1l, "LdLd", "Fne")
+BUILTIN(__builtin_expm1f128, "LLdLLd", "Fne")
BUILTIN(__builtin_fdim, "ddd", "Fne")
BUILTIN(__builtin_fdimf, "fff", "Fne")
BUILTIN(__builtin_fdiml, "LdLdLd", "Fne")
+BUILTIN(__builtin_fdimf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_floor , "dd" , "Fnc")
BUILTIN(__builtin_floorf, "ff" , "Fnc")
BUILTIN(__builtin_floorf16, "hh" , "Fnc")
BUILTIN(__builtin_floorl, "LdLd", "Fnc")
+BUILTIN(__builtin_floorf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_fma, "dddd", "Fne")
BUILTIN(__builtin_fmaf, "ffff", "Fne")
BUILTIN(__builtin_fmaf16, "hhhh", "Fne")
BUILTIN(__builtin_fmal, "LdLdLdLd", "Fne")
+BUILTIN(__builtin_fmaf128, "LLdLLdLLdLLd", "Fne")
BUILTIN(__builtin_fmax, "ddd", "Fnc")
BUILTIN(__builtin_fmaxf, "fff", "Fnc")
BUILTIN(__builtin_fmaxf16, "hhh", "Fnc")
BUILTIN(__builtin_fmaxl, "LdLdLd", "Fnc")
+BUILTIN(__builtin_fmaxf128, "LLdLLdLLd", "Fnc")
BUILTIN(__builtin_fmin, "ddd", "Fnc")
BUILTIN(__builtin_fminf, "fff", "Fnc")
BUILTIN(__builtin_fminf16, "hhh", "Fnc")
BUILTIN(__builtin_fminl, "LdLdLd", "Fnc")
+BUILTIN(__builtin_fminf128, "LLdLLdLLd", "Fnc")
BUILTIN(__builtin_hypot , "ddd" , "Fne")
BUILTIN(__builtin_hypotf, "fff" , "Fne")
BUILTIN(__builtin_hypotl, "LdLdLd", "Fne")
+BUILTIN(__builtin_hypotf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_ilogb , "id", "Fne")
BUILTIN(__builtin_ilogbf, "if", "Fne")
BUILTIN(__builtin_ilogbl, "iLd", "Fne")
+BUILTIN(__builtin_ilogbf128, "iLLd", "Fne")
BUILTIN(__builtin_lgamma , "dd", "Fn")
BUILTIN(__builtin_lgammaf, "ff", "Fn")
BUILTIN(__builtin_lgammal, "LdLd", "Fn")
+BUILTIN(__builtin_lgammaf128, "LLdLLd", "Fn")
BUILTIN(__builtin_llrint, "LLid", "Fne")
BUILTIN(__builtin_llrintf, "LLif", "Fne")
BUILTIN(__builtin_llrintl, "LLiLd", "Fne")
+BUILTIN(__builtin_llrintf128, "LLiLLd", "Fne")
BUILTIN(__builtin_llround , "LLid", "Fne")
BUILTIN(__builtin_llroundf, "LLif", "Fne")
BUILTIN(__builtin_llroundl, "LLiLd", "Fne")
+BUILTIN(__builtin_llroundf128, "LLiLLd", "Fne")
BUILTIN(__builtin_log , "dd" , "Fne")
BUILTIN(__builtin_log10 , "dd" , "Fne")
BUILTIN(__builtin_log10f, "ff" , "Fne")
BUILTIN(__builtin_log10f16, "hh" , "Fne")
BUILTIN(__builtin_log10l, "LdLd", "Fne")
+BUILTIN(__builtin_log10f128, "LLdLLd" , "Fne")
BUILTIN(__builtin_log1p , "dd" , "Fne")
BUILTIN(__builtin_log1pf, "ff" , "Fne")
BUILTIN(__builtin_log1pl, "LdLd", "Fne")
+BUILTIN(__builtin_log1pf128, "LLdLLd", "Fne")
BUILTIN(__builtin_log2, "dd" , "Fne")
BUILTIN(__builtin_log2f, "ff" , "Fne")
BUILTIN(__builtin_log2f16, "hh" , "Fne")
BUILTIN(__builtin_log2l, "LdLd" , "Fne")
+BUILTIN(__builtin_log2f128, "LLdLLd" , "Fne")
BUILTIN(__builtin_logb , "dd", "Fne")
BUILTIN(__builtin_logbf, "ff", "Fne")
BUILTIN(__builtin_logbl, "LdLd", "Fne")
+BUILTIN(__builtin_logbf128, "LLdLLd", "Fne")
BUILTIN(__builtin_logf, "ff" , "Fne")
BUILTIN(__builtin_logf16, "hh" , "Fne")
BUILTIN(__builtin_logl, "LdLd", "Fne")
+BUILTIN(__builtin_logf128, "LLdLLd", "Fne")
BUILTIN(__builtin_lrint , "Lid", "Fne")
BUILTIN(__builtin_lrintf, "Lif", "Fne")
BUILTIN(__builtin_lrintl, "LiLd", "Fne")
+BUILTIN(__builtin_lrintf128, "LiLLd", "Fne")
BUILTIN(__builtin_lround , "Lid", "Fne")
BUILTIN(__builtin_lroundf, "Lif", "Fne")
BUILTIN(__builtin_lroundl, "LiLd", "Fne")
+BUILTIN(__builtin_lroundf128, "LiLLd", "Fne")
BUILTIN(__builtin_nearbyint , "dd", "Fnc")
BUILTIN(__builtin_nearbyintf, "ff", "Fnc")
BUILTIN(__builtin_nearbyintl, "LdLd", "Fnc")
+BUILTIN(__builtin_nearbyintf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_nextafter , "ddd", "Fne")
BUILTIN(__builtin_nextafterf, "fff", "Fne")
BUILTIN(__builtin_nextafterl, "LdLdLd", "Fne")
+BUILTIN(__builtin_nextafterf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_nexttoward , "ddLd", "Fne")
BUILTIN(__builtin_nexttowardf, "ffLd", "Fne")
BUILTIN(__builtin_nexttowardl, "LdLdLd", "Fne")
+BUILTIN(__builtin_nexttowardf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_remainder , "ddd", "Fne")
BUILTIN(__builtin_remainderf, "fff", "Fne")
BUILTIN(__builtin_remainderl, "LdLdLd", "Fne")
+BUILTIN(__builtin_remainderf128, "LLdLLdLLd", "Fne")
BUILTIN(__builtin_remquo , "dddi*", "Fn")
BUILTIN(__builtin_remquof, "fffi*", "Fn")
BUILTIN(__builtin_remquol, "LdLdLdi*", "Fn")
+BUILTIN(__builtin_remquof128, "LLdLLdLLdi*", "Fn")
BUILTIN(__builtin_rint , "dd", "Fnc")
BUILTIN(__builtin_rintf, "ff", "Fnc")
BUILTIN(__builtin_rintf16, "hh", "Fnc")
BUILTIN(__builtin_rintl, "LdLd", "Fnc")
+BUILTIN(__builtin_rintf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_round, "dd" , "Fnc")
BUILTIN(__builtin_roundf, "ff" , "Fnc")
BUILTIN(__builtin_roundf16, "hh" , "Fnc")
BUILTIN(__builtin_roundl, "LdLd" , "Fnc")
+BUILTIN(__builtin_roundf128, "LLdLLd" , "Fnc")
BUILTIN(__builtin_scalbln , "ddLi", "Fne")
BUILTIN(__builtin_scalblnf, "ffLi", "Fne")
BUILTIN(__builtin_scalblnl, "LdLdLi", "Fne")
+BUILTIN(__builtin_scalblnf128, "LLdLLdLi", "Fne")
BUILTIN(__builtin_scalbn , "ddi", "Fne")
BUILTIN(__builtin_scalbnf, "ffi", "Fne")
BUILTIN(__builtin_scalbnl, "LdLdi", "Fne")
+BUILTIN(__builtin_scalbnf128, "LLdLLdi", "Fne")
BUILTIN(__builtin_sin , "dd" , "Fne")
BUILTIN(__builtin_sinf, "ff" , "Fne")
BUILTIN(__builtin_sinf16, "hh" , "Fne")
BUILTIN(__builtin_sinh , "dd" , "Fne")
BUILTIN(__builtin_sinhf, "ff" , "Fne")
BUILTIN(__builtin_sinhl, "LdLd", "Fne")
+BUILTIN(__builtin_sinhf128, "LLdLLd", "Fne")
BUILTIN(__builtin_sinl, "LdLd", "Fne")
+BUILTIN(__builtin_sinf128, "LLdLLd" , "Fne")
BUILTIN(__builtin_sqrt , "dd" , "Fne")
BUILTIN(__builtin_sqrtf, "ff" , "Fne")
BUILTIN(__builtin_sqrtf16, "hh" , "Fne")
BUILTIN(__builtin_sqrtl, "LdLd", "Fne")
+BUILTIN(__builtin_sqrtf128, "LLdLLd", "Fne")
BUILTIN(__builtin_tan , "dd" , "Fne")
BUILTIN(__builtin_tanf, "ff" , "Fne")
BUILTIN(__builtin_tanh , "dd" , "Fne")
BUILTIN(__builtin_tanhf, "ff" , "Fne")
BUILTIN(__builtin_tanhl, "LdLd", "Fne")
+BUILTIN(__builtin_tanhf128, "LLdLLd", "Fne")
BUILTIN(__builtin_tanl, "LdLd", "Fne")
+BUILTIN(__builtin_tanf128, "LLdLLd" , "Fne")
BUILTIN(__builtin_tgamma , "dd", "Fne")
BUILTIN(__builtin_tgammaf, "ff", "Fne")
BUILTIN(__builtin_tgammal, "LdLd", "Fne")
+BUILTIN(__builtin_tgammaf128, "LLdLLd", "Fne")
BUILTIN(__builtin_trunc , "dd", "Fnc")
BUILTIN(__builtin_truncf, "ff", "Fnc")
BUILTIN(__builtin_truncl, "LdLd", "Fnc")
+BUILTIN(__builtin_truncf128, "LLdLLd", "Fnc")
BUILTIN(__builtin_truncf16, "hh", "Fnc")
// Access to floating point environment
@@ -398,6 +452,9 @@ BUILTIN(__builtin_ctanh, "XdXd", "Fne")
BUILTIN(__builtin_ctanhf, "XfXf", "Fne")
BUILTIN(__builtin_ctanhl, "XLdXLd", "Fne")
+// GCC-compatible C99 CMPLX implementation.
+BUILTIN(__builtin_complex, "v.", "nct")
+
// FP Comparisons.
BUILTIN(__builtin_isgreater , "i.", "Fnct")
BUILTIN(__builtin_isgreaterequal, "i.", "Fnct")
@@ -910,6 +967,7 @@ LIBBUILTIN(exit, "vi", "fr", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(_Exit, "vi", "fr", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(malloc, "v*z", "f", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(realloc, "v*v*z", "f", "stdlib.h", ALL_LANGUAGES)
+LIBBUILTIN(free, "vv*", "f", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(strtod, "dcC*c**", "f", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(strtof, "fcC*c**", "f", "stdlib.h", ALL_LANGUAGES)
LIBBUILTIN(strtold, "LdcC*c**", "f", "stdlib.h", ALL_LANGUAGES)
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def
index f07c567053de..b35510f8b691 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def
@@ -99,6 +99,12 @@ BUILTIN(__builtin_arm_tcommit, "v", "n")
BUILTIN(__builtin_arm_tcancel, "vWUIi", "n")
BUILTIN(__builtin_arm_ttest, "WUi", "nc")
+// Armv8.7-A load/store 64-byte intrinsics
+BUILTIN(__builtin_arm_ld64b, "vvC*WUi*", "n")
+BUILTIN(__builtin_arm_st64b, "vv*WUiC*", "n")
+BUILTIN(__builtin_arm_st64bv, "WUiv*WUiC*", "n")
+BUILTIN(__builtin_arm_st64bv0, "WUiv*WUiC*", "n")
+
TARGET_HEADER_BUILTIN(_BitScanForward, "UcUNi*UNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_BitScanReverse, "UcUNi*UNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_BitScanForward64, "UcUNi*ULLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
@@ -153,6 +159,11 @@ TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_acq, "LLiLLiD*LLiLLi", "nh",
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_nf, "LLiLLiD*LLiLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_rel, "LLiLLiD*LLiLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128, "UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_acq,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_nf ,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_rel,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
+
TARGET_HEADER_BUILTIN(_InterlockedOr8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def
index 042a86368559..123a7ad212da 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -37,6 +37,10 @@ BUILTIN(__builtin_amdgcn_workgroup_size_x, "Us", "nc")
BUILTIN(__builtin_amdgcn_workgroup_size_y, "Us", "nc")
BUILTIN(__builtin_amdgcn_workgroup_size_z, "Us", "nc")
+BUILTIN(__builtin_amdgcn_grid_size_x, "Ui", "nc")
+BUILTIN(__builtin_amdgcn_grid_size_y, "Ui", "nc")
+BUILTIN(__builtin_amdgcn_grid_size_z, "Ui", "nc")
+
BUILTIN(__builtin_amdgcn_mbcnt_hi, "UiUiUi", "nc")
BUILTIN(__builtin_amdgcn_mbcnt_lo, "UiUiUi", "nc")
@@ -210,6 +214,8 @@ BUILTIN(__builtin_amdgcn_read_exec, "LUi", "nc")
BUILTIN(__builtin_amdgcn_read_exec_lo, "Ui", "nc")
BUILTIN(__builtin_amdgcn_read_exec_hi, "Ui", "nc")
+BUILTIN(__builtin_amdgcn_endpgm, "v", "nr")
+
//===----------------------------------------------------------------------===//
// R600-NI only builtins.
//===----------------------------------------------------------------------===//
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def
index 237e9dc8784b..190062645ec4 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def
@@ -21,7 +21,13 @@
TARGET_BUILTIN(__builtin_preserve_field_info, "Ui.", "t", "")
// Get BTF type id.
-TARGET_BUILTIN(__builtin_btf_type_id, "Ui.", "t", "")
+TARGET_BUILTIN(__builtin_btf_type_id, "LUi.", "t", "")
+
+// Get type information.
+TARGET_BUILTIN(__builtin_preserve_type_info, "Ui.", "t", "")
+
+// Preserve enum value.
+TARGET_BUILTIN(__builtin_preserve_enum_value, "Li.", "t", "")
#undef BUILTIN
#undef TARGET_BUILTIN
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def
index 759c91290a60..d149fa0127b9 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -43,7 +43,7 @@
#define PTX60 "ptx60|" PTX61
#pragma push_macro("AND")
-#define AND(a, b) a "," b
+#define AND(a, b) "(" a "),(" b ")"
// Special Registers
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def
index 6b291e6b0806..39c66f5daeb1 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def
@@ -7,14 +7,23 @@
//===----------------------------------------------------------------------===//
//
// This file defines the PowerPC-specific builtin function database. Users of
-// this file must define the BUILTIN macro to make use of this information.
+// this file must define the BUILTIN macro or the CUSTOM_BUILTIN macro to
+// make use of this information. The latter is used for builtins requiring
+// custom code generation and checking.
//
//===----------------------------------------------------------------------===//
// FIXME: this needs to be the full list supported by GCC. Right now, I'm just
// adding stuff on demand.
-// The format of this database matches clang/Basic/Builtins.def.
+// The format of this database matches clang/Basic/Builtins.def except for the
+// MMA builtins that are using their own format documented below.
+
+#if defined(BUILTIN) && !defined(CUSTOM_BUILTIN)
+# define CUSTOM_BUILTIN(ID, TYPES, ACCUMULATE) BUILTIN(__builtin_##ID, "i.", "t")
+#elif defined(CUSTOM_BUILTIN) && !defined(BUILTIN)
+# define BUILTIN(ID, TYPES, ATTRS)
+#endif
BUILTIN(__builtin_ppc_get_timebase, "ULLi", "n")
@@ -100,6 +109,11 @@ BUILTIN(__builtin_altivec_vmulouh, "V4UiV8UsV8Us", "")
BUILTIN(__builtin_altivec_vmulosh, "V4SiV8SsV8Ss", "")
BUILTIN(__builtin_altivec_vmulouw, "V2ULLiV4UiV4Ui", "")
BUILTIN(__builtin_altivec_vmulosw, "V2SLLiV4SiV4Si", "")
+BUILTIN(__builtin_altivec_vmuleud, "V1ULLLiV2ULLiV2ULLi", "")
+BUILTIN(__builtin_altivec_vmulesd, "V1SLLLiV2SLLiV2SLLi", "")
+BUILTIN(__builtin_altivec_vmuloud, "V1ULLLiV2ULLiV2ULLi", "")
+BUILTIN(__builtin_altivec_vmulosd, "V1SLLLiV2SLLiV2SLLi", "")
+BUILTIN(__builtin_altivec_vmsumcud, "V1ULLLiV2ULLiV2ULLiV1ULLLi", "")
BUILTIN(__builtin_altivec_vnmsubfp, "V4fV4fV4fV4f", "")
@@ -151,6 +165,14 @@ BUILTIN(__builtin_altivec_vcmpgtsd, "V2LLiV2LLiV2LLi", "")
BUILTIN(__builtin_altivec_vcmpgtud, "V2LLiV2ULLiV2ULLi", "")
BUILTIN(__builtin_altivec_vcmpgtfp, "V4iV4fV4f", "")
+// P10 Vector compare builtins.
+BUILTIN(__builtin_altivec_vcmpequq, "V1LLLiV1ULLLiV1ULLLi", "")
+BUILTIN(__builtin_altivec_vcmpgtsq, "V1LLLiV1SLLLiV1SLLLi", "")
+BUILTIN(__builtin_altivec_vcmpgtuq, "V1LLLiV1ULLLiV1ULLLi", "")
+BUILTIN(__builtin_altivec_vcmpequq_p, "iiV1ULLLiV1LLLi", "")
+BUILTIN(__builtin_altivec_vcmpgtsq_p, "iiV1SLLLiV1SLLLi", "")
+BUILTIN(__builtin_altivec_vcmpgtuq_p, "iiV1ULLLiV1ULLLi", "")
+
BUILTIN(__builtin_altivec_vmaxsb, "V16ScV16ScV16Sc", "")
BUILTIN(__builtin_altivec_vmaxub, "V16UcV16UcV16Uc", "")
BUILTIN(__builtin_altivec_vmaxsh, "V8SsV8SsV8Ss", "")
@@ -298,10 +320,71 @@ BUILTIN(__builtin_altivec_vrldmi, "V2ULLiV2ULLiV2ULLiV2ULLi", "")
BUILTIN(__builtin_altivec_vrlwnm, "V4UiV4UiV4Ui", "")
BUILTIN(__builtin_altivec_vrldnm, "V2ULLiV2ULLiV2ULLi", "")
+// P9 Vector extend sign builtins.
+BUILTIN(__builtin_altivec_vextsb2w, "V4SiV16Sc", "")
+BUILTIN(__builtin_altivec_vextsb2d, "V2SLLiV16Sc", "")
+BUILTIN(__builtin_altivec_vextsh2w, "V4SiV8Ss", "")
+BUILTIN(__builtin_altivec_vextsh2d, "V2SLLiV8Ss", "")
+BUILTIN(__builtin_altivec_vextsw2d, "V2SLLiV4Si", "")
+
+// P10 Vector extend sign builtins.
+BUILTIN(__builtin_altivec_vextsd2q, "V1SLLLiV2SLLi", "")
+
+// P10 Vector Extract with Mask built-ins.
+BUILTIN(__builtin_altivec_vextractbm, "UiV16Uc", "")
+BUILTIN(__builtin_altivec_vextracthm, "UiV8Us", "")
+BUILTIN(__builtin_altivec_vextractwm, "UiV4Ui", "")
+BUILTIN(__builtin_altivec_vextractdm, "UiV2ULLi", "")
+BUILTIN(__builtin_altivec_vextractqm, "UiV1ULLLi", "")
+
+// P10 Vector Divide Extended built-ins.
+BUILTIN(__builtin_altivec_vdivesw, "V4SiV4SiV4Si", "")
+BUILTIN(__builtin_altivec_vdiveuw, "V4UiV4UiV4Ui", "")
+BUILTIN(__builtin_altivec_vdivesd, "V2LLiV2LLiV2LLi", "")
+BUILTIN(__builtin_altivec_vdiveud, "V2ULLiV2ULLiV2ULLi", "")
+BUILTIN(__builtin_altivec_vdivesq, "V1SLLLiV1SLLLiV1SLLLi", "")
+BUILTIN(__builtin_altivec_vdiveuq, "V1ULLLiV1ULLLiV1ULLLi", "")
+
+// P10 Vector Multiply High built-ins.
+BUILTIN(__builtin_altivec_vmulhsw, "V4SiV4SiV4Si", "")
+BUILTIN(__builtin_altivec_vmulhuw, "V4UiV4UiV4Ui", "")
+BUILTIN(__builtin_altivec_vmulhsd, "V2LLiV2LLiV2LLi", "")
+BUILTIN(__builtin_altivec_vmulhud, "V2ULLiV2ULLiV2ULLi", "")
+
+// P10 Vector Expand with Mask built-ins.
+BUILTIN(__builtin_altivec_vexpandbm, "V16UcV16Uc", "")
+BUILTIN(__builtin_altivec_vexpandhm, "V8UsV8Us", "")
+BUILTIN(__builtin_altivec_vexpandwm, "V4UiV4Ui", "")
+BUILTIN(__builtin_altivec_vexpanddm, "V2ULLiV2ULLi", "")
+BUILTIN(__builtin_altivec_vexpandqm, "V1ULLLiV1ULLLi", "")
+
+// P10 Vector Count with Mask built-ins.
+BUILTIN(__builtin_altivec_vcntmbb, "ULLiV16UcUi", "")
+BUILTIN(__builtin_altivec_vcntmbh, "ULLiV8UsUi", "")
+BUILTIN(__builtin_altivec_vcntmbw, "ULLiV4UiUi", "")
+BUILTIN(__builtin_altivec_vcntmbd, "ULLiV2ULLiUi", "")
+
+// P10 Move to VSR with Mask built-ins.
+BUILTIN(__builtin_altivec_mtvsrbm, "V16UcULLi", "")
+BUILTIN(__builtin_altivec_mtvsrhm, "V8UsULLi", "")
+BUILTIN(__builtin_altivec_mtvsrwm, "V4UiULLi", "")
+BUILTIN(__builtin_altivec_mtvsrdm, "V2ULLiULLi", "")
+BUILTIN(__builtin_altivec_mtvsrqm, "V1ULLLiULLi", "")
+
// P10 Vector Parallel Bits built-ins.
BUILTIN(__builtin_altivec_vpdepd, "V2ULLiV2ULLiV2ULLi", "")
BUILTIN(__builtin_altivec_vpextd, "V2ULLiV2ULLiV2ULLi", "")
+// P10 Vector String Isolate Built-ins.
+BUILTIN(__builtin_altivec_vstribr, "V16cV16c", "")
+BUILTIN(__builtin_altivec_vstribl, "V16cV16c", "")
+BUILTIN(__builtin_altivec_vstrihr, "V8sV8s", "")
+BUILTIN(__builtin_altivec_vstrihl, "V8sV8s", "")
+BUILTIN(__builtin_altivec_vstribr_p, "iiV16c", "")
+BUILTIN(__builtin_altivec_vstribl_p, "iiV16c", "")
+BUILTIN(__builtin_altivec_vstrihr_p, "iiV8s", "")
+BUILTIN(__builtin_altivec_vstrihl_p, "iiV8s", "")
+
// P10 Vector Centrifuge built-in.
BUILTIN(__builtin_altivec_vcfuged, "V2ULLiV2ULLiV2ULLi", "")
@@ -321,20 +404,36 @@ BUILTIN(__builtin_altivec_vsldbi, "V16UcV16UcV16UcIi", "")
BUILTIN(__builtin_altivec_vsrdbi, "V16UcV16UcV16UcIi", "")
// P10 Vector Insert built-ins.
-BUILTIN(__builtin_altivec_vinsblx, "V16UcV16UcULLiULLi", "")
-BUILTIN(__builtin_altivec_vinsbrx, "V16UcV16UcULLiULLi", "")
-BUILTIN(__builtin_altivec_vinshlx, "V8UsV8UsULLiULLi", "")
-BUILTIN(__builtin_altivec_vinshrx, "V8UsV8UsULLiULLi", "")
-BUILTIN(__builtin_altivec_vinswlx, "V4UiV4UiULLiULLi", "")
-BUILTIN(__builtin_altivec_vinswrx, "V4UiV4UiULLiULLi", "")
+BUILTIN(__builtin_altivec_vinsblx, "V16UcV16UcUiUi", "")
+BUILTIN(__builtin_altivec_vinsbrx, "V16UcV16UcUiUi", "")
+BUILTIN(__builtin_altivec_vinshlx, "V8UsV8UsUiUi", "")
+BUILTIN(__builtin_altivec_vinshrx, "V8UsV8UsUiUi", "")
+BUILTIN(__builtin_altivec_vinswlx, "V4UiV4UiUiUi", "")
+BUILTIN(__builtin_altivec_vinswrx, "V4UiV4UiUiUi", "")
BUILTIN(__builtin_altivec_vinsdlx, "V2ULLiV2ULLiULLiULLi", "")
BUILTIN(__builtin_altivec_vinsdrx, "V2ULLiV2ULLiULLiULLi", "")
-BUILTIN(__builtin_altivec_vinsbvlx, "V16UcV16UcULLiV16Uc", "")
-BUILTIN(__builtin_altivec_vinsbvrx, "V16UcV16UcULLiV16Uc", "")
-BUILTIN(__builtin_altivec_vinshvlx, "V8UsV8UsULLiV8Us", "")
-BUILTIN(__builtin_altivec_vinshvrx, "V8UsV8UsULLiV8Us", "")
-BUILTIN(__builtin_altivec_vinswvlx, "V4UiV4UiULLiV4Ui", "")
-BUILTIN(__builtin_altivec_vinswvrx, "V4UiV4UiULLiV4Ui", "")
+BUILTIN(__builtin_altivec_vinsbvlx, "V16UcV16UcUiV16Uc", "")
+BUILTIN(__builtin_altivec_vinsbvrx, "V16UcV16UcUiV16Uc", "")
+BUILTIN(__builtin_altivec_vinshvlx, "V8UsV8UsUiV8Us", "")
+BUILTIN(__builtin_altivec_vinshvrx, "V8UsV8UsUiV8Us", "")
+BUILTIN(__builtin_altivec_vinswvlx, "V4UiV4UiUiV4Ui", "")
+BUILTIN(__builtin_altivec_vinswvrx, "V4UiV4UiUiV4Ui", "")
+BUILTIN(__builtin_altivec_vec_replace_elt, "V4UiV4UiUiIi", "t")
+BUILTIN(__builtin_altivec_vec_replace_unaligned, "V4UiV4UiUiIi", "t")
+
+// P10 Vector Extract built-ins.
+BUILTIN(__builtin_altivec_vextdubvlx, "V2ULLiV16UcV16UcUi", "")
+BUILTIN(__builtin_altivec_vextdubvrx, "V2ULLiV16UcV16UcUi", "")
+BUILTIN(__builtin_altivec_vextduhvlx, "V2ULLiV8UsV8UsUi", "")
+BUILTIN(__builtin_altivec_vextduhvrx, "V2ULLiV8UsV8UsUi", "")
+BUILTIN(__builtin_altivec_vextduwvlx, "V2ULLiV4UiV4UiUi", "")
+BUILTIN(__builtin_altivec_vextduwvrx, "V2ULLiV4UiV4UiUi", "")
+BUILTIN(__builtin_altivec_vextddvlx, "V2ULLiV2ULLiV2ULLiUi", "")
+BUILTIN(__builtin_altivec_vextddvrx, "V2ULLiV2ULLiV2ULLiUi", "")
+
+// P10 Vector rotate built-ins.
+BUILTIN(__builtin_altivec_vrlqmi, "V1ULLLiV1ULLLiV1ULLLiV1ULLLi", "")
+BUILTIN(__builtin_altivec_vrlqnm, "V1ULLLiV1ULLLiV1ULLLi", "")
// VSX built-ins.
@@ -455,6 +554,9 @@ BUILTIN(__builtin_vsx_xvcvdpsp, "V4fV2d", "")
BUILTIN(__builtin_vsx_xvcvsphp, "V4fV4f", "")
BUILTIN(__builtin_vsx_xvcvhpsp, "V4fV8Us", "")
+BUILTIN(__builtin_vsx_xvcvspbf16, "V16UcV16Uc", "")
+BUILTIN(__builtin_vsx_xvcvbf16spn, "V16UcV16Uc", "")
+
// Vector Test Data Class builtins
BUILTIN(__builtin_vsx_xvtstdcdp, "V2ULLiV2dIi", "")
BUILTIN(__builtin_vsx_xvtstdcsp, "V4UiV4fIi", "")
@@ -467,7 +569,12 @@ BUILTIN(__builtin_vsx_xxsldwi, "v.", "t")
BUILTIN(__builtin_vsx_xxeval, "V2ULLiV2ULLiV2ULLiV2ULLiIi", "")
-BUILTIN(__builtin_vsx_xvtlsbb, "iV16Ucb", "")
+BUILTIN(__builtin_vsx_xvtlsbb, "iV16UcUi", "")
+
+BUILTIN(__builtin_vsx_xvtdivdp, "iV2dV2d", "")
+BUILTIN(__builtin_vsx_xvtdivsp, "iV4fV4f", "")
+BUILTIN(__builtin_vsx_xvtsqrtdp, "iV2d", "")
+BUILTIN(__builtin_vsx_xvtsqrtsp, "iV4f", "")
// P10 Vector Permute Extended built-in.
BUILTIN(__builtin_vsx_xxpermx, "V16UcV16UcV16UcV16UcIi", "")
@@ -532,6 +639,11 @@ BUILTIN(__builtin_cfuged, "ULLiULLiULLi", "")
BUILTIN(__builtin_cntlzdm, "ULLiULLiULLi", "")
BUILTIN(__builtin_cnttzdm, "ULLiULLiULLi", "")
+// Generate random number
+BUILTIN(__builtin_darn, "LLi", "")
+BUILTIN(__builtin_darn_raw, "LLi", "")
+BUILTIN(__builtin_darn_32, "i", "")
+
// Vector int128 (un)pack
BUILTIN(__builtin_unpack_vector_int128, "ULLiV1LLLii", "")
BUILTIN(__builtin_pack_vector_int128, "V1LLLiULLiULLi", "")
@@ -539,9 +651,103 @@ BUILTIN(__builtin_pack_vector_int128, "V1LLLiULLiULLi", "")
// Set the floating point rounding mode
BUILTIN(__builtin_setrnd, "di", "")
+// Get content from current FPSCR
+BUILTIN(__builtin_readflm, "d", "")
+
+// Set content of FPSCR, and return its content before update
+BUILTIN(__builtin_setflm, "dd", "")
+
// Cache built-ins
BUILTIN(__builtin_dcbf, "vvC*", "")
+// Built-ins requiring custom code generation.
+// Because these built-ins rely on target-dependent types and to avoid pervasive
+// change, they are type checked manually in Sema using custom type descriptors.
+// The first argument of the CUSTOM_BUILTIN macro is the name of the built-in
+// with its prefix, the second argument specifies the type of the function
+// (result value, then each argument) as follows:
+// i -> Unsigned integer followed by the greatest possible value for that
+// argument or 0 if no constraint on the value.
+// (e.g. i15 for a 4-bits value)
+// V -> Vector type used with MMA builtins (vector unsigned char)
+// W -> PPC Vector type followed by the size of the vector type.
+// (e.g. W512 for __vector_quad)
+// any other descriptor -> Fall back to generic type descriptor decoding.
+// The 'C' suffix can be used as a suffix to specify the const type.
+// The '*' suffix can be used as a suffix to specify a pointer to a type.
+// The third argument is set to true if the builtin accumulates its result into
+// its given accumulator.
+
+CUSTOM_BUILTIN(vsx_lxvp, "W256SLLiW256C*", false)
+CUSTOM_BUILTIN(vsx_stxvp, "vW256SLLiW256C*", false)
+CUSTOM_BUILTIN(vsx_assemble_pair, "vW256*VV", false)
+CUSTOM_BUILTIN(vsx_disassemble_pair, "vv*W256*", false)
+
+CUSTOM_BUILTIN(mma_assemble_acc, "vW512*VVVV", false)
+CUSTOM_BUILTIN(mma_disassemble_acc, "vv*W512*", false)
+CUSTOM_BUILTIN(mma_xxmtacc, "vW512*", true)
+CUSTOM_BUILTIN(mma_xxmfacc, "vW512*", true)
+CUSTOM_BUILTIN(mma_xxsetaccz, "vW512*", false)
+CUSTOM_BUILTIN(mma_xvi4ger8, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvi8ger4, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvi16ger2, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvi16ger2s, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvf16ger2, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvf32ger, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_xvf64ger, "vW512*W256V", false)
+CUSTOM_BUILTIN(mma_pmxvi4ger8, "vW512*VVi15i15i255", false)
+CUSTOM_BUILTIN(mma_pmxvi8ger4, "vW512*VVi15i15i15", false)
+CUSTOM_BUILTIN(mma_pmxvi16ger2, "vW512*VVi15i15i3", false)
+CUSTOM_BUILTIN(mma_pmxvi16ger2s, "vW512*VVi15i15i3", false)
+CUSTOM_BUILTIN(mma_pmxvf16ger2, "vW512*VVi15i15i3", false)
+CUSTOM_BUILTIN(mma_pmxvf32ger, "vW512*VVi15i15", false)
+CUSTOM_BUILTIN(mma_pmxvf64ger, "vW512*W256Vi15i3", false)
+CUSTOM_BUILTIN(mma_xvi4ger8pp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvi8ger4pp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvi8ger4spp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvi16ger2pp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvi16ger2spp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_pmxvi4ger8pp, "vW512*VVi15i15i255", true)
+CUSTOM_BUILTIN(mma_pmxvi8ger4pp, "vW512*VVi15i15i15", true)
+CUSTOM_BUILTIN(mma_pmxvi8ger4spp, "vW512*VVi15i15i15", true)
+CUSTOM_BUILTIN(mma_pmxvi16ger2pp, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvi16ger2spp, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_xvf16ger2pp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf16ger2pn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf16ger2np, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf16ger2nn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_pmxvf16ger2pp, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf16ger2pn, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf16ger2np, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf16ger2nn, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_xvf32gerpp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf32gerpn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf32gernp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvf32gernn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_pmxvf32gerpp, "vW512*VVi15i15", true)
+CUSTOM_BUILTIN(mma_pmxvf32gerpn, "vW512*VVi15i15", true)
+CUSTOM_BUILTIN(mma_pmxvf32gernp, "vW512*VVi15i15", true)
+CUSTOM_BUILTIN(mma_pmxvf32gernn, "vW512*VVi15i15", true)
+CUSTOM_BUILTIN(mma_xvf64gerpp, "vW512*W256V", true)
+CUSTOM_BUILTIN(mma_xvf64gerpn, "vW512*W256V", true)
+CUSTOM_BUILTIN(mma_xvf64gernp, "vW512*W256V", true)
+CUSTOM_BUILTIN(mma_xvf64gernn, "vW512*W256V", true)
+CUSTOM_BUILTIN(mma_pmxvf64gerpp, "vW512*W256Vi15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf64gerpn, "vW512*W256Vi15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf64gernp, "vW512*W256Vi15i3", true)
+CUSTOM_BUILTIN(mma_pmxvf64gernn, "vW512*W256Vi15i3", true)
+CUSTOM_BUILTIN(mma_xvbf16ger2, "vW512*VV", false)
+CUSTOM_BUILTIN(mma_pmxvbf16ger2, "vW512*VVi15i15i3", false)
+CUSTOM_BUILTIN(mma_xvbf16ger2pp, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvbf16ger2pn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvbf16ger2np, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_xvbf16ger2nn, "vW512*VV", true)
+CUSTOM_BUILTIN(mma_pmxvbf16ger2pp, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvbf16ger2pn, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvbf16ger2np, "vW512*VVi15i15i3", true)
+CUSTOM_BUILTIN(mma_pmxvbf16ger2nn, "vW512*VVi15i15i3", true)
+
// FIXME: Obviously incomplete.
#undef BUILTIN
+#undef CUSTOM_BUILTIN
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def
index ecee7782920f..bb7d6d379e58 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def
@@ -38,12 +38,12 @@ BUILTIN(__builtin_wasm_max_f64, "ddd", "nc")
// Exception handling builtins.
TARGET_BUILTIN(__builtin_wasm_throw, "vIUiv*", "r", "exception-handling")
-TARGET_BUILTIN(__builtin_wasm_rethrow_in_catch, "v", "r", "exception-handling")
+TARGET_BUILTIN(__builtin_wasm_rethrow, "v", "r", "exception-handling")
// Atomic wait and notify.
-TARGET_BUILTIN(__builtin_wasm_atomic_wait_i32, "ii*iLLi", "n", "atomics")
-TARGET_BUILTIN(__builtin_wasm_atomic_wait_i64, "iLLi*LLiLLi", "n", "atomics")
-TARGET_BUILTIN(__builtin_wasm_atomic_notify, "Uii*Ui", "n", "atomics")
+TARGET_BUILTIN(__builtin_wasm_memory_atomic_wait32, "ii*iLLi", "n", "atomics")
+TARGET_BUILTIN(__builtin_wasm_memory_atomic_wait64, "iLLi*LLiLLi", "n", "atomics")
+TARGET_BUILTIN(__builtin_wasm_memory_atomic_notify, "Uii*Ui", "n", "atomics")
// Trapping fp-to-int conversions
BUILTIN(__builtin_wasm_trunc_s_i32_f32, "if", "nc")
@@ -66,69 +66,101 @@ TARGET_BUILTIN(__builtin_wasm_trunc_saturate_s_i64_f64, "LLid", "nc", "nontrappi
TARGET_BUILTIN(__builtin_wasm_trunc_saturate_u_i64_f64, "LLid", "nc", "nontrapping-fptoint")
// SIMD builtins
-TARGET_BUILTIN(__builtin_wasm_swizzle_v8x16, "V16cV16cV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_swizzle_v8x16, "V16ScV16ScV16Sc", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_extract_lane_s_i8x16, "iV16cIi", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_extract_lane_u_i8x16, "iV16cIi", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extract_lane_s_i8x16, "iV16ScIi", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extract_lane_u_i8x16, "iV16UcIUi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_extract_lane_s_i16x8, "iV8sIi", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_extract_lane_u_i16x8, "iV8sIi", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extract_lane_u_i16x8, "iV8UsIUi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_extract_lane_i32x4, "iV4iIi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_extract_lane_i64x2, "LLiV2LLiIi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_extract_lane_f32x4, "fV4fIi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_extract_lane_f64x2, "dV2dIi", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_replace_lane_i8x16, "V16cV16cIii", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_replace_lane_i8x16, "V16ScV16ScIii", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_replace_lane_i16x8, "V8sV8sIii", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_replace_lane_i32x4, "V4iV4iIii", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_replace_lane_i64x2, "V2LLiV2LLiIiLLi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_replace_lane_f32x4, "V4fV4fIif", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_replace_lane_f64x2, "V2dV2dIid", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_add_saturate_s_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_add_saturate_u_i8x16, "V16cV16cV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_add_saturate_s_i8x16, "V16ScV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_add_saturate_u_i8x16, "V16UcV16UcV16Uc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_add_saturate_s_i16x8, "V8sV8sV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_add_saturate_u_i16x8, "V8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_add_saturate_u_i16x8, "V8UsV8UsV8Us", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_sub_saturate_s_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_sub_saturate_u_i8x16, "V16cV16cV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_sub_saturate_s_i8x16, "V16ScV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_sub_saturate_u_i8x16, "V16UcV16UcV16Uc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_sub_saturate_s_i16x8, "V8sV8sV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_sub_saturate_u_i16x8, "V8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_sub_saturate_u_i16x8, "V8UsV8UsV8Us", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_abs_i8x16, "V16cV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_abs_i8x16, "V16ScV16Sc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_abs_i16x8, "V8sV8s", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_abs_i32x4, "V4iV4i", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_min_s_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_min_u_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_max_s_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_max_u_i8x16, "V16cV16cV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_min_s_i8x16, "V16ScV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_min_u_i8x16, "V16UcV16UcV16Uc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_max_s_i8x16, "V16ScV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_max_u_i8x16, "V16UcV16UcV16Uc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_min_s_i16x8, "V8sV8sV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_min_u_i16x8, "V8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_min_u_i16x8, "V8UsV8UsV8Us", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_max_s_i16x8, "V8sV8sV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_max_u_i16x8, "V8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_max_u_i16x8, "V8UsV8UsV8Us", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_min_s_i32x4, "V4iV4iV4i", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_min_u_i32x4, "V4iV4iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_min_u_i32x4, "V4UiV4UiV4Ui", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_max_s_i32x4, "V4iV4iV4i", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_max_u_i32x4, "V4iV4iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_max_u_i32x4, "V4UiV4UiV4Ui", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_avgr_u_i8x16, "V16cV16cV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_avgr_u_i16x8, "V8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_avgr_u_i8x16, "V16UcV16UcV16Uc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_avgr_u_i16x8, "V8UsV8UsV8Us", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_popcnt_i8x16, "V16ScV16Sc", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_q15mulr_saturate_s_i16x8, "V8sV8sV8s", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i8x16_s_i16x8, "V8sV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i8x16_s_i16x8, "V8sV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i8x16_u_i16x8, "V8UsV16UcV16Uc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i8x16_u_i16x8, "V8UsV16UcV16Uc", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i16x8_s_i32x4, "V4iV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i16x8_s_i32x4, "V4iV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i16x8_u_i32x4, "V4UiV8UsV8Us", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i16x8_u_i32x4, "V4UiV8UsV8Us", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i32x4_s_i64x2, "V2LLiV4iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i32x4_s_i64x2, "V2LLiV4iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_low_i32x4_u_i64x2, "V2ULLiV4UiV4Ui", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extmul_high_i32x4_u_i64x2, "V2ULLiV4UiV4Ui", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_extadd_pairwise_i8x16_s_i16x8, "V8sV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extadd_pairwise_i8x16_u_i16x8, "V8UsV16Uc", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_extadd_pairwise_i16x8_s_i32x4, "V4iV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_extadd_pairwise_i16x8_u_i32x4, "V4UiV8Us", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_bitselect, "V4iV4iV4iV4i", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_shuffle_v8x16, "V16cV16cV16cIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIi", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_any_true_i8x16, "iV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_signselect_i8x16, "V16ScV16ScV16ScV16Sc", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_signselect_i16x8, "V8sV8sV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_signselect_i32x4, "V4iV4iV4iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_signselect_i64x2, "V2LLiV2LLiV2LLiV2LLi", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_shuffle_v8x16, "V16ScV16ScV16ScIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIi", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_any_true_i8x16, "iV16Sc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_any_true_i16x8, "iV8s", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_any_true_i32x4, "iV4i", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_any_true_i64x2, "iV2LLi", "nc", "unimplemented-simd128")
-TARGET_BUILTIN(__builtin_wasm_all_true_i8x16, "iV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_all_true_i8x16, "iV16Sc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_all_true_i16x8, "iV8s", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_all_true_i32x4, "iV4i", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_all_true_i64x2, "iV2LLi", "nc", "unimplemented-simd128")
-TARGET_BUILTIN(__builtin_wasm_bitmask_i8x16, "iV16c", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_bitmask_i8x16, "iV16Sc", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_bitmask_i16x8, "iV8s", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_bitmask_i32x4, "iV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_bitmask_i64x2, "iV2LLi", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_abs_f32x4, "V4fV4f", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_abs_f64x2, "V2dV2d", "nc", "simd128")
@@ -164,19 +196,39 @@ TARGET_BUILTIN(__builtin_wasm_qfms_f64x2, "V2dV2dV2dV2d", "nc", "unimplemented-s
TARGET_BUILTIN(__builtin_wasm_trunc_saturate_s_i32x4_f32x4, "V4iV4f", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_trunc_saturate_u_i32x4_f32x4, "V4iV4f", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_narrow_s_i8x16_i16x8, "V16cV8sV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_narrow_u_i8x16_i16x8, "V16cV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_narrow_s_i8x16_i16x8, "V16ScV8sV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_narrow_u_i8x16_i16x8, "V16UcV8UsV8Us", "nc", "simd128")
TARGET_BUILTIN(__builtin_wasm_narrow_s_i16x8_i32x4, "V8sV4iV4i", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_narrow_u_i16x8_i32x4, "V8sV4iV4i", "nc", "simd128")
-
-TARGET_BUILTIN(__builtin_wasm_widen_low_s_i16x8_i8x16, "V8sV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_high_s_i16x8_i8x16, "V8sV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_low_u_i16x8_i8x16, "V8sV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_high_u_i16x8_i8x16, "V8sV16c", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_low_s_i32x4_i16x8, "V4iV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_high_s_i32x4_i16x8, "V4iV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_low_u_i32x4_i16x8, "V4iV8s", "nc", "simd128")
-TARGET_BUILTIN(__builtin_wasm_widen_high_u_i32x4_i16x8, "V4iV8s", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_narrow_u_i16x8_i32x4, "V8UsV4UiV4Ui", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_widen_low_s_i32x4_i64x2, "V2LLiV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_widen_high_s_i32x4_i64x2, "V2LLiV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_widen_low_u_i32x4_i64x2, "V2LLUiV4Ui", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_widen_high_u_i32x4_i64x2, "V2LLUiV4Ui", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_convert_low_s_i32x4_f64x2, "V2dV4i", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_convert_low_u_i32x4_f64x2, "V2dV4Ui", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_trunc_saturate_zero_s_f64x2_i32x4, "V4iV2d", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_trunc_saturate_zero_u_f64x2_i32x4, "V4UiV2d", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_demote_zero_f64x2_f32x4, "V4fV2d", "nc", "simd128")
+TARGET_BUILTIN(__builtin_wasm_promote_low_f32x4_f64x2, "V2dV4f", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_load32_zero, "V4ii*", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load64_zero, "V2LLiLLi*", "n", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_load8_lane, "V16ScSc*V16ScIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load16_lane, "V8ss*V8sIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load32_lane, "V4ii*V4iIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load64_lane, "V2LLiLLi*V2LLiIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store8_lane, "vSc*V16ScIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store16_lane, "vs*V8sIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store32_lane, "vi*V4iIi", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store64_lane, "vLLi*V2LLiIi", "n", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_eq_i64x2, "V2LLiV2LLiV2LLi", "nc", "simd128")
+
+TARGET_BUILTIN(__builtin_wasm_prefetch_t, "vv*", "n", "simd128")
+TARGET_BUILTIN(__builtin_wasm_prefetch_nt, "vv*", "n", "simd128")
#undef BUILTIN
#undef TARGET_BUILTIN
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def
index 35fb98352ec2..16fb7dd7b0e6 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def
@@ -960,17 +960,17 @@ TARGET_BUILTIN(__builtin_ia32_alignq256, "V4OiV4OiV4OiIi", "ncV:256:", "avx512vl
TARGET_BUILTIN(__builtin_ia32_extractf64x4_mask, "V4dV8dIiV4dUc", "ncV:512:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_extractf32x4_mask, "V4fV16fIiV4fUc", "ncV:512:", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_vpdpbusd128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpbusd256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpbusd128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni|avxvnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpbusd256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni|avxvnni")
TARGET_BUILTIN(__builtin_ia32_vpdpbusd512, "V16iV16iV16iV16i", "ncV:512:", "avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpbusds128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpbusds256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpbusds128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni|avxvnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpbusds256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni|avxvnni")
TARGET_BUILTIN(__builtin_ia32_vpdpbusds512, "V16iV16iV16iV16i", "ncV:512:", "avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpwssd128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpwssd256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpwssd128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni|avxvnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpwssd256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni|avxvnni")
TARGET_BUILTIN(__builtin_ia32_vpdpwssd512, "V16iV16iV16iV16i", "ncV:512:", "avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpwssds128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni")
-TARGET_BUILTIN(__builtin_ia32_vpdpwssds256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpwssds128, "V4iV4iV4iV4i", "ncV:128:", "avx512vl,avx512vnni|avxvnni")
+TARGET_BUILTIN(__builtin_ia32_vpdpwssds256, "V8iV8iV8iV8i", "ncV:256:", "avx512vl,avx512vnni|avxvnni")
TARGET_BUILTIN(__builtin_ia32_vpdpwssds512, "V16iV16iV16iV16i", "ncV:512:", "avx512vnni")
TARGET_BUILTIN(__builtin_ia32_gather3div2df, "V2dV2dvC*V2OiUcIi", "nV:128:", "avx512vl")
@@ -1871,6 +1871,28 @@ TARGET_BUILTIN(__builtin_ia32_selectpd_512, "V8dUcV8dV8d", "ncV:512:", "avx512f"
TARGET_BUILTIN(__builtin_ia32_selectss_128, "V4fUcV4fV4f", "ncV:128:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_selectsd_128, "V2dUcV2dV2d", "ncV:128:", "avx512f")
+// generic reduction intrinsics
+TARGET_BUILTIN(__builtin_ia32_reduce_add_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_add_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_and_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_and_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_fadd_pd512, "ddV8d", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ps512, "ffV16f", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_fmul_pd512, "ddV8d", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_fmul_ps512, "ffV16f", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_mul_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_mul_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_or_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_or_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_smax_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_smax_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_smin_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_smin_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_umax_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_umax_q512, "OiV8Oi", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_umin_d512, "iV16i", "ncV:512:", "avx512f")
+TARGET_BUILTIN(__builtin_ia32_reduce_umin_q512, "OiV8Oi", "ncV:512:", "avx512f")
+
// MONITORX/MWAITX
TARGET_BUILTIN(__builtin_ia32_monitorx, "vvC*UiUi", "n", "mwaitx")
TARGET_BUILTIN(__builtin_ia32_mwaitx, "vUiUiUi", "n", "mwaitx")
@@ -1900,6 +1922,19 @@ TARGET_BUILTIN(__builtin_ia32_invpcid, "vUiv*", "nc", "invpcid")
TARGET_BUILTIN(__builtin_ia32_enqcmd, "Ucv*vC*", "n", "enqcmd")
TARGET_BUILTIN(__builtin_ia32_enqcmds, "Ucv*vC*", "n", "enqcmd")
+// KEY LOCKER
+TARGET_BUILTIN(__builtin_ia32_loadiwkey, "vV2OiV2OiV2OiUi", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_encodekey128_u32, "UiUiV2Oiv*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_encodekey256_u32, "UiUiV2OiV2Oiv*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_aesenc128kl_u8, "UcV2Oi*V2OivC*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_aesenc256kl_u8, "UcV2Oi*V2OivC*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_aesdec128kl_u8, "UcV2Oi*V2OivC*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_aesdec256kl_u8, "UcV2Oi*V2OivC*", "nV:128:", "kl")
+TARGET_BUILTIN(__builtin_ia32_aesencwide128kl_u8, "UcV2Oi*V2OiC*vC*", "nV:128:", "kl,widekl")
+TARGET_BUILTIN(__builtin_ia32_aesencwide256kl_u8, "UcV2Oi*V2OiC*vC*", "nV:128:", "kl,widekl")
+TARGET_BUILTIN(__builtin_ia32_aesdecwide128kl_u8, "UcV2Oi*V2OiC*vC*", "nV:128:", "kl,widekl")
+TARGET_BUILTIN(__builtin_ia32_aesdecwide256kl_u8, "UcV2Oi*V2OiC*vC*", "nV:128:", "kl,widekl")
+
// SERIALIZE
TARGET_BUILTIN(__builtin_ia32_serialize, "v", "n", "serialize")
diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def
index f66ae78f7e81..974ba35b3233 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def
@@ -94,6 +94,17 @@ TARGET_BUILTIN(__builtin_ia32_cvtusi2sd64, "V2dV2dUOiIi", "ncV:128:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_cvtusi2ss64, "V4fV4fUOiIi", "ncV:128:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_directstore_u64, "vULi*ULi", "n", "movdiri")
+// UINTR
+TARGET_BUILTIN(__builtin_ia32_clui, "v", "n", "uintr")
+TARGET_BUILTIN(__builtin_ia32_stui, "v", "n", "uintr")
+TARGET_BUILTIN(__builtin_ia32_testui, "Uc", "n", "uintr")
+TARGET_BUILTIN(__builtin_ia32_senduipi, "vUWi", "n", "uintr")
+
+// AMX internal builtin
+TARGET_BUILTIN(__builtin_ia32_tileloadd64_internal, "V256iUsUsvC*z", "n", "amx-tile")
+TARGET_BUILTIN(__builtin_ia32_tdpbssd_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-int8")
+TARGET_BUILTIN(__builtin_ia32_tilestored64_internal, "vUsUsv*zV256i", "n", "amx-tile")
+TARGET_BUILTIN(__builtin_ia32_tilezero_internal, "V256iUsUs", "n", "amx-tile")
// AMX
TARGET_BUILTIN(__builtin_ia32_tile_loadconfig, "vvC*", "n", "amx-tile")
TARGET_BUILTIN(__builtin_ia32_tile_storeconfig, "vvC*", "n", "amx-tile")
diff --git a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def
index c7e01eb12851..9d53b5b923bb 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def
@@ -32,11 +32,14 @@ ENUM_CODEGENOPT(CompressDebugSections, llvm::DebugCompressionType, 2,
llvm::DebugCompressionType::None)
CODEGENOPT(RelaxELFRelocations, 1, 0) ///< -Wa,--mrelax-relocations
CODEGENOPT(AsmVerbose , 1, 0) ///< -dA, -fverbose-asm.
+CODEGENOPT(Dwarf64 , 1, 0) ///< -gdwarf64.
+CODEGENOPT(Dwarf32 , 1, 1) ///< -gdwarf32.
CODEGENOPT(PreserveAsmComments, 1, 1) ///< -dA, -fno-preserve-as-comments.
CODEGENOPT(AssumeSaneOperatorNew , 1, 1) ///< implicit __attribute__((malloc)) operator new
CODEGENOPT(Autolink , 1, 1) ///< -fno-autolink
CODEGENOPT(ObjCAutoRefCountExceptions , 1, 0) ///< Whether ARC should be EH-safe.
CODEGENOPT(Backchain , 1, 0) ///< -mbackchain
+CODEGENOPT(IgnoreXCOFFVisibility , 1, 0) ///< -mignore-xcoff-visibility
CODEGENOPT(ControlFlowGuardNoChecks , 1, 0) ///< -cfguard-no-checks
CODEGENOPT(ControlFlowGuard , 1, 0) ///< -cfguard
CODEGENOPT(CXAAtExit , 1, 1) ///< Use __cxa_atexit for calling destructors.
@@ -48,11 +51,11 @@ CODEGENOPT(UniqueSectionNames, 1, 1) ///< Set for -funique-section-names.
CODEGENOPT(UniqueBasicBlockSectionNames, 1, 1) ///< Set for -funique-basic-block-section-names,
///< Produce unique section names with
///< basic block sections.
+CODEGENOPT(EnableAIXExtendedAltivecABI, 1, 0) ///< Set for -mabi=vec-extabi. Enables the extended Altivec ABI on AIX.
ENUM_CODEGENOPT(FramePointer, FramePointerKind, 2, FramePointerKind::None) /// frame-pointer: all,non-leaf,none
CODEGENOPT(DisableFree , 1, 0) ///< Don't free memory.
CODEGENOPT(DiscardValueNames , 1, 0) ///< Discard Value Names from the IR (LLVMContext flag)
-CODEGENOPT(DisableGCov , 1, 0) ///< Don't run the GCov pass, for testing.
CODEGENOPT(DisableLLVMPasses , 1, 0) ///< Don't run any LLVM IR passes to get
///< the pristine IR generated by the
///< frontend.
@@ -60,8 +63,7 @@ CODEGENOPT(DisableLifetimeMarkers, 1, 0) ///< Don't emit any lifetime markers
CODEGENOPT(DisableO0ImplyOptNone , 1, 0) ///< Don't annonate function with optnone at O0
CODEGENOPT(ExperimentalStrictFloatingPoint, 1, 0) ///< Enables the new, experimental
///< strict floating point.
-CODEGENOPT(ExperimentalNewPassManager, 1, 0) ///< Enables the new, experimental
- ///< pass manager.
+CODEGENOPT(LegacyPassManager, 1, 0) ///< Use the legacy pass manager.
CODEGENOPT(DebugPassManager, 1, 0) ///< Prints debug information for the new
///< pass manager.
CODEGENOPT(DisableRedZone , 1, 0) ///< Set when -mno-red-zone is enabled.
@@ -120,6 +122,12 @@ CODEGENOPT(XRayOmitFunctionIndex , 1, 0)
///< XRay instrumentation.
VALUE_CODEGENOPT(XRayInstructionThreshold , 32, 200)
+///< Only instrument 1 in N functions, by dividing functions into N total groups and
+///< instrumenting only the specified group at a time. Group numbers start at 0
+///< and end at N-1.
+VALUE_CODEGENOPT(XRayTotalFunctionGroups, 32, 1)
+VALUE_CODEGENOPT(XRaySelectedFunctionGroup, 32, 0)
+
VALUE_CODEGENOPT(PatchableFunctionEntryCount , 32, 0) ///< Number of NOPs at function entry
VALUE_CODEGENOPT(PatchableFunctionEntryOffset , 32, 0)
@@ -161,6 +169,7 @@ CODEGENOPT(NoImplicitFloat , 1, 0) ///< Set when -mno-implicit-float is enable
CODEGENOPT(NullPointerIsValid , 1, 0) ///< Assume Null pointer deference is defined.
CODEGENOPT(CorrectlyRoundedDivSqrt, 1, 0) ///< -cl-fp32-correctly-rounded-divide-sqrt
CODEGENOPT(UniqueInternalLinkageNames, 1, 0) ///< Internal Linkage symbols get unique names.
+CODEGENOPT(SplitMachineFunctions, 1, 0) ///< Split machine functions using profile information.
/// When false, this attempts to generate code as if the result of an
/// overflowing conversion matches the overflowing behavior of a target's native
@@ -177,6 +186,7 @@ CODEGENOPT(ObjCConvertMessagesToRuntimeCalls , 1, 1)
VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option specified.
VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is specified.
+CODEGENOPT(AtomicProfileUpdate , 1, 0) ///< Set -fprofile-update=atomic
/// Choose profile instrumenation kind or no instrumentation.
ENUM_CODEGENOPT(ProfileInstr, ProfileInstrKind, 2, ProfileNone)
/// Choose profile kind for PGO use compilation.
@@ -243,7 +253,8 @@ CODEGENOPT(SpeculativeLoadHardening, 1, 0) ///< Enable speculative load hardenin
CODEGENOPT(FineGrainedBitfieldAccesses, 1, 0) ///< Enable fine-grained bitfield accesses.
CODEGENOPT(StrictEnums , 1, 0) ///< Optimize based on strict enum definition.
CODEGENOPT(StrictVTablePointers, 1, 0) ///< Optimize based on the strict vtable pointers
-CODEGENOPT(TimePasses , 1, 0) ///< Set when -ftime-report is enabled.
+CODEGENOPT(TimePasses , 1, 0) ///< Set when -ftime-report or -ftime-report= is enabled.
+CODEGENOPT(TimePassesPerRun , 1, 0) ///< Set when -ftime-report=per-pass-run is enabled.
CODEGENOPT(TimeTrace , 1, 0) ///< Set when -ftime-trace is enabled.
VALUE_CODEGENOPT(TimeTraceGranularity, 32, 500) ///< Minimum time granularity (in microseconds),
///< traced by time profiler
@@ -255,6 +266,9 @@ CODEGENOPT(VectorizeLoop , 1, 0) ///< Run loop vectorizer.
CODEGENOPT(VectorizeSLP , 1, 0) ///< Run SLP vectorizer.
CODEGENOPT(ProfileSampleAccurate, 1, 0) ///< Sample profile is accurate.
+/// Treat loops as finite: language, always, never.
+ENUM_CODEGENOPT(FiniteLoops, FiniteLoopsKind, 2, FiniteLoopsKind::Language)
+
/// Attempt to use register sized accesses to bit-fields in structures, when
/// possible.
CODEGENOPT(UseRegisterSizedBitfieldAccess , 1, 0)
@@ -288,7 +302,6 @@ CODEGENOPT(DebugFwdTemplateParams, 1, 0) ///< Whether to emit complete
///< template parameter descriptions in
///< forward declarations (versus just
///< including them in the name).
-
CODEGENOPT(EmitLLVMUseLists, 1, 0) ///< Control whether to serialize use-lists.
CODEGENOPT(WholeProgramVTables, 1, 0) ///< Whether to apply whole-program
@@ -313,7 +326,7 @@ VALUE_CODEGENOPT(SmallDataLimit, 32, 0)
VALUE_CODEGENOPT(SSPBufferSize, 32, 0)
/// The kind of generated debug info.
-ENUM_CODEGENOPT(DebugInfo, codegenoptions::DebugInfoKind, 3, codegenoptions::NoDebugInfo)
+ENUM_CODEGENOPT(DebugInfo, codegenoptions::DebugInfoKind, 4, codegenoptions::NoDebugInfo)
/// Whether to generate macro debug info.
CODEGENOPT(MacroDebugInfo, 1, 0)
@@ -326,6 +339,9 @@ ENUM_CODEGENOPT(DebuggerTuning, llvm::DebuggerKind, 2,
/// emitted.
VALUE_CODEGENOPT(DwarfVersion, 3, 0)
+/// Whether to use experimental new variable location tracking.
+CODEGENOPT(ValueTrackingVariableLocations, 1, 0)
+
/// Whether we should emit CodeView debug information. It's possible to emit
/// CodeView and DWARF into the same object.
CODEGENOPT(EmitCodeView, 1, 0)
@@ -337,7 +353,7 @@ CODEGENOPT(CodeViewGHash, 1, 0)
ENUM_CODEGENOPT(Inlining, InliningMethod, 2, NormalInlining)
// Vector functions library to use.
-ENUM_CODEGENOPT(VecLib, VectorLibrary, 2, NoLibrary)
+ENUM_CODEGENOPT(VecLib, VectorLibrary, 3, NoLibrary)
/// The default TLS model to use.
ENUM_CODEGENOPT(DefaultTLSModel, TLSModel, 2, GeneralDynamicTLSModel)
@@ -345,6 +361,9 @@ ENUM_CODEGENOPT(DefaultTLSModel, TLSModel, 2, GeneralDynamicTLSModel)
/// Bit size of immediate TLS offsets (0 == use the default).
VALUE_CODEGENOPT(TLSSize, 8, 0)
+/// The default stack protector guard offset to use.
+VALUE_CODEGENOPT(StackProtectorGuardOffset, 32, (unsigned)-1)
+
/// Number of path components to strip when emitting checks. (0 == full
/// filename)
VALUE_CODEGENOPT(EmitCheckPathComponentsToStrip, 32, 0)
@@ -352,12 +371,8 @@ VALUE_CODEGENOPT(EmitCheckPathComponentsToStrip, 32, 0)
/// Whether to report the hotness of the code region for optimization remarks.
CODEGENOPT(DiagnosticsWithHotness, 1, 0)
-/// The minimum hotness value a diagnostic needs in order to be included in
-/// optimization diagnostics.
-VALUE_CODEGENOPT(DiagnosticsHotnessThreshold, 32, 0)
-
-/// Whether copy relocations support is available when building as PIE.
-CODEGENOPT(PIECopyRelocations, 1, 0)
+/// Whether to use direct access relocations (instead of GOT) to reference external data symbols.
+CODEGENOPT(DirectAccessExternalData, 1, 0)
/// Whether we should use the undefined behaviour optimization for control flow
/// paths that reach the end of a function without executing a required return.
@@ -366,6 +381,9 @@ CODEGENOPT(StrictReturn, 1, 1)
/// Whether emit extra debug info for sample pgo profile collection.
CODEGENOPT(DebugInfoForProfiling, 1, 0)
+/// Whether emit pseudo probes for sample pgo profile collection.
+CODEGENOPT(PseudoProbeForProfiling, 1, 0)
+
/// Whether 3-component vector type is preserved.
CODEGENOPT(PreserveVec3Type, 1, 0)
@@ -389,9 +407,16 @@ CODEGENOPT(Addrsig, 1, 0)
/// Whether to emit unused static constants.
CODEGENOPT(KeepStaticConsts, 1, 0)
-/// Whether to not follow the AAPCS that enforce at least one read before storing to a volatile bitfield
+/// Whether to follow the AAPCS enforcing at least one read before storing to a volatile bitfield
CODEGENOPT(ForceAAPCSBitfieldLoad, 1, 0)
+/// Assume that by-value parameters do not alias any other values.
+CODEGENOPT(PassByValueIsNoAlias, 1, 0)
+
+/// Whether to not follow the AAPCS that enforces volatile bit-field access width to be
+/// according to the field declaring type width.
+CODEGENOPT(AAPCSBitfieldWidth, 1, 1)
+
#undef CODEGENOPT
#undef ENUM_CODEGENOPT
#undef VALUE_CODEGENOPT
diff --git a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h
index 83c4463c3639..c550817f0f69 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h
@@ -30,6 +30,8 @@ namespace clang {
/// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
/// that this large collection of bitfields is a trivial class type.
class CodeGenOptionsBase {
+ friend class CompilerInvocation;
+
public:
#define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
#define ENUM_CODEGENOPT(Name, Type, Bits, Default)
@@ -54,11 +56,11 @@ public:
enum VectorLibrary {
NoLibrary, // Don't use any vector library.
Accelerate, // Use the Accelerate framework.
+ LIBMVEC, // GLIBC vector math library.
MASSV, // IBM MASS vector library.
SVML // Intel short vector math library.
};
-
enum ObjCDispatchMethodKind {
Legacy = 0,
NonLegacy = 1,
@@ -126,12 +128,24 @@ public:
// "none": Disable sections/labels for basic blocks.
std::string BBSections;
+ // If set, override the default value of MCAsmInfo::BinutilsVersion. If
+ // DisableIntegratedAS is specified, the assembly output will consider GNU as
+ // support. "none" means that all ELF features can be used, regardless of
+ // binutils support.
+ std::string BinutilsVersion;
+
enum class FramePointerKind {
None, // Omit all frame pointers.
NonLeaf, // Keep non-leaf frame pointers.
All, // Keep all frame pointers.
};
+ enum FiniteLoopsKind {
+ Language, // Not specified, use language standard.
+ Always, // All loops are assumed to be finite.
+ Never, // No loop is assumed to be finite.
+ };
+
/// The code model to use (-mcmodel).
std::string CodeModel;
@@ -167,6 +181,7 @@ public:
std::string RecordCommandLine;
std::map<std::string, std::string> DebugPrefixMap;
+ std::map<std::string, std::string> ProfilePrefixMap;
/// The ABI to use for passing floating point arguments.
std::string FloatABI;
@@ -211,9 +226,6 @@ public:
/// The name of the relocation model to use.
llvm::Reloc::Model RelocationModel;
- /// The thread model to use
- std::string ThreadModel;
-
/// If not an empty string, trap intrinsics are lowered to calls to this
/// function instead of to trap instructions.
std::string TrapFuncName;
@@ -231,6 +243,9 @@ public:
/// Name of the profile file to use with -fprofile-sample-use.
std::string SampleProfileFile;
+ /// Name of the profile file to use as output for with -fmemory-profile.
+ std::string MemoryProfileOutput;
+
/// Name of the profile file to use as input for -fprofile-instr-use
std::string ProfileInstrumentUsePath;
@@ -327,6 +342,15 @@ public:
/// by sanitizer coverage pass.
std::vector<std::string> SanitizeCoverageAllowlistFiles;
+ /// The guard style used for stack protector to get a initial value, this
+ /// value usually be gotten from TLS or get from __stack_chk_guard, or some
+ /// other styles we may implement in the future.
+ std::string StackProtectorGuard;
+
+ /// The TLS base register when StackProtectorGuard is "tls".
+ /// On x86 this can be "fs" or "gs".
+ std::string StackProtectorGuardReg;
+
/// Path to blocklist file specifying which objects
/// (files, functions) listed for instrumentation by sanitizer
/// coverage pass should actually not be instrumented.
@@ -337,6 +361,21 @@ public:
const char *Argv0 = nullptr;
ArrayRef<const char *> CommandLineArgs;
+ /// The minimum hotness value a diagnostic needs in order to be included in
+ /// optimization diagnostics.
+ ///
+ /// The threshold is an Optional value, which maps to one of the 3 states:
+ /// 1. 0 => threshold disabled. All remarks will be printed.
+ /// 2. positive int => manual threshold by user. Remarks with hotness exceed
+ /// threshold will be printed.
+ /// 3. None => 'auto' threshold by user. The actual value is not
+ /// available at command line, but will be synced with
+ /// hotness threshold from profile summary during
+ /// compilation.
+ ///
+ /// If threshold option is not specified, it is disabled by default.
+ Optional<uint64_t> DiagnosticsHotnessThreshold = 0;
+
public:
// Define accessors/mutators for code generation options of enumeration type.
#define CODEGENOPT(Name, Bits, Default)
@@ -388,6 +427,11 @@ public:
bool hasReducedDebugInfo() const {
return getDebugInfo() >= codegenoptions::DebugInfoConstructor;
}
+
+ /// Check if maybe unused type info should be emitted.
+ bool hasMaybeUnusedDebugInfo() const {
+ return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
+ }
};
} // end namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Cuda.h b/contrib/llvm-project/clang/include/clang/Basic/Cuda.h
index 1716325a9931..b3a2e99fe931 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Cuda.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/Cuda.h
@@ -37,6 +37,7 @@ const char *CudaVersionToString(CudaVersion V);
CudaVersion CudaStringToVersion(const llvm::Twine &S);
enum class CudaArch {
+ UNUSED,
UNKNOWN,
SM_20,
SM_21,
@@ -56,14 +57,17 @@ enum class CudaArch {
SM_80,
GFX600,
GFX601,
+ GFX602,
GFX700,
GFX701,
GFX702,
GFX703,
GFX704,
+ GFX705,
GFX801,
GFX802,
GFX803,
+ GFX805,
GFX810,
GFX900,
GFX902,
@@ -71,10 +75,14 @@ enum class CudaArch {
GFX906,
GFX908,
GFX909,
+ GFX90c,
GFX1010,
GFX1011,
GFX1012,
GFX1030,
+ GFX1031,
+ GFX1032,
+ GFX1033,
LAST,
};
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h b/contrib/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h
index 586168bd015f..7f5669c1760f 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h
@@ -46,7 +46,11 @@ enum DebugInfoKind {
LimitedDebugInfo,
/// Generate complete debug info.
- FullDebugInfo
+ FullDebugInfo,
+
+ /// Generate debug info for types that may be unused in the source
+ /// (-fno-eliminate-unused-debug-types).
+ UnusedTypeInfo,
};
} // end namespace codegenoptions
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DeclNodes.td b/contrib/llvm-project/clang/include/clang/Basic/DeclNodes.td
index 866988ee3f01..4771a3549426 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DeclNodes.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DeclNodes.td
@@ -41,6 +41,7 @@ def Named : DeclNode<Decl, "named declarations", 1>;
def OMPDeclareReduction : DeclNode<Value>, DeclContext;
def OMPDeclareMapper : DeclNode<Value>, DeclContext;
def MSGuid : DeclNode<Value>;
+ def TemplateParamObject : DeclNode<Value>;
def Declarator : DeclNode<Value, "declarators", 1>;
def Field : DeclNode<Declarator, "non-static data members">;
def ObjCIvar : DeclNode<Field>;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.h b/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.h
index 304207779c0f..3499c551cfdf 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.h
@@ -144,6 +144,44 @@ public:
}
};
+struct DiagnosticStorage {
+ enum {
+ /// The maximum number of arguments we can hold. We
+ /// currently only support up to 10 arguments (%0-%9).
+ ///
+ /// A single diagnostic with more than that almost certainly has to
+ /// be simplified anyway.
+ MaxArguments = 10
+ };
+
+ /// The number of entries in Arguments.
+ unsigned char NumDiagArgs = 0;
+
+ /// Specifies for each argument whether it is in DiagArgumentsStr
+ /// or in DiagArguments.
+ unsigned char DiagArgumentsKind[MaxArguments];
+
+ /// The values for the various substitution positions.
+ ///
+ /// This is used when the argument is not an std::string. The specific value
+ /// is mangled into an intptr_t and the interpretation depends on exactly
+ /// what sort of argument kind it is.
+ intptr_t DiagArgumentsVal[MaxArguments];
+
+ /// The values for the various substitution positions that have
+ /// string arguments.
+ std::string DiagArgumentsStr[MaxArguments];
+
+ /// The list of ranges added to this diagnostic.
+ SmallVector<CharSourceRange, 8> DiagRanges;
+
+ /// If valid, provides a hint with some code to insert, remove, or
+ /// modify at a particular position.
+ SmallVector<FixItHint, 6> FixItHints;
+
+ DiagnosticStorage() = default;
+};
+
/// Concrete class used by the front-end to report problems and issues.
///
/// This massages the diagnostics (e.g. handling things like "report warnings
@@ -928,38 +966,10 @@ private:
/// We currently only support up to 10 arguments (%0-%9). A single
/// diagnostic with more than that almost certainly has to be simplified
/// anyway.
- MaxArguments = 10,
+ MaxArguments = DiagnosticStorage::MaxArguments,
};
- /// The number of entries in Arguments.
- signed char NumDiagArgs;
-
- /// Specifies whether an argument is in DiagArgumentsStr or
- /// in DiagArguments.
- ///
- /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
- /// argument.
- unsigned char DiagArgumentsKind[MaxArguments];
-
- /// Holds the values of each string argument for the current
- /// diagnostic.
- ///
- /// This is only used when the corresponding ArgumentKind is ak_std_string.
- std::string DiagArgumentsStr[MaxArguments];
-
- /// The values for the various substitution positions.
- ///
- /// This is used when the argument is not an std::string. The specific
- /// value is mangled into an intptr_t and the interpretation depends on
- /// exactly what sort of argument kind it is.
- intptr_t DiagArgumentsVal[MaxArguments];
-
- /// The list of ranges added to this diagnostic.
- SmallVector<CharSourceRange, 8> DiagRanges;
-
- /// If valid, provides a hint with some code to insert, remove,
- /// or modify at a particular position.
- SmallVector<FixItHint, 8> DiagFixItHints;
+ DiagnosticStorage DiagStorage;
DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
bool isPragma = L.isValid();
@@ -1043,6 +1053,156 @@ public:
}
};
+/// The streaming interface shared between DiagnosticBuilder and
+/// PartialDiagnostic. This class is not intended to be constructed directly
+/// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
+///
+/// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
+/// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
+///
+/// const StreamingDiagnostic&
+/// operator<<(const StreamingDiagnostic&, NewArgType);
+///
+class StreamingDiagnostic {
+public:
+ /// An allocator for DiagnosticStorage objects, which uses a small cache to
+ /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
+ class DiagStorageAllocator {
+ static const unsigned NumCached = 16;
+ DiagnosticStorage Cached[NumCached];
+ DiagnosticStorage *FreeList[NumCached];
+ unsigned NumFreeListEntries;
+
+ public:
+ DiagStorageAllocator();
+ ~DiagStorageAllocator();
+
+ /// Allocate new storage.
+ DiagnosticStorage *Allocate() {
+ if (NumFreeListEntries == 0)
+ return new DiagnosticStorage;
+
+ DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
+ Result->NumDiagArgs = 0;
+ Result->DiagRanges.clear();
+ Result->FixItHints.clear();
+ return Result;
+ }
+
+ /// Free the given storage object.
+ void Deallocate(DiagnosticStorage *S) {
+ if (S >= Cached && S <= Cached + NumCached) {
+ FreeList[NumFreeListEntries++] = S;
+ return;
+ }
+
+ delete S;
+ }
+ };
+
+protected:
+ mutable DiagnosticStorage *DiagStorage = nullptr;
+
+ /// Allocator used to allocate storage for this diagnostic.
+ DiagStorageAllocator *Allocator = nullptr;
+
+public:
+ /// Retrieve storage for this particular diagnostic.
+ DiagnosticStorage *getStorage() const {
+ if (DiagStorage)
+ return DiagStorage;
+
+ assert(Allocator);
+ DiagStorage = Allocator->Allocate();
+ return DiagStorage;
+ }
+
+ void freeStorage() {
+ if (!DiagStorage)
+ return;
+
+ // The hot path for PartialDiagnostic is when we just used it to wrap an ID
+ // (typically so we have the flexibility of passing a more complex
+ // diagnostic into the callee, but that does not commonly occur).
+ //
+ // Split this out into a slow function for silly compilers (*cough*) which
+ // can't do decent partial inlining.
+ freeStorageSlow();
+ }
+
+ void freeStorageSlow() {
+ if (!Allocator)
+ return;
+ Allocator->Deallocate(DiagStorage);
+ DiagStorage = nullptr;
+ }
+
+ void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
+ if (!DiagStorage)
+ DiagStorage = getStorage();
+
+ assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
+ "Too many arguments to diagnostic!");
+ DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
+ DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
+ }
+
+ void AddString(StringRef V) const {
+ if (!DiagStorage)
+ DiagStorage = getStorage();
+
+ assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
+ "Too many arguments to diagnostic!");
+ DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
+ DiagnosticsEngine::ak_std_string;
+ DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
+ }
+
+ void AddSourceRange(const CharSourceRange &R) const {
+ if (!DiagStorage)
+ DiagStorage = getStorage();
+
+ DiagStorage->DiagRanges.push_back(R);
+ }
+
+ void AddFixItHint(const FixItHint &Hint) const {
+ if (Hint.isNull())
+ return;
+
+ if (!DiagStorage)
+ DiagStorage = getStorage();
+
+ DiagStorage->FixItHints.push_back(Hint);
+ }
+
+ /// Conversion of StreamingDiagnostic to bool always returns \c true.
+ ///
+ /// This allows is to be used in boolean error contexts (where \c true is
+ /// used to indicate that an error has occurred), like:
+ /// \code
+ /// return Diag(...);
+ /// \endcode
+ operator bool() const { return true; }
+
+protected:
+ StreamingDiagnostic() = default;
+
+ /// Construct with an external storage not owned by itself. The allocator
+ /// is a null pointer in this case.
+ explicit StreamingDiagnostic(DiagnosticStorage *Storage)
+ : DiagStorage(Storage) {}
+
+ /// Construct with a storage allocator which will manage the storage. The
+ /// allocator is not a null pointer in this case.
+ explicit StreamingDiagnostic(DiagStorageAllocator &Alloc)
+ : Allocator(&Alloc) {}
+
+ StreamingDiagnostic(const StreamingDiagnostic &Diag) = default;
+ StreamingDiagnostic(StreamingDiagnostic &&Diag) = default;
+
+ ~StreamingDiagnostic() { freeStorage(); }
+};
+
//===----------------------------------------------------------------------===//
// DiagnosticBuilder
//===----------------------------------------------------------------------===//
@@ -1059,12 +1219,11 @@ public:
/// This ensures that compilers with somewhat reasonable optimizers will promote
/// the common fields to registers, eliminating increments of the NumArgs field,
/// for example.
-class DiagnosticBuilder {
+class DiagnosticBuilder : public StreamingDiagnostic {
friend class DiagnosticsEngine;
friend class PartialDiagnostic;
mutable DiagnosticsEngine *DiagObj = nullptr;
- mutable unsigned NumArgs = 0;
/// Status variable indicating if this diagnostic is still active.
///
@@ -1080,17 +1239,17 @@ class DiagnosticBuilder {
DiagnosticBuilder() = default;
explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
- : DiagObj(diagObj), IsActive(true) {
+ : StreamingDiagnostic(&diagObj->DiagStorage), DiagObj(diagObj),
+ IsActive(true) {
assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
- diagObj->DiagRanges.clear();
- diagObj->DiagFixItHints.clear();
+ assert(DiagStorage &&
+ "DiagnosticBuilder requires a valid DiagnosticStorage!");
+ DiagStorage->NumDiagArgs = 0;
+ DiagStorage->DiagRanges.clear();
+ DiagStorage->FixItHints.clear();
}
protected:
- void FlushCounts() {
- DiagObj->NumDiagArgs = NumArgs;
- }
-
/// Clear out the current diagnostic.
void Clear() const {
DiagObj = nullptr;
@@ -1113,10 +1272,6 @@ protected:
// (or by a subclass, as in SemaDiagnosticBuilder).
if (!isActive()) return false;
- // When emitting diagnostics, we set the final argument count into
- // the DiagnosticsEngine object.
- FlushCounts();
-
// Process the diagnostic.
bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
@@ -1129,61 +1284,42 @@ protected:
public:
/// Copy constructor. When copied, this "takes" the diagnostic info from the
/// input and neuters it.
- DiagnosticBuilder(const DiagnosticBuilder &D) {
+ DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
DiagObj = D.DiagObj;
+ DiagStorage = D.DiagStorage;
IsActive = D.IsActive;
IsForceEmit = D.IsForceEmit;
D.Clear();
- NumArgs = D.NumArgs;
}
- DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
-
- /// Emits the diagnostic.
- ~DiagnosticBuilder() {
- Emit();
- }
-
- /// Forces the diagnostic to be emitted.
- const DiagnosticBuilder &setForceEmit() const {
- IsForceEmit = true;
+ template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
+ assert(isActive() && "Clients must not add to cleared diagnostic!");
+ const StreamingDiagnostic &DB = *this;
+ DB << V;
return *this;
}
- /// Conversion of DiagnosticBuilder to bool always returns \c true.
- ///
- /// This allows is to be used in boolean error contexts (where \c true is
- /// used to indicate that an error has occurred), like:
- /// \code
- /// return Diag(...);
- /// \endcode
- operator bool() const { return true; }
-
- void AddString(StringRef S) const {
+ // It is necessary to limit this to rvalue reference to avoid calling this
+ // function with a bitfield lvalue argument since non-const reference to
+ // bitfield is not allowed.
+ template <typename T, typename = typename std::enable_if<
+ !std::is_lvalue_reference<T>::value>::type>
+ const DiagnosticBuilder &operator<<(T &&V) const {
assert(isActive() && "Clients must not add to cleared diagnostic!");
- assert(NumArgs < DiagnosticsEngine::MaxArguments &&
- "Too many arguments to diagnostic!");
- DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
- DiagObj->DiagArgumentsStr[NumArgs++] = std::string(S);
+ const StreamingDiagnostic &DB = *this;
+ DB << std::move(V);
+ return *this;
}
- void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
- assert(isActive() && "Clients must not add to cleared diagnostic!");
- assert(NumArgs < DiagnosticsEngine::MaxArguments &&
- "Too many arguments to diagnostic!");
- DiagObj->DiagArgumentsKind[NumArgs] = Kind;
- DiagObj->DiagArgumentsVal[NumArgs++] = V;
- }
+ DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
- void AddSourceRange(const CharSourceRange &R) const {
- assert(isActive() && "Clients must not add to cleared diagnostic!");
- DiagObj->DiagRanges.push_back(R);
- }
+ /// Emits the diagnostic.
+ ~DiagnosticBuilder() { Emit(); }
- void AddFixItHint(const FixItHint &Hint) const {
- assert(isActive() && "Clients must not add to cleared diagnostic!");
- if (!Hint.isNull())
- DiagObj->DiagFixItHints.push_back(Hint);
+ /// Forces the diagnostic to be emitted.
+ const DiagnosticBuilder &setForceEmit() const {
+ IsForceEmit = true;
+ return *this;
}
void addFlagValue(StringRef V) const { DiagObj->FlagValue = std::string(V); }
@@ -1205,20 +1341,21 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- StringRef S) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ StringRef S) {
DB.AddString(S);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const char *Str) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const char *Str) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
DiagnosticsEngine::ak_c_string);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ int I) {
DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
return DB;
}
@@ -1226,26 +1363,27 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
// We use enable_if here to prevent that this overload is selected for
// pointers or other arguments that are implicitly convertible to bool.
template <typename T>
-inline std::enable_if_t<std::is_same<T, bool>::value, const DiagnosticBuilder &>
-operator<<(const DiagnosticBuilder &DB, T I) {
+inline std::enable_if_t<std::is_same<T, bool>::value,
+ const StreamingDiagnostic &>
+operator<<(const StreamingDiagnostic &DB, T I) {
DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- unsigned I) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ unsigned I) {
DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- tok::TokenKind I) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ tok::TokenKind I) {
DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const IdentifierInfo *II) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const IdentifierInfo *II) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
DiagnosticsEngine::ak_identifierinfo);
return DB;
@@ -1258,63 +1396,64 @@ inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
template <typename T>
inline std::enable_if_t<
std::is_same<std::remove_const_t<T>, DeclContext>::value,
- const DiagnosticBuilder &>
-operator<<(const DiagnosticBuilder &DB, T *DC) {
+ const StreamingDiagnostic &>
+operator<<(const StreamingDiagnostic &DB, T *DC) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
DiagnosticsEngine::ak_declcontext);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- SourceRange R) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ SourceRange R) {
DB.AddSourceRange(CharSourceRange::getTokenRange(R));
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- ArrayRef<SourceRange> Ranges) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ ArrayRef<SourceRange> Ranges) {
for (SourceRange R : Ranges)
DB.AddSourceRange(CharSourceRange::getTokenRange(R));
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const CharSourceRange &R) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const CharSourceRange &R) {
DB.AddSourceRange(R);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const FixItHint &Hint) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const FixItHint &Hint) {
DB.AddFixItHint(Hint);
return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- ArrayRef<FixItHint> Hints) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ ArrayRef<FixItHint> Hints) {
for (const FixItHint &Hint : Hints)
DB.AddFixItHint(Hint);
return DB;
}
-inline const DiagnosticBuilder &
-operator<<(const DiagnosticBuilder &DB,
+inline const StreamingDiagnostic &
+operator<<(const StreamingDiagnostic &DB,
const llvm::Optional<SourceRange> &Opt) {
if (Opt)
DB << *Opt;
return DB;
}
-inline const DiagnosticBuilder &
-operator<<(const DiagnosticBuilder &DB,
+inline const StreamingDiagnostic &
+operator<<(const StreamingDiagnostic &DB,
const llvm::Optional<CharSourceRange> &Opt) {
if (Opt)
DB << *Opt;
return DB;
}
-inline const DiagnosticBuilder &
-operator<<(const DiagnosticBuilder &DB, const llvm::Optional<FixItHint> &Opt) {
+inline const StreamingDiagnostic &
+operator<<(const StreamingDiagnostic &DB,
+ const llvm::Optional<FixItHint> &Opt) {
if (Opt)
DB << *Opt;
return DB;
@@ -1324,8 +1463,8 @@ operator<<(const DiagnosticBuilder &DB, const llvm::Optional<FixItHint> &Opt) {
/// context-sensitive keyword.
using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- DiagNullabilityKind nullability);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ DiagNullabilityKind nullability);
inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
unsigned DiagID) {
@@ -1337,8 +1476,8 @@ inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
return DiagnosticBuilder(this);
}
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- llvm::Error &&E);
+const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ llvm::Error &&E);
inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
return Report(SourceLocation(), DiagID);
@@ -1366,7 +1505,7 @@ public:
bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
- unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
+ unsigned getNumArgs() const { return DiagObj->DiagStorage.NumDiagArgs; }
/// Return the kind of the specified index.
///
@@ -1376,7 +1515,8 @@ public:
/// \pre Idx < getNumArgs()
DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
assert(Idx < getNumArgs() && "Argument index out of range!");
- return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
+ return (DiagnosticsEngine::ArgumentKind)
+ DiagObj->DiagStorage.DiagArgumentsKind[Idx];
}
/// Return the provided argument string specified by \p Idx.
@@ -1384,7 +1524,7 @@ public:
const std::string &getArgStdStr(unsigned Idx) const {
assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!");
- return DiagObj->DiagArgumentsStr[Idx];
+ return DiagObj->DiagStorage.DiagArgumentsStr[Idx];
}
/// Return the specified C string argument.
@@ -1392,7 +1532,8 @@ public:
const char *getArgCStr(unsigned Idx) const {
assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
"invalid argument accessor!");
- return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
+ return reinterpret_cast<const char *>(
+ DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
}
/// Return the specified signed integer argument.
@@ -1400,7 +1541,7 @@ public:
int getArgSInt(unsigned Idx) const {
assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
"invalid argument accessor!");
- return (int)DiagObj->DiagArgumentsVal[Idx];
+ return (int)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
}
/// Return the specified unsigned integer argument.
@@ -1408,7 +1549,7 @@ public:
unsigned getArgUInt(unsigned Idx) const {
assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
"invalid argument accessor!");
- return (unsigned)DiagObj->DiagArgumentsVal[Idx];
+ return (unsigned)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
}
/// Return the specified IdentifierInfo argument.
@@ -1416,7 +1557,8 @@ public:
const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
"invalid argument accessor!");
- return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
+ return reinterpret_cast<IdentifierInfo *>(
+ DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
}
/// Return the specified non-string argument in an opaque form.
@@ -1424,36 +1566,36 @@ public:
intptr_t getRawArg(unsigned Idx) const {
assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!");
- return DiagObj->DiagArgumentsVal[Idx];
+ return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
}
/// Return the number of source ranges associated with this diagnostic.
unsigned getNumRanges() const {
- return DiagObj->DiagRanges.size();
+ return DiagObj->DiagStorage.DiagRanges.size();
}
/// \pre Idx < getNumRanges()
const CharSourceRange &getRange(unsigned Idx) const {
assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
- return DiagObj->DiagRanges[Idx];
+ return DiagObj->DiagStorage.DiagRanges[Idx];
}
/// Return an array reference for this diagnostic's ranges.
ArrayRef<CharSourceRange> getRanges() const {
- return DiagObj->DiagRanges;
+ return DiagObj->DiagStorage.DiagRanges;
}
unsigned getNumFixItHints() const {
- return DiagObj->DiagFixItHints.size();
+ return DiagObj->DiagStorage.FixItHints.size();
}
const FixItHint &getFixItHint(unsigned Idx) const {
assert(Idx < getNumFixItHints() && "Invalid index!");
- return DiagObj->DiagFixItHints[Idx];
+ return DiagObj->DiagStorage.FixItHints[Idx];
}
ArrayRef<FixItHint> getFixItHints() const {
- return DiagObj->DiagFixItHints;
+ return DiagObj->DiagStorage.FixItHints;
}
/// Format this diagnostic into a string, substituting the
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.td b/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.td
index 48ba8c0f469f..ab2c738a2ace 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/Diagnostic.td
@@ -45,6 +45,7 @@ class TextSubstitution<string Text> {
// diagnostics
string Component = "";
string CategoryName = "";
+ bit Deferrable = 0;
}
// Diagnostic Categories. These can be applied to groups or individual
@@ -83,6 +84,7 @@ class Diagnostic<string text, DiagClass DC, Severity defaultmapping> {
bit AccessControl = 0;
bit WarningNoWerror = 0;
bit ShowInSystemHeader = 0;
+ bit Deferrable = 0;
Severity DefaultSeverity = defaultmapping;
DiagGroup Group;
string CategoryName = "";
@@ -106,6 +108,14 @@ class SuppressInSystemHeader {
bit ShowInSystemHeader = 0;
}
+class Deferrable {
+ bit Deferrable = 1;
+}
+
+class NonDeferrable {
+ bit Deferrable = 0;
+}
+
// FIXME: ExtWarn and Extension should also be SFINAEFailure by default.
class Error<string str> : Diagnostic<str, CLASS_ERROR, SEV_Error>, SFINAEFailure {
bit ShowInSystemHeader = 1;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAST.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAST.h
index afe5f62e2012..76c31ad9508e 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAST.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAST.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define ASTSTART
#include "clang/Basic/DiagnosticASTKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td
index 10bedaaf7aba..f6b936f5ccd9 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -54,6 +54,9 @@ def note_constexpr_nonliteral : Note<
def note_constexpr_non_global : Note<
"%select{pointer|reference}0 to %select{|subobject of }1"
"%select{temporary|%3}2 is not a constant expression">;
+def note_constexpr_not_static : Note<
+ "address of non-static constexpr variable %0 may differ on each invocation "
+ "of the enclosing function; add 'static' to give it a constant address">;
def note_constexpr_dynamic_alloc : Note<
"%select{pointer|reference}0 to %select{|subobject of }1"
"heap-allocated object is not a constant expression">;
@@ -69,6 +72,10 @@ def note_constexpr_array_index : Note<"cannot refer to element %0 of "
"in a constant expression">;
def note_constexpr_float_arithmetic : Note<
"floating point arithmetic produces %select{an infinity|a NaN}0">;
+def note_constexpr_dynamic_rounding : Note<
+ "cannot evaluate this expression if rounding mode is dynamic">;
+def note_constexpr_float_arithmetic_strict : Note<
+ "compile time floating point arithmetic suppressed in strict evaluation modes">;
def note_constexpr_pointer_subtraction_not_same_array : Note<
"subtracted pointers are not elements of the same array">;
def note_constexpr_pointer_subtraction_zero_size : Note<
@@ -247,7 +254,7 @@ def note_constexpr_destroy_out_of_lifetime : Note<
"destroying object '%0' whose lifetime has already ended">;
def note_constexpr_unsupported_destruction : Note<
"non-trivial destruction of type %0 in a constant expression is not supported">;
-def note_constexpr_unsupported_tempoarary_nontrivial_dtor : Note<
+def note_constexpr_unsupported_temporary_nontrivial_dtor : Note<
"non-trivial destruction of lifetime-extended temporary with type %0 "
"used in the result of a constant expression is not yet supported">;
def note_constexpr_unsupported_unsized_array : Note<
@@ -295,6 +302,8 @@ def note_constexpr_bit_cast_invalid_subtype : Note<
def note_constexpr_bit_cast_indet_dest : Note<
"indeterminate value can only initialize an object of type 'unsigned char'"
"%select{, 'char',|}1 or 'std::byte'; %0 is invalid">;
+def note_constexpr_bit_cast_unrepresentable_value : Note<
+ "value %1 cannot be represented in type %0">;
def note_constexpr_pseudo_destructor : Note<
"pseudo-destructor call is not permitted in constant expressions "
"until C++20">;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h
index eea35a4d616e..f9037cc8d75a 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define ANALYSISSTART
#include "clang/Basic/DiagnosticAnalysisKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticComment.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticComment.h
index a87bafa8b3a5..6e011bfcebab 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticComment.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticComment.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define COMMENTSTART
#include "clang/Basic/DiagnosticCommentKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 65e3755efd22..a4f96a97991e 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -234,6 +234,12 @@ def err_seh___finally_block : Error<
// Sema && AST
def note_invalid_subexpr_in_const_expr : Note<
"subexpression not valid in a constant expression">;
+def note_constexpr_invalid_template_arg : Note<
+ "%select{pointer|reference}0 to %select{|subobject of }1"
+ "%select{type_info object|string literal|temporary object|"
+ "predefined '%3' variable}2 is not allowed in a template argument">;
+def err_constexpr_invalid_template_arg : Error<
+ note_constexpr_invalid_template_arg.Text>;
// Sema && Frontend
let CategoryName = "Inline Assembly Issue" in {
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h
index c1c582bd6ee4..ded85ec3f840 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define CROSSTUSTART
#include "clang/Basic/DiagnosticCrossTUKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h
index 63913df4523b..cecd8fd6b4d5 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define DRIVERSTART
#include "clang/Basic/DiagnosticDriverKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td
index acdad15cdf6c..ad13f923fb63 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -44,6 +44,10 @@ def warn_drv_avr_libc_not_found: Warning<
def warn_drv_avr_family_linking_stdlibs_not_implemented: Warning<
"support for linking stdlibs for microcontroller '%0' is not implemented">,
InGroup<AVRRtlibLinkingQuirks>;
+def warn_drv_avr_linker_section_addresses_not_implemented: Warning<
+ "support for passing the data section address to the linker for "
+ "microcontroller '%0' is not implemented">,
+ InGroup<AVRRtlibLinkingQuirks>;
def warn_drv_avr_stdlib_not_linked: Warning<
"standard library not linked and so no interrupt vector table or "
"compiler runtime routines will be linked">,
@@ -73,12 +77,15 @@ def warn_drv_unknown_cuda_version: Warning<
InGroup<CudaUnknownVersion>;
def err_drv_cuda_host_arch : Error<"unsupported architecture '%0' for host compilation.">;
def err_drv_mix_cuda_hip : Error<"Mixed Cuda and HIP compilation is not supported.">;
+def err_drv_bad_target_id : Error<"Invalid target ID: %0 (A target ID is a processor name "
+ "followed by an optional list of predefined features post-fixed by a plus or minus sign deliminated "
+ "by colon, e.g. 'gfx908:sramecc+:xnack-')">;
+def err_drv_bad_offload_arch_combo : Error<"Invalid offload arch combinations: %0 and %1 (For a specific "
+ "processor, a feature should either exist in all offload archs, or not exist in any offload archs)">;
def err_drv_invalid_thread_model_for_target : Error<
"invalid thread model '%0' in '%1' for this target">;
def err_drv_invalid_linker_name : Error<
"invalid linker name in argument '%0'">;
-def err_drv_invalid_pgo_instrumentor : Error<
- "invalid PGO instrumentor in argument '%0'">;
def err_drv_invalid_rtlib_name : Error<
"invalid runtime library name in argument '%0'">;
def err_drv_unsupported_rtlib_for_platform : Error<
@@ -108,12 +115,12 @@ def err_drv_command_failure : Error<
"unable to execute command: %0">;
def err_drv_invalid_darwin_version : Error<
"invalid Darwin version number: %0">;
+def err_drv_invalid_diagnotics_hotness_threshold : Error<
+ "invalid argument in '%0', only integer or 'auto' is supported">;
def err_drv_missing_argument : Error<
"argument to '%0' is missing (expected %1 value%s1)">;
def err_drv_invalid_Xarch_argument_with_args : Error<
"invalid Xarch argument: '%0', options requiring arguments are unsupported">;
-def err_drv_invalid_Xarch_argument_isdriver : Error<
- "invalid Xarch argument: '%0', cannot change driver behavior inside Xarch argument">;
def err_drv_Xopenmp_target_missing_triple : Error<
"cannot deduce implicit triple value for -Xopenmp-target, specify triple using -Xopenmp-target=<triple>">;
def err_drv_invalid_Xopenmp_target_with_args : Error<
@@ -208,6 +215,7 @@ def err_drv_dllexport_inlines_and_fallback : Error<
def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
+def err_drv_invalid_value_with_suggestion : Error<"invalid value '%1' in '%0','%2'">;
def err_drv_invalid_remap_file : Error<
"invalid option '%0' not of the form <from-file>;<to-file>">;
def err_drv_invalid_gcc_output_type : Error<
@@ -248,18 +256,19 @@ def err_drv_optimization_remark_format : Error<
"unknown remark serializer format: '%0'">;
def err_drv_no_neon_modifier : Error<"[no]neon is not accepted as modifier, please use [no]simd instead">;
def err_drv_invalid_omp_target : Error<"OpenMP target is invalid: '%0'">;
+def err_drv_incompatible_omp_arch : Error<"OpenMP target architecture '%0' pointer size is incompatible with host '%1'">;
def err_drv_omp_host_ir_file_not_found : Error<
"The provided host compiler IR file '%0' is required to generate code for OpenMP target regions but cannot be found.">;
def err_drv_omp_host_target_not_supported : Error<
"The target '%0' is not a supported OpenMP host target.">;
def err_drv_expecting_fopenmp_with_fopenmp_targets : Error<
"The option -fopenmp-targets must be used in conjunction with a -fopenmp option compatible with offloading, please use -fopenmp=libomp or -fopenmp=libiomp5.">;
+def err_drv_omp_offload_target_missingbcruntime : Error<
+ "No library '%0' found in the default clang lib directory or in LIBRARY_PATH. Please use --libomptarget-nvptx-bc-path to specify nvptx bitcode library.">;
+def err_drv_omp_offload_target_bcruntime_not_found : Error<"Bitcode library '%0' does not exist.">;
def warn_drv_omp_offload_target_duplicate : Warning<
"The OpenMP offloading target '%0' is similar to target '%1' already specified - will be ignored.">,
InGroup<OpenMPTarget>;
-def warn_drv_omp_offload_target_missingbcruntime : Warning<
- "No library '%0' found in the default clang lib directory or in LIBRARY_PATH. Expect degraded performance due to no inlining of runtime functions on target devices.">,
- InGroup<OpenMPTarget>;
def err_drv_unsupported_embed_bitcode
: Error<"%0 is not supported with -fembed-bitcode">;
def err_drv_bitcode_unsupported_on_toolchain : Error<
@@ -281,6 +290,9 @@ def warn_drv_unsupported_opt_for_target : Warning<
def warn_drv_unsupported_debug_info_opt_for_target : Warning<
"debug information option '%0' is not supported for target '%1'">,
InGroup<UnsupportedTargetOpt>;
+def warn_drv_dwarf_version_limited_by_target : Warning<
+ "debug information option '%0' is not supported. It needs DWARF-%2 but target '%1' only provides DWARF-%3.">,
+ InGroup<UnsupportedTargetOpt>;
def warn_c_kext : Warning<
"ignoring -fapple-kext which is valid for C++ and Objective-C++ only">;
def warn_ignoring_fdiscard_for_bitcode : Warning<
@@ -336,6 +348,8 @@ def err_invalid_branch_protection: Error <
"invalid branch protection option '%0' in '%1'">;
def err_invalid_sls_hardening : Error<
"invalid sls hardening option '%0' in '%1'">;
+def err_sls_hardening_arm_not_supported : Error<
+ "-mharden-sls is only supported on armv7-a or later">;
def note_drv_command_failed_diag_msg : Note<
"diagnostic msg: %0">;
@@ -458,6 +472,10 @@ def warn_drv_msvc_not_found : Warning<
"try running Clang from a developer command prompt">,
InGroup<DiagGroup<"msvc-not-found">>;
+def warn_drv_fuse_ld_path : Warning<
+ "'-fuse-ld=' taking a path is deprecated. Use '--ld-path=' instead">,
+ InGroup<FUseLdPath>, DefaultIgnore;
+
def warn_drv_fine_grained_bitfield_accesses_ignored : Warning<
"option '-ffine-grained-bitfield-accesses' cannot be enabled together with a sanitizer; flag ignored">,
InGroup<OptionIgnored>;
@@ -478,6 +496,10 @@ def warn_drv_moutline_unsupported_opt : Warning<
"The '%0' architecture does not support -moutline; flag ignored">,
InGroup<OptionIgnored>;
+def warn_drv_moutline_atomics_unsupported_opt : Warning<
+ "The '%0' architecture does not support -moutline-atomics; flag ignored">,
+ InGroup<OptionIgnored>;
+
def warn_drv_darwin_sdk_invalid_settings : Warning<
"SDK settings were ignored as 'SDKSettings.json' could not be parsed">,
InGroup<DiagGroup<"darwin-sdk-settings">>;
@@ -511,4 +533,7 @@ def warn_drv_libstdcxx_not_found : Warning<
def err_drv_cannot_mix_options : Error<"cannot specify '%1' along with '%0'">;
def err_drv_invalid_object_mode : Error<"OBJECT_MODE setting %0 is not recognized and is not a valid setting.">;
+
+def err_aix_default_altivec_abi : Error<
+ "The default Altivec ABI on AIX is not yet supported, use '-mabi=vec-extabi' for the extended Altivec ABI">;
}
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h
index 57f00e73abb4..f57c587fb469 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define FRONTENDSTART
#include "clang/Basic/DiagnosticFrontendKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index b202d2abffa0..b9f8c78e43da 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -108,10 +108,8 @@ def err_fe_action_not_available : Error<
"action %0 not compiled in">;
def err_fe_invalid_alignment : Error<
"invalid value '%1' in '%0'; alignment must be a power of 2">;
-def err_fe_invalid_wchar_type
- : Error<"invalid wchar_t type '%0'; must be one of 'char', 'short', 'int'">;
def err_fe_invalid_exception_model
- : Error<"invalid exception model '%0' for target '%1'">;
+ : Error<"invalid exception model '%select{none|dwarf|sjlj|arm|seh|wasm|aix}0' for target '%1'">;
def warn_fe_concepts_ts_flag : Warning<
"-fconcepts-ts is deprecated - use '-std=c++20' for Concepts support">,
InGroup<Deprecated>;
@@ -270,8 +268,16 @@ def err_ifunc_resolver_return : Error<
"ifunc resolver function must return a pointer">;
def warn_atomic_op_misaligned : Warning<
- "%select{large|misaligned}0 atomic operation may incur "
- "significant performance penalty">, InGroup<DiagGroup<"atomic-alignment">>;
+ "misaligned atomic operation may incur "
+ "significant performance penalty"
+ "; the expected alignment (%0 bytes) exceeds the actual alignment (%1 bytes)">,
+ InGroup<AtomicAlignment>;
+
+def warn_atomic_op_oversized : Warning<
+ "large atomic operation may incur "
+ "significant performance penalty"
+ "; the access size (%0 bytes) exceeds the max lock-free size (%1 bytes)">,
+InGroup<AtomicAlignment>;
def warn_alias_with_section : Warning<
"%select{alias|ifunc}1 will not be in section '%0' but in the same section "
@@ -291,12 +297,6 @@ def warn_profile_data_missing : Warning<
def warn_profile_data_unprofiled : Warning<
"no profile data available for file \"%0\"">,
InGroup<ProfileInstrUnprofiled>;
-def warn_profile_data_misexpect : Warning<
- "Potential performance regression from use of __builtin_expect(): "
- "Annotation was correct on %0 of profiled executions.">,
- BackendInfo,
- InGroup<MisExpect>,
- DefaultIgnore;
} // end of instrumentation issue category
}
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td
index 1e829be4028e..04ba89aa457e 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td
@@ -19,6 +19,8 @@ def Implicit : DiagGroup<"implicit", [
def ODR : DiagGroup<"odr">;
def : DiagGroup<"abi">;
def AbsoluteValue : DiagGroup<"absolute-value">;
+def MisspelledAssumption : DiagGroup<"misspelled-assumption">;
+def UnknownAssumption : DiagGroup<"unknown-assumption">;
def AddressOfTemporary : DiagGroup<"address-of-temporary">;
def : DiagGroup<"aggregate-return">;
def GNUAlignofExpression : DiagGroup<"gnu-alignof-expression">;
@@ -45,6 +47,11 @@ def GNUCompoundLiteralInitializer : DiagGroup<"gnu-compound-literal-initializer"
def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion">;
def BitFieldEnumConversion : DiagGroup<"bitfield-enum-conversion">;
def BitFieldWidth : DiagGroup<"bitfield-width">;
+def CompoundTokenSplitByMacro : DiagGroup<"compound-token-split-by-macro">;
+def CompoundTokenSplitBySpace : DiagGroup<"compound-token-split-by-space">;
+def CompoundTokenSplit : DiagGroup<"compound-token-split",
+ [CompoundTokenSplitByMacro,
+ CompoundTokenSplitBySpace]>;
def CoroutineMissingUnhandledException :
DiagGroup<"coroutine-missing-unhandled-exception">;
def Coroutine : DiagGroup<"coroutine", [CoroutineMissingUnhandledException]>;
@@ -103,6 +110,7 @@ def FloatConversion :
FloatZeroConversion]>;
def FrameAddress : DiagGroup<"frame-address">;
+def FreeNonHeapObject : DiagGroup<"free-nonheap-object">;
def DoublePromotion : DiagGroup<"double-promotion">;
def EnumTooLarge : DiagGroup<"enum-too-large">;
def UnsupportedNan : DiagGroup<"unsupported-nan">;
@@ -234,6 +242,7 @@ def ExtraSemi : DiagGroup<"extra-semi", [CXX98CompatExtraSemi,
def GNUFlexibleArrayInitializer : DiagGroup<"gnu-flexible-array-initializer">;
def GNUFlexibleArrayUnionMember : DiagGroup<"gnu-flexible-array-union-member">;
def GNUFoldingConstant : DiagGroup<"gnu-folding-constant">;
+def FormatInsufficientArgs : DiagGroup<"format-insufficient-args">;
def FormatExtraArgs : DiagGroup<"format-extra-args">;
def FormatZeroLength : DiagGroup<"format-zero-length">;
@@ -479,6 +488,8 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [
def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">;
def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">;
def ObjCBoxing : DiagGroup<"objc-boxing">;
+def CompletionHandler : DiagGroup<"completion-handler">;
+def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>;
def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">;
def UnderalignedExceptionObject : DiagGroup<"underaligned-exception-object">;
def DeprecatedObjCIsaUsage : DiagGroup<"deprecated-objc-isa-usage">;
@@ -547,20 +558,26 @@ def StaticLocalInInline : DiagGroup<"static-local-in-inline">;
def GNUStaticFloatInit : DiagGroup<"gnu-static-float-init">;
def StaticFloatInit : DiagGroup<"static-float-init", [GNUStaticFloatInit]>;
def GNUStatementExpression : DiagGroup<"gnu-statement-expression">;
+def StringConcatation : DiagGroup<"string-concatenation">;
def StringCompare : DiagGroup<"string-compare">;
def StringPlusInt : DiagGroup<"string-plus-int">;
def StringPlusChar : DiagGroup<"string-plus-char">;
def StrncatSize : DiagGroup<"strncat-size">;
+def SwiftNameAttribute : DiagGroup<"swift-name-attribute">;
def IntInBoolContext : DiagGroup<"int-in-bool-context">;
def TautologicalTypeLimitCompare : DiagGroup<"tautological-type-limit-compare">;
def TautologicalUnsignedZeroCompare : DiagGroup<"tautological-unsigned-zero-compare">;
def TautologicalUnsignedEnumZeroCompare : DiagGroup<"tautological-unsigned-enum-zero-compare">;
+// For compatibility with GCC. Tautological comparison warnings for constants
+// that are an extremal value of the type.
+def TypeLimits : DiagGroup<"type-limits", [TautologicalTypeLimitCompare,
+ TautologicalUnsignedZeroCompare,
+ TautologicalUnsignedEnumZeroCompare]>;
+// Additional tautological comparison warnings based on the expression, not
+// only on its type.
+def TautologicalValueRangeCompare : DiagGroup<"tautological-value-range-compare">;
def TautologicalInRangeCompare : DiagGroup<"tautological-constant-in-range-compare",
- [TautologicalTypeLimitCompare,
- TautologicalUnsignedZeroCompare,
- TautologicalUnsignedEnumZeroCompare]>;
-// For compatibility with GCC; -Wtype-limits = -Wtautological-constant-in-range-compare
-def TypeLimits : DiagGroup<"type-limits", [TautologicalInRangeCompare]>;
+ [TypeLimits, TautologicalValueRangeCompare]>;
def TautologicalOutOfRangeCompare : DiagGroup<"tautological-constant-out-of-range-compare">;
def TautologicalConstantCompare : DiagGroup<"tautological-constant-compare",
[TautologicalOutOfRangeCompare]>;
@@ -624,7 +641,6 @@ def ImplicitFallthrough : DiagGroup<"implicit-fallthrough",
def InvalidPPToken : DiagGroup<"invalid-pp-token">;
def Trigraphs : DiagGroup<"trigraphs">;
-def : DiagGroup<"type-limits">;
def UndefinedReinterpretCast : DiagGroup<"undefined-reinterpret-cast">;
def ReinterpretBaseClass : DiagGroup<"reinterpret-base-class">;
def Unicode : DiagGroup<"unicode">;
@@ -699,6 +715,7 @@ def ReorderInitList : DiagGroup<"reorder-init-list">;
def Reorder : DiagGroup<"reorder", [ReorderCtor, ReorderInitList]>;
def UndeclaredSelector : DiagGroup<"undeclared-selector">;
def ImplicitAtomic : DiagGroup<"implicit-atomic-properties">;
+def AtomicAlignment : DiagGroup<"atomic-alignment">;
def CustomAtomic : DiagGroup<"custom-atomic-properties">;
def AtomicProperties : DiagGroup<"atomic-properties",
[ImplicitAtomic, CustomAtomic]>;
@@ -728,8 +745,8 @@ def OverridingMethodMismatch : DiagGroup<"overriding-method-mismatch">;
def VariadicMacros : DiagGroup<"variadic-macros">;
def VectorConversion : DiagGroup<"vector-conversion">; // clang specific
def VexingParse : DiagGroup<"vexing-parse">;
-def VLA : DiagGroup<"vla">;
def VLAExtension : DiagGroup<"vla-extension">;
+def VLA : DiagGroup<"vla", [VLAExtension]>;
def VolatileRegisterVar : DiagGroup<"volatile-register-var">;
def Visibility : DiagGroup<"visibility">;
def ZeroLengthArray : DiagGroup<"zero-length-array">;
@@ -838,7 +855,8 @@ def FormatPedantic : DiagGroup<"format-pedantic">;
def FormatTypeConfusion : DiagGroup<"format-type-confusion">;
def Format : DiagGroup<"format",
[FormatExtraArgs, FormatZeroLength, NonNull,
- FormatSecurity, FormatY2K, FormatInvalidSpecifier]>,
+ FormatSecurity, FormatY2K, FormatInvalidSpecifier,
+ FormatInsufficientArgs]>,
DiagCategory<"Format String Issue">;
def FormatNonLiteral : DiagGroup<"format-nonliteral">;
def Format2 : DiagGroup<"format=2",
@@ -859,6 +877,8 @@ def PointerToEnumCast : DiagGroup<"pointer-to-enum-cast",
def PointerToIntCast : DiagGroup<"pointer-to-int-cast",
[PointerToEnumCast, VoidPointerToIntCast]>;
+def FUseLdPath : DiagGroup<"fuse-ld-path">;
+
def Move : DiagGroup<"move", [
PessimizingMove,
RedundantMove,
@@ -876,7 +896,9 @@ def Extra : DiagGroup<"extra", [
SignCompare,
UnusedParameter,
NullPointerArithmetic,
- EmptyInitStatement
+ EmptyInitStatement,
+ StringConcatation,
+ FUseLdPath,
]>;
def Most : DiagGroup<"most", [
@@ -937,7 +959,8 @@ def Consumed : DiagGroup<"consumed">;
// Note that putting warnings in -Wall will not disable them by default. If a
// warning should be active _only_ when -Wall is passed in, mark it as
// DefaultIgnore in addition to putting it here.
-def All : DiagGroup<"all", [Most, Parentheses, Switch, SwitchBool, MisleadingIndentation]>;
+def All : DiagGroup<"all", [Most, Parentheses, Switch, SwitchBool,
+ MisleadingIndentation]>;
// Warnings that should be in clang-cl /w4.
def : DiagGroup<"CL4", [All, Extra]>;
@@ -1138,7 +1161,6 @@ def BackendOptimizationFailure : DiagGroup<"pass-failed">;
def ProfileInstrMissing : DiagGroup<"profile-instr-missing">;
def ProfileInstrOutOfDate : DiagGroup<"profile-instr-out-of-date">;
def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">;
-def MisExpect : DiagGroup<"misexpect">;
// AddressSanitizer frontend instrumentation remarks.
def SanitizeAddressRemarks : DiagGroup<"sanitize-address">;
@@ -1223,3 +1245,5 @@ in addition with the pragmas or -fmax-tokens flag to get any warnings.
}
def WebAssemblyExceptionSpec : DiagGroup<"wasm-exception-spec">;
+
+def RTTI : DiagGroup<"rtti">;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h
index 00c939650e54..7fd107c4add7 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h
@@ -64,8 +64,9 @@ namespace clang {
// Get typedefs for common diagnostics.
enum {
-#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
- SFINAE,CATEGORY,NOWERROR,SHOWINSYSHEADER) ENUM,
+#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, CATEGORY, \
+ NOWERROR, SHOWINSYSHEADER, DEFFERABLE) \
+ ENUM,
#define COMMONSTART
#include "clang/Basic/DiagnosticCommonKinds.inc"
NUM_BUILTIN_COMMON_DIAGNOSTICS
@@ -280,6 +281,13 @@ public:
/// are not SFINAE errors.
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID);
+ /// Whether the diagnostic message can be deferred.
+ ///
+ /// For single source offloading languages, a diagnostic message occurred
+ /// in a device host function may be deferred until the function is sure
+ /// to be emitted.
+ static bool isDeferrable(unsigned DiagID);
+
/// Get the string of all diagnostic flags.
///
/// \returns A list of all diagnostics flags as they would be written in a
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLex.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLex.h
index 33789051b286..7a3128de3b82 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLex.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLex.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define LEXSTART
#include "clang/Basic/DiagnosticLexKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td
index 9cb06cf5b5e1..130e7687bad2 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -104,10 +104,10 @@ def warn_cxx98_compat_raw_string_literal : Warning<
"raw string literals are incompatible with C++98">,
InGroup<CXX98Compat>, DefaultIgnore;
-def ext_multichar_character_literal : ExtWarn<
+def warn_multichar_character_literal : Warning<
"multi-character character constant">, InGroup<MultiChar>;
-def ext_four_char_character_literal : Extension<
- "multi-character character constant">, InGroup<FourByteMultiChar>;
+def warn_four_char_character_literal : Warning<
+ "multi-character character constant">, InGroup<FourByteMultiChar>, DefaultIgnore;
// Unicode and UCNs
@@ -695,6 +695,9 @@ def err_mmap_missing_module_unqualified : Error<
"no module named '%0' visible from '%1'">;
def err_mmap_missing_module_qualified : Error<
"no module named '%0' in '%1'">;
+def err_mmap_missing_parent_module: Error<
+ "no module named '%0' %select{found|in '%2'}1, "
+ "parent module must be defined before the submodule">;
def err_mmap_top_level_inferred_submodule : Error<
"only submodules and framework modules may be inferred with wildcard syntax">;
def err_mmap_inferred_no_umbrella : Error<
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def
index a946b5c6be8e..927710a0cb9a 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def
@@ -47,6 +47,7 @@ SEMANTIC_DIAGOPT(IgnoreWarnings, 1, 0) /// -w
DIAGOPT(NoRewriteMacros, 1, 0) /// -Wno-rewrite-macros
DIAGOPT(Pedantic, 1, 0) /// -pedantic
DIAGOPT(PedanticErrors, 1, 0) /// -pedantic-errors
+DIAGOPT(ShowLine, 1, 1) /// Show line number on diagnostics.
DIAGOPT(ShowColumn, 1, 1) /// Show column number on diagnostics.
DIAGOPT(ShowLocation, 1, 1) /// Show source location information.
DIAGOPT(ShowLevel, 1, 1) /// Show diagnostic level.
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h
index 7fbe534c5994..17533b38ff5f 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h
@@ -15,7 +15,14 @@
#include <type_traits>
#include <vector>
+namespace llvm {
+namespace opt {
+class ArgList;
+} // namespace opt
+} // namespace llvm
+
namespace clang {
+class DiagnosticsEngine;
/// Specifies which overload candidates to display when overload
/// resolution fails.
@@ -61,6 +68,11 @@ raw_ostream& operator<<(raw_ostream& Out, DiagnosticLevelMask M);
/// Options for controlling the compiler diagnostics engine.
class DiagnosticOptions : public RefCountedBase<DiagnosticOptions>{
+ friend bool ParseDiagnosticArgs(DiagnosticOptions &, llvm::opt::ArgList &,
+ clang::DiagnosticsEngine *, bool);
+
+ friend class CompilerInvocation;
+
public:
enum TextDiagnosticFormat { Clang, MSVC, Vi };
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParse.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParse.h
index 0c21ff93c5fa..d066d3f71a25 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParse.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParse.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define PARSESTART
#include "clang/Basic/DiagnosticParseKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td
index 1038a4119d4c..0ed80a481e78 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -62,6 +62,20 @@ def warn_misleading_indentation : Warning<
def note_previous_statement : Note<
"previous statement is here">;
+def subst_compound_token_kind : TextSubstitution<
+ "%select{%1 and |}0%2 tokens "
+ "%select{introducing statement expression|terminating statement expression|"
+ "introducing attribute|terminating attribute|"
+ "forming pointer to member type}3">;
+def warn_compound_token_split_by_macro : Warning<
+ "%sub{subst_compound_token_kind}0,1,2,3 appear in different "
+ "macro expansion contexts">, InGroup<CompoundTokenSplitByMacro>;
+def note_compound_token_split_second_token_here : Note<
+ "%select{|second }0%1 token is here">;
+def warn_compound_token_split_by_whitespace : Warning<
+ "%sub{subst_compound_token_kind}0,1,2,3 are separated by whitespace">,
+ InGroup<CompoundTokenSplitBySpace>, DefaultIgnore;
+
def ext_thread_before : Extension<"'__thread' before '%0'">;
def ext_keyword_as_ident : ExtWarn<
"keyword '%0' will be made available as an identifier "
@@ -695,7 +709,7 @@ def err_ms_property_expected_accessor_name : Error<
def err_ms_property_expected_comma_or_rparen : Error<
"expected ',' or ')' at end of property accessor list">;
def err_ms_property_initializer : Error<
- "property declaration cannot have an in-class initializer">;
+ "property declaration cannot have a default member initializer">;
def warn_cxx20_compat_explicit_bool : Warning<
"this expression will be parsed as explicit(bool) in C++20">,
@@ -845,21 +859,23 @@ def warn_cxx98_compat_defaulted_deleted_function : Warning<
"%select{defaulted|deleted}0 function definitions are incompatible with C++98">,
InGroup<CXX98Compat>, DefaultIgnore;
-// C++11 in-class member initialization
+// C++11 default member initialization
def ext_nonstatic_member_init : ExtWarn<
- "in-class initialization of non-static data member is a C++11 extension">,
- InGroup<CXX11>;
+ "default member initializer for non-static data member is a C++11 "
+ "extension">, InGroup<CXX11>;
def warn_cxx98_compat_nonstatic_member_init : Warning<
- "in-class initialization of non-static data members is incompatible with C++98">,
- InGroup<CXX98Compat>, DefaultIgnore;
+ "default member initializer for non-static data members is incompatible with "
+ "C++98">, InGroup<CXX98Compat>, DefaultIgnore;
def ext_bitfield_member_init: ExtWarn<
"default member initializer for bit-field is a C++20 extension">,
InGroup<CXX20>;
def warn_cxx17_compat_bitfield_member_init: Warning<
"default member initializer for bit-field is incompatible with "
"C++ standards before C++20">, InGroup<CXXPre20Compat>, DefaultIgnore;
+def err_anon_bitfield_member_init : Error<
+ "anonymous bit-field cannot have a default member initializer">;
def err_incomplete_array_member_init: Error<
- "array bound cannot be deduced from an in-class initializer">;
+ "array bound cannot be deduced from a default member initializer">;
// C++11 alias-declaration
def ext_alias_declaration : ExtWarn<
@@ -934,6 +950,8 @@ def err_lambda_capture_misplaced_ellipsis : Error<
"the name of the capture">;
def err_lambda_capture_multiple_ellipses : Error<
"multiple ellipses in pack capture">;
+def err_capture_default_first : Error<
+ "capture default must be first">;
// C++17 lambda expressions
def err_expected_star_this_capture : Error<
"expected 'this' following '*' in lambda capture list">;
@@ -1117,9 +1135,21 @@ def err_pragma_file_or_compound_scope : Error<
// - #pragma stdc unknown
def ext_stdc_pragma_ignored : ExtWarn<"unknown pragma in STDC namespace">,
InGroup<UnknownPragmas>;
-def warn_stdc_fenv_access_not_supported :
- Warning<"pragma STDC FENV_ACCESS ON is not supported, ignoring pragma">,
+// The C standard 7.6.1p2 says "The [FENV_ACCESS] pragma shall occur either
+// outside external declarations or preceding all explicit declarations and
+// statements inside a compound statement.
+def err_pragma_stdc_fenv_access_scope : Error<
+ "'#pragma STDC FENV_ACCESS' can only appear at file scope or at the start of"
+ " a compound statement">;
+def warn_stdc_fenv_round_not_supported :
+ Warning<"pragma STDC FENV_ROUND is not supported">,
InGroup<UnknownPragmas>;
+def warn_stdc_unknown_rounding_mode : Warning<
+ "invalid or unsupported rounding mode in '#pragma STDC FENV_ROUND' - ignored">,
+ InGroup<IgnoredPragmas>;
+def warn_pragma_fp_ignored : Warning<
+ "'#pragma %0' is not supported on this target - ignored">,
+ InGroup<IgnoredPragmas>;
// - #pragma comment
def err_pragma_comment_malformed : Error<
"pragma comment requires parenthesized identifier and optional string">;
@@ -1248,7 +1278,8 @@ def err_omp_decl_in_declare_simd_variant : Error<
def err_omp_unknown_map_type : Error<
"incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'">;
def err_omp_unknown_map_type_modifier : Error<
- "incorrect map type modifier, expected 'always', 'close', or 'mapper'">;
+ "incorrect map type modifier, expected 'always', 'close', "
+ "%select{or 'mapper'|'mapper', or 'present'}0">;
def err_omp_map_type_missing : Error<
"missing map type">;
def err_omp_map_type_modifier_missing : Error<
@@ -1260,6 +1291,16 @@ def err_expected_end_declare_target_or_variant : Error<
def err_expected_begin_declare_variant
: Error<"'#pragma omp end declare variant' with no matching '#pragma omp "
"begin declare variant'">;
+def err_expected_begin_assumes
+ : Error<"'#pragma omp end assumes' with no matching '#pragma omp begin assumes'">;
+def warn_omp_unknown_assumption_clause_missing_id
+ : Warning<"valid %0 clauses start with %1; %select{token|tokens}2 will be ignored">,
+ InGroup<OpenMPClauses>;
+def warn_omp_unknown_assumption_clause_without_args
+ : Warning<"%0 clause should not be followed by arguments; tokens will be ignored">,
+ InGroup<OpenMPClauses>;
+def note_omp_assumption_clause_continue_here
+ : Note<"the ignored tokens spans until here">;
def err_omp_declare_target_unexpected_clause: Error<
"unexpected '%0' clause, only %select{'to' or 'link'|'to', 'link' or 'device_type'}1 clauses expected">;
def err_omp_expected_clause: Error<
@@ -1270,11 +1311,21 @@ def err_omp_mapper_expected_declarator : Error<
"expected declarator on 'omp declare mapper' directive">;
def err_omp_declare_variant_wrong_clause : Error<
"expected '%0' clause on 'omp declare variant' directive">;
+def err_omp_declare_variant_duplicate_nested_trait : Error<
+ "nested OpenMP context selector contains duplicated trait '%0'"
+ " in selector '%1' and set '%2' with different score">;
+def err_omp_declare_variant_nested_user_condition : Error<
+ "nested user conditions in OpenMP context selector not supported (yet)">;
def warn_omp_declare_variant_string_literal_or_identifier
: Warning<"expected identifier or string literal describing a context "
"%select{set|selector|property}0; "
"%select{set|selector|property}0 skipped">,
InGroup<OpenMPClauses>;
+def warn_unknown_begin_declare_variant_isa_trait
+ : Warning<"isa trait '%0' is not known to the current target; verify the "
+ "spelling or consider restricting the context selector with the "
+ "'arch' selector further">,
+ InGroup<SourceUsesOpenMP>;
def note_omp_declare_variant_ctx_options
: Note<"context %select{set|selector|property}0 options are: %1">;
def warn_omp_declare_variant_expected
@@ -1345,14 +1396,21 @@ def err_pragma_loop_invalid_option : Error<
"%select{invalid|missing}0 option%select{ %1|}0; expected vectorize, "
"vectorize_width, interleave, interleave_count, unroll, unroll_count, "
"pipeline, pipeline_initiation_interval, vectorize_predicate, or distribute">;
+def err_pragma_loop_invalid_vectorize_option : Error<
+ "vectorize_width loop hint malformed; use vectorize_width(X, fixed) or "
+ "vectorize_width(X, scalable) where X is an integer, or vectorize_width('fixed' or 'scalable')">;
+def note_pragma_loop_invalid_vectorize_option : Note<
+ "vectorize_width loop hint malformed; use vectorize_width(X, fixed) or "
+ "vectorize_width(X, scalable) where X is an integer, or vectorize_width('fixed' or 'scalable')">;
def err_pragma_fp_invalid_option : Error<
- "%select{invalid|missing}0 option%select{ %1|}0; expected 'contract' or 'reassociate'">;
+ "%select{invalid|missing}0 option%select{ %1|}0; expected 'contract', 'reassociate' or 'exceptions'">;
def err_pragma_fp_invalid_argument : Error<
- "unexpected argument '%0' to '#pragma clang fp %1'; "
+ "unexpected argument '%0' to '#pragma clang fp %1'; expected "
"%select{"
- "expected 'fast' or 'on' or 'off'|"
- "expected 'on' or 'off'}2">;
+ "'fast' or 'on' or 'off'|"
+ "'on' or 'off'|"
+ "'ignore', 'maytrap' or 'strict'}2">;
def err_pragma_invalid_keyword : Error<
"invalid argument; expected 'enable'%select{|, 'full'}0%select{|, 'assume_safety'}1 or 'disable'">;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h
index aded0162ab33..fc7564047a24 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define REFACTORINGSTART
#include "clang/Basic/DiagnosticRefactoringKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSema.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSema.h
index 72a6b9753893..7323167aeee8 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSema.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSema.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define SEMASTART
#include "clang/Basic/DiagnosticSemaKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 941f2cafc372..67c59f3ca09a 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -91,8 +91,8 @@ def ext_cce_narrowing : ExtWarn<
"evaluates to %2, which cannot be narrowed to type %3}1">,
InGroup<CXX11Narrowing>, DefaultError, SFINAEFailure;
def err_ice_not_integral : Error<
- "integral constant expression must have integral or unscoped enumeration "
- "type, not %0">;
+ "%select{integer|integral}1 constant expression must have "
+ "%select{integer|integral or unscoped enumeration}1 type, not %0">;
def err_ice_incomplete_type : Error<
"integral constant expression has incomplete class type %0">;
def err_ice_explicit_conversion : Error<
@@ -137,8 +137,9 @@ def err_vla_decl_has_static_storage : Error<
"variable length array declaration cannot have 'static' storage duration">;
def err_vla_decl_has_extern_linkage : Error<
"variable length array declaration cannot have 'extern' linkage">;
-def ext_vla_folded_to_constant : Extension<
- "variable length array folded to constant array as an extension">, InGroup<GNUFoldingConstant>;
+def ext_vla_folded_to_constant : ExtWarn<
+ "variable length array folded to constant array as an extension">,
+ InGroup<GNUFoldingConstant>;
def err_vla_unsupported : Error<
"variable length arrays are not supported for the current target">;
def note_vla_unsupported : Note<
@@ -469,8 +470,9 @@ def err_decomp_decl_not_alone : Error<
def err_decomp_decl_requires_init : Error<
"decomposition declaration %0 requires an initializer">;
def err_decomp_decl_wrong_number_bindings : Error<
- "type %0 decomposes into %2 elements, but %select{only |}3%1 "
- "names were provided">;
+ "type %0 decomposes into %3 %plural{1:element|:elements}2, but "
+ "%select{%plural{0:no|:only %1}1|%1}4 "
+ "%plural{1:name was|:names were}1 provided">;
def err_decomp_decl_unbindable_type : Error<
"cannot decompose %select{union|non-class, non-array}1 type %2">;
def err_decomp_decl_multiple_bases_with_members : Error<
@@ -485,6 +487,8 @@ def err_decomp_decl_inaccessible_base : Error<
def err_decomp_decl_inaccessible_field : Error<
"cannot decompose %select{private|protected}0 member %1 of %3">,
AccessControl;
+def err_decomp_decl_lambda : Error<
+ "cannot decompose lambda closure type">;
def err_decomp_decl_anon_union_member : Error<
"cannot decompose class type %0 because it has an anonymous "
"%select{struct|union}1 member">;
@@ -737,6 +741,13 @@ def note_strncat_wrong_size : Note<
def warn_assume_side_effects : Warning<
"the argument to %0 has side effects that will be discarded">,
InGroup<DiagGroup<"assume">>;
+def warn_assume_attribute_string_unknown : Warning<
+ "unknown assumption string '%0'; attribute is potentially ignored">,
+ InGroup<UnknownAssumption>;
+def warn_assume_attribute_string_unknown_suggested : Warning<
+ "unknown assumption string '%0' may be misspelled; attribute is potentially "
+ "ignored, did you mean '%1'?">,
+ InGroup<MisspelledAssumption>;
def warn_builtin_chk_overflow : Warning<
"'%0' will always overflow; destination buffer has size %1,"
@@ -793,6 +804,7 @@ def ext_main_used : Extension<
/// parser diagnostics
def ext_no_declarators : ExtWarn<"declaration does not declare anything">,
InGroup<MissingDeclarations>;
+def err_no_declarators : Error<"declaration does not declare anything">;
def ext_typedef_without_a_name : ExtWarn<"typedef requires a name">,
InGroup<MissingDeclarations>;
def err_typedef_not_identifier : Error<"typedef name must be an identifier">;
@@ -843,6 +855,8 @@ def err_pragma_options_align_mac68k_target_unsupported : Error<
def warn_pragma_pack_invalid_alignment : Warning<
"expected #pragma pack parameter to be '1', '2', '4', '8', or '16'">,
InGroup<IgnoredPragmas>;
+def err_pragma_pack_invalid_alignment : Error<
+ warn_pragma_pack_invalid_alignment.Text>;
def warn_pragma_pack_non_default_at_include : Warning<
"non-default #pragma pack value changes the alignment of struct or union "
"members in the included file">, InGroup<PragmaPackSuspiciousInclude>,
@@ -876,6 +890,8 @@ def warn_cxx_ms_struct :
Warning<"ms_struct may not produce Microsoft-compatible layouts for classes "
"with base classes or virtual functions">,
DefaultError, InGroup<IncompatibleMSStruct>;
+def err_pragma_pack_identifer_not_supported : Error<
+ "specifying an identifier within `#pragma pack` is not supported on this target">;
def err_section_conflict : Error<"%0 causes a section type conflict with %1">;
def err_no_base_classes : Error<"invalid use of '__super', %0 has no base classes">;
def err_invalid_super_scope : Error<"invalid use of '__super', "
@@ -1033,6 +1049,8 @@ def warn_objc_boxing_invalid_utf8_string : Warning<
"string is ill-formed as UTF-8 and will become a null %0 when boxed">,
InGroup<ObjCBoxing>;
+def err_objc_non_runtime_protocol_in_protocol_expr : Error<
+ "cannot use a protocol declared 'objc_non_runtime_protocol' in a @protocol expression">;
def err_objc_direct_on_protocol : Error<
"'objc_direct' attribute cannot be applied to %select{methods|properties}0 "
"declared in an Objective-C protocol">;
@@ -1056,6 +1074,10 @@ def warn_objc_direct_property_ignored : Warning<
InGroup<IgnoredAttributes>;
def err_objc_direct_dynamic_property : Error<
"direct property cannot be @dynamic">;
+def err_objc_direct_protocol_conformance : Error<
+ "%select{category %1|class extension}0 cannot conform to protocol %2 because "
+ "of direct members declared in interface %3">;
+def note_direct_member_here : Note<"direct member declared here">;
def warn_conflicting_overriding_ret_types : Warning<
"conflicting return type in "
@@ -1841,7 +1863,7 @@ def note_nontrivial_no_copy : Note<
def note_nontrivial_user_provided : Note<
"because %select{base class of |field of |}0type %1 has a user-provided "
"%sub{select_special_member_kind}2">;
-def note_nontrivial_in_class_init : Note<
+def note_nontrivial_default_member_init : Note<
"because field %0 has an initializer">;
def note_nontrivial_param_type : Note<
"because its parameter is %diff{of type $, not $|of the wrong type}2,3">;
@@ -1990,8 +2012,8 @@ def err_destructor_template : Error<
// C++ initialization
def err_init_conversion_failed : Error<
- "cannot initialize %select{a variable|a parameter|return object|"
- "statement expression result|an "
+ "cannot initialize %select{a variable|a parameter|template parameter|"
+ "return object|statement expression result|an "
"exception object|a member subobject|an array element|a new value|a value|a "
"base class|a constructor delegation|a vector element|a block element|a "
"block element|a complex element|a lambda capture|a compound literal "
@@ -2004,6 +2026,8 @@ def err_init_conversion_failed : Error<
"|: different return type%diff{ ($ vs $)|}5,6"
"|: different qualifiers (%5 vs %6)"
"|: different exception specifications}4">;
+def note_forward_class_conversion : Note<"%0 is not defined, but forward "
+ "declared here; conversion would be valid if it was derived from %1">;
def err_lvalue_to_rvalue_ref : Error<"rvalue reference %diff{to type $ cannot "
"bind to lvalue of type $|cannot bind to incompatible lvalue}0,1">;
@@ -2131,7 +2155,7 @@ def warn_unsequenced_mod_use : Warning<
"unsequenced modification and access to %0">, InGroup<Unsequenced>;
def select_initialized_entity_kind : TextSubstitution<
- "%select{copying variable|copying parameter|"
+ "%select{copying variable|copying parameter|initializing template parameter|"
"returning object|initializing statement expression result|"
"throwing object|copying member subobject|copying array element|"
"allocating object|copying temporary|initializing base subobject|"
@@ -2440,7 +2464,7 @@ def err_for_range_decl_must_be_var : Error<
"for range declaration must declare a variable">;
def err_for_range_storage_class : Error<
"loop variable %0 may not be declared %select{'extern'|'static'|"
- "'__private_extern__'|'auto'|'register'|'constexpr'}1">;
+ "'__private_extern__'|'auto'|'register'|'constexpr'|'thread_local'}1">;
def err_type_defined_in_for_range : Error<
"types may not be defined in a for range declaration">;
def err_for_range_deduction_failure : Error<
@@ -2810,6 +2834,14 @@ def err_attribute_invalid_vector_type : Error<"invalid vector element type %0">;
def err_attribute_invalid_matrix_type : Error<"invalid matrix element type %0">;
def err_attribute_bad_neon_vector_size : Error<
"Neon vector size must be 64 or 128 bits">;
+def err_attribute_invalid_sve_type : Error<
+ "%0 attribute applied to non-SVE type %1">;
+def err_attribute_bad_sve_vector_size : Error<
+ "invalid SVE vector size '%0', must match value set by "
+ "'-msve-vector-bits' ('%1')">;
+def err_attribute_arm_feature_sve_bits_unsupported : Error<
+ "%0 is only supported when '-msve-vector-bits=<bits>' is specified with a "
+ "value of 128, 256, 512, 1024 or 2048.">;
def err_attribute_requires_positive_integer : Error<
"%0 attribute requires a %select{positive|non-negative}1 "
"integral compile time constant expression">;
@@ -2818,11 +2850,13 @@ def err_attribute_requires_opencl_version : Error<
def err_invalid_branch_protection_spec : Error<
"invalid or misplaced branch protection specification '%0'">;
def warn_unsupported_target_attribute
- : Warning<"%select{unsupported|duplicate}0%select{| architecture}1 '%2' in"
- " the 'target' attribute string; 'target' attribute ignored">,
+ : Warning<"%select{unsupported|duplicate|unknown}0%select{| architecture|"
+ " tune CPU}1 '%2' in the 'target' attribute string; 'target' "
+ "attribute ignored">,
InGroup<IgnoredAttributes>;
def err_attribute_unsupported
- : Error<"%0 attribute is not supported for this target">;
+ : Error<"%0 attribute is not supported on targets missing %1;"
+ " specify an appropriate -march= or -mcpu=">;
// The err_*_attribute_argument_not_int are separate because they're used by
// VerifyIntegerConstantExpression.
def err_aligned_attribute_argument_not_int : Error<
@@ -2843,7 +2877,7 @@ def err_attribute_sizeless_type : Error<
"%0 attribute cannot be applied to sizeless type %1">;
def err_attribute_argument_n_type : Error<
"%0 attribute requires parameter %1 to be %select{int or bool|an integer "
- "constant|a string|an identifier}2">;
+ "constant|a string|an identifier|a constant expression}2">;
def err_attribute_argument_type : Error<
"%0 attribute requires %select{int or bool|an integer "
"constant|a string|an identifier}1">;
@@ -2913,6 +2947,10 @@ def err_attribute_invalid_size : Error<
"vector size not an integral multiple of component size">;
def err_attribute_zero_size : Error<"zero %0 size">;
def err_attribute_size_too_large : Error<"%0 size too large">;
+def err_typecheck_sve_ambiguous : Error<
+ "cannot combine fixed-length and sizeless SVE vectors in expression, result is ambiguous (%0 and %1)">;
+def err_typecheck_sve_gnu_ambiguous : Error<
+ "cannot combine GNU and SVE vectors in expression, result is ambiguous (%0 and %1)">;
def err_typecheck_vector_not_convertable_implict_truncation : Error<
"cannot convert between %select{scalar|vector}0 type %1 and vector type"
" %2 as implicit conversion would cause truncation">;
@@ -2991,6 +3029,10 @@ def err_missing_atsign_prefix : Error<
def warn_objc_string_literal_comparison : Warning<
"direct comparison of a string literal has undefined behavior">,
InGroup<ObjCStringComparison>;
+def warn_concatenated_literal_array_init : Warning<
+ "suspicious concatenation of string literals in an array initialization; "
+ "did you mean to separate the elements with a comma?">,
+ InGroup<StringConcatation>, DefaultIgnore;
def warn_concatenated_nsarray_literal : Warning<
"concatenated NSString literal for an NSArray expression - "
"possibly missing a comma">,
@@ -3123,12 +3165,25 @@ def warn_nocf_check_attribute_ignored :
def warn_attribute_after_definition_ignored : Warning<
"attribute %0 after definition is ignored">,
InGroup<IgnoredAttributes>;
+def warn_attributes_likelihood_ifstmt_conflict
+ : Warning<"conflicting attributes %0 are ignored">,
+ InGroup<IgnoredAttributes>;
def warn_cxx11_gnu_attribute_on_type : Warning<
"attribute %0 ignored, because it cannot be applied to a type">,
InGroup<IgnoredAttributes>;
def warn_unhandled_ms_attribute_ignored : Warning<
"__declspec attribute %0 is not supported">,
InGroup<IgnoredAttributes>;
+def warn_attribute_has_no_effect_on_infinite_loop : Warning<
+ "attribute %0 has no effect when annotating an infinite loop">,
+ InGroup<IgnoredAttributes>;
+def note_attribute_has_no_effect_on_infinite_loop_here : Note<
+ "annotating the infinite loop here">;
+def warn_attribute_has_no_effect_on_if_constexpr : Warning<
+ "attribute %0 has no effect when annotating an 'if constexpr' statement">,
+ InGroup<IgnoredAttributes>;
+def note_attribute_has_no_effect_on_if_constexpr_here : Note<
+ "annotating the 'if constexpr' statement here">;
def err_decl_attribute_invalid_on_stmt : Error<
"%0 attribute cannot be applied to a statement">;
def err_stmt_attribute_invalid_on_decl : Error<
@@ -3213,7 +3268,7 @@ def warn_attribute_dllexport_explicit_instantiation_def : Warning<
"'dllexport' attribute ignored on explicit instantiation definition">,
InGroup<IgnoredAttributes>;
def warn_invalid_initializer_from_system_header : Warning<
- "invalid constructor form class in system header, should not be explicit">,
+ "invalid constructor from class in system header, should not be explicit">,
InGroup<DiagGroup<"invalid-initializer-from-system-header">>;
def note_used_in_initialization_here : Note<"used in initialization here">;
def err_attribute_dll_member_of_dll_class : Error<
@@ -3459,6 +3514,9 @@ def warn_acquired_before_after_cycle : Warning<
def warn_acquire_requires_negative_cap : Warning<
"acquiring %0 '%1' requires negative capability '%2'">,
InGroup<ThreadSafetyNegative>, DefaultIgnore;
+def warn_fun_requires_negative_cap : Warning<
+ "calling function %0 requires negative capability '%1'">,
+ InGroup<ThreadSafetyAnalysis>, DefaultIgnore;
// Thread safety warnings on pass by reference
def warn_guarded_pass_by_reference : Warning<
@@ -3896,6 +3954,43 @@ def note_protocol_decl : Note<
"protocol is declared here">;
def note_protocol_decl_undefined : Note<
"protocol %0 has no definition">;
+def err_attribute_preferred_name_arg_invalid : Error<
+ "argument %0 to 'preferred_name' attribute is not a typedef for "
+ "a specialization of %1">;
+
+// called-once attribute diagnostics.
+def err_called_once_attribute_wrong_type : Error<
+ "'called_once' attribute only applies to function-like parameters">;
+
+def warn_completion_handler_never_called : Warning<
+ "%select{|captured }1completion handler is never called">,
+ InGroup<CompletionHandler>, DefaultIgnore;
+def warn_called_once_never_called : Warning<
+ "%select{|captured }1%0 parameter marked 'called_once' is never called">,
+ InGroup<CalledOnceParameter>;
+
+def warn_completion_handler_never_called_when : Warning<
+ "completion handler is never %select{used|called}1 when "
+ "%select{taking true branch|taking false branch|"
+ "handling this case|none of the cases applies|"
+ "entering the loop|skipping the loop|taking one of the branches}2">,
+ InGroup<CompletionHandler>, DefaultIgnore;
+def warn_called_once_never_called_when : Warning<
+ "%0 parameter marked 'called_once' is never %select{used|called}1 when "
+ "%select{taking true branch|taking false branch|"
+ "handling this case|none of the cases applies|"
+ "entering the loop|skipping the loop|taking one of the branches}2">,
+ InGroup<CalledOnceParameter>;
+
+def warn_completion_handler_called_twice : Warning<
+ "completion handler is called twice">,
+ InGroup<CompletionHandler>, DefaultIgnore;
+def warn_called_once_gets_called_twice : Warning<
+ "%0 parameter marked 'called_once' is called twice">,
+ InGroup<CalledOnceParameter>;
+def note_called_once_gets_called_twice : Note<
+ "previous call is here%select{; set to nil to indicate "
+ "it cannot be called afterwards|}0">;
// objc_designated_initializer attribute diagnostics.
def warn_objc_designated_init_missing_super_call : Warning<
@@ -3950,6 +4045,65 @@ def err_objc_bridged_related_known_method : Error<
def err_objc_attr_protocol_requires_definition : Error<
"attribute %0 can only be applied to @protocol definitions, not forward declarations">;
+// Swift attributes.
+def warn_attr_swift_name_function
+ : Warning<"%0 attribute argument must be a string literal specifying a Swift function name">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_invalid_identifier
+ : Warning<"%0 attribute has invalid identifier for the %select{base|context|parameter}1 name">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_decl_kind
+ : Warning<"%0 attribute cannot be applied to this declaration">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_subscript_invalid_parameter
+ : Warning<"%0 attribute for 'subscript' must %select{be a getter or setter|"
+ "have at least one parameter|"
+ "have a 'self:' parameter}1">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_missing_parameters
+ : Warning<"%0 attribute is missing parameter label clause">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_setter_parameters
+ : Warning<"%0 attribute for setter must have one parameter for new value">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_multiple_selfs
+ : Warning<"%0 attribute cannot specify more than one 'self:' parameter">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_getter_parameters
+ : Warning<"%0 attribute for getter must not have any parameters besides 'self:'">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_subscript_setter_no_newValue
+ : Warning<"%0 attribute for 'subscript' setter must have a 'newValue:' parameter">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_subscript_setter_multiple_newValues
+ : Warning<"%0 attribute for 'subscript' setter cannot have multiple 'newValue:' parameters">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_subscript_getter_newValue
+ : Warning<"%0 attribute for 'subscript' getter cannot have a 'newValue:' parameter">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_num_params
+ : Warning<"too %select{few|many}0 parameters in the signature specified by "
+ "the %1 attribute (expected %2; got %3)">,
+ InGroup<SwiftNameAttribute>;
+def warn_attr_swift_name_decl_missing_params
+ : Warning<"%0 attribute cannot be applied to a %select{function|method}1 "
+ "with no parameters">,
+ InGroup<SwiftNameAttribute>;
+
+def err_attr_swift_error_no_error_parameter : Error<
+ "%0 attribute can only be applied to a %select{function|method}1 with an "
+ "error parameter">;
+def err_attr_swift_error_return_type : Error<
+ "%0 attribute with '%1' convention can only be applied to a "
+ "%select{function|method}2 returning %select{an integral type|a pointer}3">;
+
+def err_swift_async_no_access : Error<
+ "first argument to 'swift_async' must be either 'none', 'swift_private', or "
+ "'not_swift_private'">;
+def err_swift_async_bad_block_type : Error<
+ "'swift_async' completion handler parameter must have block type returning"
+ " 'void', type here is %0">;
+
def warn_ignored_objc_externally_retained : Warning<
"'objc_externally_retained' can only be applied to local variables "
"%select{of retainable type|with strong ownership}0">,
@@ -4029,6 +4183,8 @@ def err_ovl_static_nonstatic_member : Error<
"static and non-static member functions with the same parameter types "
"cannot be overloaded">;
+let Deferrable = 1 in {
+
def err_ovl_no_viable_function_in_call : Error<
"no matching function for call to %0">;
def err_ovl_no_viable_member_function_in_call : Error<
@@ -4197,9 +4353,9 @@ def note_ovl_candidate_bad_arc_conv : Note<
"cannot implicitly convert argument "
"%diff{of type $ to $|type to parameter type}3,4 for "
"%select{%ordinal6 argument|object argument}5 under ARC">;
-def note_ovl_candidate_bad_lvalue : Note<
+def note_ovl_candidate_bad_value_category : Note<
"candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
- "expects an l-value for "
+ "expects an %select{lvalue|rvalue}5 for "
"%select{%ordinal4 argument|object argument}3">;
def note_ovl_candidate_bad_addrspace : Note<
"candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
@@ -4342,6 +4498,8 @@ def err_addr_ovl_not_func_ptrref : Error<
def err_addr_ovl_no_qualifier : Error<
"cannot form member pointer of type %0 without '&' and class name">;
+} // let Deferrable
+
// C++11 Literal Operators
def err_ovl_no_viable_literal_operator : Error<
"no matching literal operator for call to %0"
@@ -4392,6 +4550,32 @@ def note_template_nontype_parm_prev_declaration : Note<
"previous non-type template parameter with type %0 is here">;
def err_template_nontype_parm_bad_type : Error<
"a non-type template parameter cannot have type %0">;
+def err_template_nontype_parm_bad_structural_type : Error<
+ "a non-type template parameter cannot have type %0 before C++20">;
+def err_template_nontype_parm_incomplete : Error<
+ "non-type template parameter has incomplete type %0">;
+def err_template_nontype_parm_not_literal : Error<
+ "non-type template parameter has non-literal type %0">;
+def err_template_nontype_parm_rvalue_ref : Error<
+ "non-type template parameter has rvalue reference type %0">;
+def err_template_nontype_parm_not_structural : Error<
+ "type %0 of non-type template parameter is not a structural type">;
+def note_not_structural_non_public : Note<
+ "%0 is not a structural type because it has a "
+ "%select{non-static data member|base class}1 that is not public">;
+def note_not_structural_mutable_field : Note<
+ "%0 is not a structural type because it has a mutable "
+ "non-static data member">;
+def note_not_structural_rvalue_ref_field : Note<
+ "%0 is not a structural type because it has a non-static data member "
+ "of rvalue reference type">;
+def note_not_structural_subobject : Note<
+ "%0 is not a structural type because it has a "
+ "%select{non-static data member|base class}1 of non-structural type %2">;
+def warn_cxx17_compat_template_nontype_parm_type : Warning<
+ "non-type template parameter of type %0 is incompatible with "
+ "C++ standards before C++20">,
+ DefaultIgnore, InGroup<CXXPre20Compat>;
def warn_cxx14_compat_template_nontype_parm_auto_type : Warning<
"non-type template parameters declared with %0 are incompatible with C++ "
"standards before C++17">,
@@ -4511,6 +4695,8 @@ def err_non_type_template_arg_subobject : Error<
"non-type template argument refers to subobject '%0'">;
def err_non_type_template_arg_addr_label_diff : Error<
"template argument / label address difference / what did you expect?">;
+def err_non_type_template_arg_unsupported : Error<
+ "sorry, non-type template argument of type %0 is not yet supported">;
def err_template_arg_not_convertible : Error<
"non-type template argument of type %0 cannot be converted to a value "
"of type %1">;
@@ -4942,6 +5128,8 @@ def err_mismatched_exception_spec_explicit_instantiation : Error<
def ext_mismatched_exception_spec_explicit_instantiation : ExtWarn<
err_mismatched_exception_spec_explicit_instantiation.Text>,
InGroup<MicrosoftExceptionSpec>;
+def err_explicit_instantiation_dependent : Error<
+ "explicit instantiation has dependent template arguments">;
// C++ typename-specifiers
def err_typename_nested_not_found : Error<"no type named %0 in %1">;
@@ -5035,7 +5223,8 @@ def err_unexpanded_parameter_pack : Error<
"size|static assertion|fixed underlying type|enumerator value|"
"using declaration|friend declaration|qualifier|initializer|default argument|"
"non-type template parameter type|exception type|partial specialization|"
- "__if_exists name|__if_not_exists name|lambda|block|type constraint}0 "
+ "__if_exists name|__if_not_exists name|lambda|block|type constraint|"
+ "requirement|requires clause}0 "
"contains%plural{0: an|:}1 unexpanded parameter pack"
"%plural{0:|1: %2|2:s %2 and %3|:s %2, %3, ...}1">;
@@ -5069,6 +5258,9 @@ def err_fold_expression_empty : Error<
"with no fallback value">;
def err_fold_expression_bad_operand : Error<
"expression not permitted as operand of fold expression">;
+def err_fold_expression_limit_exceeded: Error<
+ "instantiating fold expression with %0 arguments exceeded expression nesting "
+ "limit of %1">, DefaultFatal, NoSFINAE;
def err_unexpected_typedef : Error<
"unexpected type name %0: expected expression">;
@@ -5079,11 +5271,17 @@ def ext_undeclared_unqual_id_with_dependent_base : ExtWarn<
"use of undeclared identifier %0; "
"unqualified lookup into dependent bases of class template %1 is a Microsoft extension">,
InGroup<MicrosoftTemplate>;
-def ext_found_via_dependent_bases_lookup : ExtWarn<"use of identifier %0 "
+def err_found_in_dependent_base : Error<
+ "explicit qualification required to use member %0 from dependent base class">;
+def ext_found_in_dependent_base : ExtWarn<"use of member %0 "
"found via unqualified lookup into dependent bases of class templates is a "
"Microsoft extension">, InGroup<MicrosoftTemplate>;
-def note_dependent_var_use : Note<"must qualify identifier to find this "
- "declaration in dependent base class">;
+def err_found_later_in_class : Error<"member %0 used before its declaration">;
+def ext_found_later_in_class : ExtWarn<
+ "use of member %0 before its declaration is a Microsoft extension">,
+ InGroup<MicrosoftTemplate>;
+def note_dependent_member_use : Note<
+ "must qualify identifier to find this declaration in dependent base class">;
def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither "
"visible in the template definition nor found by argument-dependent lookup">;
def note_not_found_by_two_phase_lookup : Note<"%0 should be declared prior to the "
@@ -5372,8 +5570,6 @@ def warn_flag_enum_constant_out_of_range : Warning<
"enumeration value %0 is out of range of flags in enumeration type %1">,
InGroup<FlagEnum>;
-def warn_illegal_constant_array_size : Extension<
- "size of static array must be an integer constant expression">;
def err_vm_decl_in_file_scope : Error<
"variably modified type declaration not allowed at file scope">;
def err_vm_decl_has_extern_linkage : Error<
@@ -5519,8 +5715,6 @@ def err_bitfield_width_exceeds_type_width : Error<
def err_anon_bitfield_width_exceeds_type_width : Error<
"width of anonymous bit-field (%0 bits) exceeds %select{width|size}1 "
"of its type (%2 bit%s2)">;
-def err_anon_bitfield_init : Error<
- "anonymous bit-field cannot have a default member initializer">;
def err_incorrect_number_of_vector_initializers : Error<
"number of elements must be either one or match the size of the vector">;
@@ -5528,9 +5722,8 @@ def err_incorrect_number_of_vector_initializers : Error<
def warn_bitfield_width_exceeds_type_width: Warning<
"width of bit-field %0 (%1 bits) exceeds the width of its type; value will "
"be truncated to %2 bit%s2">, InGroup<BitFieldWidth>;
-def warn_anon_bitfield_width_exceeds_type_width : Warning<
- "width of anonymous bit-field (%0 bits) exceeds width of its type; value "
- "will be truncated to %1 bit%s1">, InGroup<BitFieldWidth>;
+def err_bitfield_too_wide : Error<
+ "%select{bit-field %1|anonymous bit-field}0 is too wide (%2 bits)">;
def warn_bitfield_too_small_for_enum : Warning<
"bit-field %0 is not wide enough to store all enumerators of %1">,
InGroup<BitFieldEnumConversion>, DefaultIgnore;
@@ -6130,6 +6323,9 @@ def warn_overloaded_shift_in_comparison :Warning<
def note_evaluate_comparison_first :Note<
"place parentheses around comparison expression to evaluate it first">;
+def note_concatenated_string_literal_silence :Note<
+ "place parentheses around the string literal to silence warning">;
+
def warn_addition_in_bitshift : Warning<
"operator '%0' has lower precedence than '%1'; "
"'%1' will be evaluated first">, InGroup<ShiftOpParentheses>;
@@ -6578,6 +6774,12 @@ def warn_tautological_compare_objc_bool : Warning<
"result of comparison of constant %0 with expression of type 'BOOL'"
" is always %1, as the only well defined values for 'BOOL' are YES and NO">,
InGroup<TautologicalObjCBoolCompare>;
+def subst_int_range : TextSubstitution<"%0-bit %select{signed|unsigned}1 value">;
+def warn_tautological_compare_value_range : Warning<
+ "result of comparison of "
+ "%select{%4|%sub{subst_int_range}1,2}0 %3 "
+ "%select{%sub{subst_int_range}1,2|%4}0 is always %5">,
+ InGroup<TautologicalValueRangeCompare>, DefaultIgnore;
def warn_mixed_sign_comparison : Warning<
"comparison of integers of different signs: %0 and %1">,
@@ -7174,8 +7376,8 @@ def warn_overaligned_type : Warning<
"guarantees %2 bytes">,
InGroup<OveralignedType>, DefaultIgnore;
def err_aligned_allocation_unavailable : Error<
- "aligned %select{allocation|deallocation}0 function of type '%1' is only "
- "available on %2 %3 or newer">;
+ "aligned %select{allocation|deallocation}0 function of type '%1' is "
+ "%select{only|not}4 available on %2%select{ %3 or newer|}4">;
def note_silence_aligned_allocation_unavailable : Note<
"if you supply your own aligned allocation functions, use "
"-faligned-allocation to silence this diagnostic">;
@@ -7406,6 +7608,12 @@ def err_no_typeid_with_fno_rtti : Error<
"use of typeid requires -frtti">;
def err_no_dynamic_cast_with_fno_rtti : Error<
"use of dynamic_cast requires -frtti">;
+def warn_no_dynamic_cast_with_rtti_disabled: Warning<
+ "dynamic_cast will not work since RTTI data is disabled by "
+ "%select{-fno-rtti-data|/GR-}0">, InGroup<RTTI>;
+def warn_no_typeid_with_rtti_disabled: Warning<
+ "typeid will not work since RTTI data is disabled by "
+ "%select{-fno-rtti-data|/GR-}0">, InGroup<RTTI>;
def err_cannot_form_pointer_to_member_of_reference_type : Error<
"cannot form a pointer-to-member to member %0 of reference type %1">;
@@ -7415,6 +7623,10 @@ def err_incomplete_object_call : Error<
def warn_condition_is_assignment : Warning<"using the result of an "
"assignment as a condition without parentheses">,
InGroup<Parentheses>;
+def warn_free_nonheap_object
+ : Warning<"attempt to call %0 on non-heap object %1">,
+ InGroup<FreeNonHeapObject>;
+
// Completely identical except off by default.
def warn_condition_is_idiomatic_assignment : Warning<"using the result "
"of an assignment as a condition without parentheses">,
@@ -7606,21 +7818,11 @@ def ext_typecheck_convert_incompatible_pointer_sign : ExtWarn<
"|%diff{sending $ to parameter of type $|"
"sending to parameter of different type}0,1"
"|%diff{casting $ to type $|casting between types}0,1}2"
- " converts between pointers to integer types with different sign">,
+ " converts between pointers to integer types %select{with different sign|"
+ "where one is of the unique plain 'char' type and the other is not}3">,
InGroup<DiagGroup<"pointer-sign">>;
-def err_typecheck_convert_incompatible_pointer_sign : Error<
- "%select{%diff{assigning to $ from $|assigning to different types}0,1"
- "|%diff{passing $ to parameter of type $|"
- "passing to parameter of different type}0,1"
- "|%diff{returning $ from a function with result type $|"
- "returning from function with different return type}0,1"
- "|%diff{converting $ to type $|converting between types}0,1"
- "|%diff{initializing $ with an expression of type $|"
- "initializing with expression of different type}0,1"
- "|%diff{sending $ to parameter of type $|"
- "sending to parameter of different type}0,1"
- "|%diff{casting $ to type $|casting between types}0,1}2"
- " converts between pointers to integer types with different sign">;
+def err_typecheck_convert_incompatible_pointer_sign :
+ Error<ext_typecheck_convert_incompatible_pointer_sign.Text>;
def ext_typecheck_convert_incompatible_pointer : ExtWarn<
"incompatible pointer types "
"%select{%diff{assigning to $ from $|assigning to different types}0,1"
@@ -8005,7 +8207,7 @@ def err_global_call_not_config : Error<
"call to global function %0 not configured">;
def err_ref_bad_target : Error<
"reference to %select{__device__|__global__|__host__|__host__ __device__}0 "
- "function %1 in %select{__device__|__global__|__host__|__host__ __device__}2 function">;
+ "%select{function|variable}1 %2 in %select{__device__|__global__|__host__|__host__ __device__}3 function">;
def err_ref_bad_target_global_initializer : Error<
"reference to %select{__device__|__global__|__host__|__host__ __device__}0 "
"function %1 in global initializer">;
@@ -8035,13 +8237,9 @@ def err_cuda_device_exceptions : Error<
"%select{__device__|__global__|__host__|__host__ __device__}1 function">;
def err_dynamic_var_init : Error<
"dynamic initialization is not supported for "
- "__device__, __constant__, and __shared__ variables.">;
+ "__device__, __constant__, __shared__, and __managed__ variables.">;
def err_shared_var_init : Error<
"initialization is not supported for __shared__ variables.">;
-def err_device_static_local_var : Error<
- "within a %select{__device__|__global__|__host__|__host__ __device__}0 "
- "function, only __shared__ variables or const variables without device "
- "memory qualifier may be marked 'static'">;
def err_cuda_vla : Error<
"cannot use variable-length arrays in "
"%select{__device__|__global__|__host__|__host__ __device__}0 functions">;
@@ -8049,7 +8247,8 @@ def err_cuda_extern_shared : Error<"__shared__ variable %0 cannot be 'extern'">;
def err_cuda_host_shared : Error<
"__shared__ local variables not allowed in "
"%select{__device__|__global__|__host__|__host__ __device__}0 functions">;
-def err_cuda_nonglobal_constant : Error<"__constant__ variables must be global">;
+def err_cuda_nonstatic_constdev: Error<"__constant__, __device__, and "
+ "__managed__ are not allowed on non-static local variables">;
def err_cuda_ovl_target : Error<
"%select{__device__|__global__|__host__|__host__ __device__}0 function %1 "
"cannot overload %select{__device__|__global__|__host__|__host__ __device__}2 function %3">;
@@ -8141,6 +8340,10 @@ def warn_cast_pointer_from_sel : Warning<
def warn_function_def_in_objc_container : Warning<
"function definition inside an Objective-C container is deprecated">,
InGroup<FunctionDefInObjCContainer>;
+def err_typecheck_call_requires_real_fp : Error<
+ "argument type %0 is not a real floating point type">;
+def err_typecheck_call_different_arg_types : Error<
+ "arguments are of different types%diff{ ($ vs $)|}0,1">;
def warn_cast_calling_conv : Warning<
"cast between incompatible calling conventions '%0' and '%1'; "
@@ -8299,7 +8502,7 @@ let CategoryName = "Inline Assembly Issue" in {
def err_asm_invalid_output_size : Error<
"invalid output size for constraint '%0'">;
def err_invalid_asm_cast_lvalue : Error<
- "invalid use of a cast in a inline asm context requiring an l-value: "
+ "invalid use of a cast in a inline asm context requiring an lvalue: "
"remove the cast or build with -fheinous-gnu-extensions">;
def err_invalid_asm_value_for_constraint
: Error <"value '%0' out of range for constraint '%1'">;
@@ -8312,7 +8515,7 @@ let CategoryName = "Inline Assembly Issue" in {
def warn_asm_label_on_auto_decl : Warning<
"ignored asm label '%0' on automatic variable">;
def warn_invalid_asm_cast_lvalue : Warning<
- "invalid use of a cast in an inline asm context requiring an l-value: "
+ "invalid use of a cast in an inline asm context requiring an lvalue: "
"accepted due to -fheinous-gnu-extensions, but clang may remove support "
"for this in the future">;
def warn_asm_mismatched_size_modifier : Warning<
@@ -8402,12 +8605,12 @@ def err_in_class_initializer_literal_type : Error<
"'constexpr' specifier">;
def err_in_class_initializer_non_constant : Error<
"in-class initializer for static data member is not a constant expression">;
-def err_in_class_initializer_not_yet_parsed : Error<
+def err_default_member_initializer_not_yet_parsed : Error<
"default member initializer for %1 needed within definition of enclosing "
"class %0 outside of member functions">;
-def note_in_class_initializer_not_yet_parsed : Note<
+def note_default_member_initializer_not_yet_parsed : Note<
"default member initializer declared here">;
-def err_in_class_initializer_cycle
+def err_default_member_initializer_cycle
: Error<"default member initializer for %0 uses itself">;
def ext_in_class_initializer_non_constant : Extension<
@@ -8500,6 +8703,8 @@ def err_ambiguous_member_multiple_subobjects : Error<
def err_ambiguous_member_multiple_subobject_types : Error<
"member %0 found in multiple base classes of different types">;
def note_ambiguous_member_found : Note<"member found by ambiguous name lookup">;
+def note_ambiguous_member_type_found : Note<
+ "member type %0 found by ambiguous name lookup">;
def err_ambiguous_reference : Error<"reference to %0 is ambiguous">;
def note_ambiguous_candidate : Note<"candidate found by name lookup is %q0">;
def err_ambiguous_tag_hiding : Error<"a type named %0 is hidden by a "
@@ -8802,7 +9007,7 @@ def note_array_declared_here : Note<
"array %0 declared here">;
def warn_printf_insufficient_data_args : Warning<
- "more '%%' conversions than data arguments">, InGroup<Format>;
+ "more '%%' conversions than data arguments">, InGroup<FormatInsufficientArgs>;
def warn_printf_data_arg_not_used : Warning<
"data argument not used by format string">, InGroup<FormatExtraArgs>;
def warn_format_invalid_conversion : Warning<
@@ -8942,6 +9147,10 @@ def err_ret_local_block : Error<
def note_local_var_initializer : Note<
"%select{via initialization of|binding reference}0 variable "
"%select{%2 |}1here">;
+def note_lambda_capture_initializer : Note<
+ "%select{implicitly |}2captured%select{| by reference}3"
+ "%select{%select{ due to use|}2 here|"
+ " via initialization of lambda capture %0}1">;
def note_init_with_default_member_initalizer : Note<
"initializing field %0 with default member initializer">;
@@ -9358,6 +9567,8 @@ def err_mips_builtin_requires_msa : Error<
"this builtin requires 'msa' ASE, please use -mmsa">;
def err_ppc_builtin_only_on_pwr7 : Error<
"this builtin is only valid on POWER7 or later CPUs">;
+def err_ppc_invalid_use_mma_type : Error<
+ "invalid use of PPC MMA type">;
def err_x86_builtin_invalid_rounding : Error<
"invalid rounding argument">;
def err_x86_builtin_invalid_scale : Error<
@@ -9394,7 +9605,7 @@ def err_selector_element_not_lvalue : Error<
def err_selector_element_type : Error<
"selector element type %0 is not a valid object">;
def err_selector_element_const_type : Error<
- "selector element of type %0 cannot be a constant l-value expression">;
+ "selector element of type %0 cannot be a constant lvalue expression">;
def err_collection_expr_type : Error<
"the type %0 is not a pointer to a fast-enumerable object">;
def warn_collection_expr_type : Warning<
@@ -9447,6 +9658,11 @@ def err_nsconsumed_attribute_mismatch : Error<
def err_nsreturns_retained_attribute_mismatch : Error<
"overriding method has mismatched ns_returns_%select{not_retained|retained}0"
" attributes">;
+def err_nserrordomain_invalid_decl : Error<
+ "domain argument %select{|%1 }0does not refer to global constant">;
+def err_nserrordomain_wrong_type : Error<
+ "domain argument %0 does not point to an NSString or CFString constant">;
+
def warn_nsconsumed_attribute_mismatch : Warning<
err_nsconsumed_attribute_mismatch.Text>, InGroup<NSConsumedMismatch>;
def warn_nsreturns_retained_attribute_mismatch : Warning<
@@ -9713,8 +9929,6 @@ def err_opencl_block_ref_block : Error<
"cannot refer to a block inside block">;
// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
-def err_opencl_builtin_to_addr_arg_num : Error<
- "invalid number of arguments to function: %0">;
def err_opencl_builtin_to_addr_invalid_arg : Error<
"invalid argument %0 to function: %1, expecting a generic pointer argument">;
@@ -9788,6 +10002,8 @@ def err_omp_bit_fields_forbidden_in_clause : Error<
"bit fields cannot be used to specify storage in a '%0' clause">;
def err_array_section_does_not_specify_contiguous_storage : Error<
"array section does not specify contiguous storage">;
+def err_array_section_does_not_specify_length : Error<
+ "array section does not specify length for outermost dimension">;
def err_omp_union_type_not_allowed : Error<
"mapping of union members is not allowed">;
def err_omp_expected_access_to_data_field : Error<
@@ -9796,6 +10012,8 @@ def err_omp_multiple_array_items_in_map_clause : Error<
"multiple array elements associated with the same variable are not allowed in map clauses of the same construct">;
def err_omp_duplicate_map_type_modifier : Error<
"same map type modifier has been specified more than once">;
+def err_omp_duplicate_motion_modifier : Error<
+ "same motion modifier has been specified more than once">;
def err_omp_pointer_mapped_along_with_derived_section : Error<
"pointer cannot be mapped along with a section derived from itself">;
def err_omp_original_storage_is_shared_and_does_not_contain : Error<
@@ -9996,22 +10214,22 @@ def err_omp_atomic_write_not_expression_statement : Error<
" where x is a lvalue expression with scalar type">;
def err_omp_atomic_update_not_expression_statement : Error<
"the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x',"
- " where x is an l-value expression with scalar type">;
+ " where x is an lvalue expression with scalar type">;
def err_omp_atomic_not_expression_statement : Error<
"the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x',"
- " where x is an l-value expression with scalar type">;
+ " where x is an lvalue expression with scalar type">;
def note_omp_atomic_update: Note<
"%select{expected an expression statement|expected built-in binary or unary operator|expected unary decrement/increment operation|"
"expected expression of scalar type|expected assignment expression|expected built-in binary operator|"
"expected one of '+', '*', '-', '/', '&', '^', '%|', '<<', or '>>' built-in operations|expected in right hand side of expression}0">;
def err_omp_atomic_capture_not_expression_statement : Error<
"the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x',"
- " where x and v are both l-value expressions with scalar type">;
+ " where x and v are both lvalue expressions with scalar type">;
def err_omp_atomic_capture_not_compound_statement : Error<
"the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}',"
" '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}',"
" '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}'"
- " where x is an l-value expression with scalar type">;
+ " where x is an lvalue expression with scalar type">;
def note_omp_atomic_capture: Note<
"%select{expected assignment expression|expected compound statement|expected exactly two expression statements|expected in right hand side of the first expression}0">;
def err_omp_atomic_several_clauses : Error<
@@ -10251,8 +10469,9 @@ def err_omp_invariant_or_linear_dependency : Error<
"expected loop invariant expression or '<invariant1> * %0 + <invariant2>' kind of expression">;
def err_omp_wrong_dependency_iterator_type : Error<
"expected an integer or a pointer type of the outer loop counter '%0' for non-rectangular nests">;
-def err_device_unsupported_type : Error <
- "%0 requires %1 bit size %2 type support, but device '%3' does not support it">;
+def err_device_unsupported_type
+ : Error<"%0 requires %select{|%2 bit size}1 %3 type support, but device "
+ "'%4' does not support it">;
def err_omp_lambda_capture_in_declare_target_not_to : Error<
"variable captured in declare target region must appear in a to clause">;
def err_omp_device_type_mismatch : Error<
@@ -10307,9 +10526,10 @@ def err_omp_non_lvalue_in_map_or_motion_clauses: Error<
"expected addressable lvalue in '%0' clause">;
def err_omp_var_expected : Error<
"expected variable of the '%0' type%select{|, not %2}1">;
-def warn_nested_declare_variant
- : Warning<"nesting `omp begin/end declare variant` is not supported yet; "
- "nested context ignored">,
+def warn_unknown_declare_variant_isa_trait
+ : Warning<"isa trait '%0' is not known to the current target; verify the "
+ "spelling or consider restricting the context selector with the "
+ "'arch' selector further">,
InGroup<SourceUsesOpenMP>;
def err_omp_non_pointer_type_array_shaping_base : Error<
"expected expression with a pointer to a complete type as a base of an array "
@@ -10330,6 +10550,10 @@ def err_omp_allocator_used_in_clauses : Error<
"data-sharing or data-mapping attribute clauses">;
def err_omp_allocator_not_in_uses_allocators : Error<
"allocator must be specified in the 'uses_allocators' clause">;
+def note_omp_protected_structured_block
+ : Note<"jump bypasses OpenMP structured block">;
+def note_omp_exits_structured_block
+ : Note<"jump exits scope of OpenMP structured block">;
} // end of OpenMP category
let CategoryName = "Related Result Type Issue" in {
@@ -10734,9 +10958,12 @@ def err_multiversion_duplicate : Error<
"multiversioned function redeclarations require identical target attributes">;
def err_multiversion_noproto : Error<
"multiversioned function must have a prototype">;
-def err_multiversion_no_other_attrs : Error<
+def err_multiversion_disallowed_other_attr : Error<
"attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioning cannot be combined"
- " with other attributes">;
+ " with attribute %1">;
+def err_multiversion_mismatched_attrs
+ : Error<"attributes on multiversioned functions must all match, attribute "
+ "%0 %select{is missing|has different arguments}1">;
def err_multiversion_diff : Error<
"multiversioned function declaration has a different %select{calling convention"
"|return type|constexpr specification|inline specification|storage class|"
@@ -10845,6 +11072,14 @@ def err_preserve_field_info_not_const: Error<
"__builtin_preserve_field_info argument %0 not a constant">;
def err_btf_type_id_not_const: Error<
"__builtin_btf_type_id argument %0 not a constant">;
+def err_preserve_type_info_invalid : Error<
+ "__builtin_preserve_type_info argument %0 invalid">;
+def err_preserve_type_info_not_const: Error<
+ "__builtin_preserve_type_info argument %0 not a constant">;
+def err_preserve_enum_value_invalid : Error<
+ "__builtin_preserve_enum_value argument %0 invalid">;
+def err_preserve_enum_value_not_const: Error<
+ "__builtin_preserve_enum_value argument %0 not a constant">;
def err_bit_cast_non_trivially_copyable : Error<
"__builtin_bit_cast %select{source|destination}0 type must be trivially copyable">;
@@ -10877,4 +11112,11 @@ def err_probability_not_constant_float : Error<
def err_probability_out_of_range : Error<
"probability argument to __builtin_expect_with_probability is outside the "
"range [0.0, 1.0]">;
+
+// TCB warnings
+def err_tcb_conflicting_attributes : Error<
+ "attributes '%0(\"%2\")' and '%1(\"%2\")' are mutually exclusive">;
+def warn_tcb_enforcement_violation : Warning<
+ "calling %0 is a violation of trusted computing base '%1'">,
+ InGroup<DiagGroup<"tcb-enforcement">>;
} // end of sema component.
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h
index 7e46a36a7fd3..b3d99fb3feaa 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h
@@ -15,7 +15,7 @@ namespace clang {
namespace diag {
enum {
#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
- SHOWINSYSHEADER, CATEGORY) \
+ SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
ENUM,
#define SERIALIZATIONSTART
#include "clang/Basic/DiagnosticSerializationKinds.inc"
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index f499996470c3..ce48833a8703 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -17,17 +17,10 @@ def err_fe_pch_malformed : Error<
"malformed or corrupted AST file: '%0'">, DefaultFatal;
def err_fe_pch_malformed_block : Error<
"malformed block record in PCH file: '%0'">, DefaultFatal;
-def err_fe_pch_file_modified : Error<
- "file '%0' has been modified since the precompiled header '%1' was built"
- ": %select{size|mtime|content}2 changed">,
- DefaultFatal;
-def err_fe_module_file_modified : Error<
- "file '%0' has been modified since the module file '%1' was built"
- ": %select{size|mtime|content}2 changed">,
- DefaultFatal;
def err_fe_ast_file_modified : Error<
- "file '%0' has been modified since the AST file '%1' was built"
- ": %select{size|mtime|content}2 changed">,
+ "file '%0' has been modified since the "
+ "%select{precompiled header|module file|AST file}1 '%2' was built"
+ ": %select{size|mtime|content}3 changed">,
DefaultFatal;
def err_fe_pch_file_overridden : Error<
"file '%0' from the precompiled header has been overridden">;
@@ -63,12 +56,12 @@ def err_pch_with_compiler_errors : Error<
def err_module_file_conflict : Error<
"module '%0' is defined in both '%1' and '%2'">, DefaultFatal;
-def err_module_file_not_found : Error<
+def err_ast_file_not_found : Error<
"%select{PCH|module|AST}0 file '%1' not found%select{|: %3}2">, DefaultFatal;
-def err_module_file_out_of_date : Error<
+def err_ast_file_out_of_date : Error<
"%select{PCH|module|AST}0 file '%1' is out of date and "
"needs to be rebuilt%select{|: %3}2">, DefaultFatal;
-def err_module_file_invalid : Error<
+def err_ast_file_invalid : Error<
"file '%1' is not a valid precompiled %select{PCH|module|AST}0 file">, DefaultFatal;
def note_module_file_imported_by : Note<
"imported by %select{|module '%2' in }1'%0'">;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/DirectoryEntry.h b/contrib/llvm-project/clang/include/clang/Basic/DirectoryEntry.h
new file mode 100644
index 000000000000..e0f4ae28321a
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Basic/DirectoryEntry.h
@@ -0,0 +1,298 @@
+//===- clang/Basic/DirectoryEntry.h - Directory references ------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Defines interfaces for clang::DirectoryEntry and clang::DirectoryEntryRef.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_DIRECTORYENTRY_H
+#define LLVM_CLANG_BASIC_DIRECTORYENTRY_H
+
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorOr.h"
+
+namespace clang {
+namespace FileMgr {
+
+template <class RefTy> class MapEntryOptionalStorage;
+
+} // end namespace FileMgr
+
+/// Cached information about one directory (either on disk or in
+/// the virtual file system).
+class DirectoryEntry {
+ friend class FileManager;
+
+ // FIXME: We should not be storing a directory entry name here.
+ StringRef Name; // Name of the directory.
+
+public:
+ StringRef getName() const { return Name; }
+};
+
+/// A reference to a \c DirectoryEntry that includes the name of the directory
+/// as it was accessed by the FileManager's client.
+class DirectoryEntryRef {
+public:
+ const DirectoryEntry &getDirEntry() const { return *ME->getValue(); }
+
+ StringRef getName() const { return ME->getKey(); }
+
+ /// Hash code is based on the DirectoryEntry, not the specific named
+ /// reference.
+ friend llvm::hash_code hash_value(DirectoryEntryRef Ref) {
+ return llvm::hash_value(&Ref.getDirEntry());
+ }
+
+ using MapEntry = llvm::StringMapEntry<llvm::ErrorOr<DirectoryEntry &>>;
+
+ const MapEntry &getMapEntry() const { return *ME; }
+
+ /// Check if RHS referenced the file in exactly the same way.
+ bool isSameRef(DirectoryEntryRef RHS) const { return ME == RHS.ME; }
+
+ DirectoryEntryRef() = delete;
+ DirectoryEntryRef(const MapEntry &ME) : ME(&ME) {}
+
+ /// Allow DirectoryEntryRef to degrade into 'const DirectoryEntry*' to
+ /// facilitate incremental adoption.
+ ///
+ /// The goal is to avoid code churn due to dances like the following:
+ /// \code
+ /// // Old code.
+ /// lvalue = rvalue;
+ ///
+ /// // Temporary code from an incremental patch.
+ /// lvalue = &rvalue.getDirectoryEntry();
+ ///
+ /// // Final code.
+ /// lvalue = rvalue;
+ /// \endcode
+ ///
+ /// FIXME: Once DirectoryEntryRef is "everywhere" and DirectoryEntry::getName
+ /// has been deleted, delete this implicit conversion.
+ operator const DirectoryEntry *() const { return &getDirEntry(); }
+
+private:
+ friend class FileMgr::MapEntryOptionalStorage<DirectoryEntryRef>;
+ struct optional_none_tag {};
+
+ // Private constructor for use by OptionalStorage.
+ DirectoryEntryRef(optional_none_tag) : ME(nullptr) {}
+ bool hasOptionalValue() const { return ME; }
+
+ friend struct llvm::DenseMapInfo<DirectoryEntryRef>;
+ struct dense_map_empty_tag {};
+ struct dense_map_tombstone_tag {};
+
+ // Private constructors for use by DenseMapInfo.
+ DirectoryEntryRef(dense_map_empty_tag)
+ : ME(llvm::DenseMapInfo<const MapEntry *>::getEmptyKey()) {}
+ DirectoryEntryRef(dense_map_tombstone_tag)
+ : ME(llvm::DenseMapInfo<const MapEntry *>::getTombstoneKey()) {}
+ bool isSpecialDenseMapKey() const {
+ return isSameRef(DirectoryEntryRef(dense_map_empty_tag())) ||
+ isSameRef(DirectoryEntryRef(dense_map_tombstone_tag()));
+ }
+
+ const MapEntry *ME;
+};
+
+namespace FileMgr {
+
+/// Customized storage for refs derived from map entires in FileManager, using
+/// the private optional_none_tag to keep it to the size of a single pointer.
+template <class RefTy> class MapEntryOptionalStorage {
+ using optional_none_tag = typename RefTy::optional_none_tag;
+ RefTy MaybeRef;
+
+public:
+ MapEntryOptionalStorage() : MaybeRef(optional_none_tag()) {}
+
+ template <class... ArgTypes>
+ explicit MapEntryOptionalStorage(llvm::optional_detail::in_place_t,
+ ArgTypes &&...Args)
+ : MaybeRef(std::forward<ArgTypes>(Args)...) {}
+
+ void reset() { MaybeRef = optional_none_tag(); }
+
+ bool hasValue() const { return MaybeRef.hasOptionalValue(); }
+
+ RefTy &getValue() LLVM_LVALUE_FUNCTION {
+ assert(hasValue());
+ return MaybeRef;
+ }
+ RefTy const &getValue() const LLVM_LVALUE_FUNCTION {
+ assert(hasValue());
+ return MaybeRef;
+ }
+#if LLVM_HAS_RVALUE_REFERENCE_THIS
+ RefTy &&getValue() && {
+ assert(hasValue());
+ return std::move(MaybeRef);
+ }
+#endif
+
+ template <class... Args> void emplace(Args &&...args) {
+ MaybeRef = RefTy(std::forward<Args>(args)...);
+ }
+
+ MapEntryOptionalStorage &operator=(RefTy Ref) {
+ MaybeRef = Ref;
+ return *this;
+ }
+};
+
+} // end namespace FileMgr
+} // end namespace clang
+
+namespace llvm {
+namespace optional_detail {
+
+/// Customize OptionalStorage<DirectoryEntryRef> to use DirectoryEntryRef and
+/// its optional_none_tag to keep it the size of a single pointer.
+template <>
+class OptionalStorage<clang::DirectoryEntryRef>
+ : public clang::FileMgr::MapEntryOptionalStorage<clang::DirectoryEntryRef> {
+ using StorageImpl =
+ clang::FileMgr::MapEntryOptionalStorage<clang::DirectoryEntryRef>;
+
+public:
+ OptionalStorage() = default;
+
+ template <class... ArgTypes>
+ explicit OptionalStorage(in_place_t, ArgTypes &&...Args)
+ : StorageImpl(in_place_t{}, std::forward<ArgTypes>(Args)...) {}
+
+ OptionalStorage &operator=(clang::DirectoryEntryRef Ref) {
+ StorageImpl::operator=(Ref);
+ return *this;
+ }
+};
+
+static_assert(sizeof(Optional<clang::DirectoryEntryRef>) ==
+ sizeof(clang::DirectoryEntryRef),
+ "Optional<DirectoryEntryRef> must avoid size overhead");
+
+static_assert(
+ std::is_trivially_copyable<Optional<clang::DirectoryEntryRef>>::value,
+ "Optional<DirectoryEntryRef> should be trivially copyable");
+
+} // end namespace optional_detail
+
+/// Specialisation of DenseMapInfo for DirectoryEntryRef.
+template <> struct DenseMapInfo<clang::DirectoryEntryRef> {
+ static inline clang::DirectoryEntryRef getEmptyKey() {
+ return clang::DirectoryEntryRef(
+ clang::DirectoryEntryRef::dense_map_empty_tag());
+ }
+
+ static inline clang::DirectoryEntryRef getTombstoneKey() {
+ return clang::DirectoryEntryRef(
+ clang::DirectoryEntryRef::dense_map_tombstone_tag());
+ }
+
+ static unsigned getHashValue(clang::DirectoryEntryRef Val) {
+ return hash_value(Val);
+ }
+
+ static bool isEqual(clang::DirectoryEntryRef LHS,
+ clang::DirectoryEntryRef RHS) {
+ // Catch the easy cases: both empty, both tombstone, or the same ref.
+ if (LHS.isSameRef(RHS))
+ return true;
+
+ // Confirm LHS and RHS are valid.
+ if (LHS.isSpecialDenseMapKey() || RHS.isSpecialDenseMapKey())
+ return false;
+
+ // It's safe to use operator==.
+ return LHS == RHS;
+ }
+};
+
+} // end namespace llvm
+
+namespace clang {
+
+/// Wrapper around Optional<DirectoryEntryRef> that degrades to 'const
+/// DirectoryEntry*', facilitating incremental patches to propagate
+/// DirectoryEntryRef.
+///
+/// This class can be used as return value or field where it's convenient for
+/// an Optional<DirectoryEntryRef> to degrade to a 'const DirectoryEntry*'. The
+/// purpose is to avoid code churn due to dances like the following:
+/// \code
+/// // Old code.
+/// lvalue = rvalue;
+///
+/// // Temporary code from an incremental patch.
+/// Optional<DirectoryEntryRef> MaybeF = rvalue;
+/// lvalue = MaybeF ? &MaybeF.getDirectoryEntry() : nullptr;
+///
+/// // Final code.
+/// lvalue = rvalue;
+/// \endcode
+///
+/// FIXME: Once DirectoryEntryRef is "everywhere" and DirectoryEntry::LastRef
+/// and DirectoryEntry::getName have been deleted, delete this class and
+/// replace instances with Optional<DirectoryEntryRef>.
+class OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr
+ : public Optional<DirectoryEntryRef> {
+public:
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr() = default;
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr(
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &&) = default;
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr(
+ const OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &) = default;
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &
+ operator=(OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &&) = default;
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &
+ operator=(const OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &) = default;
+
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr(llvm::NoneType) {}
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr(DirectoryEntryRef Ref)
+ : Optional<DirectoryEntryRef>(Ref) {}
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr(Optional<DirectoryEntryRef> MaybeRef)
+ : Optional<DirectoryEntryRef>(MaybeRef) {}
+
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &operator=(llvm::NoneType) {
+ Optional<DirectoryEntryRef>::operator=(None);
+ return *this;
+ }
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &operator=(DirectoryEntryRef Ref) {
+ Optional<DirectoryEntryRef>::operator=(Ref);
+ return *this;
+ }
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr &
+ operator=(Optional<DirectoryEntryRef> MaybeRef) {
+ Optional<DirectoryEntryRef>::operator=(MaybeRef);
+ return *this;
+ }
+
+ /// Degrade to 'const DirectoryEntry *' to allow DirectoryEntry::LastRef and
+ /// DirectoryEntry::getName have been deleted, delete this class and replace
+ /// instances with Optional<DirectoryEntryRef>
+ operator const DirectoryEntry *() const {
+ return hasValue() ? &getValue().getDirEntry() : nullptr;
+ }
+};
+
+static_assert(std::is_trivially_copyable<
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr>::value,
+ "OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr should be "
+ "trivially copyable");
+
+} // end namespace clang
+
+#endif // LLVM_CLANG_BASIC_DIRECTORYENTRY_H
diff --git a/contrib/llvm-project/clang/include/clang/Basic/FPOptions.def b/contrib/llvm-project/clang/include/clang/Basic/FPOptions.def
index 6b6789b8ecc8..a93fa475cd5f 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/FPOptions.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/FPOptions.def
@@ -7,14 +7,14 @@
//===----------------------------------------------------------------------===//
// This file defines the Floating Point language options. Users of this file
-// must define the FPOPT macro to make use of this information.
+// must define the OPTION macro to make use of this information.
#ifndef OPTION
# error Define the OPTION macro to handle floating point language options
#endif
// OPTION(name, type, width, previousName)
OPTION(FPContractMode, LangOptions::FPModeKind, 2, First)
-OPTION(RoundingMode, RoundingMode, 3, FPContractMode)
+OPTION(RoundingMode, LangOptions::RoundingMode, 3, FPContractMode)
OPTION(FPExceptionMode, LangOptions::FPExceptionModeKind, 2, RoundingMode)
OPTION(AllowFEnvAccess, bool, 1, FPExceptionMode)
OPTION(AllowFPReassociate, bool, 1, AllowFEnvAccess)
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Features.def b/contrib/llvm-project/clang/include/clang/Basic/Features.def
index 999bcb7e2e29..5424da67b62d 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Features.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/Features.def
@@ -85,6 +85,7 @@ FEATURE(cxx_rtti, LangOpts.RTTI &&LangOpts.RTTIData)
FEATURE(enumerator_attributes, true)
FEATURE(nullability, true)
FEATURE(nullability_on_arrays, true)
+FEATURE(nullability_nullable_result, true)
FEATURE(memory_sanitizer,
LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
@@ -256,5 +257,7 @@ EXTENSION(gnu_asm, LangOpts.GNUAsm)
EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
EXTENSION(matrix_types, LangOpts.MatrixTypes)
+FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && LangOpts.RelativeCXXABIVTables)
+
#undef EXTENSION
#undef FEATURE
diff --git a/contrib/llvm-project/clang/include/clang/Basic/FileEntry.h b/contrib/llvm-project/clang/include/clang/Basic/FileEntry.h
new file mode 100644
index 000000000000..6e91b42e18b7
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Basic/FileEntry.h
@@ -0,0 +1,406 @@
+//===- clang/Basic/FileEntry.h - File references ----------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Defines interfaces for clang::FileEntry and clang::FileEntryRef.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_FILEENTRY_H
+#define LLVM_CLANG_BASIC_FILEENTRY_H
+
+#include "clang/Basic/DirectoryEntry.h"
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
+
+namespace llvm {
+
+class MemoryBuffer;
+
+namespace vfs {
+
+class File;
+
+} // namespace vfs
+} // namespace llvm
+
+namespace clang {
+
+class FileEntryRef;
+
+} // namespace clang
+
+namespace llvm {
+namespace optional_detail {
+
+/// Forward declare a template specialization for OptionalStorage.
+template <>
+class OptionalStorage<clang::FileEntryRef, /*is_trivially_copyable*/ true>;
+
+} // namespace optional_detail
+} // namespace llvm
+
+namespace clang {
+
+class FileEntry;
+
+/// A reference to a \c FileEntry that includes the name of the file as it was
+/// accessed by the FileManager's client.
+class FileEntryRef {
+public:
+ StringRef getName() const { return ME->first(); }
+ const FileEntry &getFileEntry() const {
+ return *ME->second->V.get<FileEntry *>();
+ }
+ DirectoryEntryRef getDir() const { return *ME->second->Dir; }
+
+ inline bool isValid() const;
+ inline off_t getSize() const;
+ inline unsigned getUID() const;
+ inline const llvm::sys::fs::UniqueID &getUniqueID() const;
+ inline time_t getModificationTime() const;
+ inline bool isNamedPipe() const;
+ inline void closeFile() const;
+
+ /// Check if the underlying FileEntry is the same, intentially ignoring
+ /// whether the file was referenced with the same spelling of the filename.
+ friend bool operator==(const FileEntryRef &LHS, const FileEntryRef &RHS) {
+ return &LHS.getFileEntry() == &RHS.getFileEntry();
+ }
+ friend bool operator==(const FileEntry *LHS, const FileEntryRef &RHS) {
+ return LHS == &RHS.getFileEntry();
+ }
+ friend bool operator==(const FileEntryRef &LHS, const FileEntry *RHS) {
+ return &LHS.getFileEntry() == RHS;
+ }
+ friend bool operator!=(const FileEntryRef &LHS, const FileEntryRef &RHS) {
+ return !(LHS == RHS);
+ }
+ friend bool operator!=(const FileEntry *LHS, const FileEntryRef &RHS) {
+ return !(LHS == RHS);
+ }
+ friend bool operator!=(const FileEntryRef &LHS, const FileEntry *RHS) {
+ return !(LHS == RHS);
+ }
+
+ /// Hash code is based on the FileEntry, not the specific named reference,
+ /// just like operator==.
+ friend llvm::hash_code hash_value(FileEntryRef Ref) {
+ return llvm::hash_value(&Ref.getFileEntry());
+ }
+
+ struct MapValue;
+
+ /// Type used in the StringMap.
+ using MapEntry = llvm::StringMapEntry<llvm::ErrorOr<MapValue>>;
+
+ /// Type stored in the StringMap.
+ struct MapValue {
+ /// The pointer at another MapEntry is used when the FileManager should
+ /// silently forward from one name to another, which occurs in Redirecting
+ /// VFSs that use external names. In that case, the \c FileEntryRef
+ /// returned by the \c FileManager will have the external name, and not the
+ /// name that was used to lookup the file.
+ ///
+ /// The second type is really a `const MapEntry *`, but that confuses
+ /// gcc5.3. Once that's no longer supported, change this back.
+ llvm::PointerUnion<FileEntry *, const void *> V;
+
+ /// Directory the file was found in. Set if and only if V is a FileEntry.
+ Optional<DirectoryEntryRef> Dir;
+
+ MapValue() = delete;
+ MapValue(FileEntry &FE, DirectoryEntryRef Dir) : V(&FE), Dir(Dir) {}
+ MapValue(MapEntry &ME) : V(&ME) {}
+ };
+
+ /// Check if RHS referenced the file in exactly the same way.
+ bool isSameRef(const FileEntryRef &RHS) const { return ME == RHS.ME; }
+
+ /// Allow FileEntryRef to degrade into 'const FileEntry*' to facilitate
+ /// incremental adoption.
+ ///
+ /// The goal is to avoid code churn due to dances like the following:
+ /// \code
+ /// // Old code.
+ /// lvalue = rvalue;
+ ///
+ /// // Temporary code from an incremental patch.
+ /// lvalue = &rvalue.getFileEntry();
+ ///
+ /// // Final code.
+ /// lvalue = rvalue;
+ /// \endcode
+ ///
+ /// FIXME: Once FileEntryRef is "everywhere" and FileEntry::LastRef and
+ /// FileEntry::getName have been deleted, delete this implicit conversion.
+ operator const FileEntry *() const { return &getFileEntry(); }
+
+ FileEntryRef() = delete;
+ explicit FileEntryRef(const MapEntry &ME) : ME(&ME) {
+ assert(ME.second && "Expected payload");
+ assert(ME.second->V && "Expected non-null");
+ assert(ME.second->V.is<FileEntry *>() && "Expected FileEntry");
+ }
+
+ /// Expose the underlying MapEntry to simplify packing in a PointerIntPair or
+ /// PointerUnion and allow construction in Optional.
+ const clang::FileEntryRef::MapEntry &getMapEntry() const { return *ME; }
+
+private:
+ friend class FileMgr::MapEntryOptionalStorage<FileEntryRef>;
+ struct optional_none_tag {};
+
+ // Private constructor for use by OptionalStorage.
+ FileEntryRef(optional_none_tag) : ME(nullptr) {}
+ bool hasOptionalValue() const { return ME; }
+
+ friend struct llvm::DenseMapInfo<FileEntryRef>;
+ struct dense_map_empty_tag {};
+ struct dense_map_tombstone_tag {};
+
+ // Private constructors for use by DenseMapInfo.
+ FileEntryRef(dense_map_empty_tag)
+ : ME(llvm::DenseMapInfo<const MapEntry *>::getEmptyKey()) {}
+ FileEntryRef(dense_map_tombstone_tag)
+ : ME(llvm::DenseMapInfo<const MapEntry *>::getTombstoneKey()) {}
+ bool isSpecialDenseMapKey() const {
+ return isSameRef(FileEntryRef(dense_map_empty_tag())) ||
+ isSameRef(FileEntryRef(dense_map_tombstone_tag()));
+ }
+
+ const MapEntry *ME;
+};
+
+static_assert(sizeof(FileEntryRef) == sizeof(const FileEntry *),
+ "FileEntryRef must avoid size overhead");
+
+static_assert(std::is_trivially_copyable<FileEntryRef>::value,
+ "FileEntryRef must be trivially copyable");
+
+} // end namespace clang
+
+namespace llvm {
+namespace optional_detail {
+
+/// Customize OptionalStorage<FileEntryRef> to use FileEntryRef and its
+/// optional_none_tag to keep it the size of a single pointer.
+template <>
+class OptionalStorage<clang::FileEntryRef>
+ : public clang::FileMgr::MapEntryOptionalStorage<clang::FileEntryRef> {
+ using StorageImpl =
+ clang::FileMgr::MapEntryOptionalStorage<clang::FileEntryRef>;
+
+public:
+ OptionalStorage() = default;
+
+ template <class... ArgTypes>
+ explicit OptionalStorage(in_place_t, ArgTypes &&...Args)
+ : StorageImpl(in_place_t{}, std::forward<ArgTypes>(Args)...) {}
+
+ OptionalStorage &operator=(clang::FileEntryRef Ref) {
+ StorageImpl::operator=(Ref);
+ return *this;
+ }
+};
+
+static_assert(sizeof(Optional<clang::FileEntryRef>) ==
+ sizeof(clang::FileEntryRef),
+ "Optional<FileEntryRef> must avoid size overhead");
+
+static_assert(std::is_trivially_copyable<Optional<clang::FileEntryRef>>::value,
+ "Optional<FileEntryRef> should be trivially copyable");
+
+} // end namespace optional_detail
+
+/// Specialisation of DenseMapInfo for FileEntryRef.
+template <> struct DenseMapInfo<clang::FileEntryRef> {
+ static inline clang::FileEntryRef getEmptyKey() {
+ return clang::FileEntryRef(clang::FileEntryRef::dense_map_empty_tag());
+ }
+
+ static inline clang::FileEntryRef getTombstoneKey() {
+ return clang::FileEntryRef(clang::FileEntryRef::dense_map_tombstone_tag());
+ }
+
+ static unsigned getHashValue(clang::FileEntryRef Val) {
+ return hash_value(Val);
+ }
+
+ static bool isEqual(clang::FileEntryRef LHS, clang::FileEntryRef RHS) {
+ // Catch the easy cases: both empty, both tombstone, or the same ref.
+ if (LHS.isSameRef(RHS))
+ return true;
+
+ // Confirm LHS and RHS are valid.
+ if (LHS.isSpecialDenseMapKey() || RHS.isSpecialDenseMapKey())
+ return false;
+
+ // It's safe to use operator==.
+ return LHS == RHS;
+ }
+};
+
+} // end namespace llvm
+
+namespace clang {
+
+/// Wrapper around Optional<FileEntryRef> that degrades to 'const FileEntry*',
+/// facilitating incremental patches to propagate FileEntryRef.
+///
+/// This class can be used as return value or field where it's convenient for
+/// an Optional<FileEntryRef> to degrade to a 'const FileEntry*'. The purpose
+/// is to avoid code churn due to dances like the following:
+/// \code
+/// // Old code.
+/// lvalue = rvalue;
+///
+/// // Temporary code from an incremental patch.
+/// Optional<FileEntryRef> MaybeF = rvalue;
+/// lvalue = MaybeF ? &MaybeF.getFileEntry() : nullptr;
+///
+/// // Final code.
+/// lvalue = rvalue;
+/// \endcode
+///
+/// FIXME: Once FileEntryRef is "everywhere" and FileEntry::LastRef and
+/// FileEntry::getName have been deleted, delete this class and replace
+/// instances with Optional<FileEntryRef>.
+class OptionalFileEntryRefDegradesToFileEntryPtr
+ : public Optional<FileEntryRef> {
+public:
+ OptionalFileEntryRefDegradesToFileEntryPtr() = default;
+ OptionalFileEntryRefDegradesToFileEntryPtr(
+ OptionalFileEntryRefDegradesToFileEntryPtr &&) = default;
+ OptionalFileEntryRefDegradesToFileEntryPtr(
+ const OptionalFileEntryRefDegradesToFileEntryPtr &) = default;
+ OptionalFileEntryRefDegradesToFileEntryPtr &
+ operator=(OptionalFileEntryRefDegradesToFileEntryPtr &&) = default;
+ OptionalFileEntryRefDegradesToFileEntryPtr &
+ operator=(const OptionalFileEntryRefDegradesToFileEntryPtr &) = default;
+
+ OptionalFileEntryRefDegradesToFileEntryPtr(llvm::NoneType) {}
+ OptionalFileEntryRefDegradesToFileEntryPtr(FileEntryRef Ref)
+ : Optional<FileEntryRef>(Ref) {}
+ OptionalFileEntryRefDegradesToFileEntryPtr(Optional<FileEntryRef> MaybeRef)
+ : Optional<FileEntryRef>(MaybeRef) {}
+
+ OptionalFileEntryRefDegradesToFileEntryPtr &operator=(llvm::NoneType) {
+ Optional<FileEntryRef>::operator=(None);
+ return *this;
+ }
+ OptionalFileEntryRefDegradesToFileEntryPtr &operator=(FileEntryRef Ref) {
+ Optional<FileEntryRef>::operator=(Ref);
+ return *this;
+ }
+ OptionalFileEntryRefDegradesToFileEntryPtr &
+ operator=(Optional<FileEntryRef> MaybeRef) {
+ Optional<FileEntryRef>::operator=(MaybeRef);
+ return *this;
+ }
+
+ /// Degrade to 'const FileEntry *' to allow FileEntry::LastRef and
+ /// FileEntry::getName have been deleted, delete this class and replace
+ /// instances with Optional<FileEntryRef>
+ operator const FileEntry *() const {
+ return hasValue() ? &getValue().getFileEntry() : nullptr;
+ }
+};
+
+static_assert(
+ std::is_trivially_copyable<
+ OptionalFileEntryRefDegradesToFileEntryPtr>::value,
+ "OptionalFileEntryRefDegradesToFileEntryPtr should be trivially copyable");
+
+/// Cached information about one file (either on disk
+/// or in the virtual file system).
+///
+/// If the 'File' member is valid, then this FileEntry has an open file
+/// descriptor for the file.
+class FileEntry {
+ friend class FileManager;
+
+ std::string RealPathName; // Real path to the file; could be empty.
+ off_t Size = 0; // File size in bytes.
+ time_t ModTime = 0; // Modification time of file.
+ const DirectoryEntry *Dir = nullptr; // Directory file lives in.
+ llvm::sys::fs::UniqueID UniqueID;
+ unsigned UID = 0; // A unique (small) ID for the file.
+ bool IsNamedPipe = false;
+ bool IsValid = false; // Is this \c FileEntry initialized and valid?
+
+ /// The open file, if it is owned by the \p FileEntry.
+ mutable std::unique_ptr<llvm::vfs::File> File;
+
+ /// The file content, if it is owned by the \p FileEntry.
+ std::unique_ptr<llvm::MemoryBuffer> Content;
+
+ // First access name for this FileEntry.
+ //
+ // This is Optional only to allow delayed construction (FileEntryRef has no
+ // default constructor). It should always have a value in practice.
+ //
+ // TODO: remove this once everyone that needs a name uses FileEntryRef.
+ Optional<FileEntryRef> LastRef;
+
+public:
+ FileEntry();
+ ~FileEntry();
+
+ FileEntry(const FileEntry &) = delete;
+ FileEntry &operator=(const FileEntry &) = delete;
+
+ StringRef getName() const { return LastRef->getName(); }
+ FileEntryRef getLastRef() const { return *LastRef; }
+
+ StringRef tryGetRealPathName() const { return RealPathName; }
+ bool isValid() const { return IsValid; }
+ off_t getSize() const { return Size; }
+ unsigned getUID() const { return UID; }
+ const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
+ time_t getModificationTime() const { return ModTime; }
+
+ /// Return the directory the file lives in.
+ const DirectoryEntry *getDir() const { return Dir; }
+
+ bool operator<(const FileEntry &RHS) const { return UniqueID < RHS.UniqueID; }
+
+ /// Check whether the file is a named pipe (and thus can't be opened by
+ /// the native FileManager methods).
+ bool isNamedPipe() const { return IsNamedPipe; }
+
+ void closeFile() const;
+};
+
+bool FileEntryRef::isValid() const { return getFileEntry().isValid(); }
+
+off_t FileEntryRef::getSize() const { return getFileEntry().getSize(); }
+
+unsigned FileEntryRef::getUID() const { return getFileEntry().getUID(); }
+
+const llvm::sys::fs::UniqueID &FileEntryRef::getUniqueID() const {
+ return getFileEntry().getUniqueID();
+}
+
+time_t FileEntryRef::getModificationTime() const {
+ return getFileEntry().getModificationTime();
+}
+
+bool FileEntryRef::isNamedPipe() const { return getFileEntry().isNamedPipe(); }
+
+void FileEntryRef::closeFile() const { getFileEntry().closeFile(); }
+
+} // end namespace clang
+
+#endif // LLVM_CLANG_BASIC_FILEENTRY_H
diff --git a/contrib/llvm-project/clang/include/clang/Basic/FileManager.h b/contrib/llvm-project/clang/include/clang/Basic/FileManager.h
index 089304e1d1e6..974771a8f8f3 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/FileManager.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/FileManager.h
@@ -14,6 +14,8 @@
#ifndef LLVM_CLANG_BASIC_FILEMANAGER_H
#define LLVM_CLANG_BASIC_FILEMANAGER_H
+#include "clang/Basic/DirectoryEntry.h"
+#include "clang/Basic/FileEntry.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
@@ -41,127 +43,6 @@ namespace clang {
class FileSystemStatCache;
-/// Cached information about one directory (either on disk or in
-/// the virtual file system).
-class DirectoryEntry {
- friend class FileManager;
-
- // FIXME: We should not be storing a directory entry name here.
- StringRef Name; // Name of the directory.
-
-public:
- StringRef getName() const { return Name; }
-};
-
-/// A reference to a \c DirectoryEntry that includes the name of the directory
-/// as it was accessed by the FileManager's client.
-class DirectoryEntryRef {
-public:
- const DirectoryEntry &getDirEntry() const { return *Entry->getValue(); }
-
- StringRef getName() const { return Entry->getKey(); }
-
-private:
- friend class FileManager;
-
- DirectoryEntryRef(
- llvm::StringMapEntry<llvm::ErrorOr<DirectoryEntry &>> *Entry)
- : Entry(Entry) {}
-
- const llvm::StringMapEntry<llvm::ErrorOr<DirectoryEntry &>> *Entry;
-};
-
-/// Cached information about one file (either on disk
-/// or in the virtual file system).
-///
-/// If the 'File' member is valid, then this FileEntry has an open file
-/// descriptor for the file.
-class FileEntry {
- friend class FileManager;
-
- StringRef Name; // Name of the file.
- std::string RealPathName; // Real path to the file; could be empty.
- off_t Size; // File size in bytes.
- time_t ModTime; // Modification time of file.
- const DirectoryEntry *Dir; // Directory file lives in.
- llvm::sys::fs::UniqueID UniqueID;
- unsigned UID; // A unique (small) ID for the file.
- bool IsNamedPipe;
- bool IsValid; // Is this \c FileEntry initialized and valid?
-
- /// The open file, if it is owned by the \p FileEntry.
- mutable std::unique_ptr<llvm::vfs::File> File;
-
-public:
- FileEntry()
- : UniqueID(0, 0), IsNamedPipe(false), IsValid(false)
- {}
-
- FileEntry(const FileEntry &) = delete;
- FileEntry &operator=(const FileEntry &) = delete;
-
- StringRef getName() const { return Name; }
- StringRef tryGetRealPathName() const { return RealPathName; }
- bool isValid() const { return IsValid; }
- off_t getSize() const { return Size; }
- unsigned getUID() const { return UID; }
- const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
- time_t getModificationTime() const { return ModTime; }
-
- /// Return the directory the file lives in.
- const DirectoryEntry *getDir() const { return Dir; }
-
- bool operator<(const FileEntry &RHS) const { return UniqueID < RHS.UniqueID; }
-
- /// Check whether the file is a named pipe (and thus can't be opened by
- /// the native FileManager methods).
- bool isNamedPipe() const { return IsNamedPipe; }
-
- void closeFile() const {
- File.reset(); // rely on destructor to close File
- }
-
- // Only for use in tests to see if deferred opens are happening, rather than
- // relying on RealPathName being empty.
- bool isOpenForTests() const { return File != nullptr; }
-};
-
-/// A reference to a \c FileEntry that includes the name of the file as it was
-/// accessed by the FileManager's client.
-class FileEntryRef {
-public:
- FileEntryRef() = delete;
- FileEntryRef(StringRef Name, const FileEntry &Entry)
- : Name(Name), Entry(&Entry) {}
-
- const StringRef getName() const { return Name; }
-
- bool isValid() const { return Entry->isValid(); }
-
- const FileEntry &getFileEntry() const { return *Entry; }
-
- off_t getSize() const { return Entry->getSize(); }
-
- unsigned getUID() const { return Entry->getUID(); }
-
- const llvm::sys::fs::UniqueID &getUniqueID() const {
- return Entry->getUniqueID();
- }
-
- time_t getModificationTime() const { return Entry->getModificationTime(); }
-
- friend bool operator==(const FileEntryRef &LHS, const FileEntryRef &RHS) {
- return LHS.Entry == RHS.Entry && LHS.Name == RHS.Name;
- }
- friend bool operator!=(const FileEntryRef &LHS, const FileEntryRef &RHS) {
- return !(LHS == RHS);
- }
-
-private:
- StringRef Name;
- const FileEntry *Entry;
-};
-
/// Implements support for file system lookup, file system caching,
/// and directory search management.
///
@@ -203,26 +84,24 @@ class FileManager : public RefCountedBase<FileManager> {
llvm::StringMap<llvm::ErrorOr<DirectoryEntry &>, llvm::BumpPtrAllocator>
SeenDirEntries;
- /// A reference to the file entry that is associated with a particular
- /// filename, or a reference to another filename that should be looked up
- /// instead of the accessed filename.
- ///
- /// The reference to another filename is specifically useful for Redirecting
- /// VFSs that use external names. In that case, the \c FileEntryRef returned
- /// by the \c FileManager will have the external name, and not the name that
- /// was used to lookup the file.
- using SeenFileEntryOrRedirect =
- llvm::PointerUnion<FileEntry *, const StringRef *>;
-
/// A cache that maps paths to file entries (either real or
/// virtual) we have looked up, or an error that occurred when we looked up
/// the file.
///
/// \see SeenDirEntries
- llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
- llvm::BumpPtrAllocator>
+ llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>, llvm::BumpPtrAllocator>
SeenFileEntries;
+ /// A mirror of SeenFileEntries to give fake answers for getBypassFile().
+ ///
+ /// Don't bother hooking up a BumpPtrAllocator. This should be rarely used,
+ /// and only on error paths.
+ std::unique_ptr<llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>
+ SeenBypassFileEntries;
+
+ /// The file entry for stdin, if it has been accessed through the FileManager.
+ Optional<FileEntryRef> STDIN;
+
/// The canonical names of files and directories .
llvm::DenseMap<const void *, llvm::StringRef> CanonicalNames;
@@ -341,6 +220,14 @@ public:
bool OpenFile = false,
bool CacheFailure = true);
+ /// Get the FileEntryRef for stdin, returning an error if stdin cannot be
+ /// read.
+ ///
+ /// This reads and caches stdin before returning. Subsequent calls return the
+ /// same file entry, and a reference to the cached input is returned by calls
+ /// to getBufferForFile.
+ llvm::Expected<FileEntryRef> getSTDIN();
+
/// Get a FileEntryRef if it exists, without doing anything on error.
llvm::Optional<FileEntryRef> getOptionalFileRef(StringRef Filename,
bool OpenFile = false,
@@ -363,6 +250,9 @@ public:
/// if there were a file with the given name on disk.
///
/// The file itself is not accessed.
+ FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size,
+ time_t ModificationTime);
+
const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
time_t ModificationTime);
diff --git a/contrib/llvm-project/clang/include/clang/Basic/FixedPoint.h b/contrib/llvm-project/clang/include/clang/Basic/FixedPoint.h
deleted file mode 100644
index 0d181f30907f..000000000000
--- a/contrib/llvm-project/clang/include/clang/Basic/FixedPoint.h
+++ /dev/null
@@ -1,215 +0,0 @@
-//===- FixedPoint.h - Fixed point constant handling -------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-/// \file
-/// Defines the fixed point number interface.
-/// This is a class for abstracting various operations performed on fixed point
-/// types described in ISO/IEC JTC1 SC22 WG14 N1169 starting at clause 4.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef LLVM_CLANG_BASIC_FIXEDPOINT_H
-#define LLVM_CLANG_BASIC_FIXEDPOINT_H
-
-#include "llvm/ADT/APSInt.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/Support/raw_ostream.h"
-
-namespace clang {
-
-class ASTContext;
-class QualType;
-
-/// The fixed point semantics work similarly to llvm::fltSemantics. The width
-/// specifies the whole bit width of the underlying scaled integer (with padding
-/// if any). The scale represents the number of fractional bits in this type.
-/// When HasUnsignedPadding is true and this type is unsigned, the first bit
-/// in the value this represents is treated as padding.
-class FixedPointSemantics {
-public:
- FixedPointSemantics(unsigned Width, unsigned Scale, bool IsSigned,
- bool IsSaturated, bool HasUnsignedPadding)
- : Width(Width), Scale(Scale), IsSigned(IsSigned),
- IsSaturated(IsSaturated), HasUnsignedPadding(HasUnsignedPadding) {
- assert(Width >= Scale && "Not enough room for the scale");
- assert(!(IsSigned && HasUnsignedPadding) &&
- "Cannot have unsigned padding on a signed type.");
- }
-
- unsigned getWidth() const { return Width; }
- unsigned getScale() const { return Scale; }
- bool isSigned() const { return IsSigned; }
- bool isSaturated() const { return IsSaturated; }
- bool hasUnsignedPadding() const { return HasUnsignedPadding; }
-
- void setSaturated(bool Saturated) { IsSaturated = Saturated; }
-
- /// Return the number of integral bits represented by these semantics. These
- /// are separate from the fractional bits and do not include the sign or
- /// padding bit.
- unsigned getIntegralBits() const {
- if (IsSigned || (!IsSigned && HasUnsignedPadding))
- return Width - Scale - 1;
- else
- return Width - Scale;
- }
-
- /// Return the FixedPointSemantics that allows for calculating the full
- /// precision semantic that can precisely represent the precision and ranges
- /// of both input values. This does not compute the resulting semantics for a
- /// given binary operation.
- FixedPointSemantics
- getCommonSemantics(const FixedPointSemantics &Other) const;
-
- /// Return the FixedPointSemantics for an integer type.
- static FixedPointSemantics GetIntegerSemantics(unsigned Width,
- bool IsSigned) {
- return FixedPointSemantics(Width, /*Scale=*/0, IsSigned,
- /*IsSaturated=*/false,
- /*HasUnsignedPadding=*/false);
- }
-
-private:
- unsigned Width : 16;
- unsigned Scale : 13;
- unsigned IsSigned : 1;
- unsigned IsSaturated : 1;
- unsigned HasUnsignedPadding : 1;
-};
-
-/// The APFixedPoint class works similarly to APInt/APSInt in that it is a
-/// functional replacement for a scaled integer. It is meant to replicate the
-/// fixed point types proposed in ISO/IEC JTC1 SC22 WG14 N1169. The class carries
-/// info about the fixed point type's width, sign, scale, and saturation, and
-/// provides different operations that would normally be performed on fixed point
-/// types.
-///
-/// Semantically this does not represent any existing C type other than fixed
-/// point types and should eventually be moved to LLVM if fixed point types gain
-/// native IR support.
-class APFixedPoint {
-public:
- APFixedPoint(const llvm::APInt &Val, const FixedPointSemantics &Sema)
- : Val(Val, !Sema.isSigned()), Sema(Sema) {
- assert(Val.getBitWidth() == Sema.getWidth() &&
- "The value should have a bit width that matches the Sema width");
- }
-
- APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
- : APFixedPoint(llvm::APInt(Sema.getWidth(), Val, Sema.isSigned()),
- Sema) {}
-
- // Zero initialization.
- APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}
-
- llvm::APSInt getValue() const { return llvm::APSInt(Val, !Sema.isSigned()); }
- inline unsigned getWidth() const { return Sema.getWidth(); }
- inline unsigned getScale() const { return Sema.getScale(); }
- inline bool isSaturated() const { return Sema.isSaturated(); }
- inline bool isSigned() const { return Sema.isSigned(); }
- inline bool hasPadding() const { return Sema.hasUnsignedPadding(); }
- FixedPointSemantics getSemantics() const { return Sema; }
-
- bool getBoolValue() const { return Val.getBoolValue(); }
-
- // Convert this number to match the semantics provided. If the overflow
- // parameter is provided, set this value to true or false to indicate if this
- // operation results in an overflow.
- APFixedPoint convert(const FixedPointSemantics &DstSema,
- bool *Overflow = nullptr) const;
-
- // Perform binary operations on a fixed point type. The resulting fixed point
- // value will be in the common, full precision semantics that can represent
- // the precision and ranges of both input values. See convert() for an
- // explanation of the Overflow parameter.
- APFixedPoint add(const APFixedPoint &Other, bool *Overflow = nullptr) const;
- APFixedPoint sub(const APFixedPoint &Other, bool *Overflow = nullptr) const;
- APFixedPoint mul(const APFixedPoint &Other, bool *Overflow = nullptr) const;
- APFixedPoint div(const APFixedPoint &Other, bool *Overflow = nullptr) const;
-
- /// Perform a unary negation (-X) on this fixed point type, taking into
- /// account saturation if applicable.
- APFixedPoint negate(bool *Overflow = nullptr) const;
-
- APFixedPoint shr(unsigned Amt) const {
- return APFixedPoint(Val >> Amt, Sema);
- }
-
- APFixedPoint shl(unsigned Amt) const {
- return APFixedPoint(Val << Amt, Sema);
- }
-
- /// Return the integral part of this fixed point number, rounded towards
- /// zero. (-2.5k -> -2)
- llvm::APSInt getIntPart() const {
- if (Val < 0 && Val != -Val) // Cover the case when we have the min val
- return -(-Val >> getScale());
- else
- return Val >> getScale();
- }
-
- /// Return the integral part of this fixed point number, rounded towards
- /// zero. The value is stored into an APSInt with the provided width and sign.
- /// If the overflow parameter is provided, and the integral value is not able
- /// to be fully stored in the provided width and sign, the overflow parameter
- /// is set to true.
- ///
- /// If the overflow parameter is provided, set this value to true or false to
- /// indicate if this operation results in an overflow.
- llvm::APSInt convertToInt(unsigned DstWidth, bool DstSign,
- bool *Overflow = nullptr) const;
-
- void toString(llvm::SmallVectorImpl<char> &Str) const;
- std::string toString() const {
- llvm::SmallString<40> S;
- toString(S);
- return std::string(S.str());
- }
-
- // If LHS > RHS, return 1. If LHS == RHS, return 0. If LHS < RHS, return -1.
- int compare(const APFixedPoint &Other) const;
- bool operator==(const APFixedPoint &Other) const {
- return compare(Other) == 0;
- }
- bool operator!=(const APFixedPoint &Other) const {
- return compare(Other) != 0;
- }
- bool operator>(const APFixedPoint &Other) const { return compare(Other) > 0; }
- bool operator<(const APFixedPoint &Other) const { return compare(Other) < 0; }
- bool operator>=(const APFixedPoint &Other) const {
- return compare(Other) >= 0;
- }
- bool operator<=(const APFixedPoint &Other) const {
- return compare(Other) <= 0;
- }
-
- static APFixedPoint getMax(const FixedPointSemantics &Sema);
- static APFixedPoint getMin(const FixedPointSemantics &Sema);
-
- /// Create an APFixedPoint with a value equal to that of the provided integer,
- /// and in the same semantics as the provided target semantics. If the value
- /// is not able to fit in the specified fixed point semantics, and the
- /// overflow parameter is provided, it is set to true.
- static APFixedPoint getFromIntValue(const llvm::APSInt &Value,
- const FixedPointSemantics &DstFXSema,
- bool *Overflow = nullptr);
-
-private:
- llvm::APSInt Val;
- FixedPointSemantics Sema;
-};
-
-inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
- const APFixedPoint &FX) {
- OS << FX.toString();
- return OS;
-}
-
-} // namespace clang
-
-#endif
diff --git a/contrib/llvm-project/clang/include/clang/Basic/LLVM.h b/contrib/llvm-project/clang/include/clang/Basic/LLVM.h
index e9bb96af972e..02e422051071 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/LLVM.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/LLVM.h
@@ -54,6 +54,7 @@ namespace llvm {
namespace clang {
// Casting operators.
using llvm::isa;
+ using llvm::isa_and_nonnull;
using llvm::cast;
using llvm::dyn_cast;
using llvm::dyn_cast_or_null;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/LangOptions.def b/contrib/llvm-project/clang/include/clang/Basic/LangOptions.def
index 70f68d664bb7..c01f0cca9c9c 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/LangOptions.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/LangOptions.def
@@ -92,6 +92,7 @@ LANGOPT(CPlusPlus11 , 1, 0, "C++11")
LANGOPT(CPlusPlus14 , 1, 0, "C++14")
LANGOPT(CPlusPlus17 , 1, 0, "C++17")
LANGOPT(CPlusPlus20 , 1, 0, "C++20")
+LANGOPT(CPlusPlus2b , 1, 0, "C++2b")
LANGOPT(ObjC , 1, 0, "Objective-C")
BENIGN_LANGOPT(ObjCDefaultSynthProperties , 1, 0,
"Objective-C auto-synthesized properties")
@@ -128,10 +129,8 @@ LANGOPT(ZVector , 1, 0, "System z vector extensions")
LANGOPT(Exceptions , 1, 0, "exception handling")
LANGOPT(ObjCExceptions , 1, 0, "Objective-C exceptions")
LANGOPT(CXXExceptions , 1, 0, "C++ exceptions")
-LANGOPT(DWARFExceptions , 1, 0, "dwarf exception handling")
-LANGOPT(SjLjExceptions , 1, 0, "setjmp-longjump exception handling")
-LANGOPT(SEHExceptions , 1, 0, "SEH .xdata exception handling")
-LANGOPT(WasmExceptions , 1, 0, "WebAssembly exception handling")
+ENUM_LANGOPT(ExceptionHandling, ExceptionHandlingKind, 3,
+ ExceptionHandlingKind::None, "exception handling")
LANGOPT(IgnoreExceptions , 1, 0, "ignore exceptions")
LANGOPT(ExternCNoUnwind , 1, 0, "Assume extern C functions don't unwind")
LANGOPT(TraditionalCPP , 1, 0, "traditional CPP emulation")
@@ -148,8 +147,8 @@ LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template t
LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for all language standard modes")
-COMPATIBLE_LANGOPT(RecoveryAST, 1, 0, "Preserve expressions in AST when encountering errors")
-COMPATIBLE_LANGOPT(RecoveryASTType, 1, 0, "Preserve the type in recovery expressions")
+COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions in AST when encountering errors")
+COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery expressions")
BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
LANGOPT(POSIXThreads , 1, 0, "POSIX thread support")
@@ -183,6 +182,7 @@ VALUE_LANGOPT(AlignDouble , 1, 0, "Controls if doubles should be alig
VALUE_LANGOPT(DoubleSize , 32, 0, "width of double")
VALUE_LANGOPT(LongDoubleSize , 32, 0, "width of long double")
LANGOPT(PPCIEEELongDouble , 1, 0, "use IEEE 754 quadruple-precision for long double")
+LANGOPT(EnableAIXExtendedAltivecABI , 1, 0, "__EXTABI__ predefined macro")
COMPATIBLE_VALUE_LANGOPT(PICLevel , 2, 0, "__PIC__ level")
COMPATIBLE_VALUE_LANGOPT(PIE , 1, 0, "is pie")
LANGOPT(ROPI , 1, 0, "Read-only position independence")
@@ -240,11 +240,13 @@ LANGOPT(CUDAHostDeviceConstexpr, 1, 1, "treating unattributed constexpr function
LANGOPT(CUDADeviceApproxTranscendentals, 1, 0, "using approximate transcendental functions")
LANGOPT(GPURelocatableDeviceCode, 1, 0, "generate relocatable device code")
LANGOPT(GPUAllowDeviceInit, 1, 0, "allowing device side global init functions for HIP")
-LANGOPT(GPUMaxThreadsPerBlock, 32, 1024, "default max threads per block for kernel launch bounds for HIP")
+LANGOPT(GPUMaxThreadsPerBlock, 32, 256, "default max threads per block for kernel launch bounds for HIP")
+LANGOPT(GPUDeferDiag, 1, 0, "defer host/device related diagnostic messages for CUDA/HIP")
+LANGOPT(GPUExcludeWrongSideOverloads, 1, 0, "always exclude wrong side overloads in overloading resolution for CUDA/HIP")
LANGOPT(SYCL , 1, 0, "SYCL")
LANGOPT(SYCLIsDevice , 1, 0, "Generate code for SYCL device")
-LANGOPT(SYCLVersion , 32, 0, "Version of the SYCL standard used")
+ENUM_LANGOPT(SYCLVersion , SYCLMajorVersion, 1, SYCL_None, "Version of the SYCL standard used")
LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching API for HIP")
@@ -261,6 +263,9 @@ BENIGN_LANGOPT(DumpRecordLayoutsSimple , 1, 0, "dumping the layout of IRgen'd re
BENIGN_LANGOPT(DumpVTableLayouts , 1, 0, "dumping the layouts of emitted vtables")
LANGOPT(NoConstantCFStrings , 1, 0, "no constant CoreFoundation strings")
BENIGN_LANGOPT(InlineVisibilityHidden , 1, 0, "hidden visibility for inline C++ methods")
+BENIGN_LANGOPT(VisibilityInlinesHiddenStaticLocalVar, 1, 0,
+ "hidden visibility for static local variables in inline C++ "
+ "methods when -fvisibility-inlines hidden is enabled")
LANGOPT(GlobalAllocationFunctionVisibilityHidden , 1, 0, "hidden visibility for global operator new and delete declaration")
BENIGN_LANGOPT(ParseUnknownAnytype, 1, 0, "__unknown_anytype")
BENIGN_LANGOPT(DebuggerSupport , 1, 0, "debugger support")
@@ -270,6 +275,9 @@ BENIGN_LANGOPT(DebuggerObjCLiteral , 1, 0, "debugger Objective-C literals and su
BENIGN_LANGOPT(SpellChecking , 1, 1, "spell-checking")
LANGOPT(SinglePrecisionConstants , 1, 0, "treating double-precision floating point constants as single precision constants")
LANGOPT(FastRelaxedMath , 1, 0, "OpenCL fast relaxed math")
+BENIGN_LANGOPT(CLNoSignedZero , 1, 0, "Permit Floating Point optimization without regard to signed zeros")
+COMPATIBLE_LANGOPT(CLUnsafeMath , 1, 0, "Unsafe Floating Point Math")
+COMPATIBLE_LANGOPT(CLFiniteMathOnly , 1, 0, "__FINITE_MATH_ONLY__ predefined macro")
/// FP_CONTRACT mode (on/off/fast).
BENIGN_ENUM_LANGOPT(DefaultFPContractMode, FPModeKind, 2, FPM_Off, "FP contraction type")
COMPATIBLE_LANGOPT(ExpStrictFP, 1, false, "Enable experimental strict floating point")
@@ -303,8 +311,19 @@ ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, DefaultVisibility,
"default visibility for types [-ftype-visibility]")
LANGOPT(SetVisibilityForExternDecls, 1, 0,
"apply global symbol visibility to external declarations without an explicit visibility")
+LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
+ "set the visiblity of globals from their DLL storage class [-fvisibility-from-dllstorageclass]")
+ENUM_LANGOPT(DLLExportVisibility, Visibility, 3, DefaultVisibility,
+ "visibility for functions and variables with dllexport annotations [-fvisibility-from-dllstorageclass]")
+ENUM_LANGOPT(NoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
+ "visibility for functions and variables without an explicit DLL storage class [-fvisibility-from-dllstorageclass]")
+ENUM_LANGOPT(ExternDeclDLLImportVisibility, Visibility, 3, DefaultVisibility,
+ "visibility for external declarations with dllimport annotations [-fvisibility-from-dllstorageclass]")
+ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
+ "visibility for external declarations without an explicit DLL storage class [-fvisibility-from-dllstorageclass]")
BENIGN_LANGOPT(SemanticInterposition , 1, 0, "semantic interposition")
-BENIGN_LANGOPT(ExplicitNoSemanticInterposition, 1, 0, "explicitly no semantic interposition")
+BENIGN_LANGOPT(HalfNoSemanticInterposition, 1, 0,
+ "Like -fno-semantic-interposition but don't use local aliases")
ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff,
"stack protector mode")
ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, TrivialAutoVarInitKind::Uninitialized,
@@ -313,6 +332,7 @@ VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0,
"stop trivial automatic variable initialization after the specified number of instances. Must be greater than 0.")
ENUM_LANGOPT(SignedOverflowBehavior, SignedOverflowBehaviorTy, 2, SOB_Undefined,
"signed integer overflow handling")
+ENUM_LANGOPT(ThreadModel , ThreadModelKind, 2, ThreadModelKind::POSIX, "Thread Model")
BENIGN_LANGOPT(ArrowDepth, 32, 256,
"maximum number of operator->s to follow")
@@ -334,6 +354,8 @@ ENUM_LANGOPT(VtorDispMode, MSVtorDispMode, 2, MSVtorDispMode::ForVBaseOverride,
LANGOPT(ApplePragmaPack, 1, 0, "Apple gcc-compatible #pragma pack handling")
+LANGOPT(XLPragmaPack, 1, 0, "IBM XL #pragma pack handling")
+
LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
LANGOPT(SanitizeAddressFieldPadding, 2, 0, "controls how aggressive is ASan "
@@ -382,6 +404,8 @@ LANGOPT(SpeculativeLoadHardening, 1, 0, "Speculative load hardening enabled")
LANGOPT(RelativeCXXABIVTables, 1, 0,
"Use an ABI-incompatible v-table layout that uses relative references")
+LANGOPT(ArmSveVectorBits, 32, 0, "SVE vector size in bits")
+
#undef LANGOPT
#undef COMPATIBLE_LANGOPT
#undef BENIGN_LANGOPT
diff --git a/contrib/llvm-project/clang/include/clang/Basic/LangOptions.h b/contrib/llvm-project/clang/include/clang/Basic/LangOptions.h
index a9213b7d8668..d8bd2a8b52fc 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/LangOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/LangOptions.h
@@ -16,12 +16,14 @@
#include "clang/Basic/CommentOptions.h"
#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/Visibility.h"
#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
+#include "llvm/MC/MCTargetOptions.h"
#include <string>
#include <vector>
@@ -30,6 +32,8 @@ namespace clang {
/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
/// this large collection of bitfields is a trivial class type.
class LangOptionsBase {
+ friend class CompilerInvocation;
+
public:
// Define simple language options (with no accessors).
#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
@@ -119,6 +123,12 @@ public:
MSVC2017 = 1910,
MSVC2017_5 = 1912,
MSVC2017_7 = 1914,
+ MSVC2019 = 1920,
+ };
+
+ enum SYCLMajorVersion {
+ SYCL_None,
+ SYCL_2017,
};
/// Clang versions with different platform ABI conformance.
@@ -152,6 +162,14 @@ public:
/// NetBSD.
Ver9,
+ /// Attempt to be ABI-compatible with code generated by Clang 11.0.x
+ /// (git 2e10b7a39b93). This causes clang to pass unions with a 256-bit
+ /// vector member on the stack instead of using registers, to not properly
+ /// mangle substitutions for template names in some cases, and to mangle
+ /// declaration template arguments without a cast to the parameter type
+ /// even when that can lead to mangling collisions.
+ Ver11,
+
/// Conform to the underlying platform's C and C++ ABIs as closely
/// as we can.
Latest
@@ -181,8 +199,11 @@ public:
// Enable the floating point pragma
FPM_On,
- // Aggressively fuse FP ops (E.g. FMA).
- FPM_Fast
+ // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
+ FPM_Fast,
+
+ // Aggressively fuse FP ops and honor pragmas.
+ FPM_FastHonorPragmas
};
/// Alias for RoundingMode::NearestTiesToEven.
@@ -199,6 +220,9 @@ public:
FPE_Strict
};
+ /// Possible exception handling behavior.
+ using ExceptionHandlingKind = llvm::ExceptionHandling;
+
enum class LaxVectorConversionKind {
/// Permit no implicit vector bitcasts.
None,
@@ -226,7 +250,17 @@ public:
BKey
};
+ enum class ThreadModelKind {
+ /// POSIX Threads.
+ POSIX,
+ /// Single Threaded Environment.
+ Single
+ };
+
public:
+ /// The used language standard.
+ LangStandard::Kind LangStd;
+
/// Set of enabled sanitizers.
SanitizerSet Sanitize;
@@ -251,6 +285,10 @@ public:
/// attribute(s).
std::vector<std::string> XRayAttrListFiles;
+ /// Paths to special case list files specifying which entities
+ /// (files, functions) should or should not be instrumented.
+ std::vector<std::string> ProfileListFiles;
+
clang::ObjCRuntime ObjCRuntime;
CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
@@ -363,6 +401,22 @@ public:
bool isSignReturnAddressScopeAll() const {
return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
}
+
+ bool hasSjLjExceptions() const {
+ return getExceptionHandling() == llvm::ExceptionHandling::SjLj;
+ }
+
+ bool hasSEHExceptions() const {
+ return getExceptionHandling() == llvm::ExceptionHandling::WinEH;
+ }
+
+ bool hasDWARFExceptions() const {
+ return getExceptionHandling() == llvm::ExceptionHandling::DwarfCFI;
+ }
+
+ bool hasWasmExceptions() const {
+ return getExceptionHandling() == llvm::ExceptionHandling::Wasm;
+ }
};
/// Floating point control options
@@ -374,6 +428,8 @@ public:
using RoundingMode = llvm::RoundingMode;
+ static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
+
// Define a fake option named "First" so that we have a PREVIOUS even for the
// real first option.
static constexpr storage_type FirstShift = 0, FirstWidth = 0;
@@ -385,6 +441,12 @@ public:
<< NAME##Shift;
#include "clang/Basic/FPOptions.def"
+ static constexpr storage_type TotalWidth = 0
+#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
+#include "clang/Basic/FPOptions.def"
+ ;
+ static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
+
private:
storage_type Value;
@@ -394,21 +456,31 @@ public:
setRoundingMode(static_cast<RoundingMode>(LangOptions::FPR_ToNearest));
setFPExceptionMode(LangOptions::FPE_Ignore);
}
- // Used for serializing.
- explicit FPOptions(unsigned I) { getFromOpaqueInt(I); }
-
explicit FPOptions(const LangOptions &LO) {
Value = 0;
- setFPContractMode(LO.getDefaultFPContractMode());
+ // The language fp contract option FPM_FastHonorPragmas has the same effect
+ // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
+ // frontend.
+ auto LangOptContractMode = LO.getDefaultFPContractMode();
+ if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
+ LangOptContractMode = LangOptions::FPM_Fast;
+ setFPContractMode(LangOptContractMode);
setRoundingMode(LO.getFPRoundingMode());
setFPExceptionMode(LO.getFPExceptionMode());
- setAllowFEnvAccess(LangOptions::FPM_Off),
- setAllowFPReassociate(LO.AllowFPReassoc);
+ setAllowFPReassociate(LO.AllowFPReassoc);
setNoHonorNaNs(LO.NoHonorNaNs);
setNoHonorInfs(LO.NoHonorInfs);
setNoSignedZero(LO.NoSignedZero);
setAllowReciprocal(LO.AllowRecip);
setAllowApproxFunc(LO.ApproxFunc);
+ if (getFPContractMode() == LangOptions::FPM_On &&
+ getRoundingMode() == llvm::RoundingMode::Dynamic &&
+ getFPExceptionMode() == LangOptions::FPE_Strict)
+ // If the FP settings are set to the "strict" model, then
+ // FENV access is set to true. (ffp-model=strict)
+ setAllowFEnvAccess(true);
+ else
+ setAllowFEnvAccess(LangOptions::FPM_Off);
}
bool allowFPContractWithinStatement() const {
@@ -426,8 +498,7 @@ public:
}
bool isFPConstrained() const {
- return getRoundingMode() !=
- static_cast<unsigned>(RoundingMode::NearestTiesToEven) ||
+ return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
getFPExceptionMode() != LangOptions::FPE_Ignore ||
getAllowFEnvAccess();
}
@@ -439,12 +510,16 @@ public:
static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
storage_type getAsOpaqueInt() const { return Value; }
- void getFromOpaqueInt(storage_type value) { Value = value; }
+ static FPOptions getFromOpaqueInt(storage_type Value) {
+ FPOptions Opts;
+ Opts.Value = Value;
+ return Opts;
+ }
// We can define most of the accessors automatically:
#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
- unsigned get##NAME() const { \
- return static_cast<unsigned>(TYPE((Value & NAME##Mask) >> NAME##Shift)); \
+ TYPE get##NAME() const { \
+ return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift); \
} \
void set##NAME(TYPE value) { \
Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift); \
@@ -453,18 +528,42 @@ public:
LLVM_DUMP_METHOD void dump();
};
-/// The FPOptions override type is value of the new FPOptions
-/// plus a mask showing which fields are actually set in it:
+/// Represents difference between two FPOptions values.
+///
+/// The effect of language constructs changing the set of floating point options
+/// is usually a change of some FP properties while leaving others intact. This
+/// class describes such changes by keeping information about what FP options
+/// are overridden.
+///
+/// The integral set of FP options, described by the class FPOptions, may be
+/// represented as a default FP option set, defined by language standard and
+/// command line options, with the overrides introduced by pragmas.
+///
+/// The is implemented as a value of the new FPOptions plus a mask showing which
+/// fields are actually set in it.
class FPOptionsOverride {
- FPOptions Options;
+ FPOptions Options = FPOptions::getFromOpaqueInt(0);
FPOptions::storage_type OverrideMask = 0;
public:
using RoundingMode = llvm::RoundingMode;
- FPOptionsOverride() {}
- // Used for serializing.
- explicit FPOptionsOverride(unsigned I) { getFromOpaqueInt(I); }
+ /// The type suitable for storing values of FPOptionsOverride. Must be twice
+ /// as wide as bit size of FPOption.
+ using storage_type = uint32_t;
+ static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
+ "Too short type for FPOptionsOverride");
+
+ /// Bit mask selecting bits of OverrideMask in serialized representation of
+ /// FPOptionsOverride.
+ static constexpr storage_type OverrideMaskBits =
+ (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
+
+ FPOptionsOverride() {}
+ FPOptionsOverride(const LangOptions &LO)
+ : Options(LO), OverrideMask(OverrideMaskBits) {}
+ FPOptionsOverride(FPOptions FPO)
+ : Options(FPO), OverrideMask(OverrideMaskBits) {}
bool requiresTrailingStorage() const { return OverrideMask != 0; }
@@ -495,19 +594,27 @@ public:
setAllowFPContractAcrossStatement();
}
- unsigned getAsOpaqueInt() const {
- return Options.getAsOpaqueInt() << 16 | OverrideMask;
+ storage_type getAsOpaqueInt() const {
+ return (static_cast<storage_type>(Options.getAsOpaqueInt())
+ << FPOptions::StorageBitSize) |
+ OverrideMask;
+ }
+ static FPOptionsOverride getFromOpaqueInt(storage_type I) {
+ FPOptionsOverride Opts;
+ Opts.OverrideMask = I & OverrideMaskBits;
+ Opts.Options = FPOptions::getFromOpaqueInt(I >> FPOptions::StorageBitSize);
+ return Opts;
}
- void getFromOpaqueInt(unsigned I) {
- OverrideMask = I & 0xffff;
- Options.getFromOpaqueInt(I >> 16);
+
+ FPOptions applyOverrides(FPOptions Base) {
+ FPOptions Result =
+ FPOptions::getFromOpaqueInt((Base.getAsOpaqueInt() & ~OverrideMask) |
+ (Options.getAsOpaqueInt() & OverrideMask));
+ return Result;
}
FPOptions applyOverrides(const LangOptions &LO) {
- FPOptions Base(LO);
- FPOptions result((Base.getAsOpaqueInt() & ~OverrideMask) |
- (Options.getAsOpaqueInt() & OverrideMask));
- return result;
+ return applyOverrides(FPOptions(LO));
}
bool operator==(FPOptionsOverride other) const {
@@ -519,7 +626,7 @@ public:
bool has##NAME##Override() const { \
return OverrideMask & FPOptions::NAME##Mask; \
} \
- unsigned get##NAME##Override() const { \
+ TYPE get##NAME##Override() const { \
assert(has##NAME##Override()); \
return Options.get##NAME(); \
} \
diff --git a/contrib/llvm-project/clang/include/clang/Basic/LangStandard.h b/contrib/llvm-project/clang/include/clang/Basic/LangStandard.h
index ad7f7510b234..f82ce05a6369 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/LangStandard.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/LangStandard.h
@@ -49,11 +49,12 @@ enum LangFeatures {
CPlusPlus14 = (1 << 7),
CPlusPlus17 = (1 << 8),
CPlusPlus20 = (1 << 9),
- Digraphs = (1 << 10),
- GNUMode = (1 << 11),
- HexFloat = (1 << 12),
- ImplicitInt = (1 << 13),
- OpenCL = (1 << 14)
+ CPlusPlus2b = (1 << 10),
+ Digraphs = (1 << 11),
+ GNUMode = (1 << 12),
+ HexFloat = (1 << 13),
+ ImplicitInt = (1 << 14),
+ OpenCL = (1 << 15)
};
/// LangStandard - Information about the properties of a particular language
@@ -111,6 +112,9 @@ public:
/// isCPlusPlus20 - Language is a C++20 variant (or later).
bool isCPlusPlus20() const { return Flags & CPlusPlus20; }
+ /// isCPlusPlus2b - Language is a post-C++20 variant (or later).
+ bool isCPlusPlus2b() const { return Flags & CPlusPlus2b; }
+
/// hasDigraphs - Language supports digraphs.
bool hasDigraphs() const { return Flags & Digraphs; }
diff --git a/contrib/llvm-project/clang/include/clang/Basic/LangStandards.def b/contrib/llvm-project/clang/include/clang/Basic/LangStandards.def
index b09568e8b3e8..f086d8a43ccb 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/LangStandards.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/LangStandards.def
@@ -152,6 +152,16 @@ LANGSTANDARD(gnucxx20, "gnu++20",
CPlusPlus20 | Digraphs | HexFloat | GNUMode)
LANGSTANDARD_ALIAS_DEPR(gnucxx20, "gnu++2a")
+LANGSTANDARD(cxx2b, "c++2b",
+ CXX, "Working draft for ISO C++ 2023 DIS",
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 |
+ CPlusPlus20 | CPlusPlus2b | Digraphs | HexFloat)
+
+LANGSTANDARD(gnucxx2b, "gnu++2b",
+ CXX, "Working draft for ISO C++ 2023 DIS with GNU extensions",
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 |
+ CPlusPlus20 | CPlusPlus2b | Digraphs | HexFloat | GNUMode)
+
// OpenCL
LANGSTANDARD(opencl10, "cl1.0",
OpenCL, "OpenCL 1.0",
@@ -167,6 +177,9 @@ LANGSTANDARD(opencl12, "cl1.2",
LANGSTANDARD(opencl20, "cl2.0",
OpenCL, "OpenCL 2.0",
LineComment | C99 | Digraphs | HexFloat | OpenCL)
+LANGSTANDARD(opencl30, "cl3.0",
+ OpenCL, "OpenCL 3.0",
+ LineComment | C99 | Digraphs | HexFloat | OpenCL)
LANGSTANDARD(openclcpp, "clc++",
OpenCL, "C++ for OpenCL",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 |
@@ -176,6 +189,7 @@ LANGSTANDARD_ALIAS_DEPR(opencl10, "CL")
LANGSTANDARD_ALIAS_DEPR(opencl11, "CL1.1")
LANGSTANDARD_ALIAS_DEPR(opencl12, "CL1.2")
LANGSTANDARD_ALIAS_DEPR(opencl20, "CL2.0")
+LANGSTANDARD_ALIAS_DEPR(opencl30, "CL3.0")
LANGSTANDARD_ALIAS_DEPR(openclcpp, "CLC++")
// CUDA
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Module.h b/contrib/llvm-project/clang/include/clang/Basic/Module.h
index 6b932a9a84d0..f5b176f8d20b 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Module.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/Module.h
@@ -15,6 +15,8 @@
#ifndef LLVM_CLANG_BASIC_MODULE_H
#define LLVM_CLANG_BASIC_MODULE_H
+#include "clang/Basic/DirectoryEntry.h"
+#include "clang/Basic/FileEntry.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
@@ -43,8 +45,6 @@ class raw_ostream;
namespace clang {
-class DirectoryEntry;
-class FileEntry;
class FileManager;
class LangOptions;
class TargetInfo;
@@ -62,6 +62,15 @@ struct ASTFileSignature : std::array<uint8_t, 20> {
explicit operator bool() const { return *this != BaseT({{0}}); }
+ /// Returns the value truncated to the size of an uint64_t.
+ uint64_t truncatedValue() const {
+ uint64_t Value = 0;
+ static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
+ for (unsigned I = 0; I < sizeof(uint64_t); ++I)
+ Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
+ return Value;
+ }
+
static ASTFileSignature create(StringRef Bytes) {
return create(Bytes.bytes_begin(), Bytes.bytes_end());
}
@@ -124,7 +133,9 @@ public:
std::string PresumedModuleMapFile;
/// The umbrella header or directory.
- const void *Umbrella = nullptr;
+ llvm::PointerUnion<const FileEntryRef::MapEntry *,
+ const DirectoryEntryRef::MapEntry *>
+ Umbrella;
/// The module signature.
ASTFileSignature Signature;
@@ -151,7 +162,7 @@ private:
/// The AST file if this is a top-level module which has a
/// corresponding serialized AST file, or null otherwise.
- const FileEntry *ASTFile = nullptr;
+ Optional<FileEntryRef> ASTFile;
/// The top-level headers associated with this module.
llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
@@ -179,18 +190,18 @@ public:
/// file.
struct Header {
std::string NameAsWritten;
- const FileEntry *Entry;
+ OptionalFileEntryRefDegradesToFileEntryPtr Entry;
- explicit operator bool() { return Entry; }
+ explicit operator bool() { return Entry != None; }
};
/// Information about a directory name as found in the module map
/// file.
struct DirectoryName {
std::string NameAsWritten;
- const DirectoryEntry *Entry;
+ OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr Entry;
- explicit operator bool() { return Entry; }
+ explicit operator bool() { return Entry != None; }
};
/// The headers that are part of this module.
@@ -293,9 +304,6 @@ public:
/// to a regular (public) module map.
unsigned ModuleMapIsPrivate : 1;
- /// Whether Umbrella is a directory or header.
- unsigned HasUmbrellaDir : 1;
-
/// Describes the visibility of the various names within a
/// particular module.
enum NameVisibilityKind {
@@ -457,8 +465,12 @@ public:
/// Determine whether this module is a submodule.
bool isSubModule() const { return Parent != nullptr; }
- /// Determine whether this module is a submodule of the given other
- /// module.
+ /// Check if this module is a (possibly transitive) submodule of \p Other.
+ ///
+ /// The 'A is a submodule of B' relation is a partial order based on the
+ /// the parent-child relationship between individual modules.
+ ///
+ /// Returns \c false if \p Other is \c nullptr.
bool isSubModuleOf(const Module *Other) const;
/// Determine whether this module is a part of a framework,
@@ -516,14 +528,14 @@ public:
}
/// The serialized AST file for this module, if one was created.
- const FileEntry *getASTFile() const {
+ OptionalFileEntryRefDegradesToFileEntryPtr getASTFile() const {
return getTopLevelModule()->ASTFile;
}
/// Set the serialized AST file for the top-level module of this module.
- void setASTFile(const FileEntry *File) {
- assert((File == nullptr || getASTFile() == nullptr ||
- getASTFile() == File) && "file path changed");
+ void setASTFile(Optional<FileEntryRef> File) {
+ assert((!File || !getASTFile() || getASTFile() == File) &&
+ "file path changed");
getTopLevelModule()->ASTFile = File;
}
@@ -534,15 +546,16 @@ public:
/// Retrieve the header that serves as the umbrella header for this
/// module.
Header getUmbrellaHeader() const {
- if (!HasUmbrellaDir)
- return Header{UmbrellaAsWritten,
- static_cast<const FileEntry *>(Umbrella)};
+ if (auto *ME = Umbrella.dyn_cast<const FileEntryRef::MapEntry *>())
+ return Header{UmbrellaAsWritten, FileEntryRef(*ME)};
return Header{};
}
/// Determine whether this module has an umbrella directory that is
/// not based on an umbrella header.
- bool hasUmbrellaDir() const { return Umbrella && HasUmbrellaDir; }
+ bool hasUmbrellaDir() const {
+ return Umbrella && Umbrella.is<const DirectoryEntryRef::MapEntry *>();
+ }
/// Add a top-level header associated with this module.
void addTopHeader(const FileEntry *File);
diff --git a/contrib/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def b/contrib/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def
index 1ae36b32fb0a..801916c3ab94 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def
@@ -10,98 +10,100 @@
//
//===----------------------------------------------------------------------===//
-// Macro OPENCLEXT or OPENCLEXT_INTERNAL can be defined to enumerate the
+// Macro OPENCLEXTNAME or OPENCL_GENERIC_EXTENSION can be defined to enumerate all
// OpenCL extensions listed in this file.
//
-// If the extensions are to be enumerated without the supported OpenCL version,
-// define OPENCLEXT(ext) where ext is the name of the extension.
-//
-// If the extensions are to be enumerated with supported OpenCL version,
-// define OPENCLEXT_INTERNAL(ext, avail, core) where
+// If extensions are to be enumerated with information about whether
+// an extension is core or optional core and minimum OpenCL version
+// when an extension becomes available,
+// define OPENCL_GENERIC_EXTENSION(ext, avail, core, opt) where
// ext - name of the extension or optional core feature.
// avail - minimum OpenCL version supporting it.
-// core - minimum OpenCL version when the extension becomes optional core
-// feature or core feature. ~0U indicates not a core feature or an
-// optional core feature.
+// core - OpenCL versions mask when the extension becomes core feature.
+// 0U indicates not a core feature.
+// opt - OpenCL versions mask when the extension becomes optional core
+// feature. 0U indicates not a optional core feature.
+//
+// If extensions are to be enumerated without any information,
+// define OPENCLEXTNAME(ext) where ext is the name of the extension.
+//
+// Difference between optional core feature and core feature is that the
+// later is unconditionally supported in specific OpenCL version.
+//
+// As per The OpenCL Extension Specification, Section 1.2, in this file, an
+// extension is defined if and only it either:
+// * affects the OpenCL language semantics or its syntax,
+// * adds built-in functions to the language.
+//
+// For such an extension, a preprocessor #define that matches the extension
+// name must be created and a #pragma is required if and only if the
+// compilation flow is impacted, e.g. due to a difference of syntax or
+// semantics in the language compared to the core standard. #pragma directive
+// has no effect for optional core and core features.
-#ifndef OPENCLEXT_INTERNAL
-#ifndef OPENCLEXT
-#pragma error "macro OPENCLEXT or OPENCLEXT_INTERNAL is required"
+#ifndef OPENCL_GENERIC_EXTENSION
+#ifndef OPENCLEXTNAME
+#pragma error "macro OPENCLEXTNAME or OPENCL_GENERIC_EXTENSION is required"
#else
-#define OPENCLEXT_INTERNAL(ext, ...) OPENCLEXT(ext)
-#endif // OPENCLEXT
-#endif // OPENCLEXT_INTERNAL
+#define OPENCL_GENERIC_EXTENSION(ext, ...) OPENCLEXTNAME(ext)
+#endif // OPENCLEXTNAME
+#endif // OPENCL_GENERIC_EXTENSION
-// OpenCL 1.0.
-OPENCLEXT_INTERNAL(cl_khr_3d_image_writes, 100, 200)
-// fprounding mode is special since it is not mentioned beyond 1.0
-OPENCLEXT_INTERNAL(cl_khr_select_fprounding_mode, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_byte_addressable_store, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_fp16, 100, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_fp64, 100, 120)
-OPENCLEXT_INTERNAL(cl_khr_global_int32_base_atomics, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_global_int32_extended_atomics, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_local_int32_base_atomics, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_local_int32_extended_atomics, 100, 110)
-OPENCLEXT_INTERNAL(cl_khr_int64_base_atomics, 100, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_int64_extended_atomics, 100, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_gl_sharing, 100, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_icd, 100, ~0U)
+// Declaration helpers
+#define OPENCL_EXTENSION(ext, avail) OPENCL_GENERIC_EXTENSION(ext, avail, 0U, 0U)
+#define OPENCL_COREFEATURE(ext, avail, core) OPENCL_GENERIC_EXTENSION(ext, avail, core, 0U)
+#define OPENCL_OPTIONALCOREFEATURE(ext, avail, opt) OPENCL_GENERIC_EXTENSION(ext, avail, 0U, opt)
-// OpenCL 1.1.
-OPENCLEXT_INTERNAL(cl_khr_gl_event, 110, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_d3d10_sharing, 110, ~0U)
+// OpenCL 1.0.
+OPENCL_COREFEATURE(cl_khr_byte_addressable_store, 100, OCL_C_11P)
+OPENCL_COREFEATURE(cl_khr_global_int32_base_atomics, 100, OCL_C_11P)
+OPENCL_COREFEATURE(cl_khr_global_int32_extended_atomics, 100, OCL_C_11P)
+OPENCL_COREFEATURE(cl_khr_local_int32_base_atomics, 100, OCL_C_11P)
+OPENCL_COREFEATURE(cl_khr_local_int32_extended_atomics, 100, OCL_C_11P)
+OPENCL_OPTIONALCOREFEATURE(cl_khr_fp64, 100, OCL_C_12P)
+OPENCL_EXTENSION(cl_khr_fp16, 100)
+OPENCL_EXTENSION(cl_khr_int64_base_atomics, 100)
+OPENCL_EXTENSION(cl_khr_int64_extended_atomics, 100)
+OPENCL_GENERIC_EXTENSION(cl_khr_3d_image_writes, 100, OCL_C_20, OCL_C_30)
// EMBEDDED_PROFILE
-OPENCLEXT_INTERNAL(cles_khr_int64, 110, ~0U)
+OPENCL_EXTENSION(cles_khr_int64, 110)
// OpenCL 1.2.
-OPENCLEXT_INTERNAL(cl_khr_context_abort, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_d3d11_sharing, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_depth_images, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_dx9_media_sharing, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_image2d_from_buffer, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_initialize_memory, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_gl_depth_images, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_gl_msaa_sharing, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_spir, 120, ~0U)
+OPENCL_EXTENSION(cl_khr_depth_images, 120)
+OPENCL_EXTENSION(cl_khr_gl_msaa_sharing, 120)
// OpenCL 2.0.
-OPENCLEXT_INTERNAL(cl_khr_egl_event, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_egl_image, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_mipmap_image, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_mipmap_image_writes, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_srgb_image_writes, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroups, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_terminate_context, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_extended_types, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_non_uniform_vote, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_ballot, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_non_uniform_arithmetic, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_shuffle, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_shuffle_relative, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_subgroup_clustered_reduce, 200, ~0U)
+OPENCL_EXTENSION(cl_khr_mipmap_image, 200)
+OPENCL_EXTENSION(cl_khr_mipmap_image_writes, 200)
+OPENCL_EXTENSION(cl_khr_srgb_image_writes, 200)
+OPENCL_EXTENSION(cl_khr_subgroups, 200)
// Clang Extensions.
-OPENCLEXT_INTERNAL(cl_clang_storage_class_specifiers, 100, ~0U)
+OPENCL_EXTENSION(cl_clang_storage_class_specifiers, 100)
+OPENCL_EXTENSION(__cl_clang_function_pointers, 100)
+OPENCL_EXTENSION(__cl_clang_variadic_functions, 100)
// AMD OpenCL extensions
-OPENCLEXT_INTERNAL(cl_amd_media_ops, 100, ~0U)
-OPENCLEXT_INTERNAL(cl_amd_media_ops2, 100, ~0U)
+OPENCL_EXTENSION(cl_amd_media_ops, 100)
+OPENCL_EXTENSION(cl_amd_media_ops2, 100)
// ARM OpenCL extensions
-OPENCLEXT_INTERNAL(cl_arm_integer_dot_product_int8, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_arm_integer_dot_product_accumulate_int8, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_arm_integer_dot_product_accumulate_int16, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_arm_integer_dot_product_accumulate_saturate_int8, 120, ~0U)
+OPENCL_EXTENSION(cl_arm_integer_dot_product_int8, 120)
+OPENCL_EXTENSION(cl_arm_integer_dot_product_accumulate_int8, 120)
+OPENCL_EXTENSION(cl_arm_integer_dot_product_accumulate_int16, 120)
+OPENCL_EXTENSION(cl_arm_integer_dot_product_accumulate_saturate_int8, 120)
// Intel OpenCL extensions
-OPENCLEXT_INTERNAL(cl_intel_subgroups, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_intel_subgroups_short, 120, ~0U)
-OPENCLEXT_INTERNAL(cl_intel_device_side_avc_motion_estimation, 120, ~0U)
+OPENCL_EXTENSION(cl_intel_subgroups, 120)
+OPENCL_EXTENSION(cl_intel_subgroups_short, 120)
+OPENCL_EXTENSION(cl_intel_device_side_avc_motion_estimation, 120)
+
-#undef OPENCLEXT_INTERNAL
+#undef OPENCL_OPTIONALCOREFEATURE
+#undef OPENCL_COREFEATURE
+#undef OPENCL_GENERIC_EXTENSION
-#ifdef OPENCLEXT
-#undef OPENCLEXT
+#ifdef OPENCLEXTNAME
+#undef OPENCLEXTNAME
#endif
diff --git a/contrib/llvm-project/clang/include/clang/Basic/OpenCLOptions.h b/contrib/llvm-project/clang/include/clang/Basic/OpenCLOptions.h
index 15661154eab5..fe27ef19d4d5 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/OpenCLOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/OpenCLOptions.h
@@ -19,122 +19,145 @@
namespace clang {
+namespace {
+// This enum maps OpenCL version(s) into value. These values are used as
+// a mask to indicate in which OpenCL version(s) extension is a core or
+// optional core feature.
+enum OpenCLVersionID : unsigned int {
+ OCL_C_10 = 0x1,
+ OCL_C_11 = 0x2,
+ OCL_C_12 = 0x4,
+ OCL_C_20 = 0x8,
+ OCL_C_30 = 0x10,
+ OCL_C_ALL = 0x1f,
+ OCL_C_11P = OCL_C_ALL ^ OCL_C_10, // OpenCL C 1.1+
+ OCL_C_12P = OCL_C_ALL ^ (OCL_C_10 | OCL_C_11), // OpenCL C 1.2+
+};
+
+static inline OpenCLVersionID encodeOpenCLVersion(unsigned OpenCLVersion) {
+ switch (OpenCLVersion) {
+ default:
+ llvm_unreachable("Unknown OpenCL version code");
+ case 100:
+ return OCL_C_10;
+ case 110:
+ return OCL_C_11;
+ case 120:
+ return OCL_C_12;
+ case 200:
+ return OCL_C_20;
+ case 300:
+ return OCL_C_30;
+ }
+}
+
+// Simple helper to check if OpenCL C version is contained in a given encoded
+// OpenCL C version mask
+static inline bool isOpenCLVersionIsContainedInMask(const LangOptions &LO,
+ unsigned Mask) {
+ auto CLVer = LO.OpenCLCPlusPlus ? 200 : LO.OpenCLVersion;
+ OpenCLVersionID Code = encodeOpenCLVersion(CLVer);
+ return Mask & Code;
+}
+} // end anonymous namespace
+
/// OpenCL supported extensions and optional core features
class OpenCLOptions {
- struct Info {
- bool Supported; // Is this option supported
- bool Enabled; // Is this option enabled
- unsigned Avail; // Option starts to be available in this OpenCL version
- unsigned Core; // Option becomes (optional) core feature in this OpenCL
- // version
- Info(bool S = false, bool E = false, unsigned A = 100, unsigned C = ~0U)
- :Supported(S), Enabled(E), Avail(A), Core(C){}
- };
- llvm::StringMap<Info> OptMap;
public:
- bool isKnown(llvm::StringRef Ext) const {
- return OptMap.find(Ext) != OptMap.end();
- }
+ struct OpenCLOptionInfo {
+ // Option starts to be available in this OpenCL version
+ unsigned Avail;
- bool isEnabled(llvm::StringRef Ext) const {
- return OptMap.find(Ext)->second.Enabled;
- }
+ // Option becomes core feature in this OpenCL versions
+ unsigned Core;
- // Is supported as either an extension or an (optional) core feature for
- // OpenCL version \p CLVer.
- bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const {
- // In C++ mode all extensions should work at least as in v2.0.
- auto CLVer = LO.OpenCLCPlusPlus ? 200 : LO.OpenCLVersion;
- auto I = OptMap.find(Ext)->getValue();
- return I.Supported && I.Avail <= CLVer;
- }
+ // Option becomes optional core feature in this OpenCL versions
+ unsigned Opt;
- // Is supported (optional) OpenCL core features for OpenCL version \p CLVer.
- // For supported extension, return false.
- bool isSupportedCore(llvm::StringRef Ext, const LangOptions &LO) const {
- // In C++ mode all extensions should work at least as in v2.0.
- auto CLVer = LO.OpenCLCPlusPlus ? 200 : LO.OpenCLVersion;
- auto I = OptMap.find(Ext)->getValue();
- return I.Supported && I.Avail <= CLVer && I.Core != ~0U && CLVer >= I.Core;
- }
+ // Is this option supported
+ bool Supported = false;
- // Is supported OpenCL extension for OpenCL version \p CLVer.
- // For supported (optional) core feature, return false.
- bool isSupportedExtension(llvm::StringRef Ext, const LangOptions &LO) const {
- // In C++ mode all extensions should work at least as in v2.0.
- auto CLVer = LO.OpenCLCPlusPlus ? 200 : LO.OpenCLVersion;
- auto I = OptMap.find(Ext)->getValue();
- return I.Supported && I.Avail <= CLVer && (I.Core == ~0U || CLVer < I.Core);
- }
+ // Is this option enabled
+ bool Enabled = false;
- void enable(llvm::StringRef Ext, bool V = true) {
- OptMap[Ext].Enabled = V;
- }
+ OpenCLOptionInfo(unsigned A = 100, unsigned C = 0U, unsigned O = 0U)
+ : Avail(A), Core(C), Opt(O) {}
- /// Enable or disable support for OpenCL extensions
- /// \param Ext name of the extension optionally prefixed with
- /// '+' or '-'
- /// \param V used when \p Ext is not prefixed by '+' or '-'
- void support(llvm::StringRef Ext, bool V = true) {
- assert(!Ext.empty() && "Extension is empty.");
-
- switch (Ext[0]) {
- case '+':
- V = true;
- Ext = Ext.drop_front();
- break;
- case '-':
- V = false;
- Ext = Ext.drop_front();
- break;
+ bool isCore() const { return Core != 0U; }
+
+ bool isOptionalCore() const { return Opt != 0U; }
+
+ // Is option available in OpenCL version \p LO.
+ bool isAvailableIn(const LangOptions &LO) const {
+ // In C++ mode all extensions should work at least as in v2.0.
+ auto CLVer = LO.OpenCLCPlusPlus ? 200 : LO.OpenCLVersion;
+ return CLVer >= Avail;
}
- if (Ext.equals("all")) {
- supportAll(V);
- return;
+ // Is core option in OpenCL version \p LO.
+ bool isCoreIn(const LangOptions &LO) const {
+ return isAvailableIn(LO) && isOpenCLVersionIsContainedInMask(LO, Core);
}
- OptMap[Ext].Supported = V;
- }
- OpenCLOptions(){
-#define OPENCLEXT_INTERNAL(Ext, AvailVer, CoreVer) \
- OptMap[#Ext].Avail = AvailVer; \
- OptMap[#Ext].Core = CoreVer;
-#include "clang/Basic/OpenCLExtensions.def"
- }
+ // Is optional core option in OpenCL version \p LO.
+ bool isOptionalCoreIn(const LangOptions &LO) const {
+ return isAvailableIn(LO) && isOpenCLVersionIsContainedInMask(LO, Opt);
+ }
+ };
- void addSupport(const OpenCLOptions &Opts) {
- for (auto &I:Opts.OptMap)
- if (I.second.Supported)
- OptMap[I.getKey()].Supported = true;
- }
+ bool isKnown(llvm::StringRef Ext) const;
- void copy(const OpenCLOptions &Opts) {
- OptMap = Opts.OptMap;
- }
+ bool isEnabled(llvm::StringRef Ext) const;
- // Turn on or off support of all options.
- void supportAll(bool On = true) {
- for (llvm::StringMap<Info>::iterator I = OptMap.begin(),
- E = OptMap.end(); I != E; ++I)
- I->second.Supported = On;
- }
+ // Is supported as either an extension or an (optional) core feature for
+ // OpenCL version \p LO.
+ bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const;
- void disableAll() {
- for (llvm::StringMap<Info>::iterator I = OptMap.begin(),
- E = OptMap.end(); I != E; ++I)
- I->second.Enabled = false;
- }
+ // Is supported OpenCL core feature for OpenCL version \p LO.
+ // For supported extension, return false.
+ bool isSupportedCore(llvm::StringRef Ext, const LangOptions &LO) const;
- void enableSupportedCore(LangOptions LO) {
- for (llvm::StringMap<Info>::iterator I = OptMap.begin(), E = OptMap.end();
- I != E; ++I)
- if (isSupportedCore(I->getKey(), LO))
- I->second.Enabled = true;
- }
+ // Is supported optional core OpenCL feature for OpenCL version \p LO.
+ // For supported extension, return false.
+ bool isSupportedOptionalCore(llvm::StringRef Ext,
+ const LangOptions &LO) const;
+
+ // Is supported optional core or core OpenCL feature for OpenCL version \p
+ // LO. For supported extension, return false.
+ bool isSupportedCoreOrOptionalCore(llvm::StringRef Ext,
+ const LangOptions &LO) const;
+
+ // Is supported OpenCL extension for OpenCL version \p LO.
+ // For supported core or optional core feature, return false.
+ bool isSupportedExtension(llvm::StringRef Ext, const LangOptions &LO) const;
+
+ void enable(llvm::StringRef Ext, bool V = true);
+
+ /// Enable or disable support for OpenCL extensions
+ /// \param Ext name of the extension (not prefixed with '+' or '-')
+ /// \param V value to set for a extension
+ void support(llvm::StringRef Ext, bool V = true);
+
+ OpenCLOptions();
+ OpenCLOptions(const OpenCLOptions &) = default;
+
+ // Set supported options based on target settings and language version
+ void addSupport(const llvm::StringMap<bool> &FeaturesMap,
+ const LangOptions &Opts);
+
+ // Disable all extensions
+ void disableAll();
+
+ // Enable supported core and optional core features
+ void enableSupportedCore(const LangOptions &LO);
friend class ASTWriter;
friend class ASTReader;
+
+ using OpenCLOptionInfoMap = llvm::StringMap<OpenCLOptionInfo>;
+
+private:
+ OpenCLOptionInfoMap OptMap;
};
} // end namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.def b/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.def
index 9f2bf1abc287..9f9c32da4aa0 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.def
@@ -29,11 +29,8 @@
#ifndef OPENMP_MAP_MODIFIER_KIND
#define OPENMP_MAP_MODIFIER_KIND(Name)
#endif
-#ifndef OPENMP_TO_MODIFIER_KIND
-#define OPENMP_TO_MODIFIER_KIND(Name)
-#endif
-#ifndef OPENMP_FROM_MODIFIER_KIND
-#define OPENMP_FROM_MODIFIER_KIND(Name)
+#ifndef OPENMP_MOTION_MODIFIER_KIND
+#define OPENMP_MOTION_MODIFIER_KIND(Name)
#endif
#ifndef OPENMP_DIST_SCHEDULE_KIND
#define OPENMP_DIST_SCHEDULE_KIND(Name)
@@ -92,6 +89,7 @@ OPENMP_DEFAULTMAP_MODIFIER(tofrom)
OPENMP_DEFAULTMAP_MODIFIER(firstprivate)
OPENMP_DEFAULTMAP_MODIFIER(none)
OPENMP_DEFAULTMAP_MODIFIER(default)
+OPENMP_DEFAULTMAP_MODIFIER(present)
// Static attributes for 'depend' clause.
OPENMP_DEPEND_KIND(in)
@@ -124,12 +122,11 @@ OPENMP_MAP_KIND(release)
OPENMP_MAP_MODIFIER_KIND(always)
OPENMP_MAP_MODIFIER_KIND(close)
OPENMP_MAP_MODIFIER_KIND(mapper)
+OPENMP_MAP_MODIFIER_KIND(present)
-// Modifiers for 'to' clause.
-OPENMP_TO_MODIFIER_KIND(mapper)
-
-// Modifiers for 'from' clause.
-OPENMP_FROM_MODIFIER_KIND(mapper)
+// Modifiers for 'to' or 'from' clause.
+OPENMP_MOTION_MODIFIER_KIND(mapper)
+OPENMP_MOTION_MODIFIER_KIND(present)
// Static attributes for 'dist_schedule' clause.
OPENMP_DIST_SCHEDULE_KIND(static)
@@ -162,8 +159,7 @@ OPENMP_REDUCTION_MODIFIER(task)
#undef OPENMP_ATOMIC_DEFAULT_MEM_ORDER_KIND
#undef OPENMP_MAP_KIND
#undef OPENMP_MAP_MODIFIER_KIND
-#undef OPENMP_TO_MODIFIER_KIND
-#undef OPENMP_FROM_MODIFIER_KIND
+#undef OPENMP_MOTION_MODIFIER_KIND
#undef OPENMP_DIST_SCHEDULE_KIND
#undef OPENMP_DEFAULTMAP_KIND
#undef OPENMP_DEFAULTMAP_MODIFIER
diff --git a/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.h b/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.h
index 08aaf2d43bfd..0f37dc9ad997 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/OpenMPKinds.h
@@ -86,21 +86,17 @@ enum OpenMPMapModifierKind {
static constexpr unsigned NumberOfOMPMapClauseModifiers =
OMPC_MAP_MODIFIER_last - OMPC_MAP_MODIFIER_unknown - 1;
-/// OpenMP modifier kind for 'to' clause.
-enum OpenMPToModifierKind {
-#define OPENMP_TO_MODIFIER_KIND(Name) \
- OMPC_TO_MODIFIER_##Name,
+/// OpenMP modifier kind for 'to' or 'from' clause.
+enum OpenMPMotionModifierKind {
+#define OPENMP_MOTION_MODIFIER_KIND(Name) \
+ OMPC_MOTION_MODIFIER_##Name,
#include "clang/Basic/OpenMPKinds.def"
- OMPC_TO_MODIFIER_unknown
+ OMPC_MOTION_MODIFIER_unknown
};
-/// OpenMP modifier kind for 'from' clause.
-enum OpenMPFromModifierKind {
-#define OPENMP_FROM_MODIFIER_KIND(Name) \
- OMPC_FROM_MODIFIER_##Name,
-#include "clang/Basic/OpenMPKinds.def"
- OMPC_FROM_MODIFIER_unknown
-};
+/// Number of allowed motion-modifiers.
+static constexpr unsigned NumberOfOMPMotionModifiers =
+ OMPC_MOTION_MODIFIER_unknown;
/// OpenMP attributes for 'dist_schedule' clause.
enum OpenMPDistScheduleClauseKind {
@@ -170,7 +166,8 @@ enum OpenMPReductionClauseModifier {
OMPC_REDUCTION_unknown,
};
-unsigned getOpenMPSimpleClauseType(OpenMPClauseKind Kind, llvm::StringRef Str);
+unsigned getOpenMPSimpleClauseType(OpenMPClauseKind Kind, llvm::StringRef Str,
+ unsigned OpenMPVersion);
const char *getOpenMPSimpleClauseTypeName(OpenMPClauseKind Kind, unsigned Type);
/// Checks if the specified directive is a directive with an associated
diff --git a/contrib/llvm-project/clang/include/clang/Basic/OperatorKinds.h b/contrib/llvm-project/clang/include/clang/Basic/OperatorKinds.h
index d66189144511..3315df246981 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/OperatorKinds.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/OperatorKinds.h
@@ -49,6 +49,11 @@ getRewrittenOverloadedOperator(OverloadedOperatorKind Kind) {
}
}
+/// Determine if this is a compound assignment operator.
+inline bool isCompoundAssignmentOperator(OverloadedOperatorKind Kind) {
+ return Kind >= OO_PlusEqual && Kind <= OO_PipeEqual;
+}
+
} // end namespace clang
#endif
diff --git a/contrib/llvm-project/clang/include/clang/Basic/PPCTypes.def b/contrib/llvm-project/clang/include/clang/Basic/PPCTypes.def
new file mode 100644
index 000000000000..9e2cb2aedc9f
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Basic/PPCTypes.def
@@ -0,0 +1,38 @@
+//===-- PPCTypes.def - Metadata about PPC types -----------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines PPC types.
+// Custom code should define one of these macros:
+//
+// PPC_VECTOR_TYPE(Name, Id, Size) - A PPC vector type of a given size
+// (in bits).
+//
+// PPC_VECTOR_MMA_TYPE(Name, Id, Size) - A PPC MMA vector type of a given
+// size (in bits).
+//
+// PPC_VECTOR_VSX_TYPE(Name, Id, Size) - A PPC VSX vector type of a given
+// size (in bits).
+//
+//===----------------------------------------------------------------------===//
+
+#if defined(PPC_VECTOR_TYPE)
+ #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) PPC_VECTOR_TYPE(Name, Id, Size)
+ #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) PPC_VECTOR_TYPE(Name, Id, Size)
+#elif defined(PPC_VECTOR_MMA_TYPE)
+ #define PPC_VECTOR_VSX_TYPE(Name, Id, Size)
+#elif defined(PPC_VECTOR_VSX_TYPE)
+ #define PPC_VECTOR_MMA_TYPE(Name, Id, Size)
+#endif
+
+
+PPC_VECTOR_MMA_TYPE(__vector_quad, VectorQuad, 512)
+PPC_VECTOR_VSX_TYPE(__vector_pair, VectorPair, 256)
+
+#undef PPC_VECTOR_MMA_TYPE
+#undef PPC_VECTOR_VSX_TYPE
+#undef PPC_VECTOR_TYPE
diff --git a/contrib/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h b/contrib/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h
index 107d621f0dec..9fb70bff7fee 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h
@@ -31,89 +31,7 @@ namespace clang {
class DeclContext;
class IdentifierInfo;
-class PartialDiagnostic {
-public:
- enum {
- // The MaxArguments and MaxFixItHints member enum values from
- // DiagnosticsEngine are private but DiagnosticsEngine declares
- // PartialDiagnostic a friend. These enum values are redeclared
- // here so that the nested Storage class below can access them.
- MaxArguments = DiagnosticsEngine::MaxArguments
- };
-
- struct Storage {
- enum {
- /// The maximum number of arguments we can hold. We
- /// currently only support up to 10 arguments (%0-%9).
- ///
- /// A single diagnostic with more than that almost certainly has to
- /// be simplified anyway.
- MaxArguments = PartialDiagnostic::MaxArguments
- };
-
- /// The number of entries in Arguments.
- unsigned char NumDiagArgs = 0;
-
- /// Specifies for each argument whether it is in DiagArgumentsStr
- /// or in DiagArguments.
- unsigned char DiagArgumentsKind[MaxArguments];
-
- /// The values for the various substitution positions.
- ///
- /// This is used when the argument is not an std::string. The specific value
- /// is mangled into an intptr_t and the interpretation depends on exactly
- /// what sort of argument kind it is.
- intptr_t DiagArgumentsVal[MaxArguments];
-
- /// The values for the various substitution positions that have
- /// string arguments.
- std::string DiagArgumentsStr[MaxArguments];
-
- /// The list of ranges added to this diagnostic.
- SmallVector<CharSourceRange, 8> DiagRanges;
-
- /// If valid, provides a hint with some code to insert, remove, or
- /// modify at a particular position.
- SmallVector<FixItHint, 6> FixItHints;
-
- Storage() = default;
- };
-
- /// An allocator for Storage objects, which uses a small cache to
- /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
- class StorageAllocator {
- static const unsigned NumCached = 16;
- Storage Cached[NumCached];
- Storage *FreeList[NumCached];
- unsigned NumFreeListEntries;
-
- public:
- StorageAllocator();
- ~StorageAllocator();
-
- /// Allocate new storage.
- Storage *Allocate() {
- if (NumFreeListEntries == 0)
- return new Storage;
-
- Storage *Result = FreeList[--NumFreeListEntries];
- Result->NumDiagArgs = 0;
- Result->DiagRanges.clear();
- Result->FixItHints.clear();
- return Result;
- }
-
- /// Free the given storage object.
- void Deallocate(Storage *S) {
- if (S >= Cached && S <= Cached + NumCached) {
- FreeList[NumFreeListEntries++] = S;
- return;
- }
-
- delete S;
- }
- };
-
+class PartialDiagnostic : public StreamingDiagnostic {
private:
// NOTE: Sema assumes that PartialDiagnostic is location-invariant
// in the sense that its bits can be safely memcpy'ed and destructed
@@ -121,65 +39,6 @@ private:
/// The diagnostic ID.
mutable unsigned DiagID = 0;
-
- /// Storage for args and ranges.
- mutable Storage *DiagStorage = nullptr;
-
- /// Allocator used to allocate storage for this diagnostic.
- StorageAllocator *Allocator = nullptr;
-
- /// Retrieve storage for this particular diagnostic.
- Storage *getStorage() const {
- if (DiagStorage)
- return DiagStorage;
-
- if (Allocator)
- DiagStorage = Allocator->Allocate();
- else {
- assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)));
- DiagStorage = new Storage;
- }
- return DiagStorage;
- }
-
- void freeStorage() {
- if (!DiagStorage)
- return;
-
- // The hot path for PartialDiagnostic is when we just used it to wrap an ID
- // (typically so we have the flexibility of passing a more complex
- // diagnostic into the callee, but that does not commonly occur).
- //
- // Split this out into a slow function for silly compilers (*cough*) which
- // can't do decent partial inlining.
- freeStorageSlow();
- }
-
- void freeStorageSlow() {
- if (Allocator)
- Allocator->Deallocate(DiagStorage);
- else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
- delete DiagStorage;
- DiagStorage = nullptr;
- }
-
- void AddSourceRange(const CharSourceRange &R) const {
- if (!DiagStorage)
- DiagStorage = getStorage();
-
- DiagStorage->DiagRanges.push_back(R);
- }
-
- void AddFixItHint(const FixItHint &Hint) const {
- if (Hint.isNull())
- return;
-
- if (!DiagStorage)
- DiagStorage = getStorage();
-
- DiagStorage->FixItHints.push_back(Hint);
- }
-
public:
struct NullDiagnostic {};
@@ -187,32 +46,53 @@ public:
/// and only exists to be swapped with a real partial diagnostic.
PartialDiagnostic(NullDiagnostic) {}
- PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
- : DiagID(DiagID), Allocator(&Allocator) {}
+ PartialDiagnostic(unsigned DiagID, DiagStorageAllocator &Allocator_)
+ : StreamingDiagnostic(Allocator_), DiagID(DiagID) {}
PartialDiagnostic(const PartialDiagnostic &Other)
- : DiagID(Other.DiagID), Allocator(Other.Allocator) {
+ : StreamingDiagnostic(), DiagID(Other.DiagID) {
+ Allocator = Other.Allocator;
if (Other.DiagStorage) {
DiagStorage = getStorage();
*DiagStorage = *Other.DiagStorage;
}
}
- PartialDiagnostic(PartialDiagnostic &&Other)
- : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage),
- Allocator(Other.Allocator) {
+ template <typename T> const PartialDiagnostic &operator<<(const T &V) const {
+ const StreamingDiagnostic &DB = *this;
+ DB << V;
+ return *this;
+ }
+
+ // It is necessary to limit this to rvalue reference to avoid calling this
+ // function with a bitfield lvalue argument since non-const reference to
+ // bitfield is not allowed.
+ template <typename T, typename = typename std::enable_if<
+ !std::is_lvalue_reference<T>::value>::type>
+ const PartialDiagnostic &operator<<(T &&V) const {
+ const StreamingDiagnostic &DB = *this;
+ DB << std::move(V);
+ return *this;
+ }
+
+ PartialDiagnostic(PartialDiagnostic &&Other) : DiagID(Other.DiagID) {
+ Allocator = Other.Allocator;
+ DiagStorage = Other.DiagStorage;
Other.DiagStorage = nullptr;
}
- PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
- : DiagID(Other.DiagID), DiagStorage(DiagStorage),
- Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) {
+ PartialDiagnostic(const PartialDiagnostic &Other,
+ DiagnosticStorage *DiagStorage_)
+ : DiagID(Other.DiagID) {
+ Allocator = reinterpret_cast<DiagStorageAllocator *>(~uintptr_t(0));
+ DiagStorage = DiagStorage_;
if (Other.DiagStorage)
*this->DiagStorage = *Other.DiagStorage;
}
- PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
- : DiagID(Other.getID()), Allocator(&Allocator) {
+ PartialDiagnostic(const Diagnostic &Other, DiagStorageAllocator &Allocator_)
+ : DiagID(Other.getID()) {
+ Allocator = &Allocator_;
// Copy arguments.
for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) {
if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string)
@@ -255,10 +135,6 @@ public:
return *this;
}
- ~PartialDiagnostic() {
- freeStorage();
- }
-
void swap(PartialDiagnostic &PD) {
std::swap(DiagID, PD.DiagID);
std::swap(DiagStorage, PD.DiagStorage);
@@ -266,27 +142,7 @@ public:
}
unsigned getDiagID() const { return DiagID; }
-
- void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
- if (!DiagStorage)
- DiagStorage = getStorage();
-
- assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&
- "Too many arguments to diagnostic!");
- DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
- DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
- }
-
- void AddString(StringRef V) const {
- if (!DiagStorage)
- DiagStorage = getStorage();
-
- assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&
- "Too many arguments to diagnostic!");
- DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
- = DiagnosticsEngine::ak_std_string;
- DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
- }
+ void setDiagID(unsigned ID) { DiagID = ID; }
void Emit(const DiagnosticBuilder &DB) const {
if (!DiagStorage)
@@ -317,7 +173,6 @@ public:
// messing with the state of the diagnostics engine.
DiagnosticBuilder DB(Diags.Report(getDiagID()));
Emit(DB);
- DB.FlushCounts();
Diagnostic(&Diags).FormatDiagnostic(Buf);
DB.Clear();
Diags.Clear();
@@ -340,70 +195,6 @@ public:
== DiagnosticsEngine::ak_std_string && "Not a string arg");
return DiagStorage->DiagArgumentsStr[I];
}
-
- friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- unsigned I) {
- PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
- return PD;
- }
-
- friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- int I) {
- PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
- return PD;
- }
-
- friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const char *S) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(S),
- DiagnosticsEngine::ak_c_string);
- return PD;
- }
-
- friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- StringRef S) {
-
- PD.AddString(S);
- return PD;
- }
-
- friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const IdentifierInfo *II) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(II),
- DiagnosticsEngine::ak_identifierinfo);
- return PD;
- }
-
- // Adds a DeclContext to the diagnostic. The enable_if template magic is here
- // so that we only match those arguments that are (statically) DeclContexts;
- // other arguments that derive from DeclContext (e.g., RecordDecls) will not
- // match.
- template <typename T>
- friend inline std::enable_if_t<std::is_same<T, DeclContext>::value,
- const PartialDiagnostic &>
- operator<<(const PartialDiagnostic &PD, T *DC) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
- DiagnosticsEngine::ak_declcontext);
- return PD;
- }
-
- friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- SourceRange R) {
- PD.AddSourceRange(CharSourceRange::getTokenRange(R));
- return PD;
- }
-
- friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const CharSourceRange &R) {
- PD.AddSourceRange(R);
- return PD;
- }
-
- friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const FixItHint &Hint) {
- PD.AddFixItHint(Hint);
- return PD;
- }
};
inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
diff --git a/contrib/llvm-project/clang/include/clang/Basic/ProfileList.h b/contrib/llvm-project/clang/include/clang/Basic/ProfileList.h
new file mode 100644
index 000000000000..989c36549a3d
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Basic/ProfileList.h
@@ -0,0 +1,58 @@
+//===--- ProfileList.h - ProfileList filter ---------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// User-provided filters include/exclude profile instrumentation in certain
+// functions.
+//
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_CLANG_BASIC_INSTRPROFLIST_H
+#define LLVM_CLANG_BASIC_INSTRPROFLIST_H
+
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include <memory>
+
+namespace llvm {
+class SpecialCaseList;
+}
+
+namespace clang {
+
+class ProfileSpecialCaseList;
+
+class ProfileList {
+ std::unique_ptr<ProfileSpecialCaseList> SCL;
+ const bool Empty;
+ const bool Default;
+ SourceManager &SM;
+
+public:
+ ProfileList(ArrayRef<std::string> Paths, SourceManager &SM);
+ ~ProfileList();
+
+ bool isEmpty() const { return Empty; }
+ bool getDefault() const { return Default; }
+
+ llvm::Optional<bool>
+ isFunctionExcluded(StringRef FunctionName,
+ CodeGenOptions::ProfileInstrKind Kind) const;
+ llvm::Optional<bool>
+ isLocationExcluded(SourceLocation Loc,
+ CodeGenOptions::ProfileInstrKind Kind) const;
+ llvm::Optional<bool>
+ isFileExcluded(StringRef FileName,
+ CodeGenOptions::ProfileInstrKind Kind) const;
+};
+
+} // namespace clang
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Sanitizers.def b/contrib/llvm-project/clang/include/clang/Basic/Sanitizers.def
index 2912bdd44b2d..9b8936cc520c 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Sanitizers.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/Sanitizers.def
@@ -107,6 +107,7 @@ SANITIZER("vptr", Vptr)
// IntegerSanitizer
SANITIZER("unsigned-integer-overflow", UnsignedIntegerOverflow)
+SANITIZER("unsigned-shift-base", UnsignedShiftBase)
// DataFlowSanitizer
SANITIZER("dataflow", DataFlow)
@@ -171,7 +172,8 @@ SANITIZER_GROUP("implicit-conversion", ImplicitConversion,
SANITIZER_GROUP("integer", Integer,
ImplicitConversion | IntegerDivideByZero | Shift |
- SignedIntegerOverflow | UnsignedIntegerOverflow)
+ SignedIntegerOverflow | UnsignedIntegerOverflow |
+ UnsignedShiftBase)
SANITIZER("local-bounds", LocalBounds)
SANITIZER_GROUP("bounds", Bounds, ArrayBounds | LocalBounds)
diff --git a/contrib/llvm-project/clang/include/clang/Basic/SourceLocation.h b/contrib/llvm-project/clang/include/clang/Basic/SourceLocation.h
index 3735b904ef47..fc722b1d563d 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/SourceLocation.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/SourceLocation.h
@@ -26,6 +26,9 @@ namespace llvm {
template <typename T> struct DenseMapInfo;
+class FoldingSetNodeID;
+template <typename T> struct FoldingSetTrait;
+
} // namespace llvm
namespace clang {
@@ -87,6 +90,7 @@ class SourceLocation {
friend class ASTReader;
friend class ASTWriter;
friend class SourceManager;
+ friend struct llvm::FoldingSetTrait<SourceLocation>;
unsigned ID = 0;
@@ -175,6 +179,7 @@ public:
End.isFileID();
}
+ unsigned getHashValue() const;
void print(raw_ostream &OS, const SourceManager &SM) const;
std::string printToString(const SourceManager &SM) const;
void dump(const SourceManager &SM) const;
@@ -479,6 +484,32 @@ namespace llvm {
}
};
+ /// Define DenseMapInfo so that SourceLocation's can be used as keys in
+ /// DenseMap and DenseSet. This trait class is eqivalent to
+ /// DenseMapInfo<unsigned> which uses SourceLocation::ID is used as a key.
+ template <> struct DenseMapInfo<clang::SourceLocation> {
+ static clang::SourceLocation getEmptyKey() {
+ return clang::SourceLocation::getFromRawEncoding(~0U);
+ }
+
+ static clang::SourceLocation getTombstoneKey() {
+ return clang::SourceLocation::getFromRawEncoding(~0U - 1);
+ }
+
+ static unsigned getHashValue(clang::SourceLocation Loc) {
+ return Loc.getHashValue();
+ }
+
+ static bool isEqual(clang::SourceLocation LHS, clang::SourceLocation RHS) {
+ return LHS == RHS;
+ }
+ };
+
+ // Allow calling FoldingSetNodeID::Add with SourceLocation object as parameter
+ template <> struct FoldingSetTrait<clang::SourceLocation> {
+ static void Profile(const clang::SourceLocation &X, FoldingSetNodeID &ID);
+ };
+
// Teach SmallPtrSet how to handle SourceLocation.
template<>
struct PointerLikeTypeTraits<clang::SourceLocation> {
diff --git a/contrib/llvm-project/clang/include/clang/Basic/SourceManager.h b/contrib/llvm-project/clang/include/clang/Basic/SourceManager.h
index 5c666c1760b4..8cd37756d8f1 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/SourceManager.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/SourceManager.h
@@ -35,6 +35,7 @@
#define LLVM_CLANG_BASIC_SOURCEMANAGER_H
#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/FileEntry.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
@@ -60,8 +61,6 @@ namespace clang {
class ASTReader;
class ASTWriter;
class FileManager;
-class FileEntry;
-class FileEntryRef;
class LineTableInfo;
class SourceManager;
@@ -69,419 +68,446 @@ class SourceManager;
/// SourceManager implementation.
namespace SrcMgr {
- /// Indicates whether a file or directory holds normal user code,
- /// system code, or system code which is implicitly 'extern "C"' in C++ mode.
+/// Indicates whether a file or directory holds normal user code,
+/// system code, or system code which is implicitly 'extern "C"' in C++ mode.
+///
+/// Entire directories can be tagged with this (this is maintained by
+/// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
+/// system_header is seen or in various other cases.
+///
+enum CharacteristicKind {
+ C_User,
+ C_System,
+ C_ExternCSystem,
+ C_User_ModuleMap,
+ C_System_ModuleMap
+};
+
+/// Determine whether a file / directory characteristic is for system code.
+inline bool isSystem(CharacteristicKind CK) {
+ return CK != C_User && CK != C_User_ModuleMap;
+}
+
+/// Determine whether a file characteristic is for a module map.
+inline bool isModuleMap(CharacteristicKind CK) {
+ return CK == C_User_ModuleMap || CK == C_System_ModuleMap;
+}
+
+/// Mapping of line offsets into a source file. This does not own the storage
+/// for the line numbers.
+class LineOffsetMapping {
+public:
+ explicit operator bool() const { return Storage; }
+ unsigned size() const {
+ assert(Storage);
+ return Storage[0];
+ }
+ ArrayRef<unsigned> getLines() const {
+ assert(Storage);
+ return ArrayRef<unsigned>(Storage + 1, Storage + 1 + size());
+ }
+ const unsigned *begin() const { return getLines().begin(); }
+ const unsigned *end() const { return getLines().end(); }
+ const unsigned &operator[](int I) const { return getLines()[I]; }
+
+ static LineOffsetMapping get(llvm::MemoryBufferRef Buffer,
+ llvm::BumpPtrAllocator &Alloc);
+
+ LineOffsetMapping() = default;
+ LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
+ llvm::BumpPtrAllocator &Alloc);
+
+private:
+ /// First element is the size, followed by elements at off-by-one indexes.
+ unsigned *Storage = nullptr;
+};
+
+/// One instance of this struct is kept for every file loaded or used.
+///
+/// This object owns the MemoryBuffer object.
+class alignas(8) ContentCache {
+ /// The actual buffer containing the characters from the input
+ /// file.
+ mutable std::unique_ptr<llvm::MemoryBuffer> Buffer;
+
+public:
+ /// Reference to the file entry representing this ContentCache.
///
- /// Entire directories can be tagged with this (this is maintained by
- /// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
- /// system_header is seen or in various other cases.
+ /// This reference does not own the FileEntry object.
///
- enum CharacteristicKind {
- C_User, C_System, C_ExternCSystem, C_User_ModuleMap, C_System_ModuleMap
- };
+ /// It is possible for this to be NULL if the ContentCache encapsulates
+ /// an imaginary text buffer.
+ ///
+ /// FIXME: Turn this into a FileEntryRef and remove Filename.
+ const FileEntry *OrigEntry;
+
+ /// References the file which the contents were actually loaded from.
+ ///
+ /// Can be different from 'Entry' if we overridden the contents of one file
+ /// with the contents of another file.
+ const FileEntry *ContentsEntry;
+
+ /// The filename that is used to access OrigEntry.
+ ///
+ /// FIXME: Remove this once OrigEntry is a FileEntryRef with a stable name.
+ StringRef Filename;
+
+ /// A bump pointer allocated array of offsets for each source line.
+ ///
+ /// This is lazily computed. The lines are owned by the SourceManager
+ /// BumpPointerAllocator object.
+ mutable LineOffsetMapping SourceLineCache;
+
+ /// Indicates whether the buffer itself was provided to override
+ /// the actual file contents.
+ ///
+ /// When true, the original entry may be a virtual file that does not
+ /// exist.
+ unsigned BufferOverridden : 1;
+
+ /// True if this content cache was initially created for a source file
+ /// considered to be volatile (likely to change between stat and open).
+ unsigned IsFileVolatile : 1;
+
+ /// True if this file may be transient, that is, if it might not
+ /// exist at some later point in time when this content entry is used,
+ /// after serialization and deserialization.
+ unsigned IsTransient : 1;
+
+ mutable unsigned IsBufferInvalid : 1;
+
+ ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
+
+ ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
+ : OrigEntry(Ent), ContentsEntry(contentEnt), BufferOverridden(false),
+ IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {}
+
+ /// The copy ctor does not allow copies where source object has either
+ /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
+ /// is not transferred, so this is a logical error.
+ ContentCache(const ContentCache &RHS)
+ : BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
+ IsBufferInvalid(false) {
+ OrigEntry = RHS.OrigEntry;
+ ContentsEntry = RHS.ContentsEntry;
+
+ assert(!RHS.Buffer && !RHS.SourceLineCache &&
+ "Passed ContentCache object cannot own a buffer.");
+ }
+
+ ContentCache &operator=(const ContentCache &RHS) = delete;
+
+ /// Returns the memory buffer for the associated content.
+ ///
+ /// \param Diag Object through which diagnostics will be emitted if the
+ /// buffer cannot be retrieved.
+ ///
+ /// \param Loc If specified, is the location that invalid file diagnostics
+ /// will be emitted at.
+ llvm::Optional<llvm::MemoryBufferRef>
+ getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
+ SourceLocation Loc = SourceLocation()) const;
+
+ /// Returns the size of the content encapsulated by this
+ /// ContentCache.
+ ///
+ /// This can be the size of the source file or the size of an
+ /// arbitrary scratch buffer. If the ContentCache encapsulates a source
+ /// file this size is retrieved from the file's FileEntry.
+ unsigned getSize() const;
+
+ /// Returns the number of bytes actually mapped for this
+ /// ContentCache.
+ ///
+ /// This can be 0 if the MemBuffer was not actually expanded.
+ unsigned getSizeBytesMapped() const;
+
+ /// Returns the kind of memory used to back the memory buffer for
+ /// this content cache. This is used for performance analysis.
+ llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
+
+ /// Return the buffer, only if it has been loaded.
+ llvm::Optional<llvm::MemoryBufferRef> getBufferIfLoaded() const {
+ if (Buffer)
+ return Buffer->getMemBufferRef();
+ return None;
+ }
- /// Determine whether a file / directory characteristic is for system code.
- inline bool isSystem(CharacteristicKind CK) {
- return CK != C_User && CK != C_User_ModuleMap;
+ /// Return a StringRef to the source buffer data, only if it has already
+ /// been loaded.
+ llvm::Optional<StringRef> getBufferDataIfLoaded() const {
+ if (Buffer)
+ return Buffer->getBuffer();
+ return None;
}
- /// Determine whether a file characteristic is for a module map.
- inline bool isModuleMap(CharacteristicKind CK) {
- return CK == C_User_ModuleMap || CK == C_System_ModuleMap;
+ /// Set the buffer.
+ void setBuffer(std::unique_ptr<llvm::MemoryBuffer> B) {
+ IsBufferInvalid = false;
+ Buffer = std::move(B);
}
- /// One instance of this struct is kept for every file loaded or used.
+ /// Set the buffer to one that's not owned (or to nullptr).
///
- /// This object owns the MemoryBuffer object.
- class alignas(8) ContentCache {
- enum CCFlags {
- /// Whether the buffer is invalid.
- InvalidFlag = 0x01,
+ /// \pre Buffer cannot already be set.
+ void setUnownedBuffer(llvm::Optional<llvm::MemoryBufferRef> B) {
+ assert(!Buffer && "Expected to be called right after construction");
+ if (B)
+ setBuffer(llvm::MemoryBuffer::getMemBuffer(*B));
+ }
- /// Whether the buffer should not be freed on destruction.
- DoNotFreeFlag = 0x02
- };
+ // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
+ // nullptr
+ static const char *getInvalidBOM(StringRef BufStr);
+};
- /// The actual buffer containing the characters from the input
- /// file.
- ///
- /// This is owned by the ContentCache object. The bits indicate
- /// whether the buffer is invalid.
- mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer;
-
- public:
- /// Reference to the file entry representing this ContentCache.
- ///
- /// This reference does not own the FileEntry object.
- ///
- /// It is possible for this to be NULL if the ContentCache encapsulates
- /// an imaginary text buffer.
- const FileEntry *OrigEntry;
-
- /// References the file which the contents were actually loaded from.
- ///
- /// Can be different from 'Entry' if we overridden the contents of one file
- /// with the contents of another file.
- const FileEntry *ContentsEntry;
-
- /// A bump pointer allocated array of offsets for each source line.
- ///
- /// This is lazily computed. This is owned by the SourceManager
- /// BumpPointerAllocator object.
- unsigned *SourceLineCache = nullptr;
-
- /// The number of lines in this ContentCache.
- ///
- /// This is only valid if SourceLineCache is non-null.
- unsigned NumLines = 0;
-
- /// Indicates whether the buffer itself was provided to override
- /// the actual file contents.
- ///
- /// When true, the original entry may be a virtual file that does not
- /// exist.
- unsigned BufferOverridden : 1;
-
- /// True if this content cache was initially created for a source file
- /// considered to be volatile (likely to change between stat and open).
- unsigned IsFileVolatile : 1;
-
- /// True if this file may be transient, that is, if it might not
- /// exist at some later point in time when this content entry is used,
- /// after serialization and deserialization.
- unsigned IsTransient : 1;
-
- ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
-
- ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
- : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
- BufferOverridden(false), IsFileVolatile(false), IsTransient(false) {}
-
- /// The copy ctor does not allow copies where source object has either
- /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
- /// is not transferred, so this is a logical error.
- ContentCache(const ContentCache &RHS)
- : Buffer(nullptr, false), BufferOverridden(false),
- IsFileVolatile(false), IsTransient(false) {
- OrigEntry = RHS.OrigEntry;
- ContentsEntry = RHS.ContentsEntry;
-
- assert(RHS.Buffer.getPointer() == nullptr &&
- RHS.SourceLineCache == nullptr &&
- "Passed ContentCache object cannot own a buffer.");
-
- NumLines = RHS.NumLines;
- }
+// Assert that the \c ContentCache objects will always be 8-byte aligned so
+// that we can pack 3 bits of integer into pointers to such objects.
+static_assert(alignof(ContentCache) >= 8,
+ "ContentCache must be 8-byte aligned.");
- ContentCache &operator=(const ContentCache& RHS) = delete;
-
- ~ContentCache();
-
- /// Returns the memory buffer for the associated content.
- ///
- /// \param Diag Object through which diagnostics will be emitted if the
- /// buffer cannot be retrieved.
- ///
- /// \param Loc If specified, is the location that invalid file diagnostics
- /// will be emitted at.
- ///
- /// \param Invalid If non-NULL, will be set \c true if an error occurred.
- const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
- FileManager &FM,
- SourceLocation Loc = SourceLocation(),
- bool *Invalid = nullptr) const;
-
- /// Returns the size of the content encapsulated by this
- /// ContentCache.
- ///
- /// This can be the size of the source file or the size of an
- /// arbitrary scratch buffer. If the ContentCache encapsulates a source
- /// file this size is retrieved from the file's FileEntry.
- unsigned getSize() const;
-
- /// Returns the number of bytes actually mapped for this
- /// ContentCache.
- ///
- /// This can be 0 if the MemBuffer was not actually expanded.
- unsigned getSizeBytesMapped() const;
-
- /// Returns the kind of memory used to back the memory buffer for
- /// this content cache. This is used for performance analysis.
- llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
-
- /// Get the underlying buffer, returning NULL if the buffer is not
- /// yet available.
- const llvm::MemoryBuffer *getRawBuffer() const {
- return Buffer.getPointer();
- }
+/// Information about a FileID, basically just the logical file
+/// that it represents and include stack information.
+///
+/// Each FileInfo has include stack information, indicating where it came
+/// from. This information encodes the \#include chain that a token was
+/// expanded from. The main include file has an invalid IncludeLoc.
+///
+/// FileInfo should not grow larger than ExpansionInfo. Doing so will
+/// cause memory to bloat in compilations with many unloaded macro
+/// expansions, since the two data structurs are stored in a union in
+/// SLocEntry. Extra fields should instead go in "ContentCache *", which
+/// stores file contents and other bits on the side.
+///
+class FileInfo {
+ friend class clang::SourceManager;
+ friend class clang::ASTWriter;
+ friend class clang::ASTReader;
- /// Replace the existing buffer (which will be deleted)
- /// with the given buffer.
- void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
+ /// The location of the \#include that brought in this file.
+ ///
+ /// This is an invalid SLOC for the main file (top of the \#include chain).
+ SourceLocation IncludeLoc;
- /// Determine whether the buffer itself is invalid.
- bool isBufferInvalid() const {
- return Buffer.getInt() & InvalidFlag;
- }
+ /// Number of FileIDs (files and macros) that were created during
+ /// preprocessing of this \#include, including this SLocEntry.
+ ///
+ /// Zero means the preprocessor didn't provide such info for this SLocEntry.
+ unsigned NumCreatedFIDs : 31;
- /// Determine whether the buffer should be freed.
- bool shouldFreeBuffer() const {
- return (Buffer.getInt() & DoNotFreeFlag) == 0;
- }
+ /// Whether this FileInfo has any \#line directives.
+ unsigned HasLineDirectives : 1;
- // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
- // nullptr
- static const char *getInvalidBOM(StringRef BufStr);
- };
+ /// The content cache and the characteristic of the file.
+ llvm::PointerIntPair<const ContentCache *, 3, CharacteristicKind>
+ ContentAndKind;
- // Assert that the \c ContentCache objects will always be 8-byte aligned so
- // that we can pack 3 bits of integer into pointers to such objects.
- static_assert(alignof(ContentCache) >= 8,
- "ContentCache must be 8-byte aligned.");
-
- /// Information about a FileID, basically just the logical file
- /// that it represents and include stack information.
- ///
- /// Each FileInfo has include stack information, indicating where it came
- /// from. This information encodes the \#include chain that a token was
- /// expanded from. The main include file has an invalid IncludeLoc.
- ///
- /// FileInfos contain a "ContentCache *", with the contents of the file.
- ///
- class FileInfo {
- friend class clang::SourceManager;
- friend class clang::ASTWriter;
- friend class clang::ASTReader;
-
- /// The location of the \#include that brought in this file.
- ///
- /// This is an invalid SLOC for the main file (top of the \#include chain).
- unsigned IncludeLoc; // Really a SourceLocation
-
- /// Number of FileIDs (files and macros) that were created during
- /// preprocessing of this \#include, including this SLocEntry.
- ///
- /// Zero means the preprocessor didn't provide such info for this SLocEntry.
- unsigned NumCreatedFIDs : 31;
-
- /// Whether this FileInfo has any \#line directives.
- unsigned HasLineDirectives : 1;
-
- /// The content cache and the characteristic of the file.
- llvm::PointerIntPair<const ContentCache*, 3, CharacteristicKind>
- ContentAndKind;
-
- /// The filename that is used to access the file entry represented by the
- /// content cache.
- StringRef Filename;
-
- public:
- /// Return a FileInfo object.
- static FileInfo get(SourceLocation IL, const ContentCache *Con,
- CharacteristicKind FileCharacter, StringRef Filename) {
- FileInfo X;
- X.IncludeLoc = IL.getRawEncoding();
- X.NumCreatedFIDs = 0;
- X.HasLineDirectives = false;
- X.ContentAndKind.setPointer(Con);
- X.ContentAndKind.setInt(FileCharacter);
- X.Filename = Filename;
- return X;
- }
+public:
+ /// Return a FileInfo object.
+ static FileInfo get(SourceLocation IL, ContentCache &Con,
+ CharacteristicKind FileCharacter, StringRef Filename) {
+ FileInfo X;
+ X.IncludeLoc = IL;
+ X.NumCreatedFIDs = 0;
+ X.HasLineDirectives = false;
+ X.ContentAndKind.setPointer(&Con);
+ X.ContentAndKind.setInt(FileCharacter);
+ Con.Filename = Filename;
+ return X;
+ }
- SourceLocation getIncludeLoc() const {
- return SourceLocation::getFromRawEncoding(IncludeLoc);
- }
+ SourceLocation getIncludeLoc() const {
+ return IncludeLoc;
+ }
- const ContentCache *getContentCache() const {
- return ContentAndKind.getPointer();
- }
+ const ContentCache &getContentCache() const {
+ return *ContentAndKind.getPointer();
+ }
- /// Return whether this is a system header or not.
- CharacteristicKind getFileCharacteristic() const {
- return ContentAndKind.getInt();
- }
+ /// Return whether this is a system header or not.
+ CharacteristicKind getFileCharacteristic() const {
+ return ContentAndKind.getInt();
+ }
- /// Return true if this FileID has \#line directives in it.
- bool hasLineDirectives() const { return HasLineDirectives; }
+ /// Return true if this FileID has \#line directives in it.
+ bool hasLineDirectives() const { return HasLineDirectives; }
- /// Set the flag that indicates that this FileID has
- /// line table entries associated with it.
- void setHasLineDirectives() {
- HasLineDirectives = true;
- }
+ /// Set the flag that indicates that this FileID has
+ /// line table entries associated with it.
+ void setHasLineDirectives() { HasLineDirectives = true; }
- /// Returns the name of the file that was used when the file was loaded from
- /// the underlying file system.
- StringRef getName() const { return Filename; }
- };
+ /// Returns the name of the file that was used when the file was loaded from
+ /// the underlying file system.
+ StringRef getName() const { return getContentCache().Filename; }
+};
- /// Each ExpansionInfo encodes the expansion location - where
- /// the token was ultimately expanded, and the SpellingLoc - where the actual
- /// character data for the token came from.
- class ExpansionInfo {
- // Really these are all SourceLocations.
-
- /// Where the spelling for the token can be found.
- unsigned SpellingLoc;
-
- /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
- /// indicate the start and end of the expansion. In object-like macros,
- /// they will be the same. In a function-like macro expansion, the start
- /// will be the identifier and the end will be the ')'. Finally, in
- /// macro-argument instantiations, the end will be 'SourceLocation()', an
- /// invalid location.
- unsigned ExpansionLocStart, ExpansionLocEnd;
-
- /// Whether the expansion range is a token range.
- bool ExpansionIsTokenRange;
-
- public:
- SourceLocation getSpellingLoc() const {
- SourceLocation SpellLoc = SourceLocation::getFromRawEncoding(SpellingLoc);
- return SpellLoc.isInvalid() ? getExpansionLocStart() : SpellLoc;
- }
+/// Each ExpansionInfo encodes the expansion location - where
+/// the token was ultimately expanded, and the SpellingLoc - where the actual
+/// character data for the token came from.
+class ExpansionInfo {
+ // Really these are all SourceLocations.
- SourceLocation getExpansionLocStart() const {
- return SourceLocation::getFromRawEncoding(ExpansionLocStart);
- }
+ /// Where the spelling for the token can be found.
+ SourceLocation SpellingLoc;
- SourceLocation getExpansionLocEnd() const {
- SourceLocation EndLoc =
- SourceLocation::getFromRawEncoding(ExpansionLocEnd);
- return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
- }
+ /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
+ /// indicate the start and end of the expansion. In object-like macros,
+ /// they will be the same. In a function-like macro expansion, the start
+ /// will be the identifier and the end will be the ')'. Finally, in
+ /// macro-argument instantiations, the end will be 'SourceLocation()', an
+ /// invalid location.
+ SourceLocation ExpansionLocStart, ExpansionLocEnd;
- bool isExpansionTokenRange() const {
- return ExpansionIsTokenRange;
- }
+ /// Whether the expansion range is a token range.
+ bool ExpansionIsTokenRange;
- CharSourceRange getExpansionLocRange() const {
- return CharSourceRange(
- SourceRange(getExpansionLocStart(), getExpansionLocEnd()),
- isExpansionTokenRange());
- }
+public:
+ SourceLocation getSpellingLoc() const {
+ return SpellingLoc.isInvalid() ? getExpansionLocStart() : SpellingLoc;
+ }
- bool isMacroArgExpansion() const {
- // Note that this needs to return false for default constructed objects.
- return getExpansionLocStart().isValid() &&
- SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
- }
+ SourceLocation getExpansionLocStart() const {
+ return ExpansionLocStart;
+ }
- bool isMacroBodyExpansion() const {
- return getExpansionLocStart().isValid() &&
- SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
- }
+ SourceLocation getExpansionLocEnd() const {
+ return ExpansionLocEnd.isInvalid() ? getExpansionLocStart()
+ : ExpansionLocEnd;
+ }
- bool isFunctionMacroExpansion() const {
- return getExpansionLocStart().isValid() &&
- getExpansionLocStart() != getExpansionLocEnd();
- }
+ bool isExpansionTokenRange() const { return ExpansionIsTokenRange; }
- /// Return a ExpansionInfo for an expansion.
- ///
- /// Start and End specify the expansion range (where the macro is
- /// expanded), and SpellingLoc specifies the spelling location (where
- /// the characters from the token come from). All three can refer to
- /// normal File SLocs or expansion locations.
- static ExpansionInfo create(SourceLocation SpellingLoc,
- SourceLocation Start, SourceLocation End,
- bool ExpansionIsTokenRange = true) {
- ExpansionInfo X;
- X.SpellingLoc = SpellingLoc.getRawEncoding();
- X.ExpansionLocStart = Start.getRawEncoding();
- X.ExpansionLocEnd = End.getRawEncoding();
- X.ExpansionIsTokenRange = ExpansionIsTokenRange;
- return X;
- }
+ CharSourceRange getExpansionLocRange() const {
+ return CharSourceRange(
+ SourceRange(getExpansionLocStart(), getExpansionLocEnd()),
+ isExpansionTokenRange());
+ }
- /// Return a special ExpansionInfo for the expansion of
- /// a macro argument into a function-like macro's body.
- ///
- /// ExpansionLoc specifies the expansion location (where the macro is
- /// expanded). This doesn't need to be a range because a macro is always
- /// expanded at a macro parameter reference, and macro parameters are
- /// always exactly one token. SpellingLoc specifies the spelling location
- /// (where the characters from the token come from). ExpansionLoc and
- /// SpellingLoc can both refer to normal File SLocs or expansion locations.
- ///
- /// Given the code:
- /// \code
- /// #define F(x) f(x)
- /// F(42);
- /// \endcode
- ///
- /// When expanding '\c F(42)', the '\c x' would call this with an
- /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
- /// location in the definition of '\c F'.
- static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
- SourceLocation ExpansionLoc) {
- // We store an intentionally invalid source location for the end of the
- // expansion range to mark that this is a macro argument location rather
- // than a normal one.
- return create(SpellingLoc, ExpansionLoc, SourceLocation());
- }
+ bool isMacroArgExpansion() const {
+ // Note that this needs to return false for default constructed objects.
+ return getExpansionLocStart().isValid() && ExpansionLocEnd.isInvalid();
+ }
- /// Return a special ExpansionInfo representing a token that ends
- /// prematurely. This is used to model a '>>' token that has been split
- /// into '>' tokens and similar cases. Unlike for the other forms of
- /// expansion, the expansion range in this case is a character range, not
- /// a token range.
- static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc,
- SourceLocation Start,
- SourceLocation End) {
- return create(SpellingLoc, Start, End, false);
- }
- };
+ bool isMacroBodyExpansion() const {
+ return getExpansionLocStart().isValid() && ExpansionLocEnd.isValid();
+ }
+
+ bool isFunctionMacroExpansion() const {
+ return getExpansionLocStart().isValid() &&
+ getExpansionLocStart() != getExpansionLocEnd();
+ }
- /// This is a discriminated union of FileInfo and ExpansionInfo.
+ /// Return a ExpansionInfo for an expansion.
///
- /// SourceManager keeps an array of these objects, and they are uniquely
- /// identified by the FileID datatype.
- class SLocEntry {
- unsigned Offset : 31;
- unsigned IsExpansion : 1;
- union {
- FileInfo File;
- ExpansionInfo Expansion;
- };
+ /// Start and End specify the expansion range (where the macro is
+ /// expanded), and SpellingLoc specifies the spelling location (where
+ /// the characters from the token come from). All three can refer to
+ /// normal File SLocs or expansion locations.
+ static ExpansionInfo create(SourceLocation SpellingLoc, SourceLocation Start,
+ SourceLocation End,
+ bool ExpansionIsTokenRange = true) {
+ ExpansionInfo X;
+ X.SpellingLoc = SpellingLoc;
+ X.ExpansionLocStart = Start;
+ X.ExpansionLocEnd = End;
+ X.ExpansionIsTokenRange = ExpansionIsTokenRange;
+ return X;
+ }
- public:
- SLocEntry() : Offset(), IsExpansion(), File() {}
+ /// Return a special ExpansionInfo for the expansion of
+ /// a macro argument into a function-like macro's body.
+ ///
+ /// ExpansionLoc specifies the expansion location (where the macro is
+ /// expanded). This doesn't need to be a range because a macro is always
+ /// expanded at a macro parameter reference, and macro parameters are
+ /// always exactly one token. SpellingLoc specifies the spelling location
+ /// (where the characters from the token come from). ExpansionLoc and
+ /// SpellingLoc can both refer to normal File SLocs or expansion locations.
+ ///
+ /// Given the code:
+ /// \code
+ /// #define F(x) f(x)
+ /// F(42);
+ /// \endcode
+ ///
+ /// When expanding '\c F(42)', the '\c x' would call this with an
+ /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
+ /// location in the definition of '\c F'.
+ static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
+ SourceLocation ExpansionLoc) {
+ // We store an intentionally invalid source location for the end of the
+ // expansion range to mark that this is a macro argument location rather
+ // than a normal one.
+ return create(SpellingLoc, ExpansionLoc, SourceLocation());
+ }
+
+ /// Return a special ExpansionInfo representing a token that ends
+ /// prematurely. This is used to model a '>>' token that has been split
+ /// into '>' tokens and similar cases. Unlike for the other forms of
+ /// expansion, the expansion range in this case is a character range, not
+ /// a token range.
+ static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc,
+ SourceLocation Start,
+ SourceLocation End) {
+ return create(SpellingLoc, Start, End, false);
+ }
+};
- unsigned getOffset() const { return Offset; }
+// Assert that the \c FileInfo objects are no bigger than \c ExpansionInfo
+// objects. This controls the size of \c SLocEntry, of which we have one for
+// each macro expansion. The number of (unloaded) macro expansions can be
+// very large. Any other fields needed in FileInfo should go in ContentCache.
+static_assert(sizeof(FileInfo) <= sizeof(ExpansionInfo),
+ "FileInfo must be no larger than ExpansionInfo.");
- bool isExpansion() const { return IsExpansion; }
- bool isFile() const { return !isExpansion(); }
+/// This is a discriminated union of FileInfo and ExpansionInfo.
+///
+/// SourceManager keeps an array of these objects, and they are uniquely
+/// identified by the FileID datatype.
+class SLocEntry {
+ unsigned Offset : 31;
+ unsigned IsExpansion : 1;
+ union {
+ FileInfo File;
+ ExpansionInfo Expansion;
+ };
- const FileInfo &getFile() const {
- assert(isFile() && "Not a file SLocEntry!");
- return File;
- }
+public:
+ SLocEntry() : Offset(), IsExpansion(), File() {}
- const ExpansionInfo &getExpansion() const {
- assert(isExpansion() && "Not a macro expansion SLocEntry!");
- return Expansion;
- }
+ unsigned getOffset() const { return Offset; }
- static SLocEntry get(unsigned Offset, const FileInfo &FI) {
- assert(!(Offset & (1u << 31)) && "Offset is too large");
- SLocEntry E;
- E.Offset = Offset;
- E.IsExpansion = false;
- E.File = FI;
- return E;
- }
+ bool isExpansion() const { return IsExpansion; }
+ bool isFile() const { return !isExpansion(); }
- static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
- assert(!(Offset & (1u << 31)) && "Offset is too large");
- SLocEntry E;
- E.Offset = Offset;
- E.IsExpansion = true;
- E.Expansion = Expansion;
- return E;
- }
- };
+ const FileInfo &getFile() const {
+ assert(isFile() && "Not a file SLocEntry!");
+ return File;
+ }
+
+ const ExpansionInfo &getExpansion() const {
+ assert(isExpansion() && "Not a macro expansion SLocEntry!");
+ return Expansion;
+ }
+
+ static SLocEntry get(unsigned Offset, const FileInfo &FI) {
+ assert(!(Offset & (1u << 31)) && "Offset is too large");
+ SLocEntry E;
+ E.Offset = Offset;
+ E.IsExpansion = false;
+ E.File = FI;
+ return E;
+ }
+
+ static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
+ assert(!(Offset & (1u << 31)) && "Offset is too large");
+ SLocEntry E;
+ E.Offset = Offset;
+ E.IsExpansion = true;
+ new (&E.Expansion) ExpansionInfo(Expansion);
+ return E;
+ }
+};
} // namespace SrcMgr
@@ -659,7 +685,7 @@ class SourceManager : public RefCountedBase<SourceManager> {
///
/// Negative FileIDs are indexes into this table. To get from ID to an index,
/// use (-ID - 2).
- mutable SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
+ SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
/// The starting offset of the next local SLocEntry.
///
@@ -699,7 +725,7 @@ class SourceManager : public RefCountedBase<SourceManager> {
/// These ivars serve as a cache used in the getLineNumber
/// method which is used to speedup getLineNumber calls to nearby locations.
mutable FileID LastLineNoFileIDQuery;
- mutable SrcMgr::ContentCache *LastLineNoContentCache;
+ mutable const SrcMgr::ContentCache *LastLineNoContentCache;
mutable unsigned LastLineNoFilePos;
mutable unsigned LastLineNoResult;
@@ -741,6 +767,8 @@ class SourceManager : public RefCountedBase<SourceManager> {
mutable std::unique_ptr<SrcMgr::ContentCache> FakeContentCacheForRecovery;
+ mutable std::unique_ptr<SrcMgr::SLocEntry> FakeSLocEntryForRecovery;
+
/// Lazily computed map of macro argument chunks to their expanded
/// source location.
using MacroArgsMap = std::map<unsigned, SourceLocation>;
@@ -816,7 +844,7 @@ public:
/// Returns true when the given FileEntry corresponds to the main file.
///
/// The main file should be set prior to calling this function.
- bool isMainFile(FileEntryRef SourceFile);
+ bool isMainFile(const FileEntry &SourceFile);
/// Set the file ID for the precompiled preamble.
void setPreambleFileID(FileID Preamble) {
@@ -852,13 +880,11 @@ public:
int LoadedID = 0, unsigned LoadedOffset = 0,
SourceLocation IncludeLoc = SourceLocation());
- enum UnownedTag { Unowned };
-
/// Create a new FileID that represents the specified memory buffer.
///
/// This does not take ownership of the MemoryBuffer. The memory buffer must
/// outlive the SourceManager.
- FileID createFileID(UnownedTag, const llvm::MemoryBuffer *Buffer,
+ FileID createFileID(const llvm::MemoryBufferRef &Buffer,
SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
int LoadedID = 0, unsigned LoadedOffset = 0,
SourceLocation IncludeLoc = SourceLocation());
@@ -895,10 +921,18 @@ public:
/// Retrieve the memory buffer associated with the given file.
///
- /// \param Invalid If non-NULL, will be set \c true if an error
- /// occurs while retrieving the memory buffer.
- const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
- bool *Invalid = nullptr);
+ /// Returns None if the buffer is not valid.
+ llvm::Optional<llvm::MemoryBufferRef>
+ getMemoryBufferForFileOrNone(const FileEntry *File);
+
+ /// Retrieve the memory buffer associated with the given file.
+ ///
+ /// Returns a fake buffer if there isn't a real one.
+ llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File) {
+ if (auto B = getMemoryBufferForFileOrNone(File))
+ return *B;
+ return getFakeBufferForRecovery();
+ }
/// Override the contents of the given source file by providing an
/// already-allocated buffer.
@@ -907,14 +941,23 @@ public:
///
/// \param Buffer the memory buffer whose contents will be used as the
/// data in the given source file.
- ///
- /// \param DoNotFree If true, then the buffer will not be freed when the
- /// source manager is destroyed.
void overrideFileContents(const FileEntry *SourceFile,
- llvm::MemoryBuffer *Buffer, bool DoNotFree);
+ const llvm::MemoryBufferRef &Buffer) {
+ overrideFileContents(SourceFile, llvm::MemoryBuffer::getMemBuffer(Buffer));
+ }
+
+ /// Override the contents of the given source file by providing an
+ /// already-allocated buffer.
+ ///
+ /// \param SourceFile the source file whose contents will be overridden.
+ ///
+ /// \param Buffer the memory buffer whose contents will be used as the
+ /// data in the given source file.
void overrideFileContents(const FileEntry *SourceFile,
+ std::unique_ptr<llvm::MemoryBuffer> Buffer);
+ void overrideFileContents(FileEntryRef SourceFile,
std::unique_ptr<llvm::MemoryBuffer> Buffer) {
- overrideFileContents(SourceFile, Buffer.release(), /*DoNotFree*/ false);
+ overrideFileContents(&SourceFile.getFileEntry(), std::move(Buffer));
}
/// Override the given source file with another one.
@@ -939,11 +982,11 @@ public:
}
/// Bypass the overridden contents of a file. This creates a new FileEntry
- /// and initializes the content cache for it. Returns nullptr if there is no
+ /// and initializes the content cache for it. Returns None if there is no
/// such file in the filesystem.
///
/// This should be called before parsing has begun.
- const FileEntry *bypassFileContentsOverride(const FileEntry &File);
+ Optional<FileEntryRef> bypassFileContentsOverride(FileEntryRef File);
/// Specify that a file is transient.
void setFileIsTransient(const FileEntry *SourceFile);
@@ -960,61 +1003,50 @@ public:
/// Return the buffer for the specified FileID.
///
- /// If there is an error opening this buffer the first time, this
- /// manufactures a temporary buffer and returns a non-empty error string.
- const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
- bool *Invalid = nullptr) const {
- bool MyInvalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
- if (MyInvalid || !Entry.isFile()) {
- if (Invalid)
- *Invalid = true;
-
- return getFakeBufferForRecovery();
- }
-
- return Entry.getFile().getContentCache()->getBuffer(Diag, getFileManager(),
- Loc, Invalid);
+ /// If there is an error opening this buffer the first time, return None.
+ llvm::Optional<llvm::MemoryBufferRef>
+ getBufferOrNone(FileID FID, SourceLocation Loc = SourceLocation()) const {
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return Entry->getFile().getContentCache().getBufferOrNone(
+ Diag, getFileManager(), Loc);
+ return None;
}
- const llvm::MemoryBuffer *getBuffer(FileID FID,
- bool *Invalid = nullptr) const {
- bool MyInvalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
- if (MyInvalid || !Entry.isFile()) {
- if (Invalid)
- *Invalid = true;
-
- return getFakeBufferForRecovery();
- }
-
- return Entry.getFile().getContentCache()->getBuffer(
- Diag, getFileManager(), SourceLocation(), Invalid);
+ /// Return the buffer for the specified FileID.
+ ///
+ /// If there is an error opening this buffer the first time, this
+ /// manufactures a temporary buffer and returns it.
+ llvm::MemoryBufferRef
+ getBufferOrFake(FileID FID, SourceLocation Loc = SourceLocation()) const {
+ if (auto B = getBufferOrNone(FID, Loc))
+ return *B;
+ return getFakeBufferForRecovery();
}
/// Returns the FileEntry record for the provided FileID.
const FileEntry *getFileEntryForID(FileID FID) const {
- bool MyInvalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
- if (MyInvalid || !Entry.isFile())
- return nullptr;
-
- const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
- if (!Content)
- return nullptr;
- return Content->OrigEntry;
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return Entry->getFile().getContentCache().OrigEntry;
+ return nullptr;
}
/// Returns the FileEntryRef for the provided FileID.
- Optional<FileEntryRef> getFileEntryRefForID(FileID FID) const;
+ Optional<FileEntryRef> getFileEntryRefForID(FileID FID) const {
+ if (auto *Entry = getFileEntryForID(FID))
+ return Entry->getLastRef();
+ return None;
+ }
+
+ /// Returns the filename for the provided FileID, unless it's a built-in
+ /// buffer that's not represented by a filename.
+ ///
+ /// Returns None for non-files and built-in files.
+ Optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const;
/// Returns the FileEntry record for the provided SLocEntry.
const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
{
- const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
- if (!Content)
- return nullptr;
- return Content->OrigEntry;
+ return sloc.getFile().getContentCache().OrigEntry;
}
/// Return a StringRef to the source buffer data for the
@@ -1024,28 +1056,35 @@ public:
/// \param Invalid If non-NULL, will be set true if an error occurred.
StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
+ /// Return a StringRef to the source buffer data for the
+ /// specified FileID, returning None if invalid.
+ ///
+ /// \param FID The file ID whose contents will be returned.
+ llvm::Optional<StringRef> getBufferDataOrNone(FileID FID) const;
+
+ /// Return a StringRef to the source buffer data for the
+ /// specified FileID, returning None if it's not yet loaded.
+ ///
+ /// \param FID The file ID whose contents will be returned.
+ llvm::Optional<StringRef> getBufferDataIfLoaded(FileID FID) const;
+
/// Get the number of FileIDs (files and macros) that were created
/// during preprocessing of \p FID, including it.
unsigned getNumCreatedFIDsForFileID(FileID FID) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid || !Entry.isFile())
- return 0;
-
- return Entry.getFile().NumCreatedFIDs;
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return Entry->getFile().NumCreatedFIDs;
+ return 0;
}
/// Set the number of FileIDs (files and macros) that were created
/// during preprocessing of \p FID, including it.
void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs,
bool Force = false) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid || !Entry.isFile())
+ auto *Entry = getSLocEntryForFile(FID);
+ if (!Entry)
return;
-
- assert((Force || Entry.getFile().NumCreatedFIDs == 0) && "Already set!");
- const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
+ assert((Force || Entry->getFile().NumCreatedFIDs == 0) && "Already set!");
+ const_cast<SrcMgr::FileInfo &>(Entry->getFile()).NumCreatedFIDs = NumFIDs;
}
//===--------------------------------------------------------------------===//
@@ -1074,36 +1113,26 @@ public:
/// Return the source location corresponding to the first byte of
/// the specified file.
SourceLocation getLocForStartOfFile(FileID FID) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid || !Entry.isFile())
- return SourceLocation();
-
- unsigned FileOffset = Entry.getOffset();
- return SourceLocation::getFileLoc(FileOffset);
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return SourceLocation::getFileLoc(Entry->getOffset());
+ return SourceLocation();
}
/// Return the source location corresponding to the last byte of the
/// specified file.
SourceLocation getLocForEndOfFile(FileID FID) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid || !Entry.isFile())
- return SourceLocation();
-
- unsigned FileOffset = Entry.getOffset();
- return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return SourceLocation::getFileLoc(Entry->getOffset() +
+ getFileIDSize(FID));
+ return SourceLocation();
}
/// Returns the include location if \p FID is a \#include'd file
/// otherwise it returns an invalid location.
SourceLocation getIncludeLoc(FileID FID) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid || !Entry.isFile())
- return SourceLocation();
-
- return Entry.getFile().getIncludeLoc();
+ if (auto *Entry = getSLocEntryForFile(FID))
+ return Entry->getFile().getIncludeLoc();
+ return SourceLocation();
}
// Returns the import location if the given source location is
@@ -1188,14 +1217,13 @@ public:
/// Form a SourceLocation from a FileID and Offset pair.
SourceLocation getComposedLoc(FileID FID, unsigned Offset) const {
- bool Invalid = false;
- const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
- if (Invalid)
+ auto *Entry = getSLocEntryOrNull(FID);
+ if (!Entry)
return SourceLocation();
- unsigned GlobalOffset = Entry.getOffset() + Offset;
- return Entry.isFile() ? SourceLocation::getFileLoc(GlobalOffset)
- : SourceLocation::getMacroLoc(GlobalOffset);
+ unsigned GlobalOffset = Entry->getOffset() + Offset;
+ return Entry->isFile() ? SourceLocation::getFileLoc(GlobalOffset)
+ : SourceLocation::getMacroLoc(GlobalOffset);
}
/// Decompose the specified location into a raw FileID + Offset pair.
@@ -1204,11 +1232,10 @@ public:
/// start of the buffer of the location.
std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
FileID FID = getFileID(Loc);
- bool Invalid = false;
- const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
- if (Invalid)
+ auto *Entry = getSLocEntryOrNull(FID);
+ if (!Entry)
return std::make_pair(FileID(), 0);
- return std::make_pair(FID, Loc.getOffset()-E.getOffset());
+ return std::make_pair(FID, Loc.getOffset() - Entry->getOffset());
}
/// Decompose the specified location into a raw FileID + Offset pair.
@@ -1218,9 +1245,8 @@ public:
std::pair<FileID, unsigned>
getDecomposedExpansionLoc(SourceLocation Loc) const {
FileID FID = getFileID(Loc);
- bool Invalid = false;
- const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
- if (Invalid)
+ auto *E = getSLocEntryOrNull(FID);
+ if (!E)
return std::make_pair(FileID(), 0);
unsigned Offset = Loc.getOffset()-E->getOffset();
@@ -1237,9 +1263,8 @@ public:
std::pair<FileID, unsigned>
getDecomposedSpellingLoc(SourceLocation Loc) const {
FileID FID = getFileID(Loc);
- bool Invalid = false;
- const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
- if (Invalid)
+ auto *E = getSLocEntryOrNull(FID);
+ if (!E)
return std::make_pair(FileID(), 0);
unsigned Offset = Loc.getOffset()-E->getOffset();
@@ -1565,6 +1590,9 @@ public:
/// If the source file is included multiple times, the FileID will be the
/// first inclusion.
FileID translateFile(const FileEntry *SourceFile) const;
+ FileID translateFile(FileEntryRef SourceFile) const {
+ return translateFile(&SourceFile.getFileEntry());
+ }
/// Get the source location in \p FID for the given line:col.
/// Returns null location if \p FID is not a file SLocEntry.
@@ -1732,11 +1760,24 @@ private:
friend class ASTReader;
friend class ASTWriter;
- llvm::MemoryBuffer *getFakeBufferForRecovery() const;
- const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
+ llvm::MemoryBufferRef getFakeBufferForRecovery() const;
+ SrcMgr::ContentCache &getFakeContentCacheForRecovery() const;
const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
+ const SrcMgr::SLocEntry *getSLocEntryOrNull(FileID FID) const {
+ bool Invalid = false;
+ const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
+ return Invalid ? nullptr : &Entry;
+ }
+
+ const SrcMgr::SLocEntry *getSLocEntryForFile(FileID FID) const {
+ if (auto *Entry = getSLocEntryOrNull(FID))
+ if (Entry->isFile())
+ return Entry;
+ return nullptr;
+ }
+
/// Get the entry with the given unwrapped FileID.
/// Invalid will not be modified for Local IDs.
const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
@@ -1792,18 +1833,17 @@ private:
///
/// This works regardless of whether the ContentCache corresponds to a
/// file or some other input source.
- FileID createFileID(const SrcMgr::ContentCache *File, StringRef Filename,
- SourceLocation IncludePos,
- SrcMgr::CharacteristicKind DirCharacter, int LoadedID,
- unsigned LoadedOffset);
+ FileID createFileIDImpl(SrcMgr::ContentCache &File, StringRef Filename,
+ SourceLocation IncludePos,
+ SrcMgr::CharacteristicKind DirCharacter, int LoadedID,
+ unsigned LoadedOffset);
- const SrcMgr::ContentCache *
- getOrCreateContentCache(const FileEntry *SourceFile,
- bool isSystemFile = false);
+ SrcMgr::ContentCache &getOrCreateContentCache(FileEntryRef SourceFile,
+ bool isSystemFile = false);
/// Create a new ContentCache for the specified memory buffer.
- const SrcMgr::ContentCache *
- createMemBufferContentCache(const llvm::MemoryBuffer *Buf, bool DoNotFree);
+ SrcMgr::ContentCache &
+ createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buf);
FileID getFileIDSlow(unsigned SLocOffset) const;
FileID getFileIDLocal(unsigned SLocOffset) const;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/Specifiers.h b/contrib/llvm-project/clang/include/clang/Basic/Specifiers.h
index 2834dea20d00..07d8177b8ab2 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/Specifiers.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/Specifiers.h
@@ -29,32 +29,15 @@ namespace clang {
};
/// Define the kind of constexpr specifier.
- enum ConstexprSpecKind {
- CSK_unspecified,
- CSK_constexpr,
- CSK_consteval,
- CSK_constinit
- };
+ enum class ConstexprSpecKind { Unspecified, Constexpr, Consteval, Constinit };
/// Specifies the width of a type, e.g., short, long, or long long.
- enum TypeSpecifierWidth {
- TSW_unspecified,
- TSW_short,
- TSW_long,
- TSW_longlong
- };
+ enum class TypeSpecifierWidth { Unspecified, Short, Long, LongLong };
/// Specifies the signedness of a type, e.g., signed or unsigned.
- enum TypeSpecifierSign {
- TSS_unspecified,
- TSS_signed,
- TSS_unsigned
- };
+ enum class TypeSpecifierSign { Unspecified, Signed, Unsigned };
- enum TypeSpecifiersPipe {
- TSP_unspecified,
- TSP_pipe
- };
+ enum class TypeSpecifiersPipe { Unspecified, Pipe };
/// Specifies the kind of type.
enum TypeSpecifierType {
@@ -106,7 +89,7 @@ namespace clang {
static_assert(TST_error < 1 << 6, "Type bitfield not wide enough for TST");
/*DeclSpec::TST*/ unsigned Type : 6;
/*DeclSpec::TSS*/ unsigned Sign : 2;
- /*DeclSpec::TSW*/ unsigned Width : 2;
+ /*TypeSpecifierWidth*/ unsigned Width : 2;
unsigned ModeAttr : 1;
};
@@ -326,7 +309,12 @@ namespace clang {
/// unspecified. This captures a (fairly rare) case where we
/// can't conclude anything about the nullability of the type even
/// though it has been considered.
- Unspecified
+ Unspecified,
+ // Generally behaves like Nullable, except when used in a block parameter
+ // that was imported into a swift async method. There, swift will assume
+ // that the parameter can get null even if no error occured. _Nullable
+ // parameters are assumed to only get null on error.
+ NullableResult,
};
/// Return true if \p L has a weaker nullability annotation than \p R. The
diff --git a/contrib/llvm-project/clang/include/clang/Basic/TargetCXXABI.h b/contrib/llvm-project/clang/include/clang/Basic/TargetCXXABI.h
index 93f70fc70dd8..2d267f43f92b 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/TargetCXXABI.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/TargetCXXABI.h
@@ -15,6 +15,7 @@
#ifndef LLVM_CLANG_BASIC_TARGETCXXABI_H
#define LLVM_CLANG_BASIC_TARGETCXXABI_H
+#include "clang/Basic/LLVM.h"
#include "llvm/Support/ErrorHandling.h"
namespace clang {
@@ -61,17 +62,17 @@ public:
/// - constructor/destructor signatures.
iOS,
- /// The iOS 64-bit ABI is follows ARM's published 64-bit ABI more
- /// closely, but we don't guarantee to follow it perfectly.
+ /// The iOS 64-bit and macOS 64-bit ARM ABI follows ARM's published 64-bit
+ /// ABI more closely, but we don't guarantee to follow it perfectly.
///
/// It is documented here:
/// http://infocenter.arm.com
/// /help/topic/com.arm.doc.ihi0059a/IHI0059A_cppabi64.pdf
- iOS64,
+ AppleARM64,
/// WatchOS is a modernisation of the iOS ABI, which roughly means it's
- /// the iOS64 ABI ported to 32-bits. The primary difference from iOS64 is
- /// that RTTI objects must still be unique at the moment.
+ /// the AppleARM64 ABI ported to 32-bits. The primary difference from
+ /// AppleARM64 is that RTTI objects must still be unique at the moment.
WatchOS,
/// The generic AArch64 ABI is also a modified version of the Itanium ABI,
@@ -97,7 +98,7 @@ public:
/// - guard variables are 32-bit on wasm32, as in ARM;
/// - unused bits of guard variables are reserved, as in ARM;
/// - inline functions are never key functions, as in ARM;
- /// - C++11 POD rules are used for tail padding, as in iOS64.
+ /// - C++11 POD rules are used for tail padding, as in AppleARM64.
///
/// TODO: At present the WebAssembly ABI is not considered stable, so none
/// of these details is necessarily final yet.
@@ -146,12 +147,12 @@ public:
/// Does this ABI generally fall into the Itanium family of ABIs?
bool isItaniumFamily() const {
switch (getKind()) {
+ case AppleARM64:
case Fuchsia:
case GenericAArch64:
case GenericItanium:
case GenericARM:
case iOS:
- case iOS64:
case WatchOS:
case GenericMIPS:
case WebAssembly:
@@ -167,12 +168,12 @@ public:
/// Is this ABI an MSVC-compatible ABI?
bool isMicrosoft() const {
switch (getKind()) {
+ case AppleARM64:
case Fuchsia:
case GenericAArch64:
case GenericItanium:
case GenericARM:
case iOS:
- case iOS64:
case WatchOS:
case GenericMIPS:
case WebAssembly:
@@ -199,6 +200,7 @@ public:
case WebAssembly:
// WebAssembly doesn't require any special alignment for member functions.
return false;
+ case AppleARM64:
case Fuchsia:
case GenericARM:
case GenericAArch64:
@@ -208,7 +210,6 @@ public:
// special alignment and could therefore also return false.
case GenericItanium:
case iOS:
- case iOS64:
case WatchOS:
case Microsoft:
case XL:
@@ -276,9 +277,9 @@ public:
/// done on a generic Itanium platform.
bool canKeyFunctionBeInline() const {
switch (getKind()) {
+ case AppleARM64:
case Fuchsia:
case GenericARM:
- case iOS64:
case WebAssembly:
case WatchOS:
return false;
@@ -329,10 +330,10 @@ public:
case XL:
return UseTailPaddingUnlessPOD03;
- // iOS on ARM64 and WebAssembly use the C++11 POD rules. They do not honor
+ // AppleARM64 and WebAssembly use the C++11 POD rules. They do not honor
// the Itanium exception about classes with over-large bitfields.
+ case AppleARM64:
case Fuchsia:
- case iOS64:
case WebAssembly:
case WatchOS:
return UseTailPaddingUnlessPOD11;
diff --git a/contrib/llvm-project/clang/include/clang/Basic/TargetID.h b/contrib/llvm-project/clang/include/clang/Basic/TargetID.h
new file mode 100644
index 000000000000..1a9785574d06
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Basic/TargetID.h
@@ -0,0 +1,56 @@
+//===--- TargetID.h - Utilities for target ID -------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_TARGET_ID_H
+#define LLVM_CLANG_BASIC_TARGET_ID_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/Triple.h"
+#include <set>
+
+namespace clang {
+
+/// Get all feature strings that can be used in target ID for \p Processor.
+/// Target ID is a processor name with optional feature strings
+/// postfixed by a plus or minus sign delimited by colons, e.g.
+/// gfx908:xnack+:sramecc-. Each processor have a limited
+/// number of predefined features when showing up in a target ID.
+const llvm::SmallVector<llvm::StringRef, 4>
+getAllPossibleTargetIDFeatures(const llvm::Triple &T,
+ llvm::StringRef Processor);
+
+/// Get processor name from target ID.
+/// Returns canonical processor name or empty if the processor name is invalid.
+llvm::StringRef getProcessorFromTargetID(const llvm::Triple &T,
+ llvm::StringRef OffloadArch);
+
+/// Parse a target ID to get processor and feature map.
+/// Returns canonicalized processor name or None if the target ID is invalid.
+/// Returns target ID features in \p FeatureMap if it is not null pointer.
+/// This function assumes \p OffloadArch is a valid target ID.
+/// If the target ID contains feature+, map it to true.
+/// If the target ID contains feature-, map it to false.
+/// If the target ID does not contain a feature (default), do not map it.
+llvm::Optional<llvm::StringRef>
+parseTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch,
+ llvm::StringMap<bool> *FeatureMap);
+
+/// Returns canonical target ID, assuming \p Processor is canonical and all
+/// entries in \p Features are valid.
+std::string getCanonicalTargetID(llvm::StringRef Processor,
+ const llvm::StringMap<bool> &Features);
+
+/// Get the conflicted pair of target IDs for a compilation or a bundled code
+/// object, assuming \p TargetIDs are canonicalized. If there is no conflicts,
+/// returns None.
+llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
+getConflictTargetIDCombination(const std::set<llvm::StringRef> &TargetIDs);
+} // namespace clang
+
+#endif
diff --git a/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h b/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h
index 2ee3b1659630..b782172d93a3 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h
@@ -100,8 +100,8 @@ struct TransferrableTargetInfo {
unsigned char MinGlobalAlign;
unsigned short NewAlign;
- unsigned short MaxVectorAlign;
- unsigned short MaxTLSAlign;
+ unsigned MaxVectorAlign;
+ unsigned MaxTLSAlign;
const llvm::fltSemantics *HalfFormat, *BFloat16Format, *FloatFormat,
*DoubleFormat, *LongDoubleFormat, *Float128Format;
@@ -218,6 +218,8 @@ protected:
unsigned HasAArch64SVETypes : 1;
+ unsigned AllowAMDGPUUnsafeFPAtomics : 1;
+
unsigned ARMCDECoprocMask : 8;
unsigned MaxOpenCLWorkGroupSize;
@@ -581,8 +583,9 @@ public:
/// Determine whether constrained floating point is supported on this target.
virtual bool hasStrictFP() const { return HasStrictFP; }
- /// Return the alignment that is suitable for storing any
- /// object with a fundamental alignment requirement.
+ /// Return the alignment that is the largest alignment ever used for any
+ /// scalar/SIMD data type on the target machine you are compiling for
+ /// (including types with an extended alignment requirement).
unsigned getSuitableAlign() const { return SuitableAlign; }
/// Return the default alignment for __attribute__((aligned)) on
@@ -856,6 +859,10 @@ public:
/// available on this target.
bool hasAArch64SVETypes() const { return HasAArch64SVETypes; }
+ /// Returns whether or not the AMDGPU unsafe floating point atomics are
+ /// allowed.
+ bool allowAMDGPUUnsafeFPAtomics() const { return AllowAMDGPUUnsafeFPAtomics; }
+
/// For ARM targets returns a mask defining which coprocessors are configured
/// as Custom Datapath.
uint32_t getARMCDECoprocMask() const { return ARMCDECoprocMask; }
@@ -1061,6 +1068,9 @@ public:
return Triple;
}
+ /// Returns the target ID if supported.
+ virtual llvm::Optional<std::string> getTargetID() const { return llvm::None; }
+
const llvm::DataLayout &getDataLayout() const {
assert(DataLayout && "Uninitialized DataLayout!");
return *DataLayout;
@@ -1088,6 +1098,13 @@ public:
/// either; the entire thing is pretty badly mangled.
virtual bool hasProtectedVisibility() const { return true; }
+ /// Does this target aim for semantic compatibility with
+ /// Microsoft C++ code using dllimport/export attributes?
+ virtual bool shouldDLLImportComdatSymbols() const {
+ return getTriple().isWindowsMSVCEnvironment() ||
+ getTriple().isWindowsItaniumEnvironment() || getTriple().isPS4CPU();
+ }
+
/// An optional hook that targets can implement to perform semantic
/// checking on attribute((section("foo"))) specifiers.
///
@@ -1140,11 +1157,27 @@ public:
/// Fill a SmallVectorImpl with the valid values to setCPU.
virtual void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const {}
+ /// Fill a SmallVectorImpl with the valid values for tuning CPU.
+ virtual void fillValidTuneCPUList(SmallVectorImpl<StringRef> &Values) const {
+ fillValidCPUList(Values);
+ }
+
/// brief Determine whether this TargetInfo supports the given CPU name.
virtual bool isValidCPUName(StringRef Name) const {
return true;
}
+ /// brief Determine whether this TargetInfo supports the given CPU name for
+ // tuning.
+ virtual bool isValidTuneCPUName(StringRef Name) const {
+ return isValidCPUName(Name);
+ }
+
+ /// brief Determine whether this TargetInfo supports tune in target attribute.
+ virtual bool supportsTargetAttributeTune() const {
+ return false;
+ }
+
/// Use the specified ABI.
///
/// \return False on error (invalid ABI name).
@@ -1271,9 +1304,7 @@ public:
///
/// Gets the maximum alignment (in bits) of a TLS variable on this target.
/// Returns zero if there is no such constraint.
- unsigned short getMaxTLSAlign() const {
- return MaxTLSAlign;
- }
+ unsigned getMaxTLSAlign() const { return MaxTLSAlign; }
/// Whether target supports variable-length arrays.
bool isVLASupported() const { return VLASupported; }
@@ -1401,24 +1432,45 @@ public:
/// Whether target allows to overalign ABI-specified preferred alignment
virtual bool allowsLargerPreferedTypeAlignment() const { return true; }
+ /// Whether target defaults to the `power` alignment rules of AIX.
+ virtual bool defaultsToAIXPowerAlignment() const { return false; }
+
/// Set supported OpenCL extensions and optional core features.
virtual void setSupportedOpenCLOpts() {}
+ virtual void supportAllOpenCLOpts(bool V = true) {
+#define OPENCLEXTNAME(Ext) getTargetOpts().OpenCLFeaturesMap[#Ext] = V;
+#include "clang/Basic/OpenCLExtensions.def"
+ }
+
/// Set supported OpenCL extensions as written on command line
- virtual void setOpenCLExtensionOpts() {
+ virtual void setCommandLineOpenCLOpts() {
for (const auto &Ext : getTargetOpts().OpenCLExtensionsAsWritten) {
- getTargetOpts().SupportedOpenCLOptions.support(Ext);
+ bool IsPrefixed = (Ext[0] == '+' || Ext[0] == '-');
+ std::string Name = IsPrefixed ? Ext.substr(1) : Ext;
+ bool V = IsPrefixed ? Ext[0] == '+' : true;
+
+ if (Name == "all") {
+ supportAllOpenCLOpts(V);
+ continue;
+ }
+
+ getTargetOpts().OpenCLFeaturesMap[Name] = V;
}
}
+ /// Define OpenCL macros based on target settings and language version
+ void getOpenCLFeatureDefines(const LangOptions &Opts,
+ MacroBuilder &Builder) const;
+
/// Get supported OpenCL extensions and optional core features.
- OpenCLOptions &getSupportedOpenCLOpts() {
- return getTargetOpts().SupportedOpenCLOptions;
+ llvm::StringMap<bool> &getSupportedOpenCLOpts() {
+ return getTargetOpts().OpenCLFeaturesMap;
}
/// Get const supported OpenCL extensions and optional core features.
- const OpenCLOptions &getSupportedOpenCLOpts() const {
- return getTargetOpts().SupportedOpenCLOptions;
+ const llvm::StringMap<bool> &getSupportedOpenCLOpts() const {
+ return getTargetOpts().OpenCLFeaturesMap;
}
/// Get address space for OpenCL type.
diff --git a/contrib/llvm-project/clang/include/clang/Basic/TargetOptions.h b/contrib/llvm-project/clang/include/clang/Basic/TargetOptions.h
index 4a5d469b8e54..81c15adb8248 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/TargetOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Basic/TargetOptions.h
@@ -35,6 +35,9 @@ public:
/// If given, the name of the target CPU to generate code for.
std::string CPU;
+ /// If given, the name of the target CPU to tune code for.
+ std::string TuneCPU;
+
/// If given, the unit to use for floating point math.
std::string FPMath;
@@ -59,7 +62,7 @@ public:
llvm::StringMap<bool> FeatureMap;
/// Supported OpenCL extensions and optional core features.
- OpenCLOptions SupportedOpenCLOptions;
+ llvm::StringMap<bool> OpenCLFeaturesMap;
/// The list of OpenCL extensions to enable or disable, as written on
/// the command line.
@@ -72,6 +75,9 @@ public:
/// address space.
bool NVPTXUseShortPointers = false;
+ /// \brief If enabled, allow AMDGPU unsafe floating point atomics.
+ bool AllowAMDGPUUnsafeFPAtomics = false;
+
// The code model to be used as specified by the user. Corresponds to
// CodeModel::Model enum defined in include/llvm/Support/CodeGen.h, plus
// "default" for the case when the user has not explicitly specified a
diff --git a/contrib/llvm-project/clang/include/clang/Basic/TokenKinds.def b/contrib/llvm-project/clang/include/clang/Basic/TokenKinds.def
index 2b353269ed52..572ebae6618d 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/TokenKinds.def
+++ b/contrib/llvm-project/clang/include/clang/Basic/TokenKinds.def
@@ -586,7 +586,7 @@ ALIAS("write_only", __write_only , KEYOPENCLC | KEYOPENCLCXX)
ALIAS("read_write", __read_write , KEYOPENCLC | KEYOPENCLCXX)
// OpenCL builtins
KEYWORD(__builtin_astype , KEYOPENCLC | KEYOPENCLCXX)
-UNARY_EXPR_OR_TYPE_TRAIT(vec_step, VecStep, KEYOPENCLC | KEYALTIVEC | KEYZVECTOR)
+UNARY_EXPR_OR_TYPE_TRAIT(vec_step, VecStep, KEYOPENCLC | KEYOPENCLCXX | KEYALTIVEC | KEYZVECTOR)
#define GENERIC_IMAGE_TYPE(ImgType, Id) KEYWORD(ImgType##_t, KEYOPENCLC | KEYOPENCLCXX)
#include "clang/Basic/OpenCLImageTypes.def"
KEYWORD(pipe , KEYOPENCLC | KEYOPENCLCXX)
@@ -650,6 +650,7 @@ ALIAS("__volatile__" , volatile , KEYALL)
// Type nullability.
KEYWORD(_Nonnull , KEYALL)
KEYWORD(_Nullable , KEYALL)
+KEYWORD(_Nullable_result , KEYALL)
KEYWORD(_Null_unspecified , KEYALL)
// Microsoft extensions which should be disabled in strict conformance mode
@@ -698,7 +699,6 @@ ALIAS("__char16_t" , char16_t , KEYCXX)
ALIAS("__char32_t" , char32_t , KEYCXX)
KEYWORD(__builtin_bit_cast , KEYALL)
KEYWORD(__builtin_available , KEYALL)
-KEYWORD(__builtin_unique_stable_name, KEYALL)
// Clang-specific keywords enabled only in testing.
TESTING_KEYWORD(__unknown_anytype , KEYALL)
@@ -757,10 +757,10 @@ ANNOTATION(non_type_undeclared) // annotation for an undeclared identifier that
// was assumed to be an ADL-only function name
ANNOTATION(non_type_dependent) // annotation for an assumed non-type member of
// a dependent base class
-ANNOTATION(primary_expr) // annotation for a primary expression
-ANNOTATION(
- uneval_primary_expr) // annotation for a primary expression which should be
- // transformed to potentially evaluated
+ANNOTATION(overload_set) // annotation for an unresolved overload set
+ANNOTATION(primary_expr) // annotation for a primary expression, used when
+ // tentatively parsing a lambda init-capture or ObjC
+ // message send
ANNOTATION(decltype) // annotation for a decltype expression,
// e.g., "decltype(foo.bar())"
@@ -829,6 +829,11 @@ PRAGMA_ANNOTATION(pragma_fp_contract)
// handles them.
PRAGMA_ANNOTATION(pragma_fenv_access)
+// Annotation for #pragma STDC FENV_ROUND
+// The lexer produces these so that they only take effect when the parser
+// handles them.
+PRAGMA_ANNOTATION(pragma_fenv_round)
+
// Annotation for #pragma float_control
// The lexer produces these so that they only take effect when the parser
// handles them.
diff --git a/contrib/llvm-project/clang/include/clang/Basic/arm_mve.td b/contrib/llvm-project/clang/include/clang/Basic/arm_mve.td
index 25daae2a0a25..8106f9a5a9de 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/arm_mve.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/arm_mve.td
@@ -406,7 +406,7 @@ def vabdq: Intrinsic<Vector, (args Vector:$a, Vector:$b),
}
multiclass VectorVectorArithmetic<string operation, dag extraArgs = (?),
- int wantXVariant = 1> {
+ bit wantXVariant = 1> {
defm "" : IntrinsicMX<
Vector, (args Vector:$a, Vector:$b, Predicate:$pred),
!con((IRInt<operation, [Vector, Predicate]> $a, $b),
@@ -415,7 +415,7 @@ multiclass VectorVectorArithmetic<string operation, dag extraArgs = (?),
multiclass VectorScalarArithmetic<string operation, string basename,
dag extraArgs = (?),
- int wantXVariant = 1> {
+ bit wantXVariant = 1> {
defm "" : IntrinsicMXNameOverride<
Vector, (args Vector:$a, unpromoted<Scalar>:$b, Predicate:$pred),
!con((IRInt<operation, [Vector, Predicate]> $a, (splat $b)),
@@ -451,7 +451,7 @@ let params = T.Usual in {
}
multiclass DblVectorVectorArithmetic<string operation, dag extraArgs = (?),
- int wantXVariant = 1> {
+ bit wantXVariant = 1> {
defm "" : IntrinsicMX<
DblVector, (args Vector:$a, Vector:$b, DblPredicate:$pred),
!con((IRInt<operation, [DblVector, Vector, DblPredicate]> $a, $b),
@@ -460,7 +460,7 @@ multiclass DblVectorVectorArithmetic<string operation, dag extraArgs = (?),
multiclass DblVectorScalarArithmetic<string operation, string basename,
dag extraArgs = (?),
- int wantXVariant = 1> {
+ bit wantXVariant = 1> {
defm "" : IntrinsicMXNameOverride<
DblVector, (args Vector:$a, unpromoted<Scalar>:$b, DblPredicate:$pred),
!con((IRInt<operation, [DblVector, Vector, DblPredicate]> $a, (splat $b)),
@@ -545,8 +545,8 @@ multiclass Reduction<Type Accumulator, string basename, list<Type> basetypes,
defvar intArgsUnpred = !con(intArgsBase,
!if(needSign, (? (unsignedflag Scalar)), (?)));
defvar intArgsPred = !con(intArgsUnpred, (? $pred));
- defvar intUnpred = !setop(intArgsUnpred, IRInt<basename, basetypes>);
- defvar intPred = !setop(intArgsPred, IRInt<
+ defvar intUnpred = !setdagop(intArgsUnpred, IRInt<basename, basetypes>);
+ defvar intPred = !setdagop(intArgsPred, IRInt<
basename#"_predicated", !listconcat(basetypes, [Predicate])>);
def "": Intrinsic<
diff --git a/contrib/llvm-project/clang/include/clang/Basic/arm_mve_defs.td b/contrib/llvm-project/clang/include/clang/Basic/arm_mve_defs.td
index 4038a18027f8..1a090c08cc85 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/arm_mve_defs.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/arm_mve_defs.td
@@ -519,7 +519,7 @@ class NameOverride<string basename_> {
// polymorph differently (typically because the type of the inactive
// parameter can be used as a disambiguator if it's present).
multiclass IntrinsicMX<Type rettype, dag arguments, dag cg,
- int wantXVariant = 1,
+ bit wantXVariant = 1,
string nameSuffix = "",
PolymorphicNameType pnt_m = PNT_Type,
PolymorphicNameType pnt_x = PNT_Type> {
@@ -532,7 +532,7 @@ multiclass IntrinsicMX<Type rettype, dag arguments, dag cg,
let pnt = pnt_m;
}
- foreach unusedVar = !if(!eq(wantXVariant, 1), [1], []<int>) in {
+ if wantXVariant then {
// The _x variant leaves off that parameter, and simply uses an
// undef value of the same type.
@@ -546,7 +546,7 @@ multiclass IntrinsicMX<Type rettype, dag arguments, dag cg,
// Same as above, but with an additional parameter 'basename' which overrides
// the C intrinsic base name
multiclass IntrinsicMXNameOverride<Type rettype, dag arguments, dag cg,
- string basename, int wantXVariant = 1,
+ string basename, bit wantXVariant = 1,
string nameSuffix = "",
PolymorphicNameType pnt_m = PNT_Type,
PolymorphicNameType pnt_x = PNT_Type> {
@@ -556,7 +556,7 @@ multiclass IntrinsicMXNameOverride<Type rettype, dag arguments, dag cg,
let pnt = pnt_m;
}
- foreach unusedVar = !if(!eq(wantXVariant, 1), [1], []<int>) in {
+ if wantXVariant then {
def "_x" # nameSuffix:
Intrinsic<rettype, arguments, (seq (undef rettype):$inactive, cg)>,
NameOverride<basename # "_x" # nameSuffix> {
diff --git a/contrib/llvm-project/clang/include/clang/Basic/arm_neon.td b/contrib/llvm-project/clang/include/clang/Basic/arm_neon.td
index d0269f31c32d..3b2a578f796e 100644
--- a/contrib/llvm-project/clang/include/clang/Basic/arm_neon.td
+++ b/contrib/llvm-project/clang/include/clang/Basic/arm_neon.td
@@ -786,9 +786,6 @@ def VMUL_N_A64 : IOpInst<"vmul_n", "..1", "Qd", OP_MUL_N>;
def FMLA_N : SOpInst<"vfma_n", "...1", "dQd", OP_FMLA_N>;
def FMLS_N : SOpInst<"vfms_n", "...1", "fdQfQd", OP_FMLS_N>;
-def MLA_N : SOpInst<"vmla_n", "...1", "Qd", OP_MLA_N>;
-def MLS_N : SOpInst<"vmls_n", "...1", "Qd", OP_MLS_N>;
-
////////////////////////////////////////////////////////////////////////////////
// Logical operations
def BSL : SInst<"vbsl", ".U..", "dPlQdQPl">;
@@ -830,7 +827,7 @@ def XTN2 : SOpInst<"vmovn_high", "(<Q)<Q", "silUsUiUl", OP_XTN>;
////////////////////////////////////////////////////////////////////////////////
// Signed integer saturating extract and unsigned narrow to high
-def SQXTUN2 : SOpInst<"vqmovun_high", "(<U)(<q).", "HsHiHl", OP_SQXTUN>;
+def SQXTUN2 : SOpInst<"vqmovun_high", "(<U)(<Uq).", "HsHiHl", OP_SQXTUN>;
////////////////////////////////////////////////////////////////////////////////
// Integer saturating extract and narrow to high
@@ -868,7 +865,7 @@ def CFMGT : SOpInst<"vcgt", "U..", "lUldQdQlQUl", OP_GT>;
def CFMLT : SOpInst<"vclt", "U..", "lUldQdQlQUl", OP_LT>;
def CMEQ : SInst<"vceqz", "U.",
- "csilfUcUsUiUlPcPsPlQcQsQiQlQfQUcQUsQUiQUlQPcQPsdQdQPl">;
+ "csilfUcUsUiUlPcPlQcQsQiQlQfQUcQUsQUiQUlQPcdQdQPl">;
def CMGE : SInst<"vcgez", "U.", "csilfdQcQsQiQlQfQd">;
def CMLE : SInst<"vclez", "U.", "csilfdQcQsQiQlQfQd">;
def CMGT : SInst<"vcgtz", "U.", "csilfdQcQsQiQlQfQd">;
@@ -1263,13 +1260,13 @@ def VGET_LOW_A64 : NoTestOpInst<"vget_low", ".Q", "dPl", OP_LO>;
////////////////////////////////////////////////////////////////////////////////
// Scalar Shift
// Scalar Shift Left
-def SCALAR_SHL: SInst<"vshl", "111", "SlSUl">;
+def SCALAR_SHL: SInst<"vshl", "11(S1)", "SlSUl">;
// Scalar Saturating Shift Left
-def SCALAR_QSHL: SInst<"vqshl", "111", "ScSsSiSlSUcSUsSUiSUl">;
+def SCALAR_QSHL: SInst<"vqshl", "11(S1)", "ScSsSiSlSUcSUsSUiSUl">;
// Scalar Saturating Rounding Shift Left
-def SCALAR_QRSHL: SInst<"vqrshl", "111", "ScSsSiSlSUcSUsSUiSUl">;
+def SCALAR_QRSHL: SInst<"vqrshl", "11(S1)", "ScSsSiSlSUcSUsSUiSUl">;
// Scalar Shift Rounding Left
-def SCALAR_RSHL: SInst<"vrshl", "111", "SlSUl">;
+def SCALAR_RSHL: SInst<"vrshl", "11(S1)", "SlSUl">;
////////////////////////////////////////////////////////////////////////////////
// Scalar Shift (Immediate)
@@ -1419,19 +1416,19 @@ def SCALAR_FRSQRTE : IInst<"vrsqrte", "11", "SfSd">;
////////////////////////////////////////////////////////////////////////////////
// Scalar Integer Comparison
-def SCALAR_CMEQ : SInst<"vceq", "111", "SlSUl">;
-def SCALAR_CMEQZ : SInst<"vceqz", "11", "SlSUl">;
-def SCALAR_CMGE : SInst<"vcge", "111", "Sl">;
-def SCALAR_CMGEZ : SInst<"vcgez", "11", "Sl">;
-def SCALAR_CMHS : SInst<"vcge", "111", "SUl">;
-def SCALAR_CMLE : SInst<"vcle", "111", "SlSUl">;
-def SCALAR_CMLEZ : SInst<"vclez", "11", "Sl">;
-def SCALAR_CMLT : SInst<"vclt", "111", "SlSUl">;
-def SCALAR_CMLTZ : SInst<"vcltz", "11", "Sl">;
-def SCALAR_CMGT : SInst<"vcgt", "111", "Sl">;
-def SCALAR_CMGTZ : SInst<"vcgtz", "11", "Sl">;
-def SCALAR_CMHI : SInst<"vcgt", "111", "SUl">;
-def SCALAR_CMTST : SInst<"vtst", "111", "SlSUl">;
+def SCALAR_CMEQ : SInst<"vceq", "(U1)11", "SlSUl">;
+def SCALAR_CMEQZ : SInst<"vceqz", "(U1)1", "SlSUl">;
+def SCALAR_CMGE : SInst<"vcge", "(U1)11", "Sl">;
+def SCALAR_CMGEZ : SInst<"vcgez", "(U1)1", "Sl">;
+def SCALAR_CMHS : SInst<"vcge", "(U1)11", "SUl">;
+def SCALAR_CMLE : SInst<"vcle", "(U1)11", "SlSUl">;
+def SCALAR_CMLEZ : SInst<"vclez", "(U1)1", "Sl">;
+def SCALAR_CMLT : SInst<"vclt", "(U1)11", "SlSUl">;
+def SCALAR_CMLTZ : SInst<"vcltz", "(U1)1", "Sl">;
+def SCALAR_CMGT : SInst<"vcgt", "(U1)11", "Sl">;
+def SCALAR_CMGTZ : SInst<"vcgtz", "(U1)1", "Sl">;
+def SCALAR_CMHI : SInst<"vcgt", "(U1)11", "SUl">;
+def SCALAR_CMTST : SInst<"vtst", "(U1)11", "SlSUl">;
////////////////////////////////////////////////////////////////////////////////
// Scalar Floating-point Comparison
@@ -1498,7 +1495,7 @@ def SCALAR_SQDMULL : SInst<"vqdmull", "(1>)11", "SsSi">;
////////////////////////////////////////////////////////////////////////////////
// Scalar Signed Saturating Extract Unsigned Narrow
-def SCALAR_SQXTUN : SInst<"vqmovun", "(1<)1", "SsSiSl">;
+def SCALAR_SQXTUN : SInst<"vqmovun", "(U1<)1", "SsSiSl">;
////////////////////////////////////////////////////////////////////////////////
// Scalar Signed Saturating Extract Narrow
@@ -1902,22 +1899,52 @@ let ArchGuard = "defined(__ARM_FEATURE_BF16_VECTOR_ARITHMETIC)" in {
def VFMLALT_LANEQ_BF : SOpInst<"vbfmlalt_laneq", "..B(BQ)I", "Qf", OP_BFMLALT_LN>;
}
+multiclass VCMLA_ROTS<string type, string lanety, string laneqty> {
+ foreach ROT = ["", "_rot90", "_rot180", "_rot270" ] in {
+ def : SInst<"vcmla" # ROT, "....", type # "Q" # type>;
+
+ // vcmla{ROT}_lane
+ def : SOpInst<"vcmla" # ROT # "_lane", "...qI", type, Op<(call "vcmla" # ROT, $p0, $p1,
+ (bitcast $p0, (dup_typed lanety , (call "vget_lane", (bitcast lanety, $p2), $p3))))>>;
+
+ // vcmlaq{ROT}_lane
+ def : SOpInst<"vcmla" # ROT # "_lane", "...qI", "Q" # type, Op<(call "vcmla" # ROT, $p0, $p1,
+ (bitcast $p0, (dup_typed laneqty , (call "vget_lane", (bitcast lanety, $p2), $p3))))>>;
+
+ let isLaneQ = 1 in {
+ // vcmla{ROT}_laneq
+ def : SOpInst<"vcmla" # ROT # "_laneq", "...QI", type, Op<(call "vcmla" # ROT, $p0, $p1,
+ (bitcast $p0, (dup_typed lanety, (call "vget_lane", (bitcast laneqty, $p2), $p3))))>>;
+
+ // vcmlaq{ROT}_laneq
+ def : SOpInst<"vcmla" # ROT # "_laneq", "...QI", "Q" # type, Op<(call "vcmla" # ROT, $p0, $p1,
+ (bitcast $p0, (dup_typed laneqty , (call "vget_lane", (bitcast laneqty, $p2), $p3))))>>;
+ }
+ }
+}
+
// v8.3-A Vector complex addition intrinsics
let ArchGuard = "defined(__ARM_FEATURE_COMPLEX) && defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)" in {
def VCADD_ROT90_FP16 : SInst<"vcadd_rot90", "...", "h">;
def VCADD_ROT270_FP16 : SInst<"vcadd_rot270", "...", "h">;
def VCADDQ_ROT90_FP16 : SInst<"vcaddq_rot90", "QQQ", "h">;
def VCADDQ_ROT270_FP16 : SInst<"vcaddq_rot270", "QQQ", "h">;
+
+ defm VCMLA_FP16 : VCMLA_ROTS<"h", "uint32x2_t", "uint32x4_t">;
}
let ArchGuard = "defined(__ARM_FEATURE_COMPLEX)" in {
def VCADD_ROT90 : SInst<"vcadd_rot90", "...", "f">;
def VCADD_ROT270 : SInst<"vcadd_rot270", "...", "f">;
def VCADDQ_ROT90 : SInst<"vcaddq_rot90", "QQQ", "f">;
def VCADDQ_ROT270 : SInst<"vcaddq_rot270", "QQQ", "f">;
+
+ defm VCMLA_F32 : VCMLA_ROTS<"f", "uint64x1_t", "uint64x2_t">;
}
let ArchGuard = "defined(__ARM_FEATURE_COMPLEX) && defined(__aarch64__)" in {
def VCADDQ_ROT90_FP64 : SInst<"vcaddq_rot90", "QQQ", "d">;
def VCADDQ_ROT270_FP64 : SInst<"vcaddq_rot270", "QQQ", "d">;
+
+ defm VCMLA_FP64 : VCMLA_ROTS<"d", "uint64x2_t", "uint64x2_t">;
}
// V8.2-A BFloat intrinsics
diff --git a/contrib/llvm-project/clang/include/clang/CodeGen/BackendUtil.h b/contrib/llvm-project/clang/include/clang/CodeGen/BackendUtil.h
index 01b1f5bbd6ee..43de07cc145b 100644
--- a/contrib/llvm-project/clang/include/clang/CodeGen/BackendUtil.h
+++ b/contrib/llvm-project/clang/include/clang/CodeGen/BackendUtil.h
@@ -45,11 +45,6 @@ namespace clang {
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
llvm::MemoryBufferRef Buf);
-
- llvm::Expected<llvm::BitcodeModule>
- FindThinLTOModule(llvm::MemoryBufferRef MBRef);
- llvm::BitcodeModule *
- FindThinLTOModule(llvm::MutableArrayRef<llvm::BitcodeModule> BMs);
}
#endif
diff --git a/contrib/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h b/contrib/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h
index eaf5a3d5aad7..253ef946ce15 100644
--- a/contrib/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h
+++ b/contrib/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h
@@ -44,10 +44,23 @@ public:
/// but also emit a zero/sign extension attribute.
Extend,
- /// Indirect - Pass the argument indirectly via a hidden pointer
- /// with the specified alignment (0 indicates default alignment).
+ /// Indirect - Pass the argument indirectly via a hidden pointer with the
+ /// specified alignment (0 indicates default alignment) and address space.
Indirect,
+ /// IndirectAliased - Similar to Indirect, but the pointer may be to an
+ /// object that is otherwise referenced. The object is known to not be
+ /// modified through any other references for the duration of the call, and
+ /// the callee must not itself modify the object. Because C allows
+ /// parameter variables to be modified and guarantees that they have unique
+ /// addresses, the callee must defensively copy the object into a local
+ /// variable if it might be modified or its address might be compared.
+ /// Since those are uncommon, in principle this convention allows programs
+ /// to avoid copies in more situations. However, it may introduce *extra*
+ /// copies if the callee fails to prove that a copy is unnecessary and the
+ /// caller naturally produces an unaliased object for the argument.
+ IndirectAliased,
+
/// Ignore - Ignore the argument (treat as void). Useful for void and
/// empty structs.
Ignore,
@@ -86,6 +99,7 @@ private:
unsigned AllocaFieldIndex; // isInAlloca()
};
Kind TheKind;
+ unsigned IndirectAddrSpace : 24; // isIndirect()
bool PaddingInReg : 1;
bool InAllocaSRet : 1; // isInAlloca()
bool InAllocaIndirect : 1;// isInAlloca()
@@ -97,7 +111,8 @@ private:
bool SignExt : 1; // isExtend()
bool canHavePaddingType() const {
- return isDirect() || isExtend() || isIndirect() || isExpand();
+ return isDirect() || isExtend() || isIndirect() || isIndirectAliased() ||
+ isExpand();
}
void setPaddingType(llvm::Type *T) {
assert(canHavePaddingType());
@@ -112,9 +127,10 @@ private:
public:
ABIArgInfo(Kind K = Direct)
: TypeData(nullptr), PaddingType(nullptr), DirectOffset(0), TheKind(K),
- PaddingInReg(false), InAllocaSRet(false), InAllocaIndirect(false),
- IndirectByVal(false), IndirectRealign(false), SRetAfterThis(false),
- InReg(false), CanBeFlattened(false), SignExt(false) {}
+ IndirectAddrSpace(0), PaddingInReg(false), InAllocaSRet(false),
+ InAllocaIndirect(false), IndirectByVal(false), IndirectRealign(false),
+ SRetAfterThis(false), InReg(false), CanBeFlattened(false),
+ SignExt(false) {}
static ABIArgInfo getDirect(llvm::Type *T = nullptr, unsigned Offset = 0,
llvm::Type *Padding = nullptr,
@@ -180,6 +196,19 @@ public:
AI.setPaddingType(Padding);
return AI;
}
+
+ /// Pass this in memory using the IR byref attribute.
+ static ABIArgInfo getIndirectAliased(CharUnits Alignment, unsigned AddrSpace,
+ bool Realign = false,
+ llvm::Type *Padding = nullptr) {
+ auto AI = ABIArgInfo(IndirectAliased);
+ AI.setIndirectAlign(Alignment);
+ AI.setIndirectRealign(Realign);
+ AI.setPaddingType(Padding);
+ AI.setIndirectAddrSpace(AddrSpace);
+ return AI;
+ }
+
static ABIArgInfo getIndirectInReg(CharUnits Alignment, bool ByVal = true,
bool Realign = false) {
auto AI = getIndirect(Alignment, ByVal, Realign);
@@ -259,6 +288,7 @@ public:
bool isExtend() const { return TheKind == Extend; }
bool isIgnore() const { return TheKind == Ignore; }
bool isIndirect() const { return TheKind == Indirect; }
+ bool isIndirectAliased() const { return TheKind == IndirectAliased; }
bool isExpand() const { return TheKind == Expand; }
bool isCoerceAndExpand() const { return TheKind == CoerceAndExpand; }
@@ -338,11 +368,11 @@ public:
// Indirect accessors
CharUnits getIndirectAlign() const {
- assert(isIndirect() && "Invalid kind!");
+ assert((isIndirect() || isIndirectAliased()) && "Invalid kind!");
return CharUnits::fromQuantity(IndirectAlign);
}
void setIndirectAlign(CharUnits IA) {
- assert(isIndirect() && "Invalid kind!");
+ assert((isIndirect() || isIndirectAliased()) && "Invalid kind!");
IndirectAlign = IA.getQuantity();
}
@@ -355,12 +385,22 @@ public:
IndirectByVal = IBV;
}
+ unsigned getIndirectAddrSpace() const {
+ assert(isIndirectAliased() && "Invalid kind!");
+ return IndirectAddrSpace;
+ }
+
+ void setIndirectAddrSpace(unsigned AddrSpace) {
+ assert(isIndirectAliased() && "Invalid kind!");
+ IndirectAddrSpace = AddrSpace;
+ }
+
bool getIndirectRealign() const {
- assert(isIndirect() && "Invalid kind!");
+ assert((isIndirect() || isIndirectAliased()) && "Invalid kind!");
return IndirectRealign;
}
void setIndirectRealign(bool IR) {
- assert(isIndirect() && "Invalid kind!");
+ assert((isIndirect() || isIndirectAliased()) && "Invalid kind!");
IndirectRealign = IR;
}
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Compilation.h b/contrib/llvm-project/clang/include/clang/Driver/Compilation.h
index 33ae133e0562..89a43b5b7dc0 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Compilation.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/Compilation.h
@@ -115,6 +115,11 @@ class Compilation {
/// Optional redirection for stdin, stdout, stderr.
std::vector<Optional<StringRef>> Redirects;
+ /// Callback called after compilation job has been finished.
+ /// Arguments of the callback are the compilation job as an instance of
+ /// class Command and the exit status of the corresponding child process.
+ std::function<void(const Command &, int)> PostCallback;
+
/// Whether we're compiling for diagnostic purposes.
bool ForDiagnostics = false;
@@ -212,6 +217,14 @@ public:
return FailureResultFiles;
}
+ /// Installs a handler that is executed when a compilation job is finished.
+ /// The arguments of the callback specify the compilation job as an instance
+ /// of class Command and the exit status of the child process executed that
+ /// job.
+ void setPostCallback(const std::function<void(const Command &, int)> &CB) {
+ PostCallback = CB;
+ }
+
/// Returns the sysroot path.
StringRef getSysRoot() const;
@@ -297,6 +310,10 @@ public:
/// Return whether an error during the parsing of the input args.
bool containsError() const { return ContainsError; }
+ /// Force driver to fail before toolchain is created. This is necessary when
+ /// error happens in action builder.
+ void setContainsError() { ContainsError = true; }
+
/// Redirect - Redirect output of this compilation. Can only be done once.
///
/// \param Redirects - array of optional paths. The array should have a size
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Distro.h b/contrib/llvm-project/clang/include/clang/Driver/Distro.h
index 038d4ce75d80..0e98d00764c1 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Distro.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/Distro.h
@@ -23,6 +23,8 @@ namespace driver {
class Distro {
public:
enum DistroType {
+ // Special value means that no detection was performed yet.
+ UninitializedDistro,
// NB: Releases of a particular Linux distro should be kept together
// in this enum, because some tests are done by integer comparison against
// the first and last known member in the family, e.g. IsRedHat().
@@ -68,6 +70,7 @@ public:
UbuntuEoan,
UbuntuFocal,
UbuntuGroovy,
+ UbuntuHirsute,
UnknownDistro
};
@@ -112,25 +115,19 @@ public:
return DistroVal == Fedora || (DistroVal >= RHEL5 && DistroVal <= RHEL7);
}
- bool IsOpenSUSE() const {
- return DistroVal == OpenSUSE;
- }
+ bool IsOpenSUSE() const { return DistroVal == OpenSUSE; }
bool IsDebian() const {
return DistroVal >= DebianLenny && DistroVal <= DebianBullseye;
}
bool IsUbuntu() const {
- return DistroVal >= UbuntuHardy && DistroVal <= UbuntuGroovy;
+ return DistroVal >= UbuntuHardy && DistroVal <= UbuntuHirsute;
}
- bool IsAlpineLinux() const {
- return DistroVal == AlpineLinux;
- }
+ bool IsAlpineLinux() const { return DistroVal == AlpineLinux; }
- bool IsGentoo() const {
- return DistroVal == Gentoo;
- }
+ bool IsGentoo() const { return DistroVal == Gentoo; }
/// @}
};
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Driver.h b/contrib/llvm-project/clang/include/clang/Driver/Driver.h
index dc18f1314f81..74a9cf3dab81 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Driver.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/Driver.h
@@ -301,7 +301,7 @@ public:
StringRef CustomResourceDir = "");
Driver(StringRef ClangExecutable, StringRef TargetTriple,
- DiagnosticsEngine &Diags,
+ DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
/// @name Accessors
@@ -314,7 +314,7 @@ public:
const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
- const DiagnosticsEngine &getDiags() const { return Diags; }
+ DiagnosticsEngine &getDiags() const { return Diags; }
llvm::vfs::FileSystem &getVFS() const { return *VFS; }
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Job.h b/contrib/llvm-project/clang/include/clang/Driver/Job.h
index 6173b9d314b4..199387cddd5c 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Job.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/Job.h
@@ -122,6 +122,9 @@ class Command {
/// The list of program arguments which are inputs.
llvm::opt::ArgStringList InputFilenames;
+ /// The list of program arguments which are outputs. May be empty.
+ std::vector<std::string> OutputFilenames;
+
/// Response file name, if this command is set to use one, or nullptr
/// otherwise
const char *ResponseFile = nullptr;
@@ -137,6 +140,9 @@ class Command {
/// See Command::setEnvironment
std::vector<const char *> Environment;
+ /// Information on executable run provided by OS.
+ mutable Optional<llvm::sys::ProcessStatistics> ProcStat;
+
/// When a response file is needed, we try to put most arguments in an
/// exclusive file, while others remains as regular command line arguments.
/// This functions fills a vector with the regular command line arguments,
@@ -158,8 +164,8 @@ public:
Command(const Action &Source, const Tool &Creator,
ResponseFileSupport ResponseSupport, const char *Executable,
- const llvm::opt::ArgStringList &Arguments,
- ArrayRef<InputInfo> Inputs);
+ const llvm::opt::ArgStringList &Arguments, ArrayRef<InputInfo> Inputs,
+ ArrayRef<InputInfo> Outputs = None);
// FIXME: This really shouldn't be copyable, but is currently copied in some
// error handling in Driver::generateCompilationDiagnostics.
Command(const Command &) = default;
@@ -201,6 +207,18 @@ public:
const llvm::opt::ArgStringList &getArguments() const { return Arguments; }
+ const llvm::opt::ArgStringList &getInputFilenames() const {
+ return InputFilenames;
+ }
+
+ const std::vector<std::string> &getOutputFilenames() const {
+ return OutputFilenames;
+ }
+
+ Optional<llvm::sys::ProcessStatistics> getProcessStatistics() const {
+ return ProcStat;
+ }
+
protected:
/// Optionally print the filenames to be compiled
void PrintFileNames() const;
@@ -212,7 +230,7 @@ public:
CC1Command(const Action &Source, const Tool &Creator,
ResponseFileSupport ResponseSupport, const char *Executable,
const llvm::opt::ArgStringList &Arguments,
- ArrayRef<InputInfo> Inputs);
+ ArrayRef<InputInfo> Inputs, ArrayRef<InputInfo> Outputs = None);
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const override;
@@ -230,7 +248,7 @@ public:
FallbackCommand(const Action &Source_, const Tool &Creator_,
ResponseFileSupport ResponseSupport, const char *Executable_,
const llvm::opt::ArgStringList &Arguments_,
- ArrayRef<InputInfo> Inputs,
+ ArrayRef<InputInfo> Inputs, ArrayRef<InputInfo> Outputs,
std::unique_ptr<Command> Fallback_);
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
@@ -250,7 +268,8 @@ public:
ResponseFileSupport ResponseSupport,
const char *Executable_,
const llvm::opt::ArgStringList &Arguments_,
- ArrayRef<InputInfo> Inputs);
+ ArrayRef<InputInfo> Inputs,
+ ArrayRef<InputInfo> Outputs = None);
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const override;
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Options.h b/contrib/llvm-project/clang/include/clang/Driver/Options.h
index 7c5cddd9e896..b641f64c3116 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Options.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/Options.h
@@ -24,7 +24,7 @@ namespace options {
/// Flags specifically for clang options. Must not overlap with
/// llvm::opt::DriverFlag.
enum ClangFlags {
- DriverOption = (1 << 4),
+ NoXarchOption = (1 << 4),
LinkerInput = (1 << 5),
NoArgumentUnused = (1 << 6),
Unsupported = (1 << 7),
@@ -33,7 +33,11 @@ enum ClangFlags {
CC1Option = (1 << 10),
CC1AsOption = (1 << 11),
NoDriverOption = (1 << 12),
- Ignored = (1 << 13)
+ LinkOption = (1 << 13),
+ FlangOption = (1 << 14),
+ FC1Option = (1 << 15),
+ FlangOnlyOption = (1 << 16),
+ Ignored = (1 << 17),
};
enum ID {
diff --git a/contrib/llvm-project/clang/include/clang/Driver/Options.td b/contrib/llvm-project/clang/include/clang/Driver/Options.td
index 966cb907b7e2..817798926650 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/Options.td
+++ b/contrib/llvm-project/clang/include/clang/Driver/Options.td
@@ -16,9 +16,9 @@ include "llvm/Option/OptParser.td"
/////////
// Flags
-// DriverOption - The option is a "driver" option, and should not be forwarded
-// to other tools.
-def DriverOption : OptionFlag;
+// The option is a "driver"-only option, and should not be forwarded to other
+// tools via `-Xarch` options.
+def NoXarchOption : OptionFlag;
// LinkerInput - The option is a linker input.
def LinkerInput : OptionFlag;
@@ -52,6 +52,21 @@ def CC1AsOption : OptionFlag;
// NoDriverOption - This option should not be accepted by the driver.
def NoDriverOption : OptionFlag;
+// If an option affects linking, but has a primary group (so Link_Group cannot
+// be used), add this flag.
+def LinkOption : OptionFlag;
+
+// FlangOption - This is considered a "core" Flang option, available in
+// flang mode.
+def FlangOption : OptionFlag;
+
+// FlangOnlyOption - This option should only be used by Flang (i.e. it is not
+// available for Clang)
+def FlangOnlyOption : OptionFlag;
+
+// FC1Option - This option should be accepted by flang -fc1.
+def FC1Option : OptionFlag;
+
// A short name to show in documentation. The name will be interpreted as rST.
class DocName<string name> { string DocName = name; }
@@ -226,13 +241,42 @@ def mno_mpx : Flag<["-"], "mno-mpx">, Group<clang_ignored_legacy_options_Group>;
def clang_ignored_gcc_optimization_f_Group : OptionGroup<
"<clang_ignored_gcc_optimization_f_Group>">, Group<f_Group>, Flags<[Ignored]>;
+class DiagnosticOpts<string base>
+ : KeyPathAndMacro<"DiagnosticOpts->", base, "DIAG_"> {}
+class LangOpts<string base>
+ : KeyPathAndMacro<"LangOpts->", base, "LANG_"> {}
+class TargetOpts<string base>
+ : KeyPathAndMacro<"TargetOpts->", base> {}
+class FrontendOpts<string base>
+ : KeyPathAndMacro<"FrontendOpts.", base> {}
+class PreprocessorOutputOpts<string base>
+ : KeyPathAndMacro<"PreprocessorOutputOpts.", base> {}
+class DependencyOutputOpts<string base>
+ : KeyPathAndMacro<"DependencyOutputOpts.", base> {}
+class CodeGenOpts<string base>
+ : KeyPathAndMacro<"CodeGenOpts.", base, "CODEGEN_"> {}
+class HeaderSearchOpts<string base>
+ : KeyPathAndMacro<"HeaderSearchOpts->", base> {}
+class PreprocessorOpts<string base>
+ : KeyPathAndMacro<"PreprocessorOpts->", base> {}
+class FileSystemOpts<string base>
+ : KeyPathAndMacro<"FileSystemOpts.", base> {}
+class AnalyzerOpts<string base>
+ : KeyPathAndMacro<"AnalyzerOpts->", base> {}
+class MigratorOpts<string base>
+ : KeyPathAndMacro<"MigratorOpts.", base> {}
+
// A boolean option which is opt-in in CC1. The positive option exists in CC1 and
// Args.hasArg(OPT_ffoo) is used to check that the flag is enabled.
// This is useful if the option is usually disabled.
multiclass OptInFFlag<string name, string pos_prefix, string neg_prefix="",
- string help="", list<OptionFlag> flags=[]> {
+ string help="", list<OptionFlag> flags=[],
+ KeyPathAndMacro kpm = EmptyKPM,
+ list<string> enablers = []> {
def f#NAME : Flag<["-"], "f"#name>, Flags<!listconcat([CC1Option], flags)>,
- Group<f_Group>, HelpText<!strconcat(pos_prefix, help)>;
+ Group<f_Group>, HelpText<!strconcat(pos_prefix, help)>,
+ MarshallingInfoFlag<kpm, "false">,
+ ImpliedByAnyOf<enablers, "true">;
def fno_#NAME : Flag<["-"], "fno-"#name>, Flags<flags>,
Group<f_Group>, HelpText<!strconcat(neg_prefix, help)>;
}
@@ -240,13 +284,166 @@ multiclass OptInFFlag<string name, string pos_prefix, string neg_prefix="",
// A boolean option which is opt-out in CC1. The negative option exists in CC1 and
// Args.hasArg(OPT_fno_foo) is used to check that the flag is disabled.
multiclass OptOutFFlag<string name, string pos_prefix, string neg_prefix,
- string help="", list<OptionFlag> flags=[]> {
+ string help="", list<OptionFlag> flags=[],
+ KeyPathAndMacro kpm = EmptyKPM,
+ list<string> disablers = []> {
def f#NAME : Flag<["-"], "f"#name>, Flags<flags>,
Group<f_Group>, HelpText<!strconcat(pos_prefix, help)>;
def fno_#NAME : Flag<["-"], "fno-"#name>, Flags<!listconcat([CC1Option], flags)>,
- Group<f_Group>, HelpText<!strconcat(neg_prefix, help)>;
+ Group<f_Group>, HelpText<!strconcat(neg_prefix, help)>,
+ MarshallingInfoFlag<kpm, "false">,
+ ImpliedByAnyOf<disablers, "true">;
+}
+
+//===----------------------------------------------------------------------===//
+// BoolOption
+//===----------------------------------------------------------------------===//
+
+// The default value of a marshalled key path.
+class Default<code value> { code Value = value; }
+
+// Convenience variables for boolean defaults.
+def DefaultTrue : Default<"true"> {}
+def DefaultFalse : Default<"false"> {}
+
+// The value set to the key path when the flag is present on the command line.
+class Set<bit value> { bit Value = value; }
+def SetTrue : Set<true> {}
+def SetFalse : Set<false> {}
+
+// Definition of single command line flag. This is an implementation detail, use
+// SetTrueBy or SetFalseBy instead.
+class FlagDef<bit polarity, bit value, list<OptionFlag> option_flags,
+ string help, list<code> implied_by_expressions = []> {
+ // The polarity. Besides spelling, this also decides whether the TableGen
+ // record will be prefixed with "no_".
+ bit Polarity = polarity;
+
+ // The value assigned to key path when the flag is present on command line.
+ bit Value = value;
+
+ // OptionFlags that control visibility of the flag in different tools.
+ list<OptionFlag> OptionFlags = option_flags;
+
+ // The help text associated with the flag.
+ string Help = help;
+
+ // List of expressions that, when true, imply this flag.
+ list<code> ImpliedBy = implied_by_expressions;
+}
+
+// Additional information to be appended to both positive and negative flag.
+class BothFlags<list<OptionFlag> option_flags, string help = ""> {
+ list<OptionFlag> OptionFlags = option_flags;
+ string Help = help;
+}
+
+// Functor that appends the suffix to the base flag definition.
+class ApplySuffix<FlagDef flag, BothFlags suffix> {
+ FlagDef Result
+ = FlagDef<flag.Polarity, flag.Value,
+ !listconcat(flag.OptionFlags, suffix.OptionFlags),
+ !strconcat(flag.Help, suffix.Help), flag.ImpliedBy>;
+}
+
+// Definition of the command line flag with positive spelling, e.g. "-ffoo".
+class PosFlag<Set value, list<OptionFlag> flags = [], string help = "",
+ list<code> implied_by_expressions = []>
+ : FlagDef<true, value.Value, flags, help, implied_by_expressions> {}
+
+// Definition of the command line flag with negative spelling, e.g. "-fno-foo".
+class NegFlag<Set value, list<OptionFlag> flags = [], string help = "",
+ list<code> implied_by_expressions = []>
+ : FlagDef<false, value.Value, flags, help, implied_by_expressions> {}
+
+// Expanded FlagDef that's convenient for creation of TableGen records.
+class FlagDefExpanded<FlagDef flag, string prefix, string name, string spelling>
+ : FlagDef<flag.Polarity, flag.Value, flag.OptionFlags, flag.Help,
+ flag.ImpliedBy> {
+ // Name of the TableGen record.
+ string RecordName = prefix#!cond(flag.Polarity : "", true : "no_")#name;
+
+ // Spelling of the flag.
+ string Spelling = prefix#!cond(flag.Polarity : "", true : "no-")#spelling;
+
+ // Can the flag be implied by another flag?
+ bit CanBeImplied = !not(!empty(flag.ImpliedBy));
+
+ // C++ code that will be assigned to the keypath when the flag is present.
+ code ValueAsCode = !cond(flag.Value : "true", true: "false");
+}
+
+// TableGen record for a single marshalled flag.
+class MarshalledFlagRec<FlagDefExpanded flag, FlagDefExpanded other,
+ FlagDefExpanded implied, KeyPathAndMacro kpm,
+ Default default>
+ : Flag<["-"], flag.Spelling>, Flags<flag.OptionFlags>, HelpText<flag.Help>,
+ MarshallingInfoBooleanFlag<kpm, default.Value, flag.ValueAsCode,
+ flag.RecordName, other.ValueAsCode,
+ other.RecordName>,
+ ImpliedByAnyOf<implied.ImpliedBy, implied.ValueAsCode> {}
+
+// Generates TableGen records for two command line flags that control the same
+// key path via the marshalling infrastructure.
+// Names of the records consist of the specified prefix, "no_" for the negative
+// flag, and NAME.
+multiclass BoolOption<string prefix = "", string spelling_base,
+ KeyPathAndMacro kpm, Default default,
+ FlagDef flag1_base, FlagDef flag2_base,
+ BothFlags suffix = BothFlags<[], "">> {
+ defvar flag1 = FlagDefExpanded<ApplySuffix<flag1_base, suffix>.Result, prefix,
+ NAME, spelling_base>;
+
+ defvar flag2 = FlagDefExpanded<ApplySuffix<flag2_base, suffix>.Result, prefix,
+ NAME, spelling_base>;
+
+ // TODO: Assert that the flags have different polarity.
+ // TODO: Assert that the flags have different value.
+ // TODO: Assert that only one of the flags can be implied.
+
+ defvar implied = !cond(flag1.CanBeImplied: flag1, true: flag2);
+
+ def flag1.RecordName : MarshalledFlagRec<flag1, flag2, implied, kpm, default>;
+ def flag2.RecordName : MarshalledFlagRec<flag2, flag1, implied, kpm, default>;
+}
+
+/// Creates a BoolOption where both of the flags are prefixed with "f", are in
+/// the Group<f_Group>.
+multiclass BoolFOption<string flag_base, KeyPathAndMacro kpm,
+ Default default, FlagDef flag1, FlagDef flag2,
+ BothFlags both = BothFlags<[], "">> {
+ defm NAME : BoolOption<"f", flag_base, kpm, default, flag1, flag2, both>,
+ Group<f_Group>;
+}
+
+// Creates a BoolOption where both of the flags are prefixed with "g" and have
+// the Group<g_Group>.
+multiclass BoolGOption<string flag_base, KeyPathAndMacro kpm,
+ Default default, FlagDef flag1, FlagDef flag2,
+ BothFlags both = BothFlags<[], "">> {
+ defm NAME : BoolOption<"g", flag_base, kpm, default, flag1, flag2, both>,
+ Group<g_Group>;
}
+// FIXME: Diagnose if target does not support protected visibility.
+class MarshallingInfoVisibility<KeyPathAndMacro kpm, code default>
+ : MarshallingInfoString<kpm, default>,
+ Values<"default,hidden,internal,protected">,
+ NormalizedValues<["DefaultVisibility", "HiddenVisibility",
+ "HiddenVisibility", "ProtectedVisibility"]>,
+ AutoNormalizeEnum {}
+
+// Key paths that are constant during parsing of options with the same key path prefix.
+defvar cplusplus = LangOpts<"CPlusPlus">;
+defvar c99 = LangOpts<"C99">;
+defvar lang_std = LangOpts<"LangStd">;
+defvar open_cl = LangOpts<"OpenCL">;
+defvar render_script = LangOpts<"RenderScript">;
+defvar hip = LangOpts<"HIP">;
+defvar gnu_mode = LangOpts<"GNUMode">;
+
+defvar std = !strconcat("LangStandard::getLangStandardForKind(", lang_std.KeyPath, ")");
+
/////////
// Options
@@ -279,19 +476,19 @@ def internal_debug_Group :
Group<internal_Group>, HelpText<"DEBUG/DEVELOPMENT OPTIONS">;
class InternalDriverOpt : Group<internal_driver_Group>,
- Flags<[DriverOption, HelpHidden]>;
+ Flags<[NoXarchOption, HelpHidden]>;
def driver_mode : Joined<["--"], "driver-mode=">, Group<internal_driver_Group>,
- Flags<[CoreOption, DriverOption, HelpHidden]>,
+ Flags<[CoreOption, NoXarchOption, HelpHidden]>,
HelpText<"Set the driver mode to either 'gcc', 'g++', 'cpp', or 'cl'">;
def rsp_quoting : Joined<["--"], "rsp-quoting=">, Group<internal_driver_Group>,
- Flags<[CoreOption, DriverOption, HelpHidden]>,
+ Flags<[CoreOption, NoXarchOption, HelpHidden]>,
HelpText<"Set the rsp quoting to either 'posix', or 'windows'">;
def ccc_gcc_name : Separate<["-"], "ccc-gcc-name">, InternalDriverOpt,
HelpText<"Name for native GCC compiler">,
MetaVarName<"<gcc-path>">;
class InternalDebugOpt : Group<internal_debug_Group>,
- Flags<[DriverOption, HelpHidden, CoreOption]>;
+ Flags<[NoXarchOption, HelpHidden, CoreOption]>;
def ccc_install_dir : Separate<["-"], "ccc-install-dir">, InternalDebugOpt,
HelpText<"Simulate installation in the given directory">;
def ccc_print_phases : Flag<["-"], "ccc-print-phases">, InternalDebugOpt,
@@ -306,53 +503,72 @@ def ccc_arcmt_modify : Flag<["-"], "ccc-arcmt-modify">, InternalDriverOpt,
def ccc_arcmt_migrate : Separate<["-"], "ccc-arcmt-migrate">, InternalDriverOpt,
HelpText<"Apply modifications and produces temporary files that conform to ARC">;
def arcmt_migrate_report_output : Separate<["-"], "arcmt-migrate-report-output">,
- HelpText<"Output path for the plist report">, Flags<[CC1Option]>;
+ HelpText<"Output path for the plist report">, Flags<[CC1Option]>,
+ MarshallingInfoString<FrontendOpts<"ARCMTMigrateReportOut">>;
def arcmt_migrate_emit_arc_errors : Flag<["-"], "arcmt-migrate-emit-errors">,
- HelpText<"Emit ARC errors even if the migrator can fix them">,
- Flags<[CC1Option]>;
+ HelpText<"Emit ARC errors even if the migrator can fix them">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<FrontendOpts<"ARCMTMigrateEmitARCErrors">>;
def gen_reproducer: Flag<["-"], "gen-reproducer">, InternalDebugOpt,
HelpText<"Auto-generates preprocessed source files and a reproduction script">;
def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, InternalDebugOpt,
HelpText<"Emit a compilation database fragment to the specified directory">;
-def _migrate : Flag<["--"], "migrate">, Flags<[DriverOption]>,
+def _migrate : Flag<["--"], "migrate">, Flags<[NoXarchOption]>,
HelpText<"Run the migrator">;
def ccc_objcmt_migrate : Separate<["-"], "ccc-objcmt-migrate">,
InternalDriverOpt,
HelpText<"Apply modifications and produces temporary files to migrate to "
"modern ObjC syntax">;
+
def objcmt_migrate_literals : Flag<["-"], "objcmt-migrate-literals">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC literals">;
+ HelpText<"Enable migration to modern ObjC literals">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_Literals">;
def objcmt_migrate_subscripting : Flag<["-"], "objcmt-migrate-subscripting">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC subscripting">;
+ HelpText<"Enable migration to modern ObjC subscripting">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_Subscripting">;
def objcmt_migrate_property : Flag<["-"], "objcmt-migrate-property">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC property">;
+ HelpText<"Enable migration to modern ObjC property">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_Property">;
def objcmt_migrate_all : Flag<["-"], "objcmt-migrate-all">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC">;
+ HelpText<"Enable migration to modern ObjC">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_MigrateDecls">;
def objcmt_migrate_readonly_property : Flag<["-"], "objcmt-migrate-readonly-property">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC readonly property">;
+ HelpText<"Enable migration to modern ObjC readonly property">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_ReadonlyProperty">;
def objcmt_migrate_readwrite_property : Flag<["-"], "objcmt-migrate-readwrite-property">, Flags<[CC1Option]>,
- HelpText<"Enable migration to modern ObjC readwrite property">;
+ HelpText<"Enable migration to modern ObjC readwrite property">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_ReadwriteProperty">;
def objcmt_migrate_property_dot_syntax : Flag<["-"], "objcmt-migrate-property-dot-syntax">, Flags<[CC1Option]>,
- HelpText<"Enable migration of setter/getter messages to property-dot syntax">;
+ HelpText<"Enable migration of setter/getter messages to property-dot syntax">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_PropertyDotSyntax">;
def objcmt_migrate_annotation : Flag<["-"], "objcmt-migrate-annotation">, Flags<[CC1Option]>,
- HelpText<"Enable migration to property and method annotations">;
+ HelpText<"Enable migration to property and method annotations">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_Annotation">;
def objcmt_migrate_instancetype : Flag<["-"], "objcmt-migrate-instancetype">, Flags<[CC1Option]>,
- HelpText<"Enable migration to infer instancetype for method result type">;
+ HelpText<"Enable migration to infer instancetype for method result type">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_Instancetype">;
def objcmt_migrate_nsmacros : Flag<["-"], "objcmt-migrate-ns-macros">, Flags<[CC1Option]>,
- HelpText<"Enable migration to NS_ENUM/NS_OPTIONS macros">;
+ HelpText<"Enable migration to NS_ENUM/NS_OPTIONS macros">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_NsMacros">;
def objcmt_migrate_protocol_conformance : Flag<["-"], "objcmt-migrate-protocol-conformance">, Flags<[CC1Option]>,
- HelpText<"Enable migration to add protocol conformance on classes">;
+ HelpText<"Enable migration to add protocol conformance on classes">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_ProtocolConformance">;
def objcmt_atomic_property : Flag<["-"], "objcmt-atomic-property">, Flags<[CC1Option]>,
- HelpText<"Make migration to 'atomic' properties">;
+ HelpText<"Make migration to 'atomic' properties">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_AtomicProperty">;
def objcmt_returns_innerpointer_property : Flag<["-"], "objcmt-returns-innerpointer-property">, Flags<[CC1Option]>,
- HelpText<"Enable migration to annotate property with NS_RETURNS_INNER_POINTER">;
+ HelpText<"Enable migration to annotate property with NS_RETURNS_INNER_POINTER">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_ReturnsInnerPointerProperty">;
def objcmt_ns_nonatomic_iosonly: Flag<["-"], "objcmt-ns-nonatomic-iosonly">, Flags<[CC1Option]>,
- HelpText<"Enable migration to use NS_NONATOMIC_IOSONLY macro for setting property's 'atomic' attribute">;
+ HelpText<"Enable migration to use NS_NONATOMIC_IOSONLY macro for setting property's 'atomic' attribute">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty">;
def objcmt_migrate_designated_init : Flag<["-"], "objcmt-migrate-designated-init">, Flags<[CC1Option]>,
- HelpText<"Enable migration to infer NS_DESIGNATED_INITIALIZER for initializer methods">;
+ HelpText<"Enable migration to infer NS_DESIGNATED_INITIALIZER for initializer methods">,
+ MarshallingInfoBitfieldFlag<FrontendOpts<"ObjCMTAction">, "FrontendOptions::ObjCMT_DesignatedInitializer">;
+
def objcmt_whitelist_dir_path: Joined<["-"], "objcmt-whitelist-dir-path=">, Flags<[CC1Option]>,
- HelpText<"Only modify files with a filename contained in the provided directory path">;
+ HelpText<"Only modify files with a filename contained in the provided directory path">,
+ MarshallingInfoString<FrontendOpts<"ObjCMTWhiteListPath">>;
// The misspelt "white-list" [sic] alias is due for removal.
def : Joined<["-"], "objcmt-white-list-dir-path=">, Flags<[CC1Option]>,
Alias<objcmt_whitelist_dir_path>;
@@ -362,36 +578,45 @@ def ccc_ : Joined<["-"], "ccc-">, Group<internal_Group>, Flags<[Unsupported]>;
// Standard Options
-def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[DriverOption, CoreOption]>,
+def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[NoXarchOption, CoreOption, FlangOption]>,
HelpText<"Print (but do not run) the commands to run for this compilation">;
def _DASH_DASH : Option<["--"], "", KIND_REMAINING_ARGS>,
- Flags<[DriverOption, CoreOption]>;
+ Flags<[NoXarchOption, CoreOption]>;
def A : JoinedOrSeparate<["-"], "A">, Flags<[RenderJoined]>, Group<gfortran_Group>;
def B : JoinedOrSeparate<["-"], "B">, MetaVarName<"<dir>">,
HelpText<"Add <dir> to search path for binaries and object files used implicitly">;
def CC : Flag<["-"], "CC">, Flags<[CC1Option]>, Group<Preprocessor_Group>,
- HelpText<"Include comments from within macros in preprocessed output">;
+ HelpText<"Include comments from within macros in preprocessed output">,
+ MarshallingInfoFlag<PreprocessorOutputOpts<"ShowMacroComments">>;
def C : Flag<["-"], "C">, Flags<[CC1Option]>, Group<Preprocessor_Group>,
- HelpText<"Include comments in preprocessed output">;
+ HelpText<"Include comments in preprocessed output">,
+ MarshallingInfoFlag<PreprocessorOutputOpts<"ShowComments">>;
def D : JoinedOrSeparate<["-"], "D">, Group<Preprocessor_Group>,
- Flags<[CC1Option]>, MetaVarName<"<macro>=<value>">,
+ Flags<[CC1Option, FlangOption, FC1Option]>, MetaVarName<"<macro>=<value>">,
HelpText<"Define <macro> to <value> (or 1 if <value> omitted)">;
-def E : Flag<["-"], "E">, Flags<[DriverOption,CC1Option]>, Group<Action_Group>,
+def E : Flag<["-"], "E">, Flags<[NoXarchOption,CC1Option, FlangOption, FC1Option]>, Group<Action_Group>,
HelpText<"Only run the preprocessor">;
def F : JoinedOrSeparate<["-"], "F">, Flags<[RenderJoined,CC1Option]>,
HelpText<"Add directory to framework include search path">;
-def G : JoinedOrSeparate<["-"], "G">, Flags<[DriverOption]>, Group<m_Group>,
+def G : JoinedOrSeparate<["-"], "G">, Flags<[NoXarchOption]>, Group<m_Group>,
MetaVarName<"<size>">, HelpText<"Put objects of at most <size> bytes "
"into small data section (MIPS / Hexagon)">;
-def G_EQ : Joined<["-"], "G=">, Flags<[DriverOption]>, Group<m_Group>, Alias<G>;
+def G_EQ : Joined<["-"], "G=">, Flags<[NoXarchOption]>, Group<m_Group>, Alias<G>;
def H : Flag<["-"], "H">, Flags<[CC1Option]>, Group<Preprocessor_Group>,
- HelpText<"Show header includes and nesting depth">;
+ HelpText<"Show header includes and nesting depth">,
+ MarshallingInfoFlag<DependencyOutputOpts<"ShowHeaderIncludes">>;
def I_ : Flag<["-"], "I-">, Group<I_Group>,
HelpText<"Restrict all prior -I flags to double-quoted inclusion and "
"remove current directory from include path">;
def I : JoinedOrSeparate<["-"], "I">, Group<I_Group>,
- Flags<[CC1Option,CC1AsOption]>, MetaVarName<"<dir>">,
- HelpText<"Add directory to include search path">;
+ Flags<[CC1Option,CC1AsOption,FlangOption,FC1Option]>, MetaVarName<"<dir>">,
+ HelpText<"Add directory to the end of the list of include search paths">,
+ DocBrief<[{Add directory to include search path. For C++ inputs, if
+there are multiple -I options, these directories are searched
+in the order they are given before the standard system directories
+are searched. If the same directory is in the SYSTEM include search
+paths, for example if also specified with -isystem, the -I option
+will be ignored}]>;
def L : JoinedOrSeparate<["-"], "L">, Flags<[RenderJoined]>, Group<Link_Group>,
MetaVarName<"<dir>">, HelpText<"Add directory to library search path">;
def MD : Flag<["-"], "MD">, Group<M_Group>,
@@ -406,36 +631,42 @@ def MF : JoinedOrSeparate<["-"], "MF">, Group<M_Group>,
HelpText<"Write depfile output from -MMD, -MD, -MM, or -M to <file>">,
MetaVarName<"<file>">;
def MG : Flag<["-"], "MG">, Group<M_Group>, Flags<[CC1Option]>,
- HelpText<"Add missing headers to depfile">;
+ HelpText<"Add missing headers to depfile">,
+ MarshallingInfoFlag<DependencyOutputOpts<"AddMissingHeaderDeps">>;
def MJ : JoinedOrSeparate<["-"], "MJ">, Group<M_Group>,
HelpText<"Write a compilation database entry per input">;
def MP : Flag<["-"], "MP">, Group<M_Group>, Flags<[CC1Option]>,
- HelpText<"Create phony target for each dependency (other than main file)">;
+ HelpText<"Create phony target for each dependency (other than main file)">,
+ MarshallingInfoFlag<DependencyOutputOpts<"UsePhonyTargets">>;
def MQ : JoinedOrSeparate<["-"], "MQ">, Group<M_Group>, Flags<[CC1Option]>,
HelpText<"Specify name of main file output to quote in depfile">;
def MT : JoinedOrSeparate<["-"], "MT">, Group<M_Group>, Flags<[CC1Option]>,
- HelpText<"Specify name of main file output in depfile">;
+ HelpText<"Specify name of main file output in depfile">,
+ MarshallingInfoStringVector<DependencyOutputOpts<"Targets">>;
def MV : Flag<["-"], "MV">, Group<M_Group>, Flags<[CC1Option]>,
- HelpText<"Use NMake/Jom format for the depfile">;
+ HelpText<"Use NMake/Jom format for the depfile">,
+ MarshallingInfoFlag<DependencyOutputOpts<"OutputFormat">, "DependencyOutputFormat::Make">,
+ Normalizer<"makeFlagToValueNormalizer(DependencyOutputFormat::NMake)">;
def Mach : Flag<["-"], "Mach">, Group<Link_Group>;
def O0 : Flag<["-"], "O0">, Group<O_Group>, Flags<[CC1Option, HelpHidden]>;
def O4 : Flag<["-"], "O4">, Group<O_Group>, Flags<[CC1Option, HelpHidden]>;
-def ObjCXX : Flag<["-"], "ObjC++">, Flags<[DriverOption]>,
+def ObjCXX : Flag<["-"], "ObjC++">, Flags<[NoXarchOption]>,
HelpText<"Treat source input files as Objective-C++ inputs">;
-def ObjC : Flag<["-"], "ObjC">, Flags<[DriverOption]>,
+def ObjC : Flag<["-"], "ObjC">, Flags<[NoXarchOption]>,
HelpText<"Treat source input files as Objective-C inputs">;
def O : Joined<["-"], "O">, Group<O_Group>, Flags<[CC1Option]>;
def O_flag : Flag<["-"], "O">, Flags<[CC1Option]>, Alias<O>, AliasArgs<["1"]>;
def Ofast : Joined<["-"], "Ofast">, Group<O_Group>, Flags<[CC1Option]>;
def P : Flag<["-"], "P">, Flags<[CC1Option]>, Group<Preprocessor_Group>,
- HelpText<"Disable linemarker output in -E mode">;
+ HelpText<"Disable linemarker output in -E mode">,
+ MarshallingInfoNegativeFlag<PreprocessorOutputOpts<"ShowLineMarkers">>;
def Qy : Flag<["-"], "Qy">, Flags<[CC1Option]>,
HelpText<"Emit metadata containing compiler name and version">;
def Qn : Flag<["-"], "Qn">, Flags<[CC1Option]>,
HelpText<"Do not emit metadata containing compiler name and version">;
def : Flag<["-"], "fident">, Group<f_Group>, Alias<Qy>, Flags<[CC1Option]>;
def : Flag<["-"], "fno-ident">, Group<f_Group>, Alias<Qn>, Flags<[CC1Option]>;
-def Qunused_arguments : Flag<["-"], "Qunused-arguments">, Flags<[DriverOption, CoreOption]>,
+def Qunused_arguments : Flag<["-"], "Qunused-arguments">, Flags<[NoXarchOption, CoreOption]>,
HelpText<"Don't emit warning for unused driver arguments">;
def Q : Flag<["-"], "Q">, IgnoredGCCCompat;
def Rpass_EQ : Joined<["-"], "Rpass=">, Group<R_value_Group>, Flags<[CC1Option]>,
@@ -451,7 +682,7 @@ def Rpass_analysis_EQ : Joined<["-"], "Rpass-analysis=">, Group<R_value_Group>,
"name matches the given POSIX regular expression">;
def R_Joined : Joined<["-"], "R">, Group<R_Group>, Flags<[CC1Option, CoreOption]>,
MetaVarName<"<remark>">, HelpText<"Enable the specified remark">;
-def S : Flag<["-"], "S">, Flags<[DriverOption,CC1Option]>, Group<Action_Group>,
+def S : Flag<["-"], "S">, Flags<[NoXarchOption,CC1Option]>, Group<Action_Group>,
HelpText<"Only run preprocess and compilation steps">;
def Tbss : JoinedOrSeparate<["-"], "Tbss">, Group<T_Group>,
MetaVarName<"<addr>">, HelpText<"Set starting address of BSS to <addr>">;
@@ -462,8 +693,8 @@ def Ttext : JoinedOrSeparate<["-"], "Ttext">, Group<T_Group>,
def T : JoinedOrSeparate<["-"], "T">, Group<T_Group>,
MetaVarName<"<script>">, HelpText<"Specify <script> as linker script">;
def U : JoinedOrSeparate<["-"], "U">, Group<Preprocessor_Group>,
- Flags<[CC1Option]>, MetaVarName<"<macro>">, HelpText<"Undefine macro <macro>">;
-def V : JoinedOrSeparate<["-"], "V">, Flags<[DriverOption, Unsupported]>;
+ Flags<[CC1Option, FlangOption, FC1Option]>, MetaVarName<"<macro>">, HelpText<"Undefine macro <macro>">;
+def V : JoinedOrSeparate<["-"], "V">, Flags<[NoXarchOption, Unsupported]>;
def Wa_COMMA : CommaJoined<["-"], "Wa,">,
HelpText<"Pass the comma separated arguments in <arg> to the assembler">,
MetaVarName<"<arg>">;
@@ -485,7 +716,8 @@ def Wp_COMMA : CommaJoined<["-"], "Wp,">,
MetaVarName<"<arg>">, Group<Preprocessor_Group>;
def Wundef_prefix_EQ : CommaJoined<["-"], "Wundef-prefix=">, Group<W_value_Group>,
Flags<[CC1Option, CoreOption, HelpHidden]>, MetaVarName<"<arg>">,
- HelpText<"Enable warnings for undefined macros with a prefix in the comma separated list <arg>">;
+ HelpText<"Enable warnings for undefined macros with a prefix in the comma separated list <arg>">,
+ MarshallingInfoStringVector<DiagnosticOpts<"UndefPrefixes">>;
def Wwrite_strings : Flag<["-"], "Wwrite-strings">, Group<W_Group>, Flags<[CC1Option, HelpHidden]>;
def Wno_write_strings : Flag<["-"], "Wno-write-strings">, Group<W_Group>, Flags<[CC1Option, HelpHidden]>;
def W_Joined : Joined<["-"], "W">, Group<W_Group>, Flags<[CC1Option, CoreOption]>,
@@ -493,17 +725,17 @@ def W_Joined : Joined<["-"], "W">, Group<W_Group>, Flags<[CC1Option, CoreOption]
def Xanalyzer : Separate<["-"], "Xanalyzer">,
HelpText<"Pass <arg> to the static analyzer">, MetaVarName<"<arg>">,
Group<StaticAnalyzer_Group>;
-def Xarch__ : JoinedAndSeparate<["-"], "Xarch_">, Flags<[DriverOption]>;
-def Xarch_host : Separate<["-"], "Xarch_host">, Flags<[DriverOption]>,
+def Xarch__ : JoinedAndSeparate<["-"], "Xarch_">, Flags<[NoXarchOption]>;
+def Xarch_host : Separate<["-"], "Xarch_host">, Flags<[NoXarchOption]>,
HelpText<"Pass <arg> to the CUDA/HIP host compilation">, MetaVarName<"<arg>">;
-def Xarch_device : Separate<["-"], "Xarch_device">, Flags<[DriverOption]>,
+def Xarch_device : Separate<["-"], "Xarch_device">, Flags<[NoXarchOption]>,
HelpText<"Pass <arg> to the CUDA/HIP device compilation">, MetaVarName<"<arg>">;
def Xassembler : Separate<["-"], "Xassembler">,
HelpText<"Pass <arg> to the assembler">, MetaVarName<"<arg>">,
Group<CompileOnly_Group>;
def Xclang : Separate<["-"], "Xclang">,
HelpText<"Pass <arg> to the clang compiler">, MetaVarName<"<arg>">,
- Flags<[DriverOption, CoreOption]>, Group<CompileOnly_Group>;
+ Flags<[NoXarchOption, CoreOption]>, Group<CompileOnly_Group>;
def Xcuda_fatbinary : Separate<["-"], "Xcuda-fatbinary">,
HelpText<"Pass <arg> to fatbinary invocation">, MetaVarName<"<arg>">;
def Xcuda_ptxas : Separate<["-"], "Xcuda-ptxas">,
@@ -528,9 +760,9 @@ def Z_Flag : Flag<["-"], "Z">, Group<Link_Group>;
def Z_Joined : Joined<["-"], "Z">;
def all__load : Flag<["-"], "all_load">;
def allowable__client : Separate<["-"], "allowable_client">;
-def ansi : Flag<["-", "--"], "ansi">;
+def ansi : Flag<["-", "--"], "ansi">, Group<CompileOnly_Group>;
def arch__errors__fatal : Flag<["-"], "arch_errors_fatal">;
-def arch : Separate<["-"], "arch">, Flags<[DriverOption]>;
+def arch : Separate<["-"], "arch">, Flags<[NoXarchOption]>;
def arch__only : Separate<["-"], "arch_only">;
def a : Joined<["-"], "a">;
def autocomplete : Joined<["--"], "autocomplete=">;
@@ -543,43 +775,53 @@ def cl_opt_disable : Flag<["-"], "cl-opt-disable">, Group<opencl_Group>, Flags<[
def cl_strict_aliasing : Flag<["-"], "cl-strict-aliasing">, Group<opencl_Group>, Flags<[CC1Option]>,
HelpText<"OpenCL only. This option is added for compatibility with OpenCL 1.0.">;
def cl_single_precision_constant : Flag<["-"], "cl-single-precision-constant">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Treat double precision floating-point constant as single precision constant.">;
+ HelpText<"OpenCL only. Treat double precision floating-point constant as single precision constant.">,
+ MarshallingInfoFlag<LangOpts<"SinglePrecisionConstants">>;
def cl_finite_math_only : Flag<["-"], "cl-finite-math-only">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Allow floating-point optimizations that assume arguments and results are not NaNs or +-Inf.">;
+ HelpText<"OpenCL only. Allow floating-point optimizations that assume arguments and results are not NaNs or +-Inf.">,
+ MarshallingInfoFlag<LangOpts<"CLFiniteMathOnly">>;
def cl_kernel_arg_info : Flag<["-"], "cl-kernel-arg-info">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Generate kernel argument metadata.">;
+ HelpText<"OpenCL only. Generate kernel argument metadata.">,
+ MarshallingInfoFlag<CodeGenOpts<"EmitOpenCLArgMetadata">>;
def cl_unsafe_math_optimizations : Flag<["-"], "cl-unsafe-math-optimizations">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Allow unsafe floating-point optimizations. Also implies -cl-no-signed-zeros and -cl-mad-enable.">;
+ HelpText<"OpenCL only. Allow unsafe floating-point optimizations. Also implies -cl-no-signed-zeros and -cl-mad-enable.">,
+ MarshallingInfoFlag<LangOpts<"CLUnsafeMath">>;
def cl_fast_relaxed_math : Flag<["-"], "cl-fast-relaxed-math">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Sets -cl-finite-math-only and -cl-unsafe-math-optimizations, and defines __FAST_RELAXED_MATH__.">;
+ HelpText<"OpenCL only. Sets -cl-finite-math-only and -cl-unsafe-math-optimizations, and defines __FAST_RELAXED_MATH__.">,
+ MarshallingInfoFlag<LangOpts<"FastRelaxedMath">>;
def cl_mad_enable : Flag<["-"], "cl-mad-enable">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Allow use of less precise MAD computations in the generated binary.">;
+ HelpText<"OpenCL only. Allow use of less precise MAD computations in the generated binary.">,
+ MarshallingInfoFlag<CodeGenOpts<"LessPreciseFPMAD">>,
+ ImpliedByAnyOf<[cl_unsafe_math_optimizations.KeyPath, cl_fast_relaxed_math.KeyPath]>;
def cl_no_signed_zeros : Flag<["-"], "cl-no-signed-zeros">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Allow use of less precise no signed zeros computations in the generated binary.">;
+ HelpText<"OpenCL only. Allow use of less precise no signed zeros computations in the generated binary.">,
+ MarshallingInfoFlag<LangOpts<"CLNoSignedZero">>;
def cl_std_EQ : Joined<["-"], "cl-std=">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL language standard to compile for.">, Values<"cl,CL,cl1.1,CL1.1,cl1.2,CL1.2,cl2.0,CL2.0,clc++,CLC++">;
+ HelpText<"OpenCL language standard to compile for.">, Values<"cl,CL,cl1.0,CL1.0,cl1.1,CL1.1,cl1.2,CL1.2,cl2.0,CL2.0,cl3.0,CL3.0,clc++,CLC++">;
def cl_denorms_are_zero : Flag<["-"], "cl-denorms-are-zero">, Group<opencl_Group>,
HelpText<"OpenCL only. Allow denormals to be flushed to zero.">;
def cl_fp32_correctly_rounded_divide_sqrt : Flag<["-"], "cl-fp32-correctly-rounded-divide-sqrt">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Specify that single precision floating-point divide and sqrt used in the program source are correctly rounded.">;
+ HelpText<"OpenCL only. Specify that single precision floating-point divide and sqrt used in the program source are correctly rounded.">,
+ MarshallingInfoFlag<CodeGenOpts<"CorrectlyRoundedDivSqrt">>;
def cl_uniform_work_group_size : Flag<["-"], "cl-uniform-work-group-size">, Group<opencl_Group>, Flags<[CC1Option]>,
- HelpText<"OpenCL only. Defines that the global work-size be a multiple of the work-group size specified to clEnqueueNDRangeKernel">;
+ HelpText<"OpenCL only. Defines that the global work-size be a multiple of the work-group size specified to clEnqueueNDRangeKernel">,
+ MarshallingInfoFlag<CodeGenOpts<"UniformWGSize">>;
def client__name : JoinedOrSeparate<["-"], "client_name">;
-def combine : Flag<["-", "--"], "combine">, Flags<[DriverOption, Unsupported]>;
+def combine : Flag<["-", "--"], "combine">, Flags<[NoXarchOption, Unsupported]>;
def compatibility__version : JoinedOrSeparate<["-"], "compatibility_version">;
-def config : Separate<["--"], "config">, Flags<[DriverOption]>,
+def config : Separate<["--"], "config">, Flags<[NoXarchOption]>,
HelpText<"Specifies configuration file">;
-def config_system_dir_EQ : Joined<["--"], "config-system-dir=">, Flags<[DriverOption, HelpHidden]>,
+def config_system_dir_EQ : Joined<["--"], "config-system-dir=">, Flags<[NoXarchOption, HelpHidden]>,
HelpText<"System directory for configuration files">;
-def config_user_dir_EQ : Joined<["--"], "config-user-dir=">, Flags<[DriverOption, HelpHidden]>,
+def config_user_dir_EQ : Joined<["--"], "config-user-dir=">, Flags<[NoXarchOption, HelpHidden]>,
HelpText<"User directory for configuration files">;
-def coverage : Flag<["-", "--"], "coverage">, Flags<[CoreOption]>;
+def coverage : Flag<["-", "--"], "coverage">, Group<Link_Group>, Flags<[CoreOption]>;
def cpp_precomp : Flag<["-"], "cpp-precomp">, Group<clang_ignored_f_Group>;
def current__version : JoinedOrSeparate<["-"], "current_version">;
def cxx_isystem : JoinedOrSeparate<["-"], "cxx-isystem">, Group<clang_i_Group>,
HelpText<"Add directory to the C++ SYSTEM include search path">, Flags<[CC1Option]>,
MetaVarName<"<directory>">;
-def c : Flag<["-"], "c">, Flags<[DriverOption]>, Group<Action_Group>,
+def c : Flag<["-"], "c">, Flags<[NoXarchOption, FlangOption]>, Group<Action_Group>,
HelpText<"Only run preprocess, compile, and assemble steps">;
def fconvergent_functions : Flag<["-"], "fconvergent-functions">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Assume functions may be convergent">;
@@ -595,22 +837,25 @@ def cuda_host_only : Flag<["--"], "cuda-host-only">,
def cuda_compile_host_device : Flag<["--"], "cuda-compile-host-device">,
HelpText<"Compile CUDA code for both host and device (default). Has no "
"effect on non-CUDA compilations.">;
-def cuda_include_ptx_EQ : Joined<["--"], "cuda-include-ptx=">, Flags<[DriverOption]>,
+def cuda_include_ptx_EQ : Joined<["--"], "cuda-include-ptx=">, Flags<[NoXarchOption]>,
HelpText<"Include PTX for the following GPU architecture (e.g. sm_35) or 'all'. May be specified more than once.">;
-def no_cuda_include_ptx_EQ : Joined<["--"], "no-cuda-include-ptx=">, Flags<[DriverOption]>,
+def no_cuda_include_ptx_EQ : Joined<["--"], "no-cuda-include-ptx=">, Flags<[NoXarchOption]>,
HelpText<"Do not include PTX for the following GPU architecture (e.g. sm_35) or 'all'. May be specified more than once.">;
-def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[DriverOption]>,
- HelpText<"CUDA/HIP offloading device architecture (e.g. sm_35, gfx906). May be specified more than once.">;
-def cuda_gpu_arch_EQ : Joined<["--"], "cuda-gpu-arch=">, Flags<[DriverOption]>,
+def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[NoXarchOption]>,
+ HelpText<"CUDA offloading device architecture (e.g. sm_35), or HIP offloading target ID in the form of a "
+ "device architecture followed by target ID features delimited by a colon. Each target ID feature "
+ "is a pre-defined string followed by a plus or minus sign (e.g. gfx908:xnack+:sramecc-). May be "
+ "specified more than once.">;
+def cuda_gpu_arch_EQ : Joined<["--"], "cuda-gpu-arch=">, Flags<[NoXarchOption]>,
Alias<offload_arch_EQ>;
def hip_link : Flag<["--"], "hip-link">,
HelpText<"Link clang-offload-bundler bundles for HIP">;
-def no_offload_arch_EQ : Joined<["--"], "no-offload-arch=">, Flags<[DriverOption]>,
+def no_offload_arch_EQ : Joined<["--"], "no-offload-arch=">, Flags<[NoXarchOption]>,
HelpText<"Remove CUDA/HIP offloading device architecture (e.g. sm_35, gfx906) from the list of devices to compile for. "
"'all' resets the list to its default value.">;
def emit_static_lib : Flag<["--"], "emit-static-lib">,
HelpText<"Enable linker job to emit a static library.">;
-def no_cuda_gpu_arch_EQ : Joined<["--"], "no-cuda-gpu-arch=">, Flags<[DriverOption]>,
+def no_cuda_gpu_arch_EQ : Joined<["--"], "no-cuda-gpu-arch=">, Flags<[NoXarchOption]>,
Alias<no_offload_arch_EQ>;
def cuda_noopt_device_debug : Flag<["--"], "cuda-noopt-device-debug">,
HelpText<"Enable device-side debug info generation. Disables ptxas optimizations.">;
@@ -627,14 +872,15 @@ def ptxas_path_EQ : Joined<["--"], "ptxas-path=">, Group<i_Group>,
def fcuda_flush_denormals_to_zero : Flag<["-"], "fcuda-flush-denormals-to-zero">,
HelpText<"Flush denormal floating point values to zero in CUDA device mode.">;
def fno_cuda_flush_denormals_to_zero : Flag<["-"], "fno-cuda-flush-denormals-to-zero">;
-defm cuda_approx_transcendentals : OptInFFlag<"cuda-approx-transcendentals", "Use", "Don't use",
- " approximate transcendental functions">;
-defm gpu_rdc : OptInFFlag<"gpu-rdc",
- "Generate relocatable device code, also known as separate compilation mode", "", "">;
+defm gpu_rdc : BoolFOption<"gpu-rdc",
+ LangOpts<"GPURelocatableDeviceCode">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Generate relocatable device code, also known as separate compilation mode">,
+ NegFlag<SetFalse>>;
def : Flag<["-"], "fcuda-rdc">, Alias<fgpu_rdc>;
def : Flag<["-"], "fno-cuda-rdc">, Alias<fno_gpu_rdc>;
defm cuda_short_ptr : OptInFFlag<"cuda-short-ptr",
- "Use 32-bit pointers for accessing const/local/shared address spaces">;
+ "Use 32-bit pointers for accessing const/local/shared address spaces", "", "",
+ [], TargetOpts<"NVPTXUseShortPointers">>;
def rocm_path_EQ : Joined<["--"], "rocm-path=">, Group<i_Group>,
HelpText<"ROCm installation path, used for finding and automatically linking required bitcode libraries.">;
def rocm_device_lib_path_EQ : Joined<["--"], "rocm-device-lib-path=">, Group<Link_Group>,
@@ -646,28 +892,54 @@ def hip_version_EQ : Joined<["--"], "hip-version=">,
HelpText<"HIP version in the format of major.minor.patch">;
def fhip_dump_offload_linker_script : Flag<["-"], "fhip-dump-offload-linker-script">,
Group<f_Group>, Flags<[NoArgumentUnused, HelpHidden]>;
-defm hip_new_launch_api : OptInFFlag<"hip-new-launch-api",
- "Use", "Don't use", " new kernel launching API for HIP">;
-defm gpu_allow_device_init : OptInFFlag<"gpu-allow-device-init",
- "Allow", "Don't allow", " device side init function in HIP">;
+defm hip_new_launch_api : BoolFOption<"hip-new-launch-api",
+ LangOpts<"HIPUseNewLaunchAPI">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use">, NegFlag<SetFalse, [], "Don't use">,
+ BothFlags<[], " new kernel launching API for HIP">>;
+defm gpu_allow_device_init : BoolFOption<"gpu-allow-device-init",
+ LangOpts<"GPUAllowDeviceInit">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Allow">, NegFlag<SetFalse, [], "Don't allow">,
+ BothFlags<[], " device side init function in HIP">>,
+ ShouldParseIf<hip.KeyPath>;
+defm gpu_defer_diag : BoolFOption<"gpu-defer-diag",
+ LangOpts<"GPUDeferDiag">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Defer">, NegFlag<SetFalse, [], "Don't defer">,
+ BothFlags<[], " host/device related diagnostic messages for CUDA/HIP">>;
+defm gpu_exclude_wrong_side_overloads : BoolFOption<"gpu-exclude-wrong-side-overloads",
+ LangOpts<"GPUExcludeWrongSideOverloads">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Always exclude wrong side overloads">,
+ NegFlag<SetFalse, [], "Exclude wrong side overloads only if there are same side overloads">,
+ BothFlags<[HelpHidden], " in overloading resolution for CUDA/HIP">>;
def gpu_max_threads_per_block_EQ : Joined<["--"], "gpu-max-threads-per-block=">,
Flags<[CC1Option]>,
- HelpText<"Default max threads per block for kernel launch bounds for HIP">;
-def libomptarget_nvptx_path_EQ : Joined<["--"], "libomptarget-nvptx-path=">, Group<i_Group>,
- HelpText<"Path to libomptarget-nvptx libraries">;
+ HelpText<"Default max threads per block for kernel launch bounds for HIP">,
+ MarshallingInfoStringInt<LangOpts<"GPUMaxThreadsPerBlock">, "256">,
+ ShouldParseIf<hip.KeyPath>;
+def gpu_instrument_lib_EQ : Joined<["--"], "gpu-instrument-lib=">,
+ HelpText<"Instrument device library for HIP, which is a LLVM bitcode containing "
+ "__cyg_profile_func_enter and __cyg_profile_func_exit">;
+def libomptarget_nvptx_bc_path_EQ : Joined<["--"], "libomptarget-nvptx-bc-path=">, Group<i_Group>,
+ HelpText<"Path to libomptarget-nvptx bitcode library">;
def dD : Flag<["-"], "dD">, Group<d_Group>, Flags<[CC1Option]>,
HelpText<"Print macro definitions in -E mode in addition to normal output">;
def dI : Flag<["-"], "dI">, Group<d_Group>, Flags<[CC1Option]>,
- HelpText<"Print include directives in -E mode in addition to normal output">;
+ HelpText<"Print include directives in -E mode in addition to normal output">,
+ MarshallingInfoFlag<PreprocessorOutputOpts<"ShowIncludeDirectives">>;
def dM : Flag<["-"], "dM">, Group<d_Group>, Flags<[CC1Option]>,
HelpText<"Print macro definitions in -E mode instead of normal output">;
def dead__strip : Flag<["-"], "dead_strip">;
def dependency_file : Separate<["-"], "dependency-file">, Flags<[CC1Option]>,
- HelpText<"Filename (or -) to write dependency output to">;
+ HelpText<"Filename (or -) to write dependency output to">,
+ MarshallingInfoString<DependencyOutputOpts<"OutputFile">>;
def dependency_dot : Separate<["-"], "dependency-dot">, Flags<[CC1Option]>,
- HelpText<"Filename to write DOT-formatted header dependencies to">;
+ HelpText<"Filename to write DOT-formatted header dependencies to">,
+ MarshallingInfoString<DependencyOutputOpts<"DOTOutputFile">>;
def module_dependency_dir : Separate<["-"], "module-dependency-dir">,
- Flags<[CC1Option]>, HelpText<"Directory to dump module dependencies to">;
+ Flags<[CC1Option]>, HelpText<"Directory to dump module dependencies to">,
+ MarshallingInfoString<DependencyOutputOpts<"ModuleDependencyOutputDir">>;
+def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
+ Flags<[NoXarchOption, RenderAsInput]>,
+ HelpText<"Directory to output dSYM's (if any) to">, MetaVarName<"<dir>">;
def dumpmachine : Flag<["-"], "dumpmachine">;
def dumpspecs : Flag<["-"], "dumpspecs">, Flags<[Unsupported]>;
def dumpversion : Flag<["-"], "dumpversion">;
@@ -683,29 +955,41 @@ def emit_ast : Flag<["-"], "emit-ast">,
def emit_llvm : Flag<["-"], "emit-llvm">, Flags<[CC1Option]>, Group<Action_Group>,
HelpText<"Use the LLVM representation for assembler and object files">;
def emit_interface_stubs : Flag<["-"], "emit-interface-stubs">, Flags<[CC1Option]>, Group<Action_Group>,
- HelpText<"Generate Inteface Stub Files.">;
+ HelpText<"Generate Interface Stub Files.">;
def emit_merged_ifs : Flag<["-"], "emit-merged-ifs">,
Flags<[CC1Option]>, Group<Action_Group>,
HelpText<"Generate Interface Stub Files, emit merged text not binary.">;
def interface_stub_version_EQ : JoinedOrSeparate<["-"], "interface-stub-version=">, Flags<[CC1Option]>;
def exported__symbols__list : Separate<["-"], "exported_symbols_list">;
-def e : JoinedOrSeparate<["-"], "e">, Group<Link_Group>;
+def e : JoinedOrSeparate<["-"], "e">, Flags<[LinkerInput]>, Group<Link_Group>;
def fmax_tokens_EQ : Joined<["-"], "fmax-tokens=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Max total number of preprocessed tokens for -Wmax-tokens.">;
+ HelpText<"Max total number of preprocessed tokens for -Wmax-tokens.">,
+ MarshallingInfoStringInt<LangOpts<"MaxTokens">>;
def fPIC : Flag<["-"], "fPIC">, Group<f_Group>;
def fno_PIC : Flag<["-"], "fno-PIC">, Group<f_Group>;
def fPIE : Flag<["-"], "fPIE">, Group<f_Group>;
def fno_PIE : Flag<["-"], "fno-PIE">, Group<f_Group>;
-defm access_control : OptOutFFlag<"no-access-control", "", "Disable C++ access control">;
+defm access_control : BoolFOption<"access-control",
+ LangOpts<"AccessControl">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable C++ access control">,
+ PosFlag<SetTrue>>;
def falign_functions : Flag<["-"], "falign-functions">, Group<f_Group>;
def falign_functions_EQ : Joined<["-"], "falign-functions=">, Group<f_Group>;
def fno_align_functions: Flag<["-"], "fno-align-functions">, Group<f_Group>;
-defm allow_editor_placeholders : OptInFFlag<"allow-editor-placeholders", "Treat editor placeholders as valid source code">;
+defm allow_editor_placeholders : BoolFOption<"allow-editor-placeholders",
+ LangOpts<"AllowEditorPlaceholders">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Treat editor placeholders as valid source code">,
+ NegFlag<SetFalse>>;
def fallow_unsupported : Flag<["-"], "fallow-unsupported">, Group<f_Group>;
def fapple_kext : Flag<["-"], "fapple-kext">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use Apple's kernel extensions ABI">;
-def fapple_pragma_pack : Flag<["-"], "fapple-pragma-pack">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Enable Apple gcc-compatible #pragma pack handling">;
+ HelpText<"Use Apple's kernel extensions ABI">,
+ MarshallingInfoFlag<LangOpts<"AppleKext">>;
+defm apple_pragma_pack : BoolFOption<"apple-pragma-pack",
+ LangOpts<"ApplePragmaPack">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable Apple gcc-compatible #pragma pack handling">,
+ NegFlag<SetFalse>>;
+def fxl_pragma_pack : Flag<["-"], "fxl-pragma-pack">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"Enable IBM XL #pragma pack handling">;
def shared_libsan : Flag<["-"], "shared-libsan">,
HelpText<"Dynamically link the sanitizer runtime">;
def static_libsan : Flag<["-"], "static-libsan">,
@@ -722,44 +1006,54 @@ def fast : Flag<["-"], "fast">, Group<f_Group>;
def fasynchronous_unwind_tables : Flag<["-"], "fasynchronous-unwind-tables">, Group<f_Group>;
def fdouble_square_bracket_attributes : Flag<[ "-" ], "fdouble-square-bracket-attributes">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>,
+ Group<f_Group>, Flags<[NoXarchOption, CC1Option]>,
HelpText<"Enable '[[]]' attributes in all C and C++ language modes">;
def fno_double_square_bracket_attributes : Flag<[ "-" ], "fno-double-square-bracket-attributes">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>,
+ Group<f_Group>, Flags<[NoXarchOption, CC1Option]>,
HelpText<"Disable '[[]]' attributes in all C and C++ language modes">;
-defm autolink : OptOutFFlag<"autolink", "", "Disable generation of linker directives for automatic library linking">;
+defm autolink : BoolFOption<"autolink",
+ CodeGenOpts<"Autolink">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable generation of linker directives for automatic library linking">,
+ PosFlag<SetTrue>>;
// C++ Coroutines TS
defm coroutines_ts : OptInFFlag<"coroutines-ts", "Enable support for the C++ Coroutines TS">;
def fembed_bitcode_EQ : Joined<["-"], "fembed-bitcode=">,
- Group<f_Group>, Flags<[DriverOption, CC1Option, CC1AsOption]>, MetaVarName<"<option>">,
- HelpText<"Embed LLVM bitcode (option: off, all, bitcode, marker)">;
+ Group<f_Group>, Flags<[NoXarchOption, CC1Option, CC1AsOption]>, MetaVarName<"<option>">,
+ HelpText<"Embed LLVM bitcode (option: off, all, bitcode, marker)">,
+ Values<"off,all,bitcode,marker">, NormalizedValuesScope<"CodeGenOptions">,
+ NormalizedValues<["Embed_Off", "Embed_All", "Embed_Bitcode", "Embed_Marker"]>,
+ MarshallingInfoString<CodeGenOpts<"EmbedBitcode">, "Embed_Off">, AutoNormalizeEnum;
def fembed_bitcode : Flag<["-"], "fembed-bitcode">, Group<f_Group>,
Alias<fembed_bitcode_EQ>, AliasArgs<["all"]>,
HelpText<"Embed LLVM IR bitcode as data">;
def fembed_bitcode_marker : Flag<["-"], "fembed-bitcode-marker">,
Alias<fembed_bitcode_EQ>, AliasArgs<["marker"]>,
HelpText<"Embed placeholder LLVM IR data as a marker">;
-defm gnu_inline_asm : OptOutFFlag<"gnu-inline-asm", "", "Disable GNU style inline asm">;
+defm gnu_inline_asm : BoolFOption<"gnu-inline-asm",
+ LangOpts<"GNUAsm">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable GNU style inline asm">, PosFlag<SetTrue>>;
def fprofile_sample_use : Flag<["-"], "fprofile-sample-use">, Group<f_Group>,
Flags<[CoreOption]>;
def fno_profile_sample_use : Flag<["-"], "fno-profile-sample-use">, Group<f_Group>,
Flags<[CoreOption]>;
def fprofile_sample_use_EQ : Joined<["-"], "fprofile-sample-use=">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>,
- HelpText<"Enable sample-based profile guided optimizations">;
+ Group<f_Group>, Flags<[NoXarchOption, CC1Option]>,
+ HelpText<"Enable sample-based profile guided optimizations">,
+ MarshallingInfoString<CodeGenOpts<"SampleProfileFile">>;
def fprofile_sample_accurate : Flag<["-"], "fprofile-sample-accurate">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>,
+ Group<f_Group>, Flags<[NoXarchOption, CC1Option]>,
HelpText<"Specifies that the sample profile is accurate">,
DocBrief<[{Specifies that the sample profile is accurate. If the sample
profile is accurate, callsites without profile samples are marked
as cold. Otherwise, treat callsites without profile samples as if
- we have no profile}]>;
+ we have no profile}]>,
+ MarshallingInfoFlag<CodeGenOpts<"ProfileSampleAccurate">>;
def fno_profile_sample_accurate : Flag<["-"], "fno-profile-sample-accurate">,
- Group<f_Group>, Flags<[DriverOption]>;
+ Group<f_Group>, Flags<[NoXarchOption]>;
def fauto_profile : Flag<["-"], "fauto-profile">, Group<f_Group>,
Alias<fprofile_sample_use>;
def fno_auto_profile : Flag<["-"], "fno-auto-profile">, Group<f_Group>,
@@ -772,12 +1066,15 @@ def fno_auto_profile_accurate : Flag<["-"], "fno-auto-profile-accurate">,
Group<f_Group>, Alias<fno_profile_sample_accurate>;
def fdebug_compilation_dir : Separate<["-"], "fdebug-compilation-dir">,
Group<f_Group>, Flags<[CC1Option, CC1AsOption, CoreOption]>,
- HelpText<"The compilation directory to embed in the debug info.">;
+ HelpText<"The compilation directory to embed in the debug info.">,
+ MarshallingInfoString<CodeGenOpts<"DebugCompilationDir">>;
def fdebug_compilation_dir_EQ : Joined<["-"], "fdebug-compilation-dir=">,
Group<f_Group>, Flags<[CC1Option, CC1AsOption, CoreOption]>,
Alias<fdebug_compilation_dir>;
-defm debug_info_for_profiling : OptInFFlag<"debug-info-for-profiling",
- "Emit extra debug info to make sample profile more accurate">;
+defm debug_info_for_profiling : BoolFOption<"debug-info-for-profiling",
+ CodeGenOpts<"DebugInfoForProfiling">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emit extra debug info to make sample profile more accurate">,
+ NegFlag<SetFalse>>;
def fprofile_instr_generate : Flag<["-"], "fprofile-instr-generate">,
Group<f_Group>, Flags<[CoreOption]>,
HelpText<"Generate instrumented code to collect execution counts into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var)">;
@@ -791,12 +1088,14 @@ def fprofile_instr_use_EQ : Joined<["-"], "fprofile-instr-use=">,
HelpText<"Use instrumentation data for profile-guided optimization">;
def fprofile_remapping_file_EQ : Joined<["-"], "fprofile-remapping-file=">,
Group<f_Group>, Flags<[CC1Option, CoreOption]>, MetaVarName<"<file>">,
- HelpText<"Use the remappings described in <file> to match the profile data against names in the program">;
+ HelpText<"Use the remappings described in <file> to match the profile data against names in the program">,
+ MarshallingInfoString<CodeGenOpts<"ProfileRemappingFile">>;
def fprofile_remapping_file : Separate<["-"], "fprofile-remapping-file">,
Group<f_Group>, Flags<[CoreOption]>, Alias<fprofile_remapping_file_EQ>;
-defm coverage_mapping : OptInFFlag<"coverage-mapping",
- "Generate coverage mapping to enable code coverage analysis", "Disable code coverage analysis", "",
- [CoreOption]>;
+defm coverage_mapping : BoolFOption<"coverage-mapping",
+ CodeGenOpts<"CoverageMapping">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Generate coverage mapping to enable code coverage analysis">,
+ NegFlag<SetFalse, [], "Disable code coverage analysis">, BothFlags<[CoreOption]>>;
def fprofile_generate : Flag<["-"], "fprofile-generate">,
Group<f_Group>, Flags<[CoreOption]>,
HelpText<"Generate instrumented code to collect execution counts into default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
@@ -812,7 +1111,7 @@ def fcs_profile_generate_EQ : Joined<["-"], "fcs-profile-generate=">,
def fprofile_use : Flag<["-"], "fprofile-use">, Group<f_Group>,
Alias<fprofile_instr_use>;
def fprofile_use_EQ : Joined<["-"], "fprofile-use=">,
- Group<f_Group>, Flags<[DriverOption]>, MetaVarName<"<pathname>">,
+ Group<f_Group>, Flags<[NoXarchOption]>, MetaVarName<"<pathname>">,
HelpText<"Use instrumentation data for profile-guided optimization. If pathname is a directory, it reads from <pathname>/default.profdata. Otherwise, it reads from file <pathname>.">;
def fno_profile_instr_generate : Flag<["-"], "fno-profile-instr-generate">,
Group<f_Group>, Flags<[CoreOption]>,
@@ -825,40 +1124,71 @@ def fno_profile_instr_use : Flag<["-"], "fno-profile-instr-use">,
HelpText<"Disable using instrumentation data for profile-guided optimization">;
def fno_profile_use : Flag<["-"], "fno-profile-use">,
Alias<fno_profile_instr_use>;
+defm profile_arcs : BoolFOption<"profile-arcs",
+ CodeGenOpts<"EmitGcovArcs">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option, LinkOption]>, NegFlag<SetFalse>>;
+defm test_coverage : BoolFOption<"test-coverage",
+ CodeGenOpts<"EmitGcovNotes">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>>;
def fprofile_filter_files_EQ : Joined<["-"], "fprofile-filter-files=">,
Group<f_Group>, Flags<[CC1Option, CoreOption]>,
- HelpText<"Instrument only functions from files where names match any regex separated by a semi-colon">;
+ HelpText<"Instrument only functions from files where names match any regex separated by a semi-colon">,
+ MarshallingInfoString<CodeGenOpts<"ProfileFilterFiles">>,
+ ShouldParseIf<!strconcat(fprofile_arcs.KeyPath, "||", ftest_coverage.KeyPath)>;
def fprofile_exclude_files_EQ : Joined<["-"], "fprofile-exclude-files=">,
Group<f_Group>, Flags<[CC1Option, CoreOption]>,
- HelpText<"Instrument only functions from files where names don't match all the regexes separated by a semi-colon">;
+ HelpText<"Instrument only functions from files where names don't match all the regexes separated by a semi-colon">,
+ MarshallingInfoString<CodeGenOpts<"ProfileExcludeFiles">>,
+ ShouldParseIf<!strconcat(fprofile_arcs.KeyPath, "||", ftest_coverage.KeyPath)>;
+def fprofile_update_EQ : Joined<["-"], "fprofile-update=">,
+ Group<f_Group>, Flags<[CC1Option, CoreOption]>, Values<"atomic,prefer-atomic,single">,
+ MetaVarName<"<method>">, HelpText<"Set update method of profile counters (atomic,prefer-atomic,single)">,
+ MarshallingInfoFlag<CodeGenOpts<"AtomicProfileUpdate">>;
+defm pseudo_probe_for_profiling : BoolFOption<"pseudo-probe-for-profiling",
+ CodeGenOpts<"PseudoProbeForProfiling">, DefaultFalse,
+ PosFlag<SetTrue, [], "Emit">, NegFlag<SetFalse, [], "Do not emit">,
+ BothFlags<[NoXarchOption, CC1Option], " pseudo probes for sample profiling">>;
def forder_file_instrumentation : Flag<["-"], "forder-file-instrumentation">,
Group<f_Group>, Flags<[CC1Option, CoreOption]>,
HelpText<"Generate instrumented code to collect order file into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var)">;
+def fprofile_list_EQ : Joined<["-"], "fprofile-list=">,
+ Group<f_Group>, Flags<[CC1Option, CoreOption]>,
+ HelpText<"Filename defining the list of functions/files to instrument">,
+ MarshallingInfoStringVector<LangOpts<"ProfileListFiles">>;
-defm addrsig : OptInFFlag<"addrsig", "Emit", "Don't emit", " an address-significance table", [CoreOption]>;
+defm addrsig : BoolFOption<"addrsig",
+ CodeGenOpts<"Addrsig">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emit">, NegFlag<SetFalse, [], "Don't emit">,
+ BothFlags<[CoreOption], " an address-significance table">>;
defm blocks : OptInFFlag<"blocks", "Enable the 'blocks' language feature", "", "", [CoreOption]>;
def fbootclasspath_EQ : Joined<["-"], "fbootclasspath=">, Group<f_Group>;
-def fborland_extensions : Flag<["-"], "fborland-extensions">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Accept non-standard constructs supported by the Borland compiler">;
+defm borland_extensions : BoolFOption<"borland-extensions",
+ LangOpts<"Borland">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Accept non-standard constructs supported by the Borland compiler">,
+ NegFlag<SetFalse>>;
def fbuiltin : Flag<["-"], "fbuiltin">, Group<f_Group>, Flags<[CoreOption]>;
def fbuiltin_module_map : Flag <["-"], "fbuiltin-module-map">, Group<f_Group>,
- Flags<[DriverOption]>, HelpText<"Load the clang builtins module map file.">;
-defm caret_diagnostics : OptOutFFlag<"caret-diagnostics", "", "">;
+ Flags<[NoXarchOption]>, HelpText<"Load the clang builtins module map file.">;
+defm caret_diagnostics : BoolFOption<"caret-diagnostics",
+ DiagnosticOpts<"ShowCarets">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>, PosFlag<SetTrue>>;
def fclang_abi_compat_EQ : Joined<["-"], "fclang-abi-compat=">, Group<f_clang_Group>,
Flags<[CC1Option]>, MetaVarName<"<version>">, Values<"<major>.<minor>,latest">,
HelpText<"Attempt to match the ABI of Clang <version>">;
def fclasspath_EQ : Joined<["-"], "fclasspath=">, Group<f_Group>;
-defm color_diagnostics : OptInFFlag<"color-diagnostics", "Enable", "Disable", " colors in diagnostics", [CoreOption]>;
+defm color_diagnostics : OptInFFlag<"color-diagnostics", "Enable", "Disable", " colors in diagnostics",
+ [CoreOption, FlangOption]>;
def fdiagnostics_color : Flag<["-"], "fdiagnostics-color">, Group<f_Group>,
- Flags<[CoreOption, DriverOption]>;
+ Flags<[CoreOption, NoXarchOption]>;
def fdiagnostics_color_EQ : Joined<["-"], "fdiagnostics-color=">, Group<f_Group>;
def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group<f_Group>,
Flags<[CoreOption, CC1Option]>, HelpText<"Use ANSI escape codes for diagnostics">,
- MarshallingInfoFlag<"DiagnosticOpts->UseANSIEscapeCodes", "false">;
+ MarshallingInfoFlag<DiagnosticOpts<"UseANSIEscapeCodes">>;
def fcomment_block_commands : CommaJoined<["-"], "fcomment-block-commands=">, Group<f_clang_Group>, Flags<[CC1Option]>,
HelpText<"Treat each comma separated argument in <arg> as a documentation comment block command">,
- MetaVarName<"<arg>">;
-def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group<f_clang_Group>, Flags<[CC1Option]>;
+ MetaVarName<"<arg>">, MarshallingInfoStringVector<LangOpts<"CommentOpts.BlockCommandNames">>;
+def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group<f_clang_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"CommentOpts.ParseAllComments">>;
def frecord_command_line : Flag<["-"], "frecord-command-line">,
Group<f_clang_Group>;
def fno_record_command_line : Flag<["-"], "fno-record-command-line">,
@@ -866,89 +1196,134 @@ def fno_record_command_line : Flag<["-"], "fno-record-command-line">,
def : Flag<["-"], "frecord-gcc-switches">, Alias<frecord_command_line>;
def : Flag<["-"], "fno-record-gcc-switches">, Alias<fno_record_command_line>;
def fcommon : Flag<["-"], "fcommon">, Group<f_Group>,
- Flags<[CoreOption, CC1Option]>, HelpText<"Place uninitialized global variables in a common block">;
+ Flags<[CoreOption, CC1Option]>, HelpText<"Place uninitialized global variables in a common block">,
+ MarshallingInfoNegativeFlag<CodeGenOpts<"NoCommon">>;
def fcompile_resource_EQ : Joined<["-"], "fcompile-resource=">, Group<f_Group>;
-def fcomplete_member_pointers : Flag<["-"], "fcomplete-member-pointers">, Group<f_clang_Group>,
- Flags<[CoreOption, CC1Option]>,
- HelpText<"Require member pointer base types to be complete if they would be significant under the Microsoft ABI">;
-def fno_complete_member_pointers : Flag<["-"], "fno-complete-member-pointers">, Group<f_clang_Group>,
- Flags<[CoreOption]>,
- HelpText<"Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI">;
+defm complete_member_pointers : BoolOption<"f", "complete-member-pointers",
+ LangOpts<"CompleteMemberPointers">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Require">, NegFlag<SetFalse, [], "Do not require">,
+ BothFlags<[CoreOption], " member pointer base types to be complete if they"
+ " would be significant under the Microsoft ABI">>,
+ Group<f_clang_Group>;
def fcf_runtime_abi_EQ : Joined<["-"], "fcf-runtime-abi=">, Group<f_Group>,
- Flags<[CC1Option]>;
-def fconstant_cfstrings : Flag<["-"], "fconstant-cfstrings">, Group<f_Group>;
+ Flags<[CC1Option]>, Values<"unspecified,standalone,objc,swift,swift-5.0,swift-4.2,swift-4.1">,
+ NormalizedValuesScope<"LangOptions::CoreFoundationABI">,
+ NormalizedValues<["ObjectiveC", "ObjectiveC", "ObjectiveC", "Swift5_0", "Swift5_0", "Swift4_2", "Swift4_1"]>,
+ MarshallingInfoString<LangOpts<"CFRuntime">, "ObjectiveC">, AutoNormalizeEnum;
+defm constant_cfstrings : BoolFOption<"constant-cfstrings",
+ LangOpts<"NoConstantCFStrings">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Disable creation of CodeFoundation-type constant strings">,
+ PosFlag<SetFalse>>;
def fconstant_string_class_EQ : Joined<["-"], "fconstant-string-class=">, Group<f_Group>;
def fconstexpr_depth_EQ : Joined<["-"], "fconstexpr-depth=">, Group<f_Group>;
def fconstexpr_steps_EQ : Joined<["-"], "fconstexpr-steps=">, Group<f_Group>;
def fexperimental_new_constant_interpreter : Flag<["-"], "fexperimental-new-constant-interpreter">, Group<f_Group>,
- HelpText<"Enable the experimental new constant interpreter">, Flags<[CC1Option]>;
+ HelpText<"Enable the experimental new constant interpreter">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"EnableNewConstInterp">>;
def fconstexpr_backtrace_limit_EQ : Joined<["-"], "fconstexpr-backtrace-limit=">,
Group<f_Group>;
def fno_crash_diagnostics : Flag<["-"], "fno-crash-diagnostics">, Group<f_clang_Group>, Flags<[NoArgumentUnused, CoreOption]>,
HelpText<"Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash">;
def fcrash_diagnostics_dir : Joined<["-"], "fcrash-diagnostics-dir=">, Group<f_clang_Group>, Flags<[NoArgumentUnused, CoreOption]>;
def fcreate_profile : Flag<["-"], "fcreate-profile">, Group<f_Group>;
-defm cxx_exceptions: OptInFFlag<"cxx-exceptions", "Enable C++ exceptions">;
+defm cxx_exceptions: BoolFOption<"cxx-exceptions",
+ LangOpts<"CXXExceptions">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable C++ exceptions">, NegFlag<SetFalse>>;
def fcxx_modules : Flag <["-"], "fcxx-modules">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fdebug_pass_arguments : Flag<["-"], "fdebug-pass-arguments">, Group<f_Group>;
def fdebug_pass_structure : Flag<["-"], "fdebug-pass-structure">, Group<f_Group>;
def fdepfile_entry : Joined<["-"], "fdepfile-entry=">,
Group<f_clang_Group>, Flags<[CC1Option]>;
def fdiagnostics_fixit_info : Flag<["-"], "fdiagnostics-fixit-info">, Group<f_clang_Group>;
+def fno_diagnostics_fixit_info : Flag<["-"], "fno-diagnostics-fixit-info">, Group<f_Group>,
+ Flags<[CC1Option]>, HelpText<"Do not include fixit information in diagnostics">,
+ MarshallingInfoNegativeFlag<DiagnosticOpts<"ShowFixits">>;
def fdiagnostics_parseable_fixits : Flag<["-"], "fdiagnostics-parseable-fixits">, Group<f_clang_Group>,
- Flags<[CoreOption, CC1Option]>, HelpText<"Print fix-its in machine parseable form">;
+ Flags<[CoreOption, CC1Option]>, HelpText<"Print fix-its in machine parseable form">,
+ MarshallingInfoFlag<DiagnosticOpts<"ShowParseableFixits">>;
def fdiagnostics_print_source_range_info : Flag<["-"], "fdiagnostics-print-source-range-info">,
Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Print source range spans in numeric form">;
-def fdiagnostics_show_hotness : Flag<["-"], "fdiagnostics-show-hotness">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Enable profile hotness information in diagnostic line">;
+ HelpText<"Print source range spans in numeric form">,
+ MarshallingInfoFlag<DiagnosticOpts<"ShowSourceRanges">>;
+defm diagnostics_show_hotness : BoolFOption<"diagnostics-show-hotness",
+ CodeGenOpts<"DiagnosticsWithHotness">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable profile hotness information in diagnostic line">,
+ NegFlag<SetFalse>>;
def fdiagnostics_hotness_threshold_EQ : Joined<["-"], "fdiagnostics-hotness-threshold=">,
- Group<f_Group>, Flags<[CC1Option]>, MetaVarName<"<number>">,
- HelpText<"Prevent optimization remarks from being output if they do not have at least this profile count">;
-def fdiagnostics_show_option : Flag<["-"], "fdiagnostics-show-option">, Group<f_Group>,
- HelpText<"Print option name with mappable diagnostics">;
-def fdiagnostics_show_note_include_stack : Flag<["-"], "fdiagnostics-show-note-include-stack">,
- Group<f_Group>, Flags<[CC1Option]>, HelpText<"Display include stacks for diagnostic notes">;
+ Group<f_Group>, Flags<[CC1Option]>, MetaVarName<"<value>">,
+ HelpText<"Prevent optimization remarks from being output if they do not have at least this profile count. "
+ "Use 'auto' to apply the threshold from profile summary">;
+defm diagnostics_show_option : BoolFOption<"diagnostics-show-option",
+ DiagnosticOpts<"ShowOptionNames">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>, PosFlag<SetTrue, [], "Print option name with mappable diagnostics">>;
+defm diagnostics_show_note_include_stack : BoolFOption<"diagnostics-show-note-include-stack",
+ DiagnosticOpts<"ShowNoteIncludeStack">, DefaultFalse,
+ PosFlag<SetTrue, [], "Display include stacks for diagnostic notes">,
+ NegFlag<SetFalse>, BothFlags<[CC1Option]>>;
def fdiagnostics_format_EQ : Joined<["-"], "fdiagnostics-format=">, Group<f_clang_Group>;
def fdiagnostics_show_category_EQ : Joined<["-"], "fdiagnostics-show-category=">, Group<f_clang_Group>;
def fdiagnostics_show_template_tree : Flag<["-"], "fdiagnostics-show-template-tree">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Print a template comparison tree for differing templates">;
+ HelpText<"Print a template comparison tree for differing templates">,
+ MarshallingInfoFlag<DiagnosticOpts<"ShowTemplateTree">>;
def fdeclspec : Flag<["-"], "fdeclspec">, Group<f_clang_Group>,
HelpText<"Allow __declspec as a keyword">, Flags<[CC1Option]>;
def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">, Group<f_clang_Group>,
- HelpText<"Discard value names in LLVM IR">, Flags<[DriverOption]>;
+ HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
def fno_discard_value_names : Flag<["-"], "fno-discard-value-names">, Group<f_clang_Group>,
- HelpText<"Do not discard value names in LLVM IR">, Flags<[DriverOption]>;
+ HelpText<"Do not discard value names in LLVM IR">, Flags<[NoXarchOption]>;
def fdollars_in_identifiers : Flag<["-"], "fdollars-in-identifiers">, Group<f_Group>,
HelpText<"Allow '$' in identifiers">, Flags<[CC1Option]>;
def fdwarf2_cfi_asm : Flag<["-"], "fdwarf2-cfi-asm">, Group<clang_ignored_f_Group>;
def fno_dwarf2_cfi_asm : Flag<["-"], "fno-dwarf2-cfi-asm">, Group<clang_ignored_f_Group>;
-defm dwarf_directory_asm : OptOutFFlag<"dwarf-directory-asm", "", "">;
-def felide_constructors : Flag<["-"], "felide-constructors">, Group<f_Group>;
+defm dwarf_directory_asm : BoolFOption<"dwarf-directory-asm",
+ CodeGenOpts<"NoDwarfDirectoryAsm">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option]>, PosFlag<SetFalse>>;
+defm elide_constructors : BoolFOption<"elide-constructors",
+ LangOpts<"ElideConstructors">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable C++ copy constructor elision">,
+ PosFlag<SetTrue>>;
def fno_elide_type : Flag<["-"], "fno-elide-type">, Group<f_Group>,
Flags<[CC1Option]>,
- HelpText<"Do not elide types when printing diagnostics">;
+ HelpText<"Do not elide types when printing diagnostics">,
+ MarshallingInfoNegativeFlag<DiagnosticOpts<"ElideType">>;
def feliminate_unused_debug_symbols : Flag<["-"], "feliminate-unused-debug-symbols">, Group<f_Group>;
+defm eliminate_unused_debug_types : OptOutFFlag<"eliminate-unused-debug-types",
+ "Do not emit ", "Emit ", " debug info for defined but unused types">;
def femit_all_decls : Flag<["-"], "femit-all-decls">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Emit all declarations, even if unused">;
-def femulated_tls : Flag<["-"], "femulated-tls">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use emutls functions to access thread_local variables">;
-def fno_emulated_tls : Flag<["-"], "fno-emulated-tls">, Group<f_Group>, Flags<[CC1Option]>;
+ HelpText<"Emit all declarations, even if unused">,
+ MarshallingInfoFlag<LangOpts<"EmitAllDecls">>;
+defm emulated_tls : BoolFOption<"emulated-tls",
+ CodeGenOpts<"EmulatedTLS">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use emutls functions to access thread_local variables">,
+ NegFlag<SetFalse>, BothFlags<[CC1Option]>>;
def fencoding_EQ : Joined<["-"], "fencoding=">, Group<f_Group>;
def ferror_limit_EQ : Joined<["-"], "ferror-limit=">, Group<f_Group>, Flags<[CoreOption]>;
-defm exceptions : OptInFFlag<"exceptions", "Enable", "Disable", " support for exception handling">;
+defm exceptions : BoolFOption<"exceptions",
+ LangOpts<"Exceptions">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[], " support for exception handling">>;
def fdwarf_exceptions : Flag<["-"], "fdwarf-exceptions">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Use DWARF style exceptions">;
+ HelpText<"Use DWARF style exceptions">;
def fsjlj_exceptions : Flag<["-"], "fsjlj-exceptions">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Use SjLj style exceptions">;
+ HelpText<"Use SjLj style exceptions">;
def fseh_exceptions : Flag<["-"], "fseh-exceptions">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Use SEH style exceptions">;
+ HelpText<"Use SEH style exceptions">;
def fwasm_exceptions : Flag<["-"], "fwasm-exceptions">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Use WebAssembly style exceptions">;
+ HelpText<"Use WebAssembly style exceptions">;
+def exception_model : Separate<["-"], "exception-model">,
+ Flags<[CC1Option, NoDriverOption]>, HelpText<"The exception model: dwarf|sjlj|seh|wasm">,
+ Values<"dwarf,sjlj,seh,wasm">,
+ NormalizedValuesScope<"llvm::ExceptionHandling">,
+ NormalizedValues<["DwarfCFI", "SjLj", "WinEH", "Wasm"]>,
+ MarshallingInfoString<LangOpts<"ExceptionHandling">, "None">,
+ AutoNormalizeEnum;
+def exception_model_EQ : Joined<["-"], "exception-model=">,
+ Flags<[CC1Option, NoDriverOption]>, Alias<exception_model>;
def fignore_exceptions : Flag<["-"], "fignore-exceptions">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Enable support for ignoring exception handling constructs">;
+ HelpText<"Enable support for ignoring exception handling constructs">,
+ MarshallingInfoFlag<LangOpts<"IgnoreExceptions">>;
def fexcess_precision_EQ : Joined<["-"], "fexcess-precision=">,
Group<clang_ignored_gcc_optimization_f_Group>;
def : Flag<["-"], "fexpensive-optimizations">, Group<clang_ignored_gcc_optimization_f_Group>;
@@ -960,23 +1335,41 @@ def : Flag<["-"], "fextended-identifiers">, Group<clang_ignored_f_Group>;
def : Flag<["-"], "fno-extended-identifiers">, Group<f_Group>, Flags<[Unsupported]>;
def fhosted : Flag<["-"], "fhosted">, Group<f_Group>;
def fdenormal_fp_math_EQ : Joined<["-"], "fdenormal-fp-math=">, Group<f_Group>, Flags<[CC1Option]>;
-def ffp_model_EQ : Joined<["-"], "ffp-model=">, Group<f_Group>, Flags<[DriverOption]>,
+def ffp_model_EQ : Joined<["-"], "ffp-model=">, Group<f_Group>, Flags<[NoXarchOption]>,
HelpText<"Controls the semantics of floating-point calculations.">;
def ffp_exception_behavior_EQ : Joined<["-"], "ffp-exception-behavior=">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Specifies the exception behavior of floating-point operations.">;
-defm fast_math : OptInFFlag<"fast-math", "Allow aggressive, lossy floating-point optimizations">;
+defm fast_math : OptInFFlag<"fast-math", "Allow aggressive, lossy floating-point optimizations", "", "", [],
+ LangOpts<"FastMath">, [cl_fast_relaxed_math.KeyPath]>;
+def menable_unsafe_fp_math : Flag<["-"], "menable-unsafe-fp-math">, Flags<[CC1Option]>,
+ HelpText<"Allow unsafe floating-point math optimizations which may decrease precision">,
+ MarshallingInfoFlag<LangOpts<"UnsafeFPMath">>,
+ ImpliedByAnyOf<[cl_unsafe_math_optimizations.KeyPath, ffast_math.KeyPath]>;
defm math_errno : OptInFFlag<"math-errno", "Require math functions to indicate errors by setting errno">;
def fbracket_depth_EQ : Joined<["-"], "fbracket-depth=">, Group<f_Group>, Flags<[CoreOption]>;
def fsignaling_math : Flag<["-"], "fsignaling-math">, Group<f_Group>;
def fno_signaling_math : Flag<["-"], "fno-signaling-math">, Group<f_Group>;
-defm jump_tables : OptOutFFlag<"jump-tables", "Use", "Do not use", " jump tables for lowering switches">;
-defm force_enable_int128 : OptInFFlag<"force-enable-int128", "Enable", "Disable", " support for int128_t type">;
-defm keep_static_consts : OptInFFlag<"keep-static-consts", "Keep", "Don't keep", " static const variables if unused", [DriverOption]>;
+defm jump_tables : BoolFOption<"jump-tables",
+ CodeGenOpts<"NoUseJumpTables">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Do not use">, PosFlag<SetFalse, [], "Use">,
+ BothFlags<[], " jump tables for lowering switches">>;
+defm force_enable_int128 : OptInFFlag<"force-enable-int128", "Enable", "Disable", " support for int128_t type", [], TargetOpts<"ForceEnableInt128">>;
+defm keep_static_consts : BoolFOption<"keep-static-consts",
+ CodeGenOpts<"KeepStaticConsts">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Keep">, NegFlag<SetFalse, [], "Don't keep">,
+ BothFlags<[NoXarchOption], " static const variables if unused">>;
defm fixed_point : OptInFFlag<"fixed-point", "Enable", "Disable", " fixed point types">;
-defm cxx_static_destructors : OptOutFFlag<"c++-static-destructors", "",
- "Disable C++ static destructor registration">;
+defm cxx_static_destructors : BoolFOption<"c++-static-destructors",
+ LangOpts<"RegisterStaticDestructors">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable C++ static destructor registration">,
+ PosFlag<SetTrue>>;
def fsymbol_partition_EQ : Joined<["-"], "fsymbol-partition=">, Group<f_Group>,
- Flags<[CC1Option]>;
+ Flags<[CC1Option]>, MarshallingInfoString<CodeGenOpts<"SymbolPartition">>;
+
+defm memory_profile : OptInFFlag<"memory-profile", "Enable", "Disable", " heap memory profiling">;
+def fmemory_profile_EQ : Joined<["-"], "fmemory-profile=">,
+ Group<f_Group>, Flags<[CC1Option]>, MetaVarName<"<directory>">,
+ HelpText<"Enable heap memory profiling and dump results into <directory>">;
// Begin sanitizer flags. These should all be core options exposed in all driver
// modes.
@@ -987,10 +1380,11 @@ def fsanitize_EQ : CommaJoined<["-"], "fsanitize=">, Group<f_clang_Group>,
HelpText<"Turn on runtime checks for various forms of undefined "
"or suspicious behavior. See user manual for available checks">;
def fno_sanitize_EQ : CommaJoined<["-"], "fno-sanitize=">, Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>;
+ Flags<[CoreOption, NoXarchOption]>;
def fsanitize_blacklist : Joined<["-"], "fsanitize-blacklist=">,
Group<f_clang_Group>,
- HelpText<"Path to blacklist file for sanitizers">;
+ HelpText<"Path to blacklist file for sanitizers">,
+ MarshallingInfoStringVector<LangOpts<"SanitizerBlacklistFiles">>;
def fsanitize_system_blacklist : Joined<["-"], "fsanitize-system-blacklist=">,
HelpText<"Path to system blacklist file for sanitizers">,
Flags<[CC1Option]>;
@@ -1003,66 +1397,62 @@ def fsanitize_coverage
HelpText<"Specify the type of coverage instrumentation for Sanitizers">;
def fno_sanitize_coverage
: CommaJoined<["-"], "fno-sanitize-coverage=">,
- Group<f_clang_Group>, Flags<[CoreOption, DriverOption]>,
+ Group<f_clang_Group>, Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable specified features of coverage instrumentation for "
"Sanitizers">, Values<"func,bb,edge,indirect-calls,trace-bb,trace-cmp,trace-div,trace-gep,8bit-counters,trace-pc,trace-pc-guard,no-prune,inline-8bit-counters,inline-bool-flag">;
def fsanitize_coverage_allowlist : Joined<["-"], "fsanitize-coverage-allowlist=">,
- Group<f_clang_Group>, Flags<[CoreOption, DriverOption]>,
- HelpText<"Restrict sanitizer coverage instrumentation exclusively to modules and functions that match the provided special case list, except the blocked ones">;
+ Group<f_clang_Group>, Flags<[CoreOption, NoXarchOption]>,
+ HelpText<"Restrict sanitizer coverage instrumentation exclusively to modules and functions that match the provided special case list, except the blocked ones">,
+ MarshallingInfoStringVector<CodeGenOpts<"SanitizeCoverageAllowlistFiles">>;
def : Joined<["-"], "fsanitize-coverage-whitelist=">,
Group<f_clang_Group>, Flags<[CoreOption, HelpHidden]>, Alias<fsanitize_coverage_allowlist>,
HelpText<"Deprecated, use -fsanitize-coverage-allowlist= instead">;
def fsanitize_coverage_blocklist : Joined<["-"], "fsanitize-coverage-blocklist=">,
- Group<f_clang_Group>, Flags<[CoreOption, DriverOption]>,
- HelpText<"Disable sanitizer coverage instrumentation for modules and functions that match the provided special case list, even the allowed ones">;
+ Group<f_clang_Group>, Flags<[CoreOption, NoXarchOption]>,
+ HelpText<"Disable sanitizer coverage instrumentation for modules and functions that match the provided special case list, even the allowed ones">,
+ MarshallingInfoStringVector<CodeGenOpts<"SanitizeCoverageBlocklistFiles">>;
def : Joined<["-"], "fsanitize-coverage-blacklist=">,
Group<f_clang_Group>, Flags<[CoreOption, HelpHidden]>, Alias<fsanitize_coverage_blocklist>,
HelpText<"Deprecated, use -fsanitize-coverage-blocklist= instead">;
def fsanitize_memory_track_origins_EQ : Joined<["-"], "fsanitize-memory-track-origins=">,
Group<f_clang_Group>,
- HelpText<"Enable origins tracking in MemorySanitizer">;
+ HelpText<"Enable origins tracking in MemorySanitizer">,
+ MarshallingInfoStringInt<CodeGenOpts<"SanitizeMemoryTrackOrigins">>;
def fsanitize_memory_track_origins : Flag<["-"], "fsanitize-memory-track-origins">,
Group<f_clang_Group>,
HelpText<"Enable origins tracking in MemorySanitizer">;
def fno_sanitize_memory_track_origins : Flag<["-"], "fno-sanitize-memory-track-origins">,
Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable origins tracking in MemorySanitizer">;
-def fsanitize_memory_use_after_dtor : Flag<["-"], "fsanitize-memory-use-after-dtor">,
- Group<f_clang_Group>,
- HelpText<"Enable use-after-destroy detection in MemorySanitizer">;
-def fno_sanitize_memory_use_after_dtor : Flag<["-"], "fno-sanitize-memory-use-after-dtor">,
- Group<f_clang_Group>,
- HelpText<"Disable use-after-destroy detection in MemorySanitizer">;
+defm sanitize_memory_use_after_dtor : BoolOption<"f", "sanitize-memory-use-after-dtor",
+ CodeGenOpts<"SanitizeMemoryUseAfterDtor">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[], " use-after-destroy detection in MemorySanitizer">>,
+ Group<f_clang_Group>;
def fsanitize_address_field_padding : Joined<["-"], "fsanitize-address-field-padding=">,
Group<f_clang_Group>,
- HelpText<"Level of field padding for AddressSanitizer">;
-def fsanitize_address_use_after_scope : Flag<["-"], "fsanitize-address-use-after-scope">,
- Group<f_clang_Group>,
- HelpText<"Enable use-after-scope detection in AddressSanitizer">;
-def fno_sanitize_address_use_after_scope : Flag<["-"], "fno-sanitize-address-use-after-scope">,
- Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
- HelpText<"Disable use-after-scope detection in AddressSanitizer">;
-def fsanitize_address_poison_custom_array_cookie
- : Flag<[ "-" ], "fsanitize-address-poison-custom-array-cookie">,
- Group<f_clang_Group>,
- HelpText<"Enable poisoning array cookies when using custom operator new[] in AddressSanitizer">;
-def fno_sanitize_address_poison_custom_array_cookie
- : Flag<[ "-" ], "fno-sanitize-address-poison-custom-array-cookie">,
- Group<f_clang_Group>,
- HelpText<"Disable poisoning array cookies when using custom operator new[] in AddressSanitizer">;
+ HelpText<"Level of field padding for AddressSanitizer">,
+ MarshallingInfoStringInt<LangOpts<"SanitizeAddressFieldPadding">>;
+defm sanitize_address_use_after_scope : BoolOption<"f", "sanitize-address-use-after-scope",
+ CodeGenOpts<"SanitizeAddressUseAfterScope">, DefaultFalse,
+ PosFlag<SetTrue, [], "Enable">, NegFlag<SetFalse, [CoreOption, NoXarchOption], "Disable">,
+ BothFlags<[], " use-after-scope detection in AddressSanitizer">>,
+ Group<f_clang_Group>;
+defm sanitize_address_poison_custom_array_cookie : BoolOption<"f", "sanitize-address-poison-custom-array-cookie",
+ CodeGenOpts<"SanitizeAddressPoisonCustomArrayCookie">, DefaultFalse,
+ PosFlag<SetTrue, [], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[], " poisoning array cookies when using custom operator new[] in AddressSanitizer">>,
+ Group<f_clang_Group>;
def fsanitize_address_globals_dead_stripping : Flag<["-"], "fsanitize-address-globals-dead-stripping">,
- Group<f_clang_Group>,
- HelpText<"Enable linker dead stripping of globals in AddressSanitizer">;
-def fsanitize_address_use_odr_indicator
- : Flag<["-"], "fsanitize-address-use-odr-indicator">,
- Group<f_clang_Group>,
- HelpText<"Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size">;
-def fno_sanitize_address_use_odr_indicator
- : Flag<["-"], "fno-sanitize-address-use-odr-indicator">,
- Group<f_clang_Group>,
- HelpText<"Disable ODR indicator globals">;
+ Group<f_clang_Group>, HelpText<"Enable linker dead stripping of globals in AddressSanitizer">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeAddressGlobalsDeadStripping">, "false">;
+defm sanitize_address_use_odr_indicator : BoolOption<"f", "sanitize-address-use-odr-indicator",
+ CodeGenOpts<"SanitizeAddressUseOdrIndicator">, DefaultFalse,
+ PosFlag<SetTrue, [], "Enable ODR indicator globals to avoid false ODR violation"
+ " reports in partially sanitized programs at the cost of an increase in binary size">,
+ NegFlag<SetFalse, [], "Disable ODR indicator globals">>,
+ Group<f_clang_Group>;
// Note: This flag was introduced when it was necessary to distinguish between
// ABI for correct codegen. This is no longer needed, but the flag is
// not removed since targeting either ABI will behave the same.
@@ -1077,24 +1467,24 @@ def fsanitize_recover_EQ : CommaJoined<["-"], "fsanitize-recover=">,
Group<f_clang_Group>,
HelpText<"Enable recovery for specified sanitizers">;
def fno_sanitize_recover_EQ : CommaJoined<["-"], "fno-sanitize-recover=">,
- Group<f_clang_Group>, Flags<[CoreOption, DriverOption]>,
+ Group<f_clang_Group>, Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable recovery for specified sanitizers">;
def fsanitize_recover : Flag<["-"], "fsanitize-recover">, Group<f_clang_Group>,
Alias<fsanitize_recover_EQ>, AliasArgs<["all"]>;
def fno_sanitize_recover : Flag<["-"], "fno-sanitize-recover">,
- Flags<[CoreOption, DriverOption]>, Group<f_clang_Group>,
+ Flags<[CoreOption, NoXarchOption]>, Group<f_clang_Group>,
Alias<fno_sanitize_recover_EQ>, AliasArgs<["all"]>;
def fsanitize_trap_EQ : CommaJoined<["-"], "fsanitize-trap=">, Group<f_clang_Group>,
HelpText<"Enable trapping for specified sanitizers">;
def fno_sanitize_trap_EQ : CommaJoined<["-"], "fno-sanitize-trap=">, Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable trapping for specified sanitizers">;
def fsanitize_trap : Flag<["-"], "fsanitize-trap">, Group<f_clang_Group>,
Alias<fsanitize_trap_EQ>, AliasArgs<["all"]>,
HelpText<"Enable trapping for all sanitizers">;
def fno_sanitize_trap : Flag<["-"], "fno-sanitize-trap">, Group<f_clang_Group>,
Alias<fno_sanitize_trap_EQ>, AliasArgs<["all"]>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable trapping for all sanitizers">;
def fsanitize_undefined_trap_on_error
: Flag<["-"], "fsanitize-undefined-trap-on-error">, Group<f_clang_Group>,
@@ -1102,10 +1492,10 @@ def fsanitize_undefined_trap_on_error
def fno_sanitize_undefined_trap_on_error
: Flag<["-"], "fno-sanitize-undefined-trap-on-error">, Group<f_clang_Group>,
Alias<fno_sanitize_trap_EQ>, AliasArgs<["undefined"]>;
-def fsanitize_minimal_runtime : Flag<["-"], "fsanitize-minimal-runtime">,
- Group<f_clang_Group>;
-def fno_sanitize_minimal_runtime : Flag<["-"], "fno-sanitize-minimal-runtime">,
- Group<f_clang_Group>;
+defm sanitize_minimal_runtime : BoolOption<"f", "sanitize-minimal-runtime",
+ CodeGenOpts<"SanitizeMinimalRuntime">, DefaultFalse,
+ PosFlag<SetTrue>, NegFlag<SetFalse>>,
+ Group<f_clang_Group>;
def fsanitize_link_runtime : Flag<["-"], "fsanitize-link-runtime">,
Group<f_clang_Group>;
def fno_sanitize_link_runtime : Flag<["-"], "fno-sanitize-link-runtime">,
@@ -1114,55 +1504,51 @@ def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
Group<f_clang_Group>;
def fno_sanitize_link_cxx_runtime : Flag<["-"], "fno-sanitize-link-c++-runtime">,
Group<f_clang_Group>;
-def fsanitize_cfi_cross_dso : Flag<["-"], "fsanitize-cfi-cross-dso">,
- Group<f_clang_Group>,
- HelpText<"Enable control flow integrity (CFI) checks for cross-DSO calls.">;
-def fno_sanitize_cfi_cross_dso : Flag<["-"], "fno-sanitize-cfi-cross-dso">,
- Flags<[CoreOption, DriverOption]>,
- Group<f_clang_Group>,
- HelpText<"Disable control flow integrity (CFI) checks for cross-DSO calls.">;
+defm sanitize_cfi_cross_dso : BoolOption<"f", "sanitize-cfi-cross-dso",
+ CodeGenOpts<"SanitizeCfiCrossDso">, DefaultFalse,
+ PosFlag<SetTrue, [], "Enable">, NegFlag<SetFalse, [CoreOption, NoXarchOption], "Disable">,
+ BothFlags<[], " control flow integrity (CFI) checks for cross-DSO calls.">>,
+ Group<f_clang_Group>;
def fsanitize_cfi_icall_generalize_pointers : Flag<["-"], "fsanitize-cfi-icall-generalize-pointers">,
Group<f_clang_Group>,
- HelpText<"Generalize pointers in CFI indirect call type signature checks">;
-def fsanitize_cfi_canonical_jump_tables : Flag<["-"], "fsanitize-cfi-canonical-jump-tables">,
- Group<f_clang_Group>,
- HelpText<"Make the jump table addresses canonical in the symbol table">;
-def fno_sanitize_cfi_canonical_jump_tables : Flag<["-"], "fno-sanitize-cfi-canonical-jump-tables">,
- Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
- HelpText<"Do not make the jump table addresses canonical in the symbol table">;
-def fsanitize_stats : Flag<["-"], "fsanitize-stats">,
- Group<f_clang_Group>,
- HelpText<"Enable sanitizer statistics gathering.">;
-def fno_sanitize_stats : Flag<["-"], "fno-sanitize-stats">,
- Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
- HelpText<"Disable sanitizer statistics gathering.">;
+ HelpText<"Generalize pointers in CFI indirect call type signature checks">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCfiICallGeneralizePointers">>;
+defm sanitize_cfi_canonical_jump_tables : BoolOption<"f", "sanitize-cfi-canonical-jump-tables",
+ CodeGenOpts<"SanitizeCfiCanonicalJumpTables">, DefaultFalse,
+ PosFlag<SetTrue, [], "Make">, NegFlag<SetFalse, [CoreOption, NoXarchOption], "Do not make">,
+ BothFlags<[], " the jump table addresses canonical in the symbol table">>,
+ Group<f_clang_Group>;
+defm sanitize_stats : BoolOption<"f", "sanitize-stats",
+ CodeGenOpts<"SanitizeStats">, DefaultFalse,
+ PosFlag<SetTrue, [], "Enable">, NegFlag<SetFalse, [CoreOption, NoXarchOption], "Disable">,
+ BothFlags<[], " sanitizer statistics gathering.">>,
+ Group<f_clang_Group>;
def fsanitize_thread_memory_access : Flag<["-"], "fsanitize-thread-memory-access">,
Group<f_clang_Group>,
HelpText<"Enable memory access instrumentation in ThreadSanitizer (default)">;
def fno_sanitize_thread_memory_access : Flag<["-"], "fno-sanitize-thread-memory-access">,
Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable memory access instrumentation in ThreadSanitizer">;
def fsanitize_thread_func_entry_exit : Flag<["-"], "fsanitize-thread-func-entry-exit">,
Group<f_clang_Group>,
HelpText<"Enable function entry/exit instrumentation in ThreadSanitizer (default)">;
def fno_sanitize_thread_func_entry_exit : Flag<["-"], "fno-sanitize-thread-func-entry-exit">,
Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable function entry/exit instrumentation in ThreadSanitizer">;
def fsanitize_thread_atomics : Flag<["-"], "fsanitize-thread-atomics">,
Group<f_clang_Group>,
HelpText<"Enable atomic operations instrumentation in ThreadSanitizer (default)">;
def fno_sanitize_thread_atomics : Flag<["-"], "fno-sanitize-thread-atomics">,
Group<f_clang_Group>,
- Flags<[CoreOption, DriverOption]>,
+ Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable atomic operations instrumentation in ThreadSanitizer">;
def fsanitize_undefined_strip_path_components_EQ : Joined<["-"], "fsanitize-undefined-strip-path-components=">,
Group<f_clang_Group>, MetaVarName<"<number>">,
HelpText<"Strip (or keep only, if negative) a given number of path components "
- "when emitting check metadata.">;
+ "when emitting check metadata.">,
+ MarshallingInfoStringInt<CodeGenOpts<"EmitCheckPathComponentsToStrip">, "0", "int">;
} // end -f[no-]sanitize* flags
@@ -1172,16 +1558,17 @@ def fno_unsafe_math_optimizations : Flag<["-"], "fno-unsafe-math-optimizations">
Group<f_Group>;
def fassociative_math : Flag<["-"], "fassociative-math">, Group<f_Group>;
def fno_associative_math : Flag<["-"], "fno-associative-math">, Group<f_Group>;
-def freciprocal_math :
- Flag<["-"], "freciprocal-math">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Allow division operations to be reassociated">;
-def fno_reciprocal_math : Flag<["-"], "fno-reciprocal-math">, Group<f_Group>;
-def ffinite_math_only : Flag<["-"], "ffinite-math-only">, Group<f_Group>, Flags<[CC1Option]>;
-def fno_finite_math_only : Flag<["-"], "fno-finite-math-only">, Group<f_Group>;
-def fsigned_zeros : Flag<["-"], "fsigned-zeros">, Group<f_Group>;
-def fno_signed_zeros :
- Flag<["-"], "fno-signed-zeros">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Allow optimizations that ignore the sign of floating point zeros">;
+defm reciprocal_math : OptInFFlag<"reciprocal-math", "Allow division operations to be reassociated", "", "", [],
+ LangOpts<"AllowRecip">, [menable_unsafe_fp_math.KeyPath]>;
+def fapprox_func : Flag<["-"], "fapprox-func">, Group<f_Group>, Flags<[CC1Option, NoDriverOption]>,
+ MarshallingInfoFlag<LangOpts<"ApproxFunc">>, ImpliedByAnyOf<[menable_unsafe_fp_math.KeyPath]>;
+defm finite_math_only : OptInFFlag<"finite-math-only", "", "", "", [],
+ LangOpts<"FiniteMathOnly">, [cl_finite_math_only.KeyPath, ffast_math.KeyPath]>;
+defm signed_zeros : BoolFOption<"signed-zeros",
+ LangOpts<"NoSignedZero">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Allow optimizations that ignore the sign of floating point zeros",
+ [cl_no_signed_zeros.KeyPath, menable_unsafe_fp_math.KeyPath]>,
+ PosFlag<SetFalse>>;
def fhonor_nans : Flag<["-"], "fhonor-nans">, Group<f_Group>;
def fno_honor_nans : Flag<["-"], "fno-honor-nans">, Group<f_Group>;
def fhonor_infinities : Flag<["-"], "fhonor-infinities">, Group<f_Group>;
@@ -1189,49 +1576,78 @@ def fno_honor_infinities : Flag<["-"], "fno-honor-infinities">, Group<f_Group>;
// This option was originally misspelt "infinites" [sic].
def : Flag<["-"], "fhonor-infinites">, Alias<fhonor_infinities>;
def : Flag<["-"], "fno-honor-infinites">, Alias<fno_honor_infinities>;
-def frounding_math : Flag<["-"], "frounding-math">, Group<f_Group>, Flags<[CC1Option]>;
+def frounding_math : Flag<["-"], "frounding-math">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"FPRoundingMode">, "llvm::RoundingMode::NearestTiesToEven">,
+ Normalizer<"makeFlagToValueNormalizer(llvm::RoundingMode::Dynamic)">;
def fno_rounding_math : Flag<["-"], "fno-rounding-math">, Group<f_Group>, Flags<[CC1Option]>;
-def ftrapping_math : Flag<["-"], "ftrapping-math">, Group<f_Group>, Flags<[CC1Option]>;
-def fno_trapping_math : Flag<["-"], "fno-trapping-math">, Group<f_Group>, Flags<[CC1Option]>;
+def ftrapping_math : Flag<["-"], "ftrapping-math">, Group<f_Group>;
+def fno_trapping_math : Flag<["-"], "fno-trapping-math">, Group<f_Group>;
def ffp_contract : Joined<["-"], "ffp-contract=">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
- " | on (according to FP_CONTRACT pragma) | off (never fuse). Default"
- " is 'fast' for CUDA/HIP and 'on' otherwise.">, Values<"fast,on,off">;
-
-defm strict_float_cast_overflow : OptOutFFlag<"strict-float-cast-overflow",
- "Assume that overflowing float-to-int casts are undefined (default)",
- "Relax language rules and try to match the behavior of the target's native float-to-int conversion instructions">;
+ Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs):"
+ " fast (fuses across statements disregarding pragmas)"
+ " | on (only fuses in the same statement unless dictated by pragmas)"
+ " | off (never fuses)"
+ " | fast-honor-pragmas (fuses across statements unless diectated by pragmas)."
+ " Default is 'fast' for CUDA, 'fast-honor-pragmas' for HIP, and 'on' otherwise.">,
+ Values<"fast,on,off,fast-honor-pragmas">;
+
+defm strict_float_cast_overflow : BoolFOption<"strict-float-cast-overflow",
+ CodeGenOpts<"StrictFloatCastOverflow">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Relax language rules and try to match the behavior"
+ " of the target's native float-to-int conversion instructions">,
+ PosFlag<SetTrue, [], "Assume that overflowing float-to-int casts are undefined (default)">>;
def ffor_scope : Flag<["-"], "ffor-scope">, Group<f_Group>;
def fno_for_scope : Flag<["-"], "fno-for-scope">, Group<f_Group>;
-defm rewrite_imports : OptInFFlag<"rewrite-imports", "">;
-defm rewrite_includes : OptInFFlag<"rewrite-includes", "">;
+defm rewrite_imports : BoolFOption<"rewrite-imports",
+ PreprocessorOutputOpts<"RewriteImports">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>>;
+defm rewrite_includes : BoolFOption<"rewrite-includes",
+ PreprocessorOutputOpts<"RewriteIncludes">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>>;
-defm delete_null_pointer_checks : OptOutFFlag<"delete-null-pointer-checks",
- "Treat usage of null pointers as undefined behavior (default)",
- "Do not treat usage of null pointers as undefined behavior">;
+defm delete_null_pointer_checks : BoolFOption<"delete-null-pointer-checks",
+ CodeGenOpts<"NullPointerIsValid">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Do not treat usage of null pointers as undefined behavior">,
+ PosFlag<SetFalse, [], "Treat usage of null pointers as undefined behavior (default)">,
+ BothFlags<[CoreOption]>>;
def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
Group<f_Group>,
- Flags<[ DriverOption, CC1Option ]>;
+ Flags<[ NoXarchOption, CC1Option ]>,
+ MarshallingInfoStringVector<CodeGenOpts<"RewriteMapFiles">>;
def frewrite_map_file_EQ : Joined<["-"], "frewrite-map-file=">,
Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
-defm use_line_directives : OptInFFlag<"use-line-directives", "Use #line in preprocessed output">;
+defm use_line_directives : BoolFOption<"use-line-directives",
+ PreprocessorOutputOpts<"UseLineDirectives">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use #line in preprocessed output">, NegFlag<SetFalse>>;
def ffreestanding : Flag<["-"], "ffreestanding">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Assert that the compilation takes place in a freestanding environment">;
+ HelpText<"Assert that the compilation takes place in a freestanding environment">,
+ MarshallingInfoFlag<LangOpts<"Freestanding">>;
def fgnuc_version_EQ : Joined<["-"], "fgnuc-version=">, Group<f_Group>,
HelpText<"Sets various macros to claim compatibility with the given GCC version (default is 4.2.1)">,
Flags<[CC1Option, CoreOption]>;
-def fgnu_keywords : Flag<["-"], "fgnu-keywords">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Allow GNU-extension keywords regardless of language standard">;
-defm gnu89_inline : OptInFFlag<"gnu89-inline", "Use the gnu89 inline semantics">;
+// We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
+// keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
+// while a subset (the non-C++ GNU keywords) is provided by GCC's
+// '-fgnu-keywords'. Clang conflates the two for simplicity under the single
+// name, as it doesn't seem a useful distinction.
+defm gnu_keywords : BoolFOption<"gnu-keywords",
+ LangOpts<"GNUKeywords">, Default<gnu_mode.KeyPath>,
+ PosFlag<SetTrue, [], "Allow GNU-extension keywords regardless of language standard">,
+ NegFlag<SetFalse>, BothFlags<[CC1Option]>>;
+defm gnu89_inline : BoolFOption<"gnu89-inline",
+ LangOpts<"GNUInline">, Default<!strconcat("!", c99.KeyPath, " && !", cplusplus.KeyPath)>,
+ PosFlag<SetTrue, [CC1Option], "Use the gnu89 inline semantics">,
+ NegFlag<SetFalse>>, ShouldParseIf<!strconcat("!", cplusplus.KeyPath)>;
def fgnu_runtime : Flag<["-"], "fgnu-runtime">, Group<f_Group>,
HelpText<"Generate output compatible with the standard GNU Objective-C runtime">;
-def fheinous_gnu_extensions : Flag<["-"], "fheinous-gnu-extensions">, Flags<[CC1Option]>;
+def fheinous_gnu_extensions : Flag<["-"], "fheinous-gnu-extensions">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"HeinousExtensions">>;
def filelist : Separate<["-"], "filelist">, Flags<[LinkerInput]>,
Group<Link_Group>;
def : Flag<["-"], "findirect-virtual-calls">, Alias<fapple_kext>;
@@ -1240,36 +1656,47 @@ def finline_functions : Flag<["-"], "finline-functions">, Group<f_clang_Group>,
def finline_hint_functions: Flag<["-"], "finline-hint-functions">, Group<f_clang_Group>, Flags<[CC1Option]>,
HelpText<"Inline functions which are (explicitly or implicitly) marked inline">;
def finline : Flag<["-"], "finline">, Group<clang_ignored_f_Group>;
-def fglobal_isel : Flag<["-"], "fglobal-isel">, Group<f_clang_Group>,
+def fglobal_isel : Flag<["-"], "fglobal-isel">, Group<f_clang_Group>,
HelpText<"Enables the global instruction selector">;
def fexperimental_isel : Flag<["-"], "fexperimental-isel">, Group<f_clang_Group>,
Alias<fglobal_isel>;
+defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
+ CodeGenOpts<"LegacyPassManager">, Default<"!static_cast<unsigned>(LLVM_ENABLE_NEW_PASS_MANAGER)">,
+ PosFlag<SetTrue, [], "Use the legacy pass manager in LLVM">,
+ NegFlag<SetFalse, [], "Use the new pass manager in LLVM">,
+ BothFlags<[CC1Option]>>, Group<f_clang_Group>;
def fexperimental_new_pass_manager : Flag<["-"], "fexperimental-new-pass-manager">,
- Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Enables an experimental new pass manager in LLVM.">;
+ Group<f_clang_Group>, Flags<[CC1Option]>, Alias<fno_legacy_pass_manager>;
+def fno_experimental_new_pass_manager : Flag<["-"], "fno-experimental-new-pass-manager">,
+ Group<f_clang_Group>, Flags<[CC1Option]>, Alias<flegacy_pass_manager>;
def fexperimental_strict_floating_point : Flag<["-"], "fexperimental-strict-floating-point">,
Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Enables experimental strict floating point in LLVM.">;
+ HelpText<"Enables experimental strict floating point in LLVM.">,
+ MarshallingInfoFlag<LangOpts<"ExpStrictFP">>;
def finput_charset_EQ : Joined<["-"], "finput-charset=">, Group<f_Group>;
def fexec_charset_EQ : Joined<["-"], "fexec-charset=">, Group<f_Group>;
def finstrument_functions : Flag<["-"], "finstrument-functions">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Generate calls to instrument function entry and exit">;
+ HelpText<"Generate calls to instrument function entry and exit">,
+ MarshallingInfoFlag<CodeGenOpts<"InstrumentFunctions">>;
def finstrument_functions_after_inlining : Flag<["-"], "finstrument-functions-after-inlining">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Like -finstrument-functions, but insert the calls after inlining">;
+ HelpText<"Like -finstrument-functions, but insert the calls after inlining">,
+ MarshallingInfoFlag<CodeGenOpts<"InstrumentFunctionsAfterInlining">>;
def finstrument_function_entry_bare : Flag<["-"], "finstrument-function-entry-bare">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Instrument function entry only, after inlining, without arguments to the instrumentation call">;
+ HelpText<"Instrument function entry only, after inlining, without arguments to the instrumentation call">,
+ MarshallingInfoFlag<CodeGenOpts<"InstrumentFunctionEntryBare">>;
def fcf_protection_EQ : Joined<["-"], "fcf-protection=">, Flags<[CoreOption, CC1Option]>, Group<f_Group>,
HelpText<"Instrument control-flow architecture protection. Options: return, branch, full, none.">, Values<"return,branch,full,none">;
def fcf_protection : Flag<["-"], "fcf-protection">, Group<f_Group>, Flags<[CoreOption, CC1Option]>,
Alias<fcf_protection_EQ>, AliasArgs<["full"]>,
HelpText<"Enable cf-protection in 'full' mode">;
-defm xray_instrument : OptInFFlag<"xray-instrument", "Generate XRay instrumentation sleds on function entry and exit">;
+defm xray_instrument : OptInFFlag<"xray-instrument", "Generate XRay instrumentation sleds on function entry and exit", "", "", [], LangOpts<"XRayInstrument">>;
def fxray_instruction_threshold_EQ :
JoinedOrSeparate<["-"], "fxray-instruction-threshold=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Sets the minimum function size to instrument with XRay">;
+ HelpText<"Sets the minimum function size to instrument with XRay">,
+ MarshallingInfoStringInt<CodeGenOpts<"XRayInstructionThreshold">, "200">;
def fxray_instruction_threshold_ :
JoinedOrSeparate<["-"], "fxray-instruction-threshold">,
Group<f_Group>, Flags<[CC1Option]>;
@@ -1277,30 +1704,33 @@ def fxray_instruction_threshold_ :
def fxray_always_instrument :
JoinedOrSeparate<["-"], "fxray-always-instrument=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"DEPRECATED: Filename defining the whitelist for imbuing the 'always instrument' XRay attribute.">;
+ HelpText<"DEPRECATED: Filename defining the whitelist for imbuing the 'always instrument' XRay attribute.">,
+ MarshallingInfoStringVector<LangOpts<"XRayAlwaysInstrumentFiles">>;
def fxray_never_instrument :
JoinedOrSeparate<["-"], "fxray-never-instrument=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"DEPRECATED: Filename defining the whitelist for imbuing the 'never instrument' XRay attribute.">;
+ HelpText<"DEPRECATED: Filename defining the whitelist for imbuing the 'never instrument' XRay attribute.">,
+ MarshallingInfoStringVector<LangOpts<"XRayNeverInstrumentFiles">>;
def fxray_attr_list :
JoinedOrSeparate<["-"], "fxray-attr-list=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Filename defining the list of functions/types for imbuing XRay attributes.">;
+ HelpText<"Filename defining the list of functions/types for imbuing XRay attributes.">,
+ MarshallingInfoStringVector<LangOpts<"XRayAttrListFiles">>;
def fxray_modes :
JoinedOrSeparate<["-"], "fxray-modes=">,
Group<f_Group>, Flags<[CC1Option]>,
HelpText<"List of modes to link in by default into XRay instrumented binaries.">;
defm xray_always_emit_customevents : OptInFFlag<"xray-always-emit-customevents",
- "Always emit __xray_customevent(...) calls even if the containing function is not always instrumented">;
+ "Always emit __xray_customevent(...) calls even if the containing function is not always instrumented", "", "", [], LangOpts<"XRayAlwaysEmitCustomEvents">>;
defm xray_always_emit_typedevents : OptInFFlag<"xray-always-emit-typedevents",
- "Always emit __xray_typedevent(...) calls even if the containing function is not always instrumented">;
+ "Always emit __xray_typedevent(...) calls even if the containing function is not always instrumented", "", "", [], LangOpts<"XRayAlwaysEmitTypedEvents">>;
defm xray_ignore_loops : OptInFFlag<"xray-ignore-loops",
- "Don't instrument functions with loops unless they also meet the minimum function size">;
+ "Don't instrument functions with loops unless they also meet the minimum function size", "", "", [], CodeGenOpts<"XRayIgnoreLoops">>;
defm xray_function_index : OptOutFFlag<"xray-function-index", "",
- "Omit function index section at the expense of single-function patching performance">;
+ "Omit function index section at the expense of single-function patching performance", "", [], CodeGenOpts<"XRayOmitFunctionIndex">>;
def fxray_link_deps : Flag<["-"], "fxray-link-deps">, Group<f_Group>,
Flags<[CC1Option]>,
@@ -1313,23 +1743,41 @@ def fxray_instrumentation_bundle :
Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Select which XRay instrumentation points to emit. Options: all, none, function-entry, function-exit, function, custom. Default is 'all'. 'function' includes both 'function-entry' and 'function-exit'.">;
-def ffine_grained_bitfield_accesses : Flag<["-"],
- "ffine-grained-bitfield-accesses">, Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Use separate accesses for consecutive bitfield runs with legal widths and alignments.">;
-def fno_fine_grained_bitfield_accesses : Flag<["-"],
- "fno-fine-grained-bitfield-accesses">, Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Use large-integer access for consecutive bitfield runs.">;
-
-def fexperimental_relative_cxx_abi_vtables : Flag<["-"], "fexperimental-relative-c++-abi-vtables">,
+def fxray_function_groups :
+ Joined<["-"], "fxray-function-groups=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use the experimental C++ class ABI for classes with virtual tables">;
-def fno_experimental_relative_cxx_abi_vtables : Flag<["-"], "fno-experimental-relative-c++-abi-vtables">,
+ HelpText<"Only instrument 1 of N groups">,
+ MarshallingInfoStringInt<CodeGenOpts<"XRayTotalFunctionGroups">, "1">;
+
+def fxray_selected_function_group :
+ Joined<["-"], "fxray-selected-function-group=">,
Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Do not use the experimental C++ class ABI for classes with virtual tables">;
+ HelpText<"When using -fxray-function-groups, select which group of functions to instrument. Valid range is 0 to fxray-function-groups - 1">,
+ MarshallingInfoStringInt<CodeGenOpts<"XRaySelectedFunctionGroup">, "0">;
+
+
+defm fine_grained_bitfield_accesses : BoolOption<"f", "fine-grained-bitfield-accesses",
+ CodeGenOpts<"FineGrainedBitfieldAccesses">, DefaultFalse,
+ PosFlag<SetTrue, [], "Use separate accesses for consecutive bitfield runs with legal widths and alignments.">,
+ NegFlag<SetFalse, [], "Use large-integer access for consecutive bitfield runs.">,
+ BothFlags<[CC1Option]>>,
+ Group<f_clang_Group>;
+
+defm experimental_relative_cxx_abi_vtables : BoolFOption<"experimental-relative-c++-abi-vtables",
+ LangOpts<"RelativeCXXABIVTables">, DefaultFalse,
+ PosFlag<SetTrue, [], "Use">, NegFlag<SetFalse, [], "Do not use">,
+ BothFlags<[CC1Option], " the experimental C++ class ABI for classes with virtual tables">>;
def flat__namespace : Flag<["-"], "flat_namespace">;
def flax_vector_conversions_EQ : Joined<["-"], "flax-vector-conversions=">, Group<f_Group>,
- HelpText<"Enable implicit vector bit-casts">, Values<"none,integer,all">, Flags<[CC1Option]>;
+ HelpText<"Enable implicit vector bit-casts">, Values<"none,integer,all">, Flags<[CC1Option]>,
+ NormalizedValues<["LangOptions::LaxVectorConversionKind::None",
+ "LangOptions::LaxVectorConversionKind::Integer",
+ "LangOptions::LaxVectorConversionKind::All"]>,
+ MarshallingInfoString<LangOpts<"LaxVectorConversions">,
+ !strconcat(open_cl.KeyPath, " ? LangOptions::LaxVectorConversionKind::None"
+ " : LangOptions::LaxVectorConversionKind::All")>,
+ AutoNormalizeEnum;
def flax_vector_conversions : Flag<["-"], "flax-vector-conversions">, Group<f_Group>,
Alias<flax_vector_conversions_EQ>, AliasArgs<["integer"]>;
def flimited_precision_EQ : Joined<["-"], "flimited-precision=">, Group<f_Group>;
@@ -1339,7 +1787,7 @@ def flto_EQ : Joined<["-"], "flto=">, Flags<[CoreOption, CC1Option]>, Group<f_Gr
HelpText<"Set LTO mode to either 'full' or 'thin'">, Values<"thin,full">;
def flto : Flag<["-"], "flto">, Flags<[CoreOption, CC1Option]>, Group<f_Group>,
HelpText<"Enable LTO in 'full' mode">;
-def fno_lto : Flag<["-"], "fno-lto">, Group<f_Group>,
+def fno_lto : Flag<["-"], "fno-lto">, Flags<[CoreOption, CC1Option]>, Group<f_Group>,
HelpText<"Disable LTO mode (default)">;
def flto_jobs_EQ : Joined<["-"], "flto-jobs=">,
Flags<[CC1Option]>, Group<f_Group>,
@@ -1351,19 +1799,25 @@ def fthinlto_index_EQ : Joined<["-"], "fthinlto-index=">,
HelpText<"Perform ThinLTO importing using provided function summary index">;
def fthin_link_bitcode_EQ : Joined<["-"], "fthin-link-bitcode=">,
Flags<[CoreOption, CC1Option]>, Group<f_Group>,
- HelpText<"Write minimized bitcode to <file> for the ThinLTO thin link only">;
+ HelpText<"Write minimized bitcode to <file> for the ThinLTO thin link only">,
+ MarshallingInfoString<CodeGenOpts<"ThinLinkBitcodeFile">>;
def fmacro_backtrace_limit_EQ : Joined<["-"], "fmacro-backtrace-limit=">,
- Group<f_Group>, Flags<[DriverOption, CoreOption]>;
-def fmerge_all_constants : Flag<["-"], "fmerge-all-constants">, Group<f_Group>,
- Flags<[CC1Option, CoreOption]>, HelpText<"Allow merging of constants">;
+ Group<f_Group>, Flags<[NoXarchOption, CoreOption]>;
+defm merge_all_constants : BoolFOption<"merge-all-constants",
+ CodeGenOpts<"MergeAllConstants">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option, CoreOption], "Allow">, NegFlag<SetFalse, [], "Disallow">,
+ BothFlags<[], " merging of constants">>;
def fmessage_length_EQ : Joined<["-"], "fmessage-length=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Format message diagnostics so that they fit within N columns">;
+ HelpText<"Format message diagnostics so that they fit within N columns">,
+ MarshallingInfoStringInt<DiagnosticOpts<"MessageLength">>;
def fms_extensions : Flag<["-"], "fms-extensions">, Group<f_Group>, Flags<[CC1Option, CoreOption]>,
HelpText<"Accept some non-standard constructs supported by the Microsoft compiler">;
def fms_compatibility : Flag<["-"], "fms-compatibility">, Group<f_Group>, Flags<[CC1Option, CoreOption]>,
- HelpText<"Enable full Microsoft Visual C++ compatibility">;
-def fms_volatile : Flag<["-"], "fms-volatile">, Group<f_Group>, Flags<[CC1Option]>;
-def fmsc_version : Joined<["-"], "fmsc-version=">, Group<f_Group>, Flags<[DriverOption, CoreOption]>,
+ HelpText<"Enable full Microsoft Visual C++ compatibility">,
+ MarshallingInfoFlag<LangOpts<"MSVCCompat">>;
+def fms_volatile : Flag<["-"], "fms-volatile">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<CodeGenOpts<"MSVolatile">>;
+def fmsc_version : Joined<["-"], "fmsc-version=">, Group<f_Group>, Flags<[NoXarchOption, CoreOption]>,
HelpText<"Microsoft compiler version number to report in _MSC_VER (0 = don't define it (default))">;
def fms_compatibility_version
: Joined<["-"], "fms-compatibility-version=">,
@@ -1372,269 +1826,263 @@ def fms_compatibility_version
HelpText<"Dot-separated value representing the Microsoft compiler "
"version number to report in _MSC_VER (0 = don't define it "
"(default))">;
-def fdelayed_template_parsing : Flag<["-"], "fdelayed-template-parsing">, Group<f_Group>,
- HelpText<"Parse templated function definitions at the end of the "
- "translation unit">, Flags<[CC1Option, CoreOption]>;
-def fms_memptr_rep_EQ : Joined<["-"], "fms-memptr-rep=">, Group<f_Group>, Flags<[CC1Option]>;
+defm delayed_template_parsing : BoolFOption<"delayed-template-parsing",
+ LangOpts<"DelayedTemplateParsing">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Parse templated function definitions at the end of the translation unit">,
+ NegFlag<SetFalse, [NoXarchOption], "Disable delayed template parsing">,
+ BothFlags<[CoreOption]>>;
+def fms_memptr_rep_EQ : Joined<["-"], "fms-memptr-rep=">, Group<f_Group>, Flags<[CC1Option]>,
+ Values<"single,multiple,virtual">, NormalizedValuesScope<"LangOptions">,
+ NormalizedValues<["PPTMK_FullGeneralitySingleInheritance", "PPTMK_FullGeneralityMultipleInheritance",
+ "PPTMK_FullGeneralityVirtualInheritance"]>,
+ MarshallingInfoString<LangOpts<"MSPointerToMemberRepresentationMethod">, "PPTMK_BestCase">,
+ AutoNormalizeEnum;
def fmodules_cache_path : Joined<["-"], "fmodules-cache-path=">, Group<i_Group>,
- Flags<[DriverOption, CC1Option]>, MetaVarName<"<directory>">,
+ Flags<[NoXarchOption, CC1Option]>, MetaVarName<"<directory>">,
HelpText<"Specify the module cache path">;
def fmodules_user_build_path : Separate<["-"], "fmodules-user-build-path">, Group<i_Group>,
- Flags<[DriverOption, CC1Option]>, MetaVarName<"<directory>">,
- HelpText<"Specify the module user build path">;
+ Flags<[NoXarchOption, CC1Option]>, MetaVarName<"<directory>">,
+ HelpText<"Specify the module user build path">,
+ MarshallingInfoString<HeaderSearchOpts<"ModuleUserBuildPath">>;
def fprebuilt_module_path : Joined<["-"], "fprebuilt-module-path=">, Group<i_Group>,
- Flags<[DriverOption, CC1Option]>, MetaVarName<"<directory>">,
+ Flags<[NoXarchOption, CC1Option]>, MetaVarName<"<directory>">,
HelpText<"Specify the prebuilt module path">;
+defm prebuilt_implicit_modules : OptInFFlag<"prebuilt-implicit-modules",
+ "Look up implicit modules in the prebuilt module path", "", "",
+ [NoXarchOption, CC1Option], HeaderSearchOpts<"EnablePrebuiltImplicitModules">>;
def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, Group<i_Group>,
Flags<[CC1Option]>, MetaVarName<"<seconds>">,
- HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">;
+ HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">,
+ MarshallingInfoStringInt<HeaderSearchOpts<"ModuleCachePruneInterval">, "7 * 24 * 60 * 60">;
def fmodules_prune_after : Joined<["-"], "fmodules-prune-after=">, Group<i_Group>,
Flags<[CC1Option]>, MetaVarName<"<seconds>">,
- HelpText<"Specify the interval (in seconds) after which a module file will be considered unused">;
+ HelpText<"Specify the interval (in seconds) after which a module file will be considered unused">,
+ MarshallingInfoStringInt<HeaderSearchOpts<"ModuleCachePruneAfter">, "31 * 24 * 60 * 60">;
def fmodules_search_all : Flag <["-"], "fmodules-search-all">, Group<f_Group>,
- Flags<[DriverOption, CC1Option]>,
+ Flags<[NoXarchOption, CC1Option]>,
HelpText<"Search even non-imported modules to resolve references">;
def fbuild_session_timestamp : Joined<["-"], "fbuild-session-timestamp=">,
Group<i_Group>, Flags<[CC1Option]>, MetaVarName<"<time since Epoch in seconds>">,
- HelpText<"Time when the current build session started">;
+ HelpText<"Time when the current build session started">,
+ MarshallingInfoStringInt<HeaderSearchOpts<"BuildSessionTimestamp">, "0", "uint64_t">;
def fbuild_session_file : Joined<["-"], "fbuild-session-file=">,
Group<i_Group>, MetaVarName<"<file>">,
HelpText<"Use the last modification time of <file> as the build session timestamp">;
def fmodules_validate_once_per_build_session : Flag<["-"], "fmodules-validate-once-per-build-session">,
Group<i_Group>, Flags<[CC1Option]>,
HelpText<"Don't verify input files for the modules if the module has been "
- "successfully validated or loaded during this build session">;
+ "successfully validated or loaded during this build session">,
+ MarshallingInfoFlag<HeaderSearchOpts<"ModulesValidateOncePerBuildSession">>;
def fmodules_disable_diagnostic_validation : Flag<["-"], "fmodules-disable-diagnostic-validation">,
Group<i_Group>, Flags<[CC1Option]>,
- HelpText<"Disable validation of the diagnostic options when loading the module">;
-def fmodules_validate_system_headers : Flag<["-"], "fmodules-validate-system-headers">,
- Group<i_Group>, Flags<[CC1Option]>,
- HelpText<"Validate the system headers that a module depends on when loading the module">;
-def fno_modules_validate_system_headers : Flag<["-"], "fno-modules-validate-system-headers">,
- Group<i_Group>, Flags<[DriverOption]>;
+ HelpText<"Disable validation of the diagnostic options when loading the module">,
+ MarshallingInfoNegativeFlag<HeaderSearchOpts<"ModulesValidateDiagnosticOptions">>;
+defm modules_validate_system_headers : BoolOption<"f", "modules-validate-system-headers",
+ HeaderSearchOpts<"ModulesValidateSystemHeaders">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Validate the system headers that a module depends on when loading the module">,
+ NegFlag<SetFalse, [NoXarchOption]>>, Group<i_Group>;
def fvalidate_ast_input_files_content:
Flag <["-"], "fvalidate-ast-input-files-content">,
Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Compute and store the hash of input files used to build an AST."
" Files with mismatching mtime's are considered valid"
- " if both contents is identical">;
+ " if both contents is identical">,
+ MarshallingInfoFlag<HeaderSearchOpts<"ValidateASTInputFilesContent">>;
def fmodules_validate_input_files_content:
Flag <["-"], "fmodules-validate-input-files-content">,
- Group<f_Group>, Flags<[DriverOption]>,
+ Group<f_Group>, Flags<[NoXarchOption]>,
HelpText<"Validate PCM input files based on content if mtime differs">;
def fno_modules_validate_input_files_content:
Flag <["-"], "fno_modules-validate-input-files-content">,
- Group<f_Group>, Flags<[DriverOption]>;
+ Group<f_Group>, Flags<[NoXarchOption]>;
def fpch_validate_input_files_content:
Flag <["-"], "fpch-validate-input-files-content">,
- Group<f_Group>, Flags<[DriverOption]>,
+ Group<f_Group>, Flags<[NoXarchOption]>,
HelpText<"Validate PCH input files based on content if mtime differs">;
def fno_pch_validate_input_files_content:
Flag <["-"], "fno_pch-validate-input-files-content">,
- Group<f_Group>, Flags<[DriverOption]>;
-def fpch_instantiate_templates:
- Flag <["-"], "fpch-instantiate-templates">,
- Group<f_Group>, Flags<[CC1Option, CoreOption]>,
- HelpText<"Instantiate templates already while building a PCH">;
-def fno_pch_instantiate_templates:
- Flag <["-"], "fno-pch-instantiate-templates">,
- Group<f_Group>, Flags<[CC1Option, CoreOption]>;
+ Group<f_Group>, Flags<[NoXarchOption]>;
+defm pch_instantiate_templates : BoolFOption<"pch-instantiate-templates",
+ LangOpts<"PCHInstantiateTemplates">, DefaultFalse,
+ PosFlag<SetTrue, [], "Instantiate templates already while building a PCH">,
+ NegFlag<SetFalse>, BothFlags<[CC1Option, CoreOption]>>;
defm pch_codegen: OptInFFlag<"pch-codegen", "Generate ", "Do not generate ",
"code for uses of this PCH that assumes an explicit object file will be built for the PCH">;
defm pch_debuginfo: OptInFFlag<"pch-debuginfo", "Generate ", "Do not generate ",
"debug info for types in an object file built from this PCH and do not generate them elsewhere">;
def fmodules : Flag <["-"], "fmodules">, Group<f_Group>,
- Flags<[DriverOption, CC1Option]>,
+ Flags<[NoXarchOption, CC1Option]>,
HelpText<"Enable the 'modules' language feature">;
def fimplicit_module_maps : Flag <["-"], "fimplicit-module-maps">, Group<f_Group>,
- Flags<[DriverOption, CC1Option]>,
- HelpText<"Implicitly search the file system for module map files.">;
+ Flags<[NoXarchOption, CC1Option]>,
+ HelpText<"Implicitly search the file system for module map files.">,
+ MarshallingInfoFlag<HeaderSearchOpts<"ImplicitModuleMaps">>;
def fmodules_ts : Flag <["-"], "fmodules-ts">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Enable support for the C++ Modules TS">;
+ Flags<[CC1Option]>, HelpText<"Enable support for the C++ Modules TS">,
+ MarshallingInfoFlag<LangOpts<"ModulesTS">>;
def fmodule_maps : Flag <["-"], "fmodule-maps">, Alias<fimplicit_module_maps>;
def fmodule_name_EQ : Joined<["-"], "fmodule-name=">, Group<f_Group>,
- Flags<[DriverOption,CC1Option]>, MetaVarName<"<name>">,
- HelpText<"Specify the name of the module to build">;
+ Flags<[NoXarchOption,CC1Option]>, MetaVarName<"<name>">,
+ HelpText<"Specify the name of the module to build">,
+ MarshallingInfoString<LangOpts<"ModuleName">>;
def fmodule_name : Separate<["-"], "fmodule-name">, Alias<fmodule_name_EQ>;
def fmodule_implementation_of : Separate<["-"], "fmodule-implementation-of">,
Flags<[CC1Option]>, Alias<fmodule_name_EQ>;
def fsystem_module : Flag<["-"], "fsystem-module">, Flags<[CC1Option]>,
- HelpText<"Build this module as a system module. Only used with -emit-module">;
+ HelpText<"Build this module as a system module. Only used with -emit-module">,
+ MarshallingInfoFlag<FrontendOpts<"IsSystemModule">>;
def fmodule_map_file : Joined<["-"], "fmodule-map-file=">,
- Group<f_Group>, Flags<[DriverOption,CC1Option]>, MetaVarName<"<file>">,
- HelpText<"Load this module map file">;
+ Group<f_Group>, Flags<[NoXarchOption,CC1Option]>, MetaVarName<"<file>">,
+ HelpText<"Load this module map file">,
+ MarshallingInfoStringVector<FrontendOpts<"ModuleMapFiles">>;
def fmodule_file : Joined<["-"], "fmodule-file=">,
- Group<i_Group>, Flags<[DriverOption,CC1Option]>, MetaVarName<"[<name>=]<file>">,
+ Group<i_Group>, Flags<[NoXarchOption,CC1Option]>, MetaVarName<"[<name>=]<file>">,
HelpText<"Specify the mapping of module name to precompiled module file, or load a module file if name is omitted.">;
def fmodules_ignore_macro : Joined<["-"], "fmodules-ignore-macro=">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Ignore the definition of the given macro when building and loading modules">;
def fmodules_decluse : Flag <["-"], "fmodules-decluse">, Group<f_Group>,
- Flags<[DriverOption,CC1Option]>,
+ Flags<[NoXarchOption,CC1Option]>,
HelpText<"Require declaration of modules used within a module">;
def fmodules_strict_decluse : Flag <["-"], "fmodules-strict-decluse">, Group<f_Group>,
- Flags<[DriverOption,CC1Option]>,
- HelpText<"Like -fmodules-decluse but requires all headers to be in modules">;
+ Flags<[NoXarchOption,CC1Option]>,
+ HelpText<"Like -fmodules-decluse but requires all headers to be in modules">,
+ MarshallingInfoFlag<LangOpts<"ModulesStrictDeclUse">>;
def fno_modules_search_all : Flag <["-"], "fno-modules-search-all">, Group<f_Group>,
- Flags<[DriverOption, CC1Option]>;
-def fno_implicit_modules :
- Flag <["-"], "fno-implicit-modules">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>;
-def fretain_comments_from_system_headers : Flag<["-"], "fretain-comments-from-system-headers">, Group<f_Group>, Flags<[CC1Option]>;
+ Flags<[NoXarchOption, CC1Option]>;
+defm implicit_modules : BoolFOption<"implicit-modules",
+ LangOpts<"ImplicitModules">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>, PosFlag<SetTrue>, BothFlags<[NoXarchOption]>>;
+def fretain_comments_from_system_headers : Flag<["-"], "fretain-comments-from-system-headers">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"RetainCommentsFromSystemHeaders">>;
def fmudflapth : Flag<["-"], "fmudflapth">, Group<f_Group>;
def fmudflap : Flag<["-"], "fmudflap">, Group<f_Group>;
def fnested_functions : Flag<["-"], "fnested-functions">, Group<f_Group>;
def fnext_runtime : Flag<["-"], "fnext-runtime">, Group<f_Group>;
-def fno_apple_pragma_pack : Flag<["-"], "fno-apple-pragma-pack">, Group<f_Group>;
+def fno_xl_pragma_pack : Flag<["-"], "fno-xl-pragma-pack">, Group<f_Group>;
def fno_asm : Flag<["-"], "fno-asm">, Group<f_Group>;
def fno_asynchronous_unwind_tables : Flag<["-"], "fno-asynchronous-unwind-tables">, Group<f_Group>;
def fno_assume_sane_operator_new : Flag<["-"], "fno-assume-sane-operator-new">, Group<f_Group>,
HelpText<"Don't assume that C++'s global operator new can't alias any pointer">,
- Flags<[CC1Option]>;
-def fno_borland_extensions : Flag<["-"], "fno-borland-extensions">, Group<f_Group>;
+ Flags<[CC1Option]>, MarshallingInfoNegativeFlag<CodeGenOpts<"AssumeSaneOperatorNew">>;
def fno_builtin : Flag<["-"], "fno-builtin">, Group<f_Group>, Flags<[CC1Option, CoreOption]>,
HelpText<"Disable implicit builtin knowledge of functions">;
def fno_builtin_ : Joined<["-"], "fno-builtin-">, Group<f_Group>, Flags<[CC1Option, CoreOption]>,
HelpText<"Disable implicit builtin knowledge of a specific function">;
def fno_diagnostics_color : Flag<["-"], "fno-diagnostics-color">, Group<f_Group>,
- Flags<[CoreOption, DriverOption]>;
+ Flags<[CoreOption, NoXarchOption]>;
def fno_common : Flag<["-"], "fno-common">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Compile common globals like normal definitions">;
-def fno_constant_cfstrings : Flag<["-"], "fno-constant-cfstrings">, Group<f_Group>,
- Flags<[CC1Option]>,
- HelpText<"Disable creation of CodeFoundation-type constant strings">;
def fno_cxx_modules : Flag <["-"], "fno-cxx-modules">, Group<f_Group>,
- Flags<[DriverOption]>;
-def fno_diagnostics_fixit_info : Flag<["-"], "fno-diagnostics-fixit-info">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Do not include fixit information in diagnostics">;
-def fno_diagnostics_show_hotness : Flag<["-"], "fno-diagnostics-show-hotness">, Group<f_Group>;
-def fno_diagnostics_show_option : Flag<["-"], "fno-diagnostics-show-option">, Group<f_Group>, Flags<[CC1Option]>;
-def fno_diagnostics_show_note_include_stack : Flag<["-"], "fno-diagnostics-show-note-include-stack">,
- Flags<[CC1Option]>, Group<f_Group>;
-def fdigraphs : Flag<["-"], "fdigraphs">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Enable alternative token representations '<:', ':>', '<%', '%>', '%:', '%:%:' (default)">;
-def fno_digraphs : Flag<["-"], "fno-digraphs">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Disallow alternative token representations '<:', ':>', '<%', '%>', '%:', '%:%:'">;
+ Flags<[NoXarchOption]>;
+defm digraphs : BoolFOption<"digraphs",
+ LangOpts<"Digraphs">, Default<std#".hasDigraphs()">,
+ PosFlag<SetTrue, [], "Enable alternative token representations '<:', ':>', '<%', '%>', '%:', '%:%:' (default)">,
+ NegFlag<SetFalse, [], "Disallow alternative token representations '<:', ':>', '<%', '%>', '%:', '%:%:'">,
+ BothFlags<[CC1Option]>>;
def fno_declspec : Flag<["-"], "fno-declspec">, Group<f_clang_Group>,
HelpText<"Disallow __declspec as a keyword">, Flags<[CC1Option]>;
def fno_dollars_in_identifiers : Flag<["-"], "fno-dollars-in-identifiers">, Group<f_Group>,
HelpText<"Disallow '$' in identifiers">, Flags<[CC1Option]>;
-def fno_elide_constructors : Flag<["-"], "fno-elide-constructors">, Group<f_Group>,
- HelpText<"Disable C++ copy constructor elision">, Flags<[CC1Option]>;
def fno_eliminate_unused_debug_symbols : Flag<["-"], "fno-eliminate-unused-debug-symbols">, Group<f_Group>;
-def fno_gnu_keywords : Flag<["-"], "fno-gnu-keywords">, Group<f_Group>, Flags<[CC1Option]>;
def fno_inline_functions : Flag<["-"], "fno-inline-functions">, Group<f_clang_Group>, Flags<[CC1Option]>;
def fno_inline : Flag<["-"], "fno-inline">, Group<f_clang_Group>, Flags<[CC1Option]>;
def fno_global_isel : Flag<["-"], "fno-global-isel">, Group<f_clang_Group>,
HelpText<"Disables the global instruction selector">;
def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, Group<f_clang_Group>,
Alias<fno_global_isel>;
-def fno_experimental_new_pass_manager : Flag<["-"], "fno-experimental-new-pass-manager">,
- Group<f_clang_Group>, Flags<[CC1Option]>,
- HelpText<"Disables an experimental new pass manager in LLVM.">;
def fveclib : Joined<["-"], "fveclib=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use the given vector functions library">, Values<"Accelerate,MASSV,SVML,none">;
+ HelpText<"Use the given vector functions library">,
+ Values<"Accelerate,libmvec,MASSV,SVML,none">,
+ NormalizedValuesScope<"CodeGenOptions">,
+ NormalizedValues<["Accelerate", "LIBMVEC", "MASSV", "SVML", "NoLibrary"]>,
+ MarshallingInfoString<CodeGenOpts<"VecLib">, "NoLibrary">, AutoNormalizeEnum;
def fno_lax_vector_conversions : Flag<["-"], "fno-lax-vector-conversions">, Group<f_Group>,
Alias<flax_vector_conversions_EQ>, AliasArgs<["none"]>;
-def fno_merge_all_constants : Flag<["-"], "fno-merge-all-constants">, Group<f_Group>,
- HelpText<"Disallow merging of constants">;
def fno_modules : Flag <["-"], "fno-modules">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fno_implicit_module_maps : Flag <["-"], "fno-implicit-module-maps">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fno_module_maps : Flag <["-"], "fno-module-maps">, Alias<fno_implicit_module_maps>;
def fno_modules_decluse : Flag <["-"], "fno-modules-decluse">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fno_modules_strict_decluse : Flag <["-"], "fno-strict-modules-decluse">, Group<f_Group>,
- Flags<[DriverOption]>;
-def fimplicit_modules : Flag <["-"], "fimplicit-modules">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fmodule_file_deps : Flag <["-"], "fmodule-file-deps">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fno_module_file_deps : Flag <["-"], "fno-module-file-deps">, Group<f_Group>,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def fno_ms_extensions : Flag<["-"], "fno-ms-extensions">, Group<f_Group>,
Flags<[CoreOption]>;
def fno_ms_compatibility : Flag<["-"], "fno-ms-compatibility">, Group<f_Group>,
Flags<[CoreOption]>;
-def fno_delayed_template_parsing : Flag<["-"], "fno-delayed-template-parsing">, Group<f_Group>,
- HelpText<"Disable delayed template parsing">,
- Flags<[DriverOption, CoreOption]>;
-def fno_objc_exceptions: Flag<["-"], "fno-objc-exceptions">, Group<f_Group>;
def fno_objc_legacy_dispatch : Flag<["-"], "fno-objc-legacy-dispatch">, Group<f_Group>;
def fno_objc_weak : Flag<["-"], "fno-objc-weak">, Group<f_Group>, Flags<[CC1Option]>;
def fno_omit_frame_pointer : Flag<["-"], "fno-omit-frame-pointer">, Group<f_Group>;
def fno_operator_names : Flag<["-"], "fno-operator-names">, Group<f_Group>,
HelpText<"Do not treat C++ operator name keywords as synonyms for operators">,
Flags<[CC1Option]>;
-def fno_pascal_strings : Flag<["-"], "fno-pascal-strings">, Group<f_Group>;
-def fno_short_enums : Flag<["-"], "fno-short-enums">, Group<f_Group>;
-def fno_show_source_location : Flag<["-"], "fno-show-source-location">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Do not include source location information with diagnostics">;
def fdiagnostics_absolute_paths : Flag<["-"], "fdiagnostics-absolute-paths">, Group<f_Group>,
- Flags<[CC1Option, CoreOption]>, HelpText<"Print absolute paths in diagnostics">;
-def fno_spell_checking : Flag<["-"], "fno-spell-checking">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Disable spell-checking">;
+ Flags<[CC1Option, CoreOption]>, HelpText<"Print absolute paths in diagnostics">,
+ MarshallingInfoFlag<DiagnosticOpts<"AbsolutePath">>;
def fno_stack_protector : Flag<["-"], "fno-stack-protector">, Group<f_Group>,
HelpText<"Disable the use of stack protectors">;
def fno_strict_aliasing : Flag<["-"], "fno-strict-aliasing">, Group<f_Group>,
- Flags<[DriverOption, CoreOption]>;
+ Flags<[NoXarchOption, CoreOption]>;
def fstruct_path_tbaa : Flag<["-"], "fstruct-path-tbaa">, Group<f_Group>;
def fno_struct_path_tbaa : Flag<["-"], "fno-struct-path-tbaa">, Group<f_Group>;
def fno_strict_enums : Flag<["-"], "fno-strict-enums">, Group<f_Group>;
-def fno_strict_vtable_pointers: Flag<["-"], "fno-strict-vtable-pointers">,
- Group<f_Group>;
def fno_strict_overflow : Flag<["-"], "fno-strict-overflow">, Group<f_Group>;
def fno_temp_file : Flag<["-"], "fno-temp-file">, Group<f_Group>,
Flags<[CC1Option, CoreOption]>, HelpText<
- "Directly create compilation output files. This may lead to incorrect incremental builds if the compiler crashes">;
-def fno_threadsafe_statics : Flag<["-"], "fno-threadsafe-statics">, Group<f_Group>,
- Flags<[CC1Option]>, HelpText<"Do not emit code to make initialization of local statics thread safe">;
-def fno_use_cxa_atexit : Flag<["-"], "fno-use-cxa-atexit">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Don't use __cxa_atexit for calling destructors">;
-def fno_register_global_dtors_with_atexit : Flag<["-"], "fno-register-global-dtors-with-atexit">, Group<f_Group>,
- HelpText<"Don't use atexit or __cxa_atexit to register global destructors">;
+ "Directly create compilation output files. This may lead to incorrect incremental builds if the compiler crashes">,
+ MarshallingInfoNegativeFlag<FrontendOpts<"UseTemporary">>;
+defm use_cxa_atexit : BoolFOption<"use-cxa-atexit",
+ CodeGenOpts<"CXAAtExit">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Don't use __cxa_atexit for calling destructors">,
+ PosFlag<SetTrue>>;
def fno_unit_at_a_time : Flag<["-"], "fno-unit-at-a-time">, Group<f_Group>;
def fno_unwind_tables : Flag<["-"], "fno-unwind-tables">, Group<f_Group>;
-def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">, Group<f_Group>, Flags<[CC1Option]>;
+def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoNegativeFlag<CodeGenOpts<"AsmVerbose">>;
def fno_working_directory : Flag<["-"], "fno-working-directory">, Group<f_Group>;
def fno_wrapv : Flag<["-"], "fno-wrapv">, Group<f_Group>;
def fobjc_arc : Flag<["-"], "fobjc-arc">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Synthesize retain and release calls for Objective-C pointers">;
def fno_objc_arc : Flag<["-"], "fno-objc-arc">, Group<f_Group>;
-def fobjc_convert_messages_to_runtime_calls :
- Flag<["-"], "fobjc-convert-messages-to-runtime-calls">, Group<f_Group>;
-def fno_objc_convert_messages_to_runtime_calls :
- Flag<["-"], "fno-objc-convert-messages-to-runtime-calls">, Group<f_Group>, Flags<[CC1Option]>;
-def fobjc_arc_exceptions : Flag<["-"], "fobjc-arc-exceptions">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use EH-safe code when synthesizing retains and releases in -fobjc-arc">;
-def fno_objc_arc_exceptions : Flag<["-"], "fno-objc-arc-exceptions">, Group<f_Group>;
+defm objc_convert_messages_to_runtime_calls : BoolFOption<"objc-convert-messages-to-runtime-calls",
+ CodeGenOpts<"ObjCConvertMessagesToRuntimeCalls">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>, PosFlag<SetTrue>>;
+defm objc_arc_exceptions : OptInFFlag<"objc-arc-exceptions",
+ "Use EH-safe code when synthesizing retains and releases in -fobjc-arc",
+ "", "", [], CodeGenOpts<"ObjCAutoRefCountExceptions">>;
def fobjc_atdefs : Flag<["-"], "fobjc-atdefs">, Group<clang_ignored_f_Group>;
def fobjc_call_cxx_cdtors : Flag<["-"], "fobjc-call-cxx-cdtors">, Group<clang_ignored_f_Group>;
-def fobjc_exceptions: Flag<["-"], "fobjc-exceptions">, Group<f_Group>,
- HelpText<"Enable Objective-C exceptions">, Flags<[CC1Option]>;
-def fapplication_extension : Flag<["-"], "fapplication-extension">,
- Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Restrict code to those available for App Extensions">;
-def fno_application_extension : Flag<["-"], "fno-application-extension">,
- Group<f_Group>;
-def frelaxed_template_template_args : Flag<["-"], "frelaxed-template-template-args">,
- Flags<[CC1Option]>, HelpText<"Enable C++17 relaxed template template argument matching">,
- Group<f_Group>;
-def fno_relaxed_template_template_args : Flag<["-"], "fno-relaxed-template-template-args">,
- Group<f_Group>;
-def fsized_deallocation : Flag<["-"], "fsized-deallocation">, Flags<[CC1Option]>,
- HelpText<"Enable C++14 sized global deallocation functions">, Group<f_Group>;
-def fno_sized_deallocation: Flag<["-"], "fno-sized-deallocation">, Group<f_Group>;
+defm objc_exceptions : BoolFOption<"objc-exceptions",
+ LangOpts<"ObjCExceptions">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable Objective-C exceptions">, NegFlag<SetFalse>>;
+defm application_extension : BoolFOption<"application-extension",
+ LangOpts<"AppExt">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Restrict code to those available for App Extensions">,
+ NegFlag<SetFalse>>;
+defm relaxed_template_template_args : BoolFOption<"relaxed-template-template-args",
+ LangOpts<"RelaxedTemplateTemplateArgs">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable C++17 relaxed template template argument matching">,
+ NegFlag<SetFalse>>;
+defm sized_deallocation : BoolFOption<"sized-deallocation",
+ LangOpts<"SizedDeallocation">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable C++14 sized global deallocation functions">,
+ NegFlag<SetFalse>>;
def faligned_allocation : Flag<["-"], "faligned-allocation">, Flags<[CC1Option]>,
HelpText<"Enable C++17 aligned allocation functions">, Group<f_Group>;
def fno_aligned_allocation: Flag<["-"], "fno-aligned-allocation">,
Group<f_Group>, Flags<[CC1Option]>;
def fnew_alignment_EQ : Joined<["-"], "fnew-alignment=">,
HelpText<"Specifies the largest alignment guaranteed by '::operator new(size_t)'">,
- MetaVarName<"<align>">, Group<f_Group>, Flags<[CC1Option]>;
+ MetaVarName<"<align>">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoStringInt<LangOpts<"NewAlignOverride">>;
def : Separate<["-"], "fnew-alignment">, Alias<fnew_alignment_EQ>;
def : Flag<["-"], "faligned-new">, Alias<faligned_allocation>;
def : Flag<["-"], "fno-aligned-new">, Alias<fno_aligned_allocation>;
@@ -1642,13 +2090,10 @@ def faligned_new_EQ : Joined<["-"], "faligned-new=">;
def fobjc_legacy_dispatch : Flag<["-"], "fobjc-legacy-dispatch">, Group<f_Group>;
def fobjc_new_property : Flag<["-"], "fobjc-new-property">, Group<clang_ignored_f_Group>;
-def fobjc_infer_related_result_type : Flag<["-"], "fobjc-infer-related-result-type">,
- Group<f_Group>;
-def fno_objc_infer_related_result_type : Flag<["-"],
- "fno-objc-infer-related-result-type">, Group<f_Group>,
- HelpText<
- "do not infer Objective-C related result type based on method family">,
- Flags<[CC1Option]>;
+defm objc_infer_related_result_type : BoolFOption<"objc-infer-related-result-type",
+ LangOpts<"ObjCInferRelatedResultType">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "do not infer Objective-C related result type based on method family">,
+ PosFlag<SetTrue>>;
def fobjc_link_runtime: Flag<["-"], "fobjc-link-runtime">, Group<f_Group>;
def fobjc_weak : Flag<["-"], "fobjc-weak">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Enable ARC-style weak references in Objective-C">;
@@ -1664,7 +2109,8 @@ def fno_objc_nonfragile_abi : Flag<["-"], "fno-objc-nonfragile-abi">, Group<f_Gr
def fobjc_sender_dependent_dispatch : Flag<["-"], "fobjc-sender-dependent-dispatch">, Group<f_Group>;
def fomit_frame_pointer : Flag<["-"], "fomit-frame-pointer">, Group<f_Group>;
def fopenmp : Flag<["-"], "fopenmp">, Group<f_Group>, Flags<[CC1Option, NoArgumentUnused]>,
- HelpText<"Parse OpenMP pragmas and generate parallel code.">;
+ HelpText<"Parse OpenMP pragmas and generate parallel code.">,
+ MarshallingInfoFlag<LangOpts<"OpenMP">, "0u">, Normalizer<"makeFlagToValueNormalizer(50u)">;
def fno_openmp : Flag<["-"], "fno-openmp">, Group<f_Group>, Flags<[NoArgumentUnused]>;
def fopenmp_version_EQ : Joined<["-"], "fopenmp-version=">, Group<f_Group>, Flags<[CC1Option, NoArgumentUnused]>;
def fopenmp_EQ : Joined<["-"], "fopenmp=">, Group<f_Group>;
@@ -1672,7 +2118,7 @@ def fopenmp_use_tls : Flag<["-"], "fopenmp-use-tls">, Group<f_Group>,
Flags<[NoArgumentUnused, HelpHidden]>;
def fnoopenmp_use_tls : Flag<["-"], "fnoopenmp-use-tls">, Group<f_Group>,
Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_targets_EQ : CommaJoined<["-"], "fopenmp-targets=">, Flags<[DriverOption, CC1Option]>,
+def fopenmp_targets_EQ : CommaJoined<["-"], "fopenmp-targets=">, Flags<[NoXarchOption, CC1Option]>,
HelpText<"Specify comma-separated list of triples OpenMP offloading targets to be supported">;
def fopenmp_relocatable_target : Flag<["-"], "fopenmp-relocatable-target">,
Group<f_Group>, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
@@ -1697,10 +2143,9 @@ def fopenmp_cuda_blocks_per_sm_EQ : Joined<["-"], "fopenmp-cuda-blocks-per-sm=">
Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
def fopenmp_cuda_teams_reduction_recs_num_EQ : Joined<["-"], "fopenmp-cuda-teams-reduction-recs-num=">, Group<f_Group>,
Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_optimistic_collapse : Flag<["-"], "fopenmp-optimistic-collapse">, Group<f_Group>,
- Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fno_openmp_optimistic_collapse : Flag<["-"], "fno-openmp-optimistic-collapse">, Group<f_Group>,
- Flags<[NoArgumentUnused, HelpHidden]>;
+defm openmp_optimistic_collapse : BoolFOption<"openmp-optimistic-collapse",
+ LangOpts<"OpenMPOptimisticCollapse">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>, BothFlags<[NoArgumentUnused, HelpHidden]>>;
def fopenmp_cuda_parallel_target_regions : Flag<["-"], "fopenmp-cuda-parallel-target-regions">, Group<f_Group>,
Flags<[CC1Option, NoArgumentUnused, HelpHidden]>,
HelpText<"Support parallel execution of target regions on Cuda-based devices.">;
@@ -1711,8 +2156,9 @@ def static_openmp: Flag<["-"], "static-openmp">,
HelpText<"Use the static host OpenMP runtime while linking.">;
def fno_optimize_sibling_calls : Flag<["-"], "fno-optimize-sibling-calls">, Group<f_Group>;
def foptimize_sibling_calls : Flag<["-"], "foptimize-sibling-calls">, Group<f_Group>;
-def fno_escaping_block_tail_calls : Flag<["-"], "fno-escaping-block-tail-calls">, Group<f_Group>, Flags<[CC1Option]>;
-def fescaping_block_tail_calls : Flag<["-"], "fescaping-block-tail-calls">, Group<f_Group>;
+defm escaping_block_tail_calls : BoolFOption<"escaping-block-tail-calls",
+ CodeGenOpts<"NoEscapingBlockTailCalls">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option]>, PosFlag<SetFalse>>;
def force__cpusubtype__ALL : Flag<["-"], "force_cpusubtype_ALL">;
def force__flat__namespace : Flag<["-"], "force_flat_namespace">;
def force__load : Separate<["-"], "force_load">;
@@ -1721,14 +2167,22 @@ def foutput_class_dir_EQ : Joined<["-"], "foutput-class-dir=">, Group<f_Group>;
def fpack_struct : Flag<["-"], "fpack-struct">, Group<f_Group>;
def fno_pack_struct : Flag<["-"], "fno-pack-struct">, Group<f_Group>;
def fpack_struct_EQ : Joined<["-"], "fpack-struct=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Specify the default maximum struct packing alignment">;
+ HelpText<"Specify the default maximum struct packing alignment">,
+ MarshallingInfoStringInt<LangOpts<"PackStruct">>;
def fmax_type_align_EQ : Joined<["-"], "fmax-type-align=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Specify the maximum alignment to enforce on pointers lacking an explicit alignment">;
+ HelpText<"Specify the maximum alignment to enforce on pointers lacking an explicit alignment">,
+ MarshallingInfoStringInt<LangOpts<"MaxTypeAlign">>;
def fno_max_type_align : Flag<["-"], "fno-max-type-align">, Group<f_Group>;
-def fpascal_strings : Flag<["-"], "fpascal-strings">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Recognize and construct Pascal-style string literals">;
+defm pascal_strings : BoolFOption<"pascal-strings",
+ LangOpts<"PascalStrings">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Recognize and construct Pascal-style string literals">,
+ NegFlag<SetFalse>>;
+// Note: This flag has different semantics in the driver and in -cc1. The driver accepts -fpatchable-function-entry=M,N
+// and forwards it to -cc1 as -fpatchable-function-entry=M and -fpatchable-function-entry-offset=N. In -cc1, both flags
+// are treated as a single integer.
def fpatchable_function_entry_EQ : Joined<["-"], "fpatchable-function-entry=">, Group<f_Group>, Flags<[CC1Option]>,
- MetaVarName<"<N,M>">, HelpText<"Generate M NOPs before function entry and N-M NOPs after function entry">;
+ MetaVarName<"<N,M>">, HelpText<"Generate M NOPs before function entry and N-M NOPs after function entry">,
+ MarshallingInfoStringInt<CodeGenOpts<"PatchableFunctionEntryCount">>;
def fpcc_struct_return : Flag<["-"], "fpcc-struct-return">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Override the default ABI to return all structs on the stack">;
def fpch_preprocess : Flag<["-"], "fpch-preprocess">, Group<f_Group>;
@@ -1736,19 +2190,32 @@ def fpic : Flag<["-"], "fpic">, Group<f_Group>;
def fno_pic : Flag<["-"], "fno-pic">, Group<f_Group>;
def fpie : Flag<["-"], "fpie">, Group<f_Group>;
def fno_pie : Flag<["-"], "fno-pie">, Group<f_Group>;
-defm plt : OptOutFFlag<"plt", "",
- "Use GOT indirection instead of PLT to make external function calls (x86 only)">;
-defm ropi : OptInFFlag<"ropi", "Generate read-only position independent code (ARM only)">;
-defm rwpi : OptInFFlag<"rwpi", "Generate read-write position independent code (ARM only)">;
-def fplugin_EQ : Joined<["-"], "fplugin=">, Group<f_Group>, Flags<[DriverOption]>, MetaVarName<"<dsopath>">,
+def fdirect_access_external_data : Flag<["-"], "fdirect-access-external-data">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"Don't use GOT indirection to reference external data symbols">;
+def fno_direct_access_external_data : Flag<["-"], "fno-direct-access-external-data">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"Use GOT indirection to reference external data symbols">;
+defm plt : BoolFOption<"plt",
+ CodeGenOpts<"NoPLT">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Use GOT indirection instead of PLT to make external function calls (x86 only)">,
+ PosFlag<SetFalse>>;
+defm ropi : BoolFOption<"ropi",
+ LangOpts<"ROPI">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Generate read-only position independent code (ARM only)">,
+ NegFlag<SetFalse>>;
+defm rwpi : BoolFOption<"rwpi",
+ LangOpts<"RWPI">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Generate read-write position independent code (ARM only)">,
+ NegFlag<SetFalse>>;
+def fplugin_EQ : Joined<["-"], "fplugin=">, Group<f_Group>, Flags<[NoXarchOption]>, MetaVarName<"<dsopath>">,
HelpText<"Load the named plugin (dynamic shared object)">;
def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
Group<f_Group>, Flags<[CC1Option]>, MetaVarName<"<dsopath>">,
- HelpText<"Load pass plugin from a dynamic shared object file (only with new pass manager).">;
-defm preserve_as_comments : OptOutFFlag<"preserve-as-comments", "",
- "Do not preserve comments in inline assembly">;
-def fprofile_arcs : Flag<["-"], "fprofile-arcs">, Group<f_Group>;
-def fno_profile_arcs : Flag<["-"], "fno-profile-arcs">, Group<f_Group>;
+ HelpText<"Load pass plugin from a dynamic shared object file (only with new pass manager).">,
+ MarshallingInfoStringVector<CodeGenOpts<"PassPlugins">>;
+defm preserve_as_comments : BoolFOption<"preserve-as-comments",
+ CodeGenOpts<"PreserveAsmComments">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Do not preserve comments in inline assembly">,
+ PosFlag<SetTrue>>;
def framework : Separate<["-"], "framework">, Flags<[LinkerInput]>;
def frandom_seed_EQ : Joined<["-"], "frandom-seed=">, Group<clang_ignored_f_Group>;
def freg_struct_return : Flag<["-"], "freg-struct-return">, Group<f_Group>, Flags<[CC1Option]>,
@@ -1756,8 +2223,11 @@ def freg_struct_return : Flag<["-"], "freg-struct-return">, Group<f_Group>, Flag
defm rtti : OptOutFFlag<"rtti", "", "Disable generation of rtti information">;
defm rtti_data : OptOutFFlag<"rtti-data", "", "Disable generation of RTTI data">;
def : Flag<["-"], "fsched-interblock">, Group<clang_ignored_f_Group>;
-def fshort_enums : Flag<["-"], "fshort-enums">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Allocate to an enum type only as many bytes as it needs for the declared range of possible values">;
+defm short_enums : BoolFOption<"short-enums",
+ LangOpts<"ShortEnums">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Allocate to an enum type only as many bytes as it"
+ " needs for the declared range of possible values">,
+ NegFlag<SetFalse>>;
def fchar8__t : Flag<["-"], "fchar8_t">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Enable C++ builtin type char8_t">;
def fno_char8__t : Flag<["-"], "fno-char8_t">, Group<f_Group>, Flags<[CC1Option]>,
@@ -1768,20 +2238,30 @@ def fno_short_wchar : Flag<["-"], "fno-short-wchar">, Group<f_Group>,
HelpText<"Force wchar_t to be an unsigned int">;
def fshow_overloads_EQ : Joined<["-"], "fshow-overloads=">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Which overload candidates to show when overload resolution fails: "
- "best|all; defaults to all">, Values<"best,all">;
-defm show_column : OptOutFFlag<"show-column", "", "Do not include column number on diagnostics">;
-def fshow_source_location : Flag<["-"], "fshow-source-location">, Group<f_Group>;
-def fspell_checking : Flag<["-"], "fspell-checking">, Group<f_Group>;
+ "best|all; defaults to all">, Values<"best,all">,
+ NormalizedValues<["Ovl_Best", "Ovl_All"]>,
+ MarshallingInfoString<DiagnosticOpts<"ShowOverloads">, "Ovl_All">, AutoNormalizeEnum;
+defm show_column : BoolFOption<"show-column",
+ DiagnosticOpts<"ShowColumn">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Do not include column number on diagnostics">,
+ PosFlag<SetTrue>>;
+defm show_source_location : BoolFOption<"show-source-location",
+ DiagnosticOpts<"ShowLocation">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Do not include source location information with diagnostics">,
+ PosFlag<SetTrue>>;
+defm spell_checking : BoolFOption<"spell-checking",
+ LangOpts<"SpellChecking">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Disable spell-checking">, PosFlag<SetTrue>>;
def fspell_checking_limit_EQ : Joined<["-"], "fspell-checking-limit=">, Group<f_Group>;
def fsigned_bitfields : Flag<["-"], "fsigned-bitfields">, Group<f_Group>;
defm signed_char : OptOutFFlag<"signed-char", "char is signed", "char is unsigned">;
def fsplit_stack : Flag<["-"], "fsplit-stack">, Group<f_Group>;
def fstack_protector_all : Flag<["-"], "fstack-protector-all">, Group<f_Group>,
HelpText<"Enable stack protectors for all functions">;
-def fstack_clash_protection : Flag<["-"], "fstack-clash-protection">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Enable stack clash protection">;
-def fno_stack_clash_protection : Flag<["-"], "fno-stack-clash-protection">, Group<f_Group>,
- HelpText<"Disable stack clash protection">;
+defm stack_clash_protection : BoolFOption<"stack-clash-protection",
+ CodeGenOpts<"StackClashProtector">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[], " stack clash protection">>;
def fstack_protector_strong : Flag<["-"], "fstack-protector-strong">, Group<f_Group>,
HelpText<"Enable stack protectors for some functions vulnerable to stack smashing. "
"Compared to -fstack-protector, this uses a stronger heuristic "
@@ -1789,18 +2269,27 @@ def fstack_protector_strong : Flag<["-"], "fstack-protector-strong">, Group<f_Gr
"as well as any calls to alloca or the taking of an address from a local variable">;
def fstack_protector : Flag<["-"], "fstack-protector">, Group<f_Group>,
HelpText<"Enable stack protectors for some functions vulnerable to stack smashing. "
- "This uses a loose heuristic which considers functions vulnerable "
- "if they contain a char (or 8bit integer) array or constant sized calls to "
- "alloca, which are of greater size than ssp-buffer-size (default: 8 bytes). "
- "All variable sized calls to alloca are considered vulnerable">;
+ "This uses a loose heuristic which considers functions vulnerable if they "
+ "contain a char (or 8bit integer) array or constant sized calls to alloca "
+ ", which are of greater size than ssp-buffer-size (default: 8 bytes). All "
+ "variable sized calls to alloca are considered vulnerable. A function with "
+ "a stack protector has a guard value added to the stack frame that is "
+ "checked on function exit. The guard value must be positioned in the "
+ "stack frame such that a buffer overflow from a vulnerable variable will "
+ "overwrite the guard value before overwriting the function's return "
+ "address. The reference stack guard value is stored in a global variable.">;
def ftrivial_auto_var_init : Joined<["-"], "ftrivial-auto-var-init=">, Group<f_Group>,
Flags<[CC1Option, CoreOption]>, HelpText<"Initialize trivial automatic stack variables: uninitialized (default)"
- " | pattern">, Values<"uninitialized,pattern">;
+ " | pattern">, Values<"uninitialized,zero,pattern">,
+ NormalizedValuesScope<"LangOptions::TrivialAutoVarInitKind">,
+ NormalizedValues<["Uninitialized", "Zero", "Pattern"]>,
+ MarshallingInfoString<LangOpts<"TrivialAutoVarInit">, "Uninitialized">, AutoNormalizeEnum;
def enable_trivial_var_init_zero : Flag<["-"], "enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang">,
Flags<[CC1Option, CoreOption]>,
HelpText<"Trivial automatic variable initialization to zero is only here for benchmarks, it'll eventually be removed, and I'm OK with that because I'm only using it to benchmark">;
def ftrivial_auto_var_init_stop_after : Joined<["-"], "ftrivial-auto-var-init-stop-after=">, Group<f_Group>,
- Flags<[CC1Option, CoreOption]>, HelpText<"Stop initializing trivial automatic stack variables after the specified number of instances">;
+ Flags<[CC1Option, CoreOption]>, HelpText<"Stop initializing trivial automatic stack variables after the specified number of instances">,
+ MarshallingInfoStringInt<LangOpts<"TrivialAutoVarInitStopAfter">>;
def fstandalone_debug : Flag<["-"], "fstandalone-debug">, Group<f_Group>, Flags<[CoreOption]>,
HelpText<"Emit full debug info for all types used by the program">;
def fno_standalone_debug : Flag<["-"], "fno-standalone-debug">, Group<f_Group>, Flags<[CoreOption]>,
@@ -1812,17 +2301,19 @@ def fdebug_macro : Flag<["-"], "fdebug-macro">, Group<f_Group>, Flags<[CoreOptio
def fno_debug_macro : Flag<["-"], "fno-debug-macro">, Group<f_Group>, Flags<[CoreOption]>,
HelpText<"Do not emit macro debug information">;
def fstrict_aliasing : Flag<["-"], "fstrict-aliasing">, Group<f_Group>,
- Flags<[DriverOption, CoreOption]>;
+ Flags<[NoXarchOption, CoreOption]>;
def fstrict_enums : Flag<["-"], "fstrict-enums">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Enable optimizations based on the strict definition of an enum's "
- "value range">;
-def fstrict_vtable_pointers: Flag<["-"], "fstrict-vtable-pointers">,
- Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Enable optimizations based on the strict rules for overwriting "
- "polymorphic C++ objects">;
+ "value range">,
+ MarshallingInfoFlag<CodeGenOpts<"StrictEnums">>;
+defm strict_vtable_pointers : BoolFOption<"strict-vtable-pointers",
+ CodeGenOpts<"StrictVTablePointers">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable optimizations based on the strict rules for"
+ " overwriting polymorphic C++ objects">,
+ NegFlag<SetFalse>>;
def fstrict_overflow : Flag<["-"], "fstrict-overflow">, Group<f_Group>;
def fsyntax_only : Flag<["-"], "fsyntax-only">,
- Flags<[DriverOption,CoreOption,CC1Option]>, Group<Action_Group>;
+ Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option]>, Group<Action_Group>;
def ftabstop_EQ : Joined<["-"], "ftabstop=">, Group<f_Group>;
def ftemplate_depth_EQ : Joined<["-"], "ftemplate-depth=">, Group<f_Group>;
def ftemplate_depth_ : Joined<["-"], "ftemplate-depth-">, Group<f_Group>;
@@ -1847,8 +2338,6 @@ def foptimization_record_passes_EQ : Joined<["-"], "foptimization-record-passes=
HelpText<"Only include passes which match a specified regular expression in the generated optimization record (by default, include all passes)">,
MetaVarName<"<regex>">;
-def ftest_coverage : Flag<["-"], "ftest-coverage">, Group<f_Group>;
-def fno_test_coverage : Flag<["-"], "fno-test-coverage">, Group<f_Group>;
def fvectorize : Flag<["-"], "fvectorize">, Group<f_Group>,
HelpText<"Enable the loop vectorization passes">;
def fno_vectorize : Flag<["-"], "fno-vectorize">, Group<f_Group>;
@@ -1862,28 +2351,48 @@ def : Flag<["-"], "fno-tree-slp-vectorize">, Alias<fno_slp_vectorize>;
def Wlarge_by_value_copy_def : Flag<["-"], "Wlarge-by-value-copy">,
HelpText<"Warn if a function definition returns or accepts an object larger "
"in bytes than a given value">, Flags<[HelpHidden]>;
-def Wlarge_by_value_copy_EQ : Joined<["-"], "Wlarge-by-value-copy=">, Flags<[CC1Option]>;
+def Wlarge_by_value_copy_EQ : Joined<["-"], "Wlarge-by-value-copy=">, Flags<[CC1Option]>,
+ MarshallingInfoStringInt<LangOpts<"NumLargeByValueCopy">>;
// These "special" warning flags are effectively processed as f_Group flags by the driver:
// Just silence warnings about -Wlarger-than for now.
def Wlarger_than_EQ : Joined<["-"], "Wlarger-than=">, Group<clang_ignored_f_Group>;
def Wlarger_than_ : Joined<["-"], "Wlarger-than-">, Alias<Wlarger_than_EQ>;
-def Wframe_larger_than_EQ : Joined<["-"], "Wframe-larger-than=">, Group<f_Group>, Flags<[DriverOption]>;
+def Wframe_larger_than_EQ : Joined<["-"], "Wframe-larger-than=">, Group<f_Group>, Flags<[NoXarchOption]>;
def : Flag<["-"], "fterminated-vtables">, Alias<fapple_kext>;
-def fthreadsafe_statics : Flag<["-"], "fthreadsafe-statics">, Group<f_Group>;
-def ftime_report : Flag<["-"], "ftime-report">, Group<f_Group>, Flags<[CC1Option]>;
+defm threadsafe_statics : BoolFOption<"threadsafe-statics",
+ LangOpts<"ThreadsafeStatics">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Do not emit code to make initialization of local statics thread safe">,
+ PosFlag<SetTrue>>;
+def ftime_report : Flag<["-"], "ftime-report">, Group<f_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<CodeGenOpts<"TimePasses">>;
+def ftime_report_EQ: Joined<["-"], "ftime-report=">, Group<f_Group>,
+ Flags<[CC1Option]>, Values<"per-pass,per-pass-run">,
+ MarshallingInfoFlag<CodeGenOpts<"TimePassesPerRun">>,
+ HelpText<"(For new pass manager) \"per-pass\": one report for each pass; "
+ "\"per-pass-run\": one report for each pass invocation">;
def ftime_trace : Flag<["-"], "ftime-trace">, Group<f_Group>,
HelpText<"Turn on time profiler. Generates JSON file based on output filename.">,
DocBrief<[{
Turn on time profiler. Generates JSON file based on output filename. Results
can be analyzed with chrome://tracing or `Speedscope App
<https://www.speedscope.app>`_ for flamegraph visualization.}]>,
- Flags<[CC1Option, CoreOption]>;
+ Flags<[CC1Option, CoreOption]>,
+ MarshallingInfoFlag<FrontendOpts<"TimeTrace">>;
def ftime_trace_granularity_EQ : Joined<["-"], "ftime-trace-granularity=">, Group<f_Group>,
HelpText<"Minimum time granularity (in microseconds) traced by time profiler">,
- Flags<[CC1Option, CoreOption]>;
-def ftlsmodel_EQ : Joined<["-"], "ftls-model=">, Group<f_Group>, Flags<[CC1Option]>;
+ Flags<[CC1Option, CoreOption]>,
+ MarshallingInfoStringInt<FrontendOpts<"TimeTraceGranularity">, "500u">;
+def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group<f_Group>,
+ HelpText<"Print subprocess statistics">;
+def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group<f_Group>,
+ HelpText<"Save subprocess statistics to the given file">;
+def ftlsmodel_EQ : Joined<["-"], "ftls-model=">, Group<f_Group>, Flags<[CC1Option]>,
+ Values<"global-dynamic,local-dynamic,initial-exec,local-exec">,
+ NormalizedValuesScope<"CodeGenOptions">,
+ NormalizedValues<["GeneralDynamicTLSModel", "LocalDynamicTLSModel", "InitialExecTLSModel", "LocalExecTLSModel"]>,
+ MarshallingInfoString<CodeGenOpts<"DefaultTLSModel">, "GeneralDynamicTLSModel">, AutoNormalizeEnum;
def ftrapv : Flag<["-"], "ftrapv">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Trap on integer overflow">;
def ftrapv_handler_EQ : Joined<["-"], "ftrapv-handler=">, Group<f_Group>,
@@ -1891,13 +2400,21 @@ def ftrapv_handler_EQ : Joined<["-"], "ftrapv-handler=">, Group<f_Group>,
HelpText<"Specify the function to be called on overflow">;
def ftrapv_handler : Separate<["-"], "ftrapv-handler">, Group<f_Group>, Flags<[CC1Option]>;
def ftrap_function_EQ : Joined<["-"], "ftrap-function=">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Issue call to specified function rather than a trap instruction">;
+ HelpText<"Issue call to specified function rather than a trap instruction">,
+ MarshallingInfoString<CodeGenOpts<"TrapFuncName">>;
def funit_at_a_time : Flag<["-"], "funit-at-a-time">, Group<f_Group>;
def funroll_loops : Flag<["-"], "funroll-loops">, Group<f_Group>,
HelpText<"Turn on loop unroller">, Flags<[CC1Option]>;
def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group<f_Group>,
HelpText<"Turn off loop unroller">, Flags<[CC1Option]>;
-defm reroll_loops : OptInFFlag<"reroll-loops", "Turn on loop reroller">;
+defm reroll_loops : BoolFOption<"reroll-loops",
+ CodeGenOpts<"RerollLoops">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Turn on loop reroller">, NegFlag<SetFalse>>;
+def ffinite_loops: Flag<["-"], "ffinite-loops">, Group<f_Group>,
+ HelpText<"Assume all loops are finite.">, Flags<[CC1Option]>;
+def fno_finite_loops: Flag<["-"], "fno-finite-loops">, Group<f_Group>,
+ HelpText<"Do not assume that any loop is finite.">, Flags<[CC1Option]>;
+
def ftrigraphs : Flag<["-"], "ftrigraphs">, Group<f_Group>,
HelpText<"Process trigraph sequences">, Flags<[CC1Option]>;
def fno_trigraphs : Flag<["-"], "fno-trigraphs">, Group<f_Group>,
@@ -1906,84 +2423,159 @@ def funsigned_bitfields : Flag<["-"], "funsigned-bitfields">, Group<f_Group>;
def funsigned_char : Flag<["-"], "funsigned-char">, Group<f_Group>;
def fno_unsigned_char : Flag<["-"], "fno-unsigned-char">;
def funwind_tables : Flag<["-"], "funwind-tables">, Group<f_Group>;
-def fuse_cxa_atexit : Flag<["-"], "fuse-cxa-atexit">, Group<f_Group>;
-def fregister_global_dtors_with_atexit : Flag<["-"], "fregister-global-dtors-with-atexit">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Use atexit or __cxa_atexit to register global destructors">;
-defm use_init_array : OptOutFFlag<"use-init-array", "", "Use .ctors/.dtors instead of .init_array/.fini_array">;
+defm register_global_dtors_with_atexit : BoolFOption<"register-global-dtors-with-atexit",
+ CodeGenOpts<"RegisterGlobalDtorsWithAtExit">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use">, NegFlag<SetFalse, [], "Don't use">,
+ BothFlags<[], " atexit or __cxa_atexit to register global destructors">>;
+defm use_init_array : BoolFOption<"use-init-array",
+ CodeGenOpts<"UseInitArray">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Use .ctors/.dtors instead of .init_array/.fini_array">,
+ PosFlag<SetTrue>>;
def fno_var_tracking : Flag<["-"], "fno-var-tracking">, Group<clang_ignored_f_Group>;
def fverbose_asm : Flag<["-"], "fverbose-asm">, Group<f_Group>,
HelpText<"Generate verbose assembly output">;
def dA : Flag<["-"], "dA">, Alias<fverbose_asm>;
+defm visibility_from_dllstorageclass : BoolFOption<"visibility-from-dllstorageclass",
+ LangOpts<"VisibilityFromDLLStorageClass">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Set the visiblity of symbols in the generated code from their DLL storage class">,
+ NegFlag<SetFalse>>;
+def fvisibility_dllexport_EQ : Joined<["-"], "fvisibility-dllexport=">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"The visibility for dllexport defintions [-fvisibility-from-dllstorageclass]">,
+ MarshallingInfoVisibility<LangOpts<"DLLExportVisibility">, "DefaultVisibility">,
+ ShouldParseIf<fvisibility_from_dllstorageclass.KeyPath>;
+def fvisibility_nodllstorageclass_EQ : Joined<["-"], "fvisibility-nodllstorageclass=">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"The visibility for defintiions without an explicit DLL export class [-fvisibility-from-dllstorageclass]">,
+ MarshallingInfoVisibility<LangOpts<"NoDLLStorageClassVisibility">, "HiddenVisibility">,
+ ShouldParseIf<fvisibility_from_dllstorageclass.KeyPath>;
+def fvisibility_externs_dllimport_EQ : Joined<["-"], "fvisibility-externs-dllimport=">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"The visibility for dllimport external declarations [-fvisibility-from-dllstorageclass]">,
+ MarshallingInfoVisibility<LangOpts<"ExternDeclDLLImportVisibility">, "DefaultVisibility">,
+ ShouldParseIf<fvisibility_from_dllstorageclass.KeyPath>;
+def fvisibility_externs_nodllstorageclass_EQ : Joined<["-"], "fvisibility-externs-nodllstorageclass=">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"The visibility for external declarations without an explicit DLL dllstorageclass [-fvisibility-from-dllstorageclass]">,
+ MarshallingInfoVisibility<LangOpts<"ExternDeclNoDLLStorageClassVisibility">, "HiddenVisibility">,
+ ShouldParseIf<fvisibility_from_dllstorageclass.KeyPath>;
def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group<f_Group>,
HelpText<"Set the default symbol visibility for all global declarations">, Values<"hidden,default">;
def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, Group<f_Group>,
HelpText<"Give inline C++ member functions hidden visibility by default">,
- Flags<[CC1Option]>;
+ Flags<[CC1Option]>, MarshallingInfoFlag<LangOpts<"InlineVisibilityHidden">>;
+defm visibility_inlines_hidden_static_local_var : BoolFOption<"visibility-inlines-hidden-static-local-var",
+ LangOpts<"VisibilityInlinesHiddenStaticLocalVar">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "When -fvisibility-inlines-hidden is enabled, static variables in"
+ " inline C++ member functions will also be given hidden visibility by default">,
+ NegFlag<SetFalse, [], "Disables -fvisibility-inlines-hidden-static-local-var"
+ " (this is the default on non-darwin targets)">, BothFlags<[CC1Option]>>;
def fvisibility_ms_compat : Flag<["-"], "fvisibility-ms-compat">, Group<f_Group>,
HelpText<"Give global types 'default' visibility and global functions and "
"variables 'hidden' visibility by default">;
def fvisibility_global_new_delete_hidden : Flag<["-"], "fvisibility-global-new-delete-hidden">, Group<f_Group>,
- HelpText<"Give global C++ operator new and delete declarations hidden visibility">, Flags<[CC1Option]>;
-defm whole_program_vtables : OptInFFlag<"whole-program-vtables",
- "Enables whole-program vtable optimization. Requires -flto", "", "", [CoreOption]>;
-defm split_lto_unit : OptInFFlag<"split-lto-unit",
- "Enables splitting of the LTO unit", "", "", [CoreOption]>;
-defm force_emit_vtables : OptInFFlag<"force-emit-vtables",
- "Emits more virtual tables to improve devirtualization", "", "", [CoreOption]>;
-defm virtual_function_elimination : OptInFFlag<"virtual-function-elimination",
- "Enables dead virtual function elimination optimization. Requires -flto=full", "", "", [CoreOption]>;
+ HelpText<"Give global C++ operator new and delete declarations hidden visibility">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<LangOpts<"GlobalAllocationFunctionVisibilityHidden">>;
+defm whole_program_vtables : BoolFOption<"whole-program-vtables",
+ CodeGenOpts<"WholeProgramVTables">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enables whole-program vtable optimization. Requires -flto">,
+ NegFlag<SetFalse>, BothFlags<[CoreOption]>>;
+defm split_lto_unit : BoolFOption<"split-lto-unit",
+ CodeGenOpts<"EnableSplitLTOUnit">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enables splitting of the LTO unit">,
+ NegFlag<SetFalse>, BothFlags<[CoreOption]>>;
+defm force_emit_vtables : BoolFOption<"force-emit-vtables",
+ CodeGenOpts<"ForceEmitVTables">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emits more virtual tables to improve devirtualization">,
+ NegFlag<SetFalse>, BothFlags<[CoreOption]>>;
+defm virtual_function_elimination : BoolFOption<"virtual-function-elimination",
+ CodeGenOpts<"VirtualFunctionElimination">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enables dead virtual function elimination optimization. Requires -flto=full">,
+ NegFlag<SetFalse>, BothFlags<[CoreOption]>>;
def fwrapv : Flag<["-"], "fwrapv">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Treat signed integer overflow as two's complement">;
def fwritable_strings : Flag<["-"], "fwritable-strings">, Group<f_Group>, Flags<[CC1Option]>,
- HelpText<"Store string literals as writable data">;
-defm zero_initialized_in_bss : OptOutFFlag<"zero-initialized-in-bss", "", "Don't place zero initialized data in BSS">;
+ HelpText<"Store string literals as writable data">,
+ MarshallingInfoFlag<LangOpts<"WritableStrings">>;
+defm zero_initialized_in_bss : BoolFOption<"zero-initialized-in-bss",
+ CodeGenOpts<"NoZeroInitializedInBSS">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Don't place zero initialized data in BSS">,
+ PosFlag<SetFalse>>;
defm function_sections : OptInFFlag<"function-sections", "Place each function in its own section">;
def fbasic_block_sections_EQ : Joined<["-"], "fbasic-block-sections=">, Group<f_Group>,
Flags<[CC1Option, CC1AsOption]>,
HelpText<"Place each function's basic blocks in unique sections (ELF Only) : all | labels | none | list=<file>">,
DocBrief<[{Generate labels for each basic block or place each basic block or a subset of basic blocks in its own section.}]>,
- Values<"all,labels,none,list=">;
-defm data_sections : OptInFFlag<"data-sections", "Place each data in its own section">;
-defm stack_size_section : OptInFFlag<"stack-size-section", "Emit section containing metadata on function stack sizes">;
-
-defm unique_basic_block_section_names : OptInFFlag<"unique-basic-block-section-names",
- "Use unique names for basic block sections (ELF Only)">;
-defm unique_internal_linkage_names : OptInFFlag<"unique-internal-linkage-names",
- "Uniqueify Internal Linkage Symbol Names by appending the MD5 hash of the module path">;
-defm unique_section_names : OptOutFFlag<"unique-section-names",
- "", "Don't use unique names for text and data sections">;
-
-defm strict_return : OptOutFFlag<"strict-return", "",
- "Don't treat control flow paths that fall off the end of a non-void function as unreachable">;
+ Values<"all,labels,none,list=">,
+ MarshallingInfoString<CodeGenOpts<"BBSections">, [{"none"}]>;
+defm data_sections : BoolFOption<"data-sections",
+ CodeGenOpts<"DataSections">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Place each data in its own section">, NegFlag<SetFalse>>;
+defm stack_size_section : BoolFOption<"stack-size-section",
+ CodeGenOpts<"StackSizeSection">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emit section containing metadata on function stack sizes">,
+ NegFlag<SetFalse>>;
+
+defm unique_basic_block_section_names : BoolFOption<"unique-basic-block-section-names",
+ CodeGenOpts<"UniqueBasicBlockSectionNames">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use unique names for basic block sections (ELF Only)">,
+ NegFlag<SetFalse>>;
+defm unique_internal_linkage_names : BoolFOption<"unique-internal-linkage-names",
+ CodeGenOpts<"UniqueInternalLinkageNames">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Uniqueify Internal Linkage Symbol Names by appending"
+ " the MD5 hash of the module path">,
+ NegFlag<SetFalse>>;
+defm unique_section_names : BoolFOption<"unique-section-names",
+ CodeGenOpts<"UniqueSectionNames">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Don't use unique names for text and data sections">,
+ PosFlag<SetTrue>>;
+
+defm split_machine_functions: BoolFOption<"split-machine-functions",
+ CodeGenOpts<"SplitMachineFunctions">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[], " late function splitting using profile information (x86 ELF)">>;
+
+defm strict_return : BoolFOption<"strict-return",
+ CodeGenOpts<"StrictReturn">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Don't treat control flow paths that fall off the end"
+ " of a non-void function as unreachable">,
+ PosFlag<SetTrue>>;
def fenable_matrix : Flag<["-"], "fenable-matrix">, Group<f_Group>,
Flags<[CC1Option]>,
- HelpText<"Enable matrix data type and related builtin functions">;
+ HelpText<"Enable matrix data type and related builtin functions">,
+ MarshallingInfoFlag<LangOpts<"MatrixTypes">>;
def fdebug_types_section: Flag <["-"], "fdebug-types-section">, Group<f_Group>,
HelpText<"Place debug types in their own section (ELF Only)">;
def fno_debug_types_section: Flag<["-"], "fno-debug-types-section">, Group<f_Group>;
-defm debug_ranges_base_address : OptInFFlag<"debug-ranges-base-address",
- "Use DWARF base address selection entries in .debug_ranges">;
-def fsplit_dwarf_inlining: Flag <["-"], "fsplit-dwarf-inlining">, Group<f_Group>,
- HelpText<"Provide minimal debug info in the object/executable to facilitate online symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF">;
-def fno_split_dwarf_inlining: Flag<["-"], "fno-split-dwarf-inlining">, Group<f_Group>,
- Flags<[CC1Option]>;
+defm debug_ranges_base_address : BoolFOption<"debug-ranges-base-address",
+ CodeGenOpts<"DebugRangesBaseAddress">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use DWARF base address selection entries in .debug_ranges">,
+ NegFlag<SetFalse>>;
+defm split_dwarf_inlining : BoolFOption<"split-dwarf-inlining",
+ CodeGenOpts<"SplitDwarfInlining">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>,
+ PosFlag<SetTrue, [], "Provide minimal debug info in the object/executable"
+ " to facilitate online symbolication/stack traces in the absence of"
+ " .dwo/.dwp files when using Split DWARF">>;
def fdebug_default_version: Joined<["-"], "fdebug-default-version=">, Group<f_Group>,
HelpText<"Default DWARF version to use, if a -g option caused DWARF debug info to be produced">;
def fdebug_prefix_map_EQ
: Joined<["-"], "fdebug-prefix-map=">, Group<f_Group>,
Flags<[CC1Option,CC1AsOption]>,
HelpText<"remap file source paths in debug info">;
+def fprofile_prefix_map_EQ
+ : Joined<["-"], "fprofile-prefix-map=">, Group<f_Group>,
+ Flags<[CC1Option]>,
+ HelpText<"remap file source paths in coverage info">;
def ffile_prefix_map_EQ
: Joined<["-"], "ffile-prefix-map=">, Group<f_Group>,
HelpText<"remap file source paths in debug info and predefined preprocessor macros">;
def fmacro_prefix_map_EQ
: Joined<["-"], "fmacro-prefix-map=">, Group<Preprocessor_Group>, Flags<[CC1Option]>,
HelpText<"remap file source paths in predefined preprocessor macros">;
-defm force_dwarf_frame : OptInFFlag<"force-dwarf-frame", "Always emit a debug frame section">;
+defm force_dwarf_frame : BoolFOption<"force-dwarf-frame",
+ CodeGenOpts<"ForceDwarfFrameSection">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Always emit a debug frame section">, NegFlag<SetFalse>>;
def g_Flag : Flag<["-"], "g">, Group<g_Group>,
HelpText<"Generate source-level debug information">;
def gline_tables_only : Flag<["-"], "gline-tables-only">, Group<gN_Group>,
@@ -2014,17 +2606,24 @@ def gdwarf_4 : Flag<["-"], "gdwarf-4">, Group<g_Group>,
HelpText<"Generate source-level debug information with dwarf version 4">;
def gdwarf_5 : Flag<["-"], "gdwarf-5">, Group<g_Group>,
HelpText<"Generate source-level debug information with dwarf version 5">;
+def gdwarf64 : Flag<["-"], "gdwarf64">, Group<g_Group>, Flags<[CC1Option]>,
+ HelpText<"Enables DWARF64 format for ELF binaries, if debug information emission is enabled.">,
+ MarshallingInfoFlag<CodeGenOpts<"Dwarf64">>;
+def gdwarf32 : Flag<["-"], "gdwarf32">, Group<g_Group>, Flags<[CC1Option]>,
+ HelpText<"Enables DWARF32 format for ELF binaries, if debug information emission is enabled.">;
def gcodeview : Flag<["-"], "gcodeview">,
HelpText<"Generate CodeView debug information">,
- Flags<[CC1Option, CC1AsOption, CoreOption]>;
-def gcodeview_ghash : Flag<["-"], "gcodeview-ghash">,
- HelpText<"Emit type record hashes in a .debug$H section">,
- Flags<[CC1Option, CoreOption]>;
-def gno_codeview_ghash : Flag<["-"], "gno-codeview-ghash">, Flags<[CoreOption]>;
-def ginline_line_tables : Flag<["-"], "ginline-line-tables">, Flags<[CoreOption]>;
-def gno_inline_line_tables : Flag<["-"], "gno-inline-line-tables">,
- Flags<[CC1Option, CoreOption]>, HelpText<"Don't emit inline line tables">;
+ Flags<[CC1Option, CC1AsOption, CoreOption]>,
+ MarshallingInfoFlag<CodeGenOpts<"EmitCodeView">>;
+defm codeview_ghash : BoolOption<"g", "codeview-ghash",
+ CodeGenOpts<"CodeViewGHash">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emit type record hashes in a .debug$H section">,
+ NegFlag<SetFalse>, BothFlags<[CoreOption]>>;
+defm inline_line_tables : BoolGOption<"inline-line-tables",
+ CodeGenOpts<"NoInlineLineTables">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Don't emit inline line tables.">,
+ PosFlag<SetFalse>, BothFlags<[CoreOption]>>;
def gfull : Flag<["-"], "gfull">, Group<g_Group>;
def gused : Flag<["-"], "gused">, Group<g_Group>;
@@ -2041,12 +2640,15 @@ def : Flag<["-"], "grecord-gcc-switches">, Alias<grecord_command_line>;
def : Flag<["-"], "gno-record-gcc-switches">, Alias<gno_record_command_line>;
def gstrict_dwarf : Flag<["-"], "gstrict-dwarf">, Group<g_flags_Group>;
def gno_strict_dwarf : Flag<["-"], "gno-strict-dwarf">, Group<g_flags_Group>;
-def gcolumn_info : Flag<["-"], "gcolumn-info">, Group<g_flags_Group>, Flags<[CoreOption]>;
-def gno_column_info : Flag<["-"], "gno-column-info">, Group<g_flags_Group>, Flags<[CoreOption, CC1Option]>;
+defm column_info : BoolOption<"g", "column-info",
+ CodeGenOpts<"DebugColumnInfo">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option]>, PosFlag<SetTrue>, BothFlags<[CoreOption]>>,
+ Group<g_flags_Group>;
def gsplit_dwarf : Flag<["-"], "gsplit-dwarf">, Group<g_flags_Group>;
def gsplit_dwarf_EQ : Joined<["-"], "gsplit-dwarf=">, Group<g_flags_Group>,
HelpText<"Set DWARF fission mode to either 'split' or 'single'">,
Values<"split,single">;
+def gno_split_dwarf : Flag<["-"], "gno-split-dwarf">, Group<g_flags_Group>;
def ggnu_pubnames : Flag<["-"], "ggnu-pubnames">, Group<g_flags_Group>, Flags<[CC1Option]>;
def gno_gnu_pubnames : Flag<["-"], "gno-gnu-pubnames">, Group<g_flags_Group>;
def gpubnames : Flag<["-"], "gpubnames">, Group<g_flags_Group>, Flags<[CC1Option]>;
@@ -2055,18 +2657,19 @@ def gdwarf_aranges : Flag<["-"], "gdwarf-aranges">, Group<g_flags_Group>;
def gmodules : Flag <["-"], "gmodules">, Group<gN_Group>,
HelpText<"Generate debug info with external references to clang modules"
" or precompiled headers">;
-def gz : Flag<["-"], "gz">, Group<g_flags_Group>,
- HelpText<"DWARF debug sections compression type">;
def gz_EQ : Joined<["-"], "gz=">, Group<g_flags_Group>,
HelpText<"DWARF debug sections compression type">;
+def gz : Flag<["-"], "gz">, Alias<gz_EQ>, AliasArgs<["zlib"]>, Group<g_flags_Group>;
def gembed_source : Flag<["-"], "gembed-source">, Group<g_flags_Group>, Flags<[CC1Option]>,
- HelpText<"Embed source text in DWARF debug sections">;
+ HelpText<"Embed source text in DWARF debug sections">,
+ MarshallingInfoFlag<CodeGenOpts<"EmbedSource">>;
def gno_embed_source : Flag<["-"], "gno-embed-source">, Group<g_flags_Group>,
- Flags<[DriverOption]>,
+ Flags<[NoXarchOption]>,
HelpText<"Restore the default behavior of not embedding source text in DWARF debug sections">;
def headerpad__max__install__names : Joined<["-"], "headerpad_max_install_names">;
-def help : Flag<["-", "--"], "help">, Flags<[CC1Option,CC1AsOption]>,
- HelpText<"Display available options">;
+def help : Flag<["-", "--"], "help">, Flags<[CC1Option,CC1AsOption, FC1Option,
+ FlangOption]>, HelpText<"Display available options">,
+ MarshallingInfoFlag<FrontendOpts<"ShowHelp">>;
def ibuiltininc : Flag<["-"], "ibuiltininc">,
HelpText<"Enable builtin #include directories even when -nostdinc is used "
"before or after -ibuiltininc. "
@@ -2083,14 +2686,17 @@ def iframeworkwithsysroot : JoinedOrSeparate<["-"], "iframeworkwithsysroot">,
"absolute paths are relative to -isysroot">,
MetaVarName<"<directory>">, Flags<[CC1Option]>;
def imacros : JoinedOrSeparate<["-", "--"], "imacros">, Group<clang_i_Group>, Flags<[CC1Option]>,
- HelpText<"Include macros from file before parsing">, MetaVarName<"<file>">;
+ HelpText<"Include macros from file before parsing">, MetaVarName<"<file>">,
+ MarshallingInfoStringVector<PreprocessorOpts<"MacroIncludes">>;
def image__base : Separate<["-"], "image_base">;
def include_ : JoinedOrSeparate<["-", "--"], "include">, Group<clang_i_Group>, EnumName<"include">,
MetaVarName<"<file>">, HelpText<"Include file before parsing">, Flags<[CC1Option]>;
def include_pch : Separate<["-"], "include-pch">, Group<clang_i_Group>, Flags<[CC1Option]>,
- HelpText<"Include precompiled header file">, MetaVarName<"<file>">;
+ HelpText<"Include precompiled header file">, MetaVarName<"<file>">,
+ MarshallingInfoString<PreprocessorOpts<"ImplicitPCHInclude">>;
def relocatable_pch : Flag<["-", "--"], "relocatable-pch">, Flags<[CC1Option]>,
- HelpText<"Whether to build a relocatable precompiled header">;
+ HelpText<"Whether to build a relocatable precompiled header">,
+ MarshallingInfoFlag<FrontendOpts<"RelocatablePCH">>;
def verify_pch : Flag<["-"], "verify-pch">, Group<Action_Group>, Flags<[CC1Option]>,
HelpText<"Load and verify that a pre-compiled header file is not stale">;
def init : Separate<["-"], "init">;
@@ -2100,12 +2706,13 @@ def iprefix : JoinedOrSeparate<["-"], "iprefix">, Group<clang_i_Group>, Flags<[C
def iquote : JoinedOrSeparate<["-"], "iquote">, Group<clang_i_Group>, Flags<[CC1Option]>,
HelpText<"Add directory to QUOTE include search path">, MetaVarName<"<directory>">;
def isysroot : JoinedOrSeparate<["-"], "isysroot">, Group<clang_i_Group>, Flags<[CC1Option]>,
- HelpText<"Set the system root directory (usually /)">, MetaVarName<"<dir>">;
+ HelpText<"Set the system root directory (usually /)">, MetaVarName<"<dir>">,
+ MarshallingInfoString<HeaderSearchOpts<"Sysroot">, [{"/"}]>;
def isystem : JoinedOrSeparate<["-"], "isystem">, Group<clang_i_Group>,
Flags<[CC1Option]>,
HelpText<"Add directory to SYSTEM include search path">, MetaVarName<"<directory>">;
def isystem_after : JoinedOrSeparate<["-"], "isystem-after">,
- Group<clang_i_Group>, Flags<[DriverOption]>, MetaVarName<"<directory>">,
+ Group<clang_i_Group>, Flags<[NoXarchOption]>, MetaVarName<"<directory>">,
HelpText<"Add directory to end of the SYSTEM include search path">;
def iwithprefixbefore : JoinedOrSeparate<["-"], "iwithprefixbefore">, Group<clang_i_Group>,
HelpText<"Set directory to include search path with prefix">, MetaVarName<"<dir>">,
@@ -2124,36 +2731,38 @@ def l : JoinedOrSeparate<["-"], "l">, Flags<[LinkerInput, RenderJoined]>,
Group<Link_Group>;
def lazy__framework : Separate<["-"], "lazy_framework">, Flags<[LinkerInput]>;
def lazy__library : Separate<["-"], "lazy_library">, Flags<[LinkerInput]>;
-def mlittle_endian : Flag<["-"], "mlittle-endian">, Flags<[DriverOption]>;
+def mlittle_endian : Flag<["-"], "mlittle-endian">, Flags<[NoXarchOption]>;
def EL : Flag<["-"], "EL">, Alias<mlittle_endian>;
-def mbig_endian : Flag<["-"], "mbig-endian">, Flags<[DriverOption]>;
+def mbig_endian : Flag<["-"], "mbig-endian">, Flags<[NoXarchOption]>;
def EB : Flag<["-"], "EB">, Alias<mbig_endian>;
-def m16 : Flag<["-"], "m16">, Group<m_Group>, Flags<[DriverOption, CoreOption]>;
-def m32 : Flag<["-"], "m32">, Group<m_Group>, Flags<[DriverOption, CoreOption]>;
-def mqdsp6_compat : Flag<["-"], "mqdsp6-compat">, Group<m_Group>, Flags<[DriverOption,CC1Option]>,
- HelpText<"Enable hexagon-qdsp6 backward compatibility">;
-def m64 : Flag<["-"], "m64">, Group<m_Group>, Flags<[DriverOption, CoreOption]>;
-def mx32 : Flag<["-"], "mx32">, Group<m_Group>, Flags<[DriverOption, CoreOption]>;
+def m16 : Flag<["-"], "m16">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>;
+def m32 : Flag<["-"], "m32">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>;
+def mqdsp6_compat : Flag<["-"], "mqdsp6-compat">, Group<m_Group>, Flags<[NoXarchOption,CC1Option]>,
+ HelpText<"Enable hexagon-qdsp6 backward compatibility">,
+ MarshallingInfoFlag<LangOpts<"HexagonQdsp6Compat">>;
+def m64 : Flag<["-"], "m64">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>;
+def mx32 : Flag<["-"], "mx32">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>;
def mabi_EQ : Joined<["-"], "mabi=">, Group<m_Group>;
-def miamcu : Flag<["-"], "miamcu">, Group<m_Group>, Flags<[DriverOption, CoreOption]>,
+def miamcu : Flag<["-"], "miamcu">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>,
HelpText<"Use Intel MCU ABI">;
-def mno_iamcu : Flag<["-"], "mno-iamcu">, Group<m_Group>, Flags<[DriverOption, CoreOption]>;
+def mno_iamcu : Flag<["-"], "mno-iamcu">, Group<m_Group>, Flags<[NoXarchOption, CoreOption]>;
def malign_functions_EQ : Joined<["-"], "malign-functions=">, Group<clang_ignored_m_Group>;
def malign_loops_EQ : Joined<["-"], "malign-loops=">, Group<clang_ignored_m_Group>;
def malign_jumps_EQ : Joined<["-"], "malign-jumps=">, Group<clang_ignored_m_Group>;
-def malign_branch_EQ : CommaJoined<["-"], "malign-branch=">, Group<m_Group>, Flags<[DriverOption]>,
+def malign_branch_EQ : CommaJoined<["-"], "malign-branch=">, Group<m_Group>, Flags<[NoXarchOption]>,
HelpText<"Specify types of branches to align">;
-def malign_branch_boundary_EQ : Joined<["-"], "malign-branch-boundary=">, Group<m_Group>, Flags<[DriverOption]>,
+def malign_branch_boundary_EQ : Joined<["-"], "malign-branch-boundary=">, Group<m_Group>, Flags<[NoXarchOption]>,
HelpText<"Specify the boundary's size to align branches">;
-def mpad_max_prefix_size_EQ : Joined<["-"], "mpad-max-prefix-size=">, Group<m_Group>, Flags<[DriverOption]>,
+def mpad_max_prefix_size_EQ : Joined<["-"], "mpad-max-prefix-size=">, Group<m_Group>, Flags<[NoXarchOption]>,
HelpText<"Specify maximum number of prefixes to use for padding">;
-def mbranches_within_32B_boundaries : Flag<["-"], "mbranches-within-32B-boundaries">, Flags<[DriverOption]>, Group<m_Group>,
+def mbranches_within_32B_boundaries : Flag<["-"], "mbranches-within-32B-boundaries">, Flags<[NoXarchOption]>, Group<m_Group>,
HelpText<"Align selected branches (fused, jcc, jmp) within 32-byte boundary">;
def mfancy_math_387 : Flag<["-"], "mfancy-math-387">, Group<clang_ignored_m_Group>;
def mlong_calls : Flag<["-"], "mlong-calls">, Group<m_Group>,
HelpText<"Generate branches with extended addressability, usually via indirect jumps.">;
def mdouble_EQ : Joined<["-"], "mdouble=">, Group<m_Group>, Values<"32,64">, Flags<[CC1Option]>,
- HelpText<"Force double to be 32 bits or 64 bits">;
+ HelpText<"Force double to be 32 bits or 64 bits">,
+ MarshallingInfoStringInt<LangOpts<"DoubleSize">, "0">;
def LongDouble_Group : OptionGroup<"<LongDouble group>">, Group<m_Group>,
DocName<"Long double flags">,
DocBrief<[{Selects the long double implementation}]>;
@@ -2181,29 +2790,33 @@ def mwatchos_version_min_EQ : Joined<["-"], "mwatchos-version-min=">, Group<m_Gr
def mwatchos_simulator_version_min_EQ : Joined<["-"], "mwatchos-simulator-version-min=">;
def mwatchsimulator_version_min_EQ : Joined<["-"], "mwatchsimulator-version-min=">, Alias<mwatchos_simulator_version_min_EQ>;
def march_EQ : Joined<["-"], "march=">, Group<m_Group>, Flags<[CoreOption]>;
-def masm_EQ : Joined<["-"], "masm=">, Group<m_Group>, Flags<[DriverOption]>;
-def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group<m_Group>, Flags<[CC1Option]>;
-def mtls_size_EQ : Joined<["-"], "mtls-size=">, Group<m_Group>, Flags<[DriverOption, CC1Option]>,
+def masm_EQ : Joined<["-"], "masm=">, Group<m_Group>, Flags<[NoXarchOption]>;
+def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group<m_Group>, Flags<[CC1Option]>,
+ MarshallingInfoString<TargetOpts<"CodeModel">, [{"default"}]>;
+def mtls_size_EQ : Joined<["-"], "mtls-size=">, Group<m_Group>, Flags<[NoXarchOption, CC1Option]>,
HelpText<"Specify bit size of immediate TLS offsets (AArch64 ELF only): "
- "12 (for 4KB) | 24 (for 16MB, default) | 32 (for 4GB) | 48 (for 256TB, needs -mcmodel=large)">;
+ "12 (for 4KB) | 24 (for 16MB, default) | 32 (for 4GB) | 48 (for 256TB, needs -mcmodel=large)">,
+ MarshallingInfoStringInt<CodeGenOpts<"TLSSize">>;
def mimplicit_it_EQ : Joined<["-"], "mimplicit-it=">, Group<m_Group>;
def mdefault_build_attributes : Joined<["-"], "mdefault-build-attributes">, Group<m_Group>;
def mno_default_build_attributes : Joined<["-"], "mno-default-build-attributes">, Group<m_Group>;
def mconstant_cfstrings : Flag<["-"], "mconstant-cfstrings">, Group<clang_ignored_m_Group>;
-def mconsole : Joined<["-"], "mconsole">, Group<m_Group>, Flags<[DriverOption]>;
-def mwindows : Joined<["-"], "mwindows">, Group<m_Group>, Flags<[DriverOption]>;
-def mdll : Joined<["-"], "mdll">, Group<m_Group>, Flags<[DriverOption]>;
-def municode : Joined<["-"], "municode">, Group<m_Group>, Flags<[DriverOption]>;
-def mthreads : Joined<["-"], "mthreads">, Group<m_Group>, Flags<[DriverOption]>;
+def mconsole : Joined<["-"], "mconsole">, Group<m_Group>, Flags<[NoXarchOption]>;
+def mwindows : Joined<["-"], "mwindows">, Group<m_Group>, Flags<[NoXarchOption]>;
+def mdll : Joined<["-"], "mdll">, Group<m_Group>, Flags<[NoXarchOption]>;
+def municode : Joined<["-"], "municode">, Group<m_Group>, Flags<[NoXarchOption]>;
+def mthreads : Joined<["-"], "mthreads">, Group<m_Group>, Flags<[NoXarchOption]>;
def mcpu_EQ : Joined<["-"], "mcpu=">, Group<m_Group>;
def mmcu_EQ : Joined<["-"], "mmcu=">, Group<m_Group>;
+def msim : Flag<["-"], "msim">, Group<m_Group>;
def mdynamic_no_pic : Joined<["-"], "mdynamic-no-pic">, Group<m_Group>;
def mfix_and_continue : Flag<["-"], "mfix-and-continue">, Group<clang_ignored_m_Group>;
def mieee_fp : Flag<["-"], "mieee-fp">, Group<clang_ignored_m_Group>;
def minline_all_stringops : Flag<["-"], "minline-all-stringops">, Group<clang_ignored_m_Group>;
def mno_inline_all_stringops : Flag<["-"], "mno-inline-all-stringops">, Group<clang_ignored_m_Group>;
def malign_double : Flag<["-"], "malign-double">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Align doubles to two words in structs (x86 only)">;
+ HelpText<"Align doubles to two words in structs (x86 only)">,
+ MarshallingInfoFlag<LangOpts<"AlignDouble">>;
def mfloat_abi_EQ : Joined<["-"], "mfloat-abi=">, Group<m_Group>, Values<"soft,softfp,hard">;
def mfpmath_EQ : Joined<["-"], "mfpmath=">, Group<m_Group>;
def mfpu_EQ : Joined<["-"], "mfpu=">, Group<m_Group>;
@@ -2219,15 +2832,17 @@ def mios_simulator_version_min_EQ : Joined<["-"], "mios-simulator-version-min=">
def miphonesimulator_version_min_EQ : Joined<["-"], "miphonesimulator-version-min=">, Alias<mios_simulator_version_min_EQ>;
def mkernel : Flag<["-"], "mkernel">, Group<m_Group>;
def mlinker_version_EQ : Joined<["-"], "mlinker-version=">,
- Flags<[DriverOption]>;
+ Flags<[NoXarchOption]>;
def mllvm : Separate<["-"], "mllvm">, Flags<[CC1Option,CC1AsOption,CoreOption]>,
- HelpText<"Additional arguments to forward to LLVM's option processing">;
+ HelpText<"Additional arguments to forward to LLVM's option processing">,
+ MarshallingInfoStringVector<FrontendOpts<"LLVMArgs">>;
def mmacosx_version_min_EQ : Joined<["-"], "mmacosx-version-min=">,
Group<m_Group>, HelpText<"Set Mac OS X deployment target">;
def mmacos_version_min_EQ : Joined<["-"], "mmacos-version-min=">,
Group<m_Group>, Alias<mmacosx_version_min_EQ>;
def mms_bitfields : Flag<["-"], "mms-bitfields">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">;
+ HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">,
+ MarshallingInfoFlag<LangOpts<"MSBitfields">>;
def moutline : Flag<["-"], "moutline">, Group<f_clang_Group>, Flags<[CC1Option]>,
HelpText<"Enable function outlining (AArch64 only)">;
def mno_outline : Flag<["-"], "mno-outline">, Group<f_clang_Group>, Flags<[CC1Option]>,
@@ -2235,19 +2850,26 @@ def mno_outline : Flag<["-"], "mno-outline">, Group<f_clang_Group>, Flags<[CC1Op
def mno_ms_bitfields : Flag<["-"], "mno-ms-bitfields">, Group<m_Group>,
HelpText<"Do not set the default structure layout to be compatible with the Microsoft compiler standard">;
def mstackrealign : Flag<["-"], "mstackrealign">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Force realign the stack at entry to every function">;
+ HelpText<"Force realign the stack at entry to every function">,
+ MarshallingInfoFlag<CodeGenOpts<"StackRealignment">>;
def mstack_alignment : Joined<["-"], "mstack-alignment=">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Set the stack alignment">;
+ HelpText<"Set the stack alignment">,
+ MarshallingInfoStringInt<CodeGenOpts<"StackAlignment">>;
def mstack_probe_size : Joined<["-"], "mstack-probe-size=">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Set the stack probe size">;
+ HelpText<"Set the stack probe size">,
+ MarshallingInfoStringInt<CodeGenOpts<"StackProbeSize">, "4096">;
def mstack_arg_probe : Flag<["-"], "mstack-arg-probe">, Group<m_Group>,
HelpText<"Enable stack probes">;
def mno_stack_arg_probe : Flag<["-"], "mno-stack-arg-probe">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Disable stack probes which are enabled by default">;
+ HelpText<"Disable stack probes which are enabled by default">,
+ MarshallingInfoFlag<CodeGenOpts<"NoStackArgProbe">>;
def mthread_model : Separate<["-"], "mthread-model">, Group<m_Group>, Flags<[CC1Option]>,
HelpText<"The thread model to use, e.g. posix, single (posix by default)">, Values<"posix,single">;
def meabi : Separate<["-"], "meabi">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends on triple)">, Values<"default,4,5,gnu">;
+ HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends on triple)">, Values<"default,4,5,gnu">,
+ MarshallingInfoString<TargetOpts<"EABIVersion">, "Default">,
+ NormalizedValuesScope<"llvm::EABI">,
+ NormalizedValues<["Default", "EABI4", "EABI5", "GNU"]>, AutoNormalizeEnum;
def mno_constant_cfstrings : Flag<["-"], "mno-constant-cfstrings">, Group<m_Group>;
def mno_global_merge : Flag<["-"], "mno-global-merge">, Group<m_Group>, Flags<[CC1Option]>,
@@ -2256,35 +2878,36 @@ def mno_pascal_strings : Flag<["-"], "mno-pascal-strings">,
Alias<fno_pascal_strings>;
def mno_red_zone : Flag<["-"], "mno-red-zone">, Group<m_Group>;
def mno_tls_direct_seg_refs : Flag<["-"], "mno-tls-direct-seg-refs">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Disable direct TLS access through segment registers">;
+ HelpText<"Disable direct TLS access through segment registers">,
+ MarshallingInfoFlag<CodeGenOpts<"IndirectTlsSegRefs">>;
def mno_relax_all : Flag<["-"], "mno-relax-all">, Group<m_Group>;
def mno_rtd: Flag<["-"], "mno-rtd">, Group<m_Group>;
def mno_soft_float : Flag<["-"], "mno-soft-float">, Group<m_Group>;
def mno_stackrealign : Flag<["-"], "mno-stackrealign">, Group<m_Group>;
-def mretpoline : Flag<["-"], "mretpoline">, Group<m_Group>, Flags<[CoreOption,DriverOption]>;
-def mno_retpoline : Flag<["-"], "mno-retpoline">, Group<m_Group>, Flags<[CoreOption,DriverOption]>;
-def mspeculative_load_hardening : Flag<["-"], "mspeculative-load-hardening">,
- Group<m_Group>, Flags<[CoreOption,CC1Option]>;
-def mno_speculative_load_hardening : Flag<["-"], "mno-speculative-load-hardening">,
- Group<m_Group>, Flags<[CoreOption]>;
-def mlvi_hardening : Flag<["-"], "mlvi-hardening">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
+def mretpoline : Flag<["-"], "mretpoline">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>;
+def mno_retpoline : Flag<["-"], "mno-retpoline">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>;
+defm speculative_load_hardening : BoolOption<"m", "speculative-load-hardening",
+ CodeGenOpts<"SpeculativeLoadHardening">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>, BothFlags<[CoreOption]>>,
+ Group<m_Group>;
+def mlvi_hardening : Flag<["-"], "mlvi-hardening">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>,
HelpText<"Enable all mitigations for Load Value Injection (LVI)">;
-def mno_lvi_hardening : Flag<["-"], "mno-lvi-hardening">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
+def mno_lvi_hardening : Flag<["-"], "mno-lvi-hardening">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>,
HelpText<"Disable mitigations for Load Value Injection (LVI)">;
-def mlvi_cfi : Flag<["-"], "mlvi-cfi">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
+def mlvi_cfi : Flag<["-"], "mlvi-cfi">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>,
HelpText<"Enable only control-flow mitigations for Load Value Injection (LVI)">;
-def mno_lvi_cfi : Flag<["-"], "mno-lvi-cfi">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
+def mno_lvi_cfi : Flag<["-"], "mno-lvi-cfi">, Group<m_Group>, Flags<[CoreOption,NoXarchOption]>,
HelpText<"Disable control-flow mitigations for Load Value Injection (LVI)">;
-def m_seses : Flag<["-"], "mseses">, Group<m_Group>, Flags<[CoreOption, DriverOption]>,
+def m_seses : Flag<["-"], "mseses">, Group<m_Group>, Flags<[CoreOption, NoXarchOption]>,
HelpText<"Enable speculative execution side effect suppression (SESES). "
"Includes LVI control flow integrity mitigations">;
-def mno_seses : Flag<["-"], "mno-seses">, Group<m_Group>, Flags<[CoreOption, DriverOption]>,
+def mno_seses : Flag<["-"], "mno-seses">, Group<m_Group>, Flags<[CoreOption, NoXarchOption]>,
HelpText<"Disable speculative execution side effect suppression (SESES)">;
-def mrelax : Flag<["-"], "mrelax">, Group<m_riscv_Features_Group>,
+def mrelax : Flag<["-"], "mrelax">, Group<m_Group>,
HelpText<"Enable linker relaxation">;
-def mno_relax : Flag<["-"], "mno-relax">, Group<m_riscv_Features_Group>,
+def mno_relax : Flag<["-"], "mno-relax">, Group<m_Group>,
HelpText<"Disable linker relaxation">;
def msmall_data_limit_EQ : Joined<["-"], "msmall-data-limit=">, Group<m_Group>,
Alias<G>,
@@ -2325,11 +2948,19 @@ def mnocrc : Flag<["-"], "mnocrc">, Group<m_arm_Features_Group>,
def mno_neg_immediates: Flag<["-"], "mno-neg-immediates">, Group<m_arm_Features_Group>,
HelpText<"Disallow converting instructions with negative immediates to their negation or inversion.">;
def mcmse : Flag<["-"], "mcmse">, Group<m_arm_Features_Group>,
- Flags<[DriverOption,CC1Option]>,
- HelpText<"Allow use of CMSE (Armv8-M Security Extensions)">;
-def ForceAAPCSBitfieldLoad : Flag<["-"], "fAAPCSBitfieldLoad">, Group<m_arm_Features_Group>,
- Flags<[DriverOption,CC1Option]>,
- HelpText<"Follows the AAPCS standard that all volatile bit-field write generates at least one load. (ARM only).">;
+ Flags<[NoXarchOption,CC1Option]>,
+ HelpText<"Allow use of CMSE (Armv8-M Security Extensions)">,
+ MarshallingInfoFlag<LangOpts<"Cmse">>;
+def ForceAAPCSBitfieldLoad : Flag<["-"], "faapcs-bitfield-load">, Group<m_arm_Features_Group>,
+ Flags<[NoXarchOption,CC1Option]>,
+ HelpText<"Follows the AAPCS standard that all volatile bit-field write generates at least one load. (ARM only).">,
+ MarshallingInfoFlag<CodeGenOpts<"ForceAAPCSBitfieldLoad">>;
+defm aapcs_bitfield_width : BoolOption<"f", "aapcs-bitfield-width",
+ CodeGenOpts<"AAPCSBitfieldWidth">, DefaultTrue,
+ NegFlag<SetFalse, [], "Do not follow">, PosFlag<SetTrue, [], "Follow">,
+ BothFlags<[NoXarchOption, CC1Option], " the AAPCS standard requirement stating that"
+ " volatile bit-field width is dictated by the field container type. (ARM only).">>,
+ Group<m_arm_Features_Group>;
def mgeneral_regs_only : Flag<["-"], "mgeneral-regs-only">, Group<m_aarch64_Features_Group>,
HelpText<"Generate code which only uses the general purpose registers (AArch64 only)">;
@@ -2339,6 +2970,9 @@ def mfix_cortex_a53_835769 : Flag<["-"], "mfix-cortex-a53-835769">,
def mno_fix_cortex_a53_835769 : Flag<["-"], "mno-fix-cortex-a53-835769">,
Group<m_aarch64_Features_Group>,
HelpText<"Don't workaround Cortex-A53 erratum 835769 (AArch64 only)">;
+def mmark_bti_property : Flag<["-"], "mmark-bti-property">,
+ Group<m_aarch64_Features_Group>,
+ HelpText<"Add .note.gnu.property with BTI to assembly files (AArch64 only)">;
foreach i = {1-31} in
def ffixed_x#i : Flag<["-"], "ffixed-x"#i>, Group<m_Group>,
HelpText<"Reserve the x"#i#" register (AArch64/RISC-V only)">;
@@ -2347,6 +2981,12 @@ foreach i = {8-15,18} in
def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, Group<m_aarch64_Features_Group>,
HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
+def msve_vector_bits_EQ : Joined<["-"], "msve-vector-bits=">,
+ Group<m_aarch64_Features_Group>, Flags<[NoXarchOption,CC1Option]>,
+ HelpText<"Specify the size in bits of an SVE vector register. Defaults to the"
+ " vector length agnostic value of \"scalable\". (AArch64 only)">,
+ Values<"128,256,512,1024,2048,scalable">;
+
def msign_return_address_EQ : Joined<["-"], "msign-return-address=">,
Flags<[CC1Option]>, Group<m_Group>, Values<"none,all,non-leaf">,
HelpText<"Select return address signing scope">;
@@ -2382,43 +3022,41 @@ def mexec_model_EQ : Joined<["-"], "mexec-model=">, Group<m_wasm_Features_Driver
Values<"command,reactor">,
HelpText<"Execution model (WebAssembly only)">;
-def mamdgpu_debugger_abi : Joined<["-"], "mamdgpu-debugger-abi=">,
- Flags<[HelpHidden]>,
- Group<m_Group>,
- HelpText<"Generate additional code for specified <version> of debugger ABI (AMDGPU only)">,
- MetaVarName<"<version>">;
-
-def mcode_object_v3 : Flag<["-"], "mcode-object-v3">, Group<m_amdgpu_Features_Group>,
- HelpText<"Enable code object v3 (AMDGPU only)">;
-def mno_code_object_v3 : Flag<["-"], "mno-code-object-v3">, Group<m_amdgpu_Features_Group>,
- HelpText<"Disable code object v3 (AMDGPU only)">;
-def mxnack : Flag<["-"], "mxnack">, Group<m_amdgpu_Features_Group>,
- HelpText<"Enable XNACK (AMDGPU only)">;
-def mno_xnack : Flag<["-"], "mno-xnack">, Group<m_amdgpu_Features_Group>,
- HelpText<"Disable XNACK (AMDGPU only)">;
-def msram_ecc : Flag<["-"], "msram-ecc">, Group<m_amdgpu_Features_Group>,
- HelpText<"Enable SRAM ECC (AMDGPU only)">;
-def mno_sram_ecc : Flag<["-"], "mno-sram-ecc">, Group<m_amdgpu_Features_Group>,
- HelpText<"Disable SRAM ECC (AMDGPU only)">;
+def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, Group<m_Group>,
+ HelpText<"Specify code object ABI version. Defaults to 3. (AMDGPU only)">,
+ MetaVarName<"<version>">, Values<"2,3,4">;
+
+def mcode_object_v3_legacy : Flag<["-"], "mcode-object-v3">, Group<m_Group>,
+ HelpText<"Legacy option to specify code object ABI V2 (-mnocode-object-v3) or V3 (-mcode-object-v3) (AMDGPU only)">;
+def mno_code_object_v3_legacy : Flag<["-"], "mno-code-object-v3">, Group<m_Group>;
def mcumode : Flag<["-"], "mcumode">, Group<m_amdgpu_Features_Group>,
- HelpText<"CU wavefront execution mode is used (AMDGPU only)">;
-def mno_cumode : Flag<["-"], "mno-cumode">, Group<m_amdgpu_Features_Group>,
- HelpText<"WGP wavefront execution mode is used (AMDGPU only)">;
+ HelpText<"Specify CU (-mcumode) or WGP (-mno-cumode) wavefront execution mode (AMDGPU only)">;
+def mno_cumode : Flag<["-"], "mno-cumode">, Group<m_amdgpu_Features_Group>;
+
+def mwavefrontsize64 : Flag<["-"], "mwavefrontsize64">, Group<m_Group>,
+ HelpText<"Specify wavefront size 64 mode (AMDGPU only)">;
+def mno_wavefrontsize64 : Flag<["-"], "mno-wavefrontsize64">, Group<m_Group>,
+ HelpText<"Specify wavefront size 32 mode (AMDGPU only)">;
-def mwavefrontsize64 : Flag<["-"], "mwavefrontsize64">,
- Group<m_Group>, HelpText<"Wavefront size 64 is used">;
-def mno_wavefrontsize64 : Flag<["-"], "mno-wavefrontsize64">,
- Group<m_Group>, HelpText<"Wavefront size 32 is used">;
+defm unsafe_fp_atomics : BoolOption<"m", "unsafe-fp-atomics",
+ TargetOpts<"AllowAMDGPUUnsafeFPAtomics">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable unsafe floating point atomic instructions (AMDGPU only)">,
+ NegFlag<SetFalse>>, Group<m_Group>;
-def faltivec : Flag<["-"], "faltivec">, Group<f_Group>, Flags<[DriverOption]>;
-def fno_altivec : Flag<["-"], "fno-altivec">, Group<f_Group>, Flags<[DriverOption]>;
+def faltivec : Flag<["-"], "faltivec">, Group<f_Group>, Flags<[NoXarchOption]>;
+def fno_altivec : Flag<["-"], "fno-altivec">, Group<f_Group>, Flags<[NoXarchOption]>;
def maltivec : Flag<["-"], "maltivec">, Group<m_ppc_Features_Group>;
def mno_altivec : Flag<["-"], "mno-altivec">, Group<m_ppc_Features_Group>;
def mpcrel: Flag<["-"], "mpcrel">, Group<m_ppc_Features_Group>;
def mno_pcrel: Flag<["-"], "mno-pcrel">, Group<m_ppc_Features_Group>;
def mspe : Flag<["-"], "mspe">, Group<m_ppc_Features_Group>;
def mno_spe : Flag<["-"], "mno-spe">, Group<m_ppc_Features_Group>;
+def mefpu2 : Flag<["-"], "mefpu2">, Group<m_ppc_Features_Group>;
+def mabi_EQ_vec_extabi : Flag<["-"], "mabi=vec-extabi">, Group<m_Group>, Flags<[CC1Option]>,
+ HelpText<"Enable the extended Altivec ABI on AIX (AIX only). Uses volatile and nonvolatile vector registers">;
+def mabi_EQ_vec_default : Flag<["-"], "mabi=vec-default">, Group<m_Group>, Flags<[CC1Option]>,
+ HelpText<"Enable the default Altivec ABI on AIX (AIX only). Uses only volatile vector registers.">;
def mvsx : Flag<["-"], "mvsx">, Group<m_ppc_Features_Group>;
def mno_vsx : Flag<["-"], "mno-vsx">, Group<m_ppc_Features_Group>;
def msecure_plt : Flag<["-"], "msecure-plt">, Group<m_ppc_Features_Group>;
@@ -2442,6 +3080,10 @@ def mdirect_move : Flag<["-"], "mdirect-move">,
Group<m_ppc_Features_Group>;
def mnodirect_move : Flag<["-"], "mno-direct-move">,
Group<m_ppc_Features_Group>;
+def mpaired_vector_memops: Flag<["-"], "mpaired-vector-memops">,
+ Group<m_ppc_Features_Group>;
+def mnopaired_vector_memops: Flag<["-"], "mno-paired-vector-memops">,
+ Group<m_ppc_Features_Group>;
def mhtm : Flag<["-"], "mhtm">, Group<m_ppc_Features_Group>;
def mno_htm : Flag<["-"], "mno-htm">, Group<m_ppc_Features_Group>;
def mfprnd : Flag<["-"], "mfprnd">, Group<m_ppc_Features_Group>;
@@ -2456,8 +3098,6 @@ def mno_mfocrf : Flag<["-"], "mno-mfocrf">, Group<m_ppc_Features_Group>;
def mno_mfcrf : Flag<["-"], "mno-mfcrf">, Alias<mno_mfocrf>;
def mpopcntd : Flag<["-"], "mpopcntd">, Group<m_ppc_Features_Group>;
def mno_popcntd : Flag<["-"], "mno-popcntd">, Group<m_ppc_Features_Group>;
-def mqpx : Flag<["-"], "mqpx">, Group<m_ppc_Features_Group>;
-def mno_qpx : Flag<["-"], "mno-qpx">, Group<m_ppc_Features_Group>;
def mcrbits : Flag<["-"], "mcrbits">, Group<m_ppc_Features_Group>;
def mno_crbits : Flag<["-"], "mno-crbits">, Group<m_ppc_Features_Group>;
def minvariant_function_descriptors :
@@ -2473,6 +3113,8 @@ def mlongcall: Flag<["-"], "mlongcall">,
Group<m_ppc_Features_Group>;
def mno_longcall : Flag<["-"], "mno-longcall">,
Group<m_ppc_Features_Group>;
+def mmma: Flag<["-"], "mmma">, Group<m_ppc_Features_Group>;
+def mno_mma: Flag<["-"], "mno-mma">, Group<m_ppc_Features_Group>;
def maix_struct_return : Flag<["-"], "maix-struct-return">,
Group<m_Group>, Flags<[CC1Option]>,
HelpText<"Return all structs in memory (PPC32 only)">;
@@ -2483,13 +3125,20 @@ def msvr4_struct_return : Flag<["-"], "msvr4-struct-return">,
def mvx : Flag<["-"], "mvx">, Group<m_Group>;
def mno_vx : Flag<["-"], "mno-vx">, Group<m_Group>;
-defm zvector : OptInFFlag<"zvector", "Enable System z vector language extension">;
+defm zvector : BoolFOption<"zvector",
+ LangOpts<"ZVector">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable System z vector language extension">,
+ NegFlag<SetFalse>>;
def mzvector : Flag<["-"], "mzvector">, Alias<fzvector>;
def mno_zvector : Flag<["-"], "mno-zvector">, Alias<fno_zvector>;
-def mbackchain : Flag<["-"], "mbackchain">, Group<m_Group>, Flags<[DriverOption,CC1Option]>,
- HelpText<"Link stack frames through backchain on System Z">;
-def mno_backchain : Flag<["-"], "mno-backchain">, Group<m_Group>, Flags<[DriverOption,CC1Option]>;
+def mignore_xcoff_visibility : Flag<["-"], "mignore-xcoff-visibility">, Group<m_Group>,
+HelpText<"Not emit the visibility attribute for asm in AIX OS or give all symbols 'unspecified' visibility in XCOFF object file">,
+ Flags<[CC1Option]>;
+defm backchain : BoolOption<"m", "backchain",
+ CodeGenOpts<"Backchain">, DefaultFalse,
+ PosFlag<SetTrue, [], "Link stack frames through backchain on System Z">,
+ NegFlag<SetFalse>, BothFlags<[NoXarchOption,CC1Option]>>, Group<m_Group>;
def mno_warn_nonportable_cfstrings : Flag<["-"], "mno-warn-nonportable-cfstrings">, Group<m_Group>;
def mno_omit_leaf_frame_pointer : Flag<["-"], "mno-omit-leaf-frame-pointer">, Group<m_Group>;
@@ -2502,10 +3151,12 @@ def mtls_direct_seg_refs : Flag<["-"], "mtls-direct-seg-refs">, Group<m_Group>,
HelpText<"Enable direct TLS access through segment registers (default)">;
def mregparm_EQ : Joined<["-"], "mregparm=">, Group<m_Group>;
def mrelax_all : Flag<["-"], "mrelax-all">, Group<m_Group>, Flags<[CC1Option,CC1AsOption]>,
- HelpText<"(integrated-as) Relax all machine instructions">;
+ HelpText<"(integrated-as) Relax all machine instructions">,
+ MarshallingInfoFlag<CodeGenOpts<"RelaxAll">>;
def mincremental_linker_compatible : Flag<["-"], "mincremental-linker-compatible">, Group<m_Group>,
Flags<[CC1Option,CC1AsOption]>,
- HelpText<"(integrated-as) Emit an object file which can be used with an incremental linker">;
+ HelpText<"(integrated-as) Emit an object file which can be used with an incremental linker">,
+ MarshallingInfoFlag<CodeGenOpts<"IncrementalLinkerCompatible">>;
def mno_incremental_linker_compatible : Flag<["-"], "mno-incremental-linker-compatible">, Group<m_Group>,
HelpText<"(integrated-as) Emit an object file which cannot be used with an incremental linker">;
def mrtd : Flag<["-"], "mrtd">, Group<m_Group>, Flags<[CC1Option]>,
@@ -2513,26 +3164,46 @@ def mrtd : Flag<["-"], "mrtd">, Group<m_Group>, Flags<[CC1Option]>,
def msmall_data_threshold_EQ : Joined <["-"], "msmall-data-threshold=">,
Group<m_Group>, Alias<G>;
def msoft_float : Flag<["-"], "msoft-float">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Use software floating point">;
+ HelpText<"Use software floating point">,
+ MarshallingInfoFlag<CodeGenOpts<"SoftFloat">>;
+def moutline_atomics : Flag<["-"], "moutline-atomics">, Group<f_clang_Group>, Flags<[CC1Option]>,
+ HelpText<"Generate local calls to out-of-line atomic operations">;
+def mno_outline_atomics : Flag<["-"], "mno-outline-atomics">, Group<f_clang_Group>, Flags<[CC1Option]>,
+ HelpText<"Don't generate local calls to out-of-line atomic operations">;
def mno_implicit_float : Flag<["-"], "mno-implicit-float">, Group<m_Group>,
HelpText<"Don't generate implicit floating point instructions">;
def mimplicit_float : Flag<["-"], "mimplicit-float">, Group<m_Group>;
def mrecip : Flag<["-"], "mrecip">, Group<m_Group>;
-def mrecip_EQ : CommaJoined<["-"], "mrecip=">, Group<m_Group>, Flags<[CC1Option]>;
+def mrecip_EQ : CommaJoined<["-"], "mrecip=">, Group<m_Group>, Flags<[CC1Option]>,
+ MarshallingInfoStringVector<CodeGenOpts<"Reciprocals">>;
def mprefer_vector_width_EQ : Joined<["-"], "mprefer-vector-width=">, Group<m_Group>, Flags<[CC1Option]>,
- HelpText<"Specifies preferred vector width for auto-vectorization. Defaults to 'none' which allows target specific decisions.">;
-def mpie_copy_relocations : Flag<["-"], "mpie-copy-relocations">, Group<m_Group>,
- Flags<[CC1Option]>,
- HelpText<"Use copy relocations support for PIE builds">;
-def mno_pie_copy_relocations : Flag<["-"], "mno-pie-copy-relocations">, Group<m_Group>;
+ HelpText<"Specifies preferred vector width for auto-vectorization. Defaults to 'none' which allows target specific decisions.">,
+ MarshallingInfoString<CodeGenOpts<"PreferVectorWidth">>;
+def mstack_protector_guard_EQ : Joined<["-"], "mstack-protector-guard=">, Group<m_Group>, Flags<[CC1Option]>,
+ HelpText<"Use the given guard (global, tls) for addressing the stack-protector guard">,
+ MarshallingInfoString<CodeGenOpts<"StackProtectorGuard">>;
+def mstack_protector_guard_offset_EQ : Joined<["-"], "mstack-protector-guard-offset=">, Group<m_Group>, Flags<[CC1Option]>,
+ HelpText<"Use the given offset for addressing the stack-protector guard">,
+ MarshallingInfoStringInt<CodeGenOpts<"StackProtectorGuardOffset">, "(unsigned)-1">;
+def mstack_protector_guard_reg_EQ : Joined<["-"], "mstack-protector-guard-reg=">, Group<m_Group>, Flags<[CC1Option]>,
+ HelpText<"Use the given reg for addressing the stack-protector guard">,
+ MarshallingInfoString<CodeGenOpts<"StackProtectorGuardReg">, [{"none"}]>;
+def mpie_copy_relocations : Flag<["-"], "mpie-copy-relocations">,
+ Alias<fdirect_access_external_data>, Group<m_Group>;
+def mno_pie_copy_relocations : Flag<["-"], "mno-pie-copy-relocations">,
+ Alias<fno_direct_access_external_data>, Group<m_Group>;
def mfentry : Flag<["-"], "mfentry">, HelpText<"Insert calls to fentry at function entry (x86/SystemZ only)">,
- Flags<[CC1Option]>, Group<m_Group>;
+ Flags<[CC1Option]>, Group<m_Group>,
+ MarshallingInfoFlag<CodeGenOpts<"CallFEntry">>;
def mnop_mcount : Flag<["-"], "mnop-mcount">, HelpText<"Generate mcount/__fentry__ calls as nops. To activate they need to be patched in.">,
- Flags<[CC1Option]>, Group<m_Group>;
+ Flags<[CC1Option]>, Group<m_Group>,
+ MarshallingInfoFlag<CodeGenOpts<"MNopMCount">>;
def mrecord_mcount : Flag<["-"], "mrecord-mcount">, HelpText<"Generate a __mcount_loc section entry for each __fentry__ call.">,
- Flags<[CC1Option]>, Group<m_Group>;
+ Flags<[CC1Option]>, Group<m_Group>,
+ MarshallingInfoFlag<CodeGenOpts<"RecordMCount">>;
def mpacked_stack : Flag<["-"], "mpacked-stack">, HelpText<"Use packed stack layout (SystemZ only).">,
- Flags<[CC1Option]>, Group<m_Group>;
+ Flags<[CC1Option]>, Group<m_Group>,
+ MarshallingInfoFlag<CodeGenOpts<"PackedStack">>;
def mno_packed_stack : Flag<["-"], "mno-packed-stack">, Flags<[CC1Option]>, Group<m_Group>;
def mips16 : Flag<["-"], "mips16">, Group<m_mips_Features_Group>;
def mno_mips16 : Flag<["-"], "mno-mips16">, Group<m_mips_Features_Group>;
@@ -2681,11 +3352,11 @@ def mno_relax_pic_calls : Flag<["-"], "mno-relax-pic-calls">,
"call sequences into direct calls (MIPS only)">, Flags<[HelpHidden]>;
def mglibc : Flag<["-"], "mglibc">, Group<m_libc_Group>, Flags<[HelpHidden]>;
def muclibc : Flag<["-"], "muclibc">, Group<m_libc_Group>, Flags<[HelpHidden]>;
-def module_file_info : Flag<["-"], "module-file-info">, Flags<[DriverOption,CC1Option]>, Group<Action_Group>,
+def module_file_info : Flag<["-"], "module-file-info">, Flags<[NoXarchOption,CC1Option]>, Group<Action_Group>,
HelpText<"Provide information about a particular module file">;
def mthumb : Flag<["-"], "mthumb">, Group<m_Group>;
def mtune_EQ : Joined<["-"], "mtune=">, Group<m_Group>,
- HelpText<"Accepted for compatibility with GCC. Currently has no effect.">;
+ HelpText<"Only supported on X86 and RISC-V. Otherwise accepted for compatibility with GCC.">;
def multi__module : Flag<["-"], "multi_module">;
def multiply__defined__unused : Separate<["-"], "multiply_defined_unused">;
def multiply__defined : Separate<["-"], "multiply_defined">;
@@ -2693,12 +3364,14 @@ def mwarn_nonportable_cfstrings : Flag<["-"], "mwarn-nonportable-cfstrings">, Gr
def no_canonical_prefixes : Flag<["-"], "no-canonical-prefixes">, Flags<[HelpHidden, CoreOption]>,
HelpText<"Use relative instead of canonical paths">;
def no_cpp_precomp : Flag<["-"], "no-cpp-precomp">, Group<clang_ignored_f_Group>;
-def no_integrated_cpp : Flag<["-", "--"], "no-integrated-cpp">, Flags<[DriverOption]>;
+def no_integrated_cpp : Flag<["-", "--"], "no-integrated-cpp">, Flags<[NoXarchOption]>;
def no_pedantic : Flag<["-", "--"], "no-pedantic">, Group<pedantic_Group>;
def no__dead__strip__inits__and__terms : Flag<["-"], "no_dead_strip_inits_and_terms">;
def nobuiltininc : Flag<["-"], "nobuiltininc">, Flags<[CC1Option, CoreOption]>,
- HelpText<"Disable builtin #include directories">;
-def nogpuinc : Flag<["-"], "nogpuinc">;
+ HelpText<"Disable builtin #include directories">,
+ MarshallingInfoNegativeFlag<HeaderSearchOpts<"UseBuiltinIncludes">>;
+def nogpuinc : Flag<["-"], "nogpuinc">, HelpText<"Do not add include paths for CUDA/HIP and"
+ " do not include the default CUDA/HIP wrapper headers">;
def : Flag<["-"], "nocudainc">, Alias<nogpuinc>;
def nogpulib : Flag<["-"], "nogpulib">,
HelpText<"Do not link device library for CUDA/HIP device compilation">;
@@ -2712,21 +3385,27 @@ def no_pie : Flag<["-"], "no-pie">, Alias<nopie>;
def noprebind : Flag<["-"], "noprebind">;
def noprofilelib : Flag<["-"], "noprofilelib">;
def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group<Link_Group>;
def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
def nostdlibinc : Flag<["-"], "nostdlibinc">;
def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
- HelpText<"Disable standard #include directories for the C++ standard library">;
-def nostdlib : Flag<["-"], "nostdlib">;
+ HelpText<"Disable standard #include directories for the C++ standard library">,
+ MarshallingInfoNegativeFlag<HeaderSearchOpts<"UseStandardCXXIncludes">>;
+def nostdlib : Flag<["-"], "nostdlib">, Group<Link_Group>;
def nostdlibxx : Flag<["-"], "nostdlib++">;
def object : Flag<["-"], "object">;
-def o : JoinedOrSeparate<["-"], "o">, Flags<[DriverOption, RenderAsInput, CC1Option, CC1AsOption]>,
- HelpText<"Write output to <file>">, MetaVarName<"<file>">;
+def o : JoinedOrSeparate<["-"], "o">, Flags<[NoXarchOption, RenderAsInput,
+ CC1Option, CC1AsOption, FC1Option, FlangOption]>,
+ HelpText<"Write output to <file>">, MetaVarName<"<file>">,
+ MarshallingInfoString<FrontendOpts<"OutputFile">>;
def pagezero__size : JoinedOrSeparate<["-"], "pagezero_size">;
def pass_exit_codes : Flag<["-", "--"], "pass-exit-codes">, Flags<[Unsupported]>;
-def pedantic_errors : Flag<["-", "--"], "pedantic-errors">, Group<pedantic_Group>, Flags<[CC1Option]>;
-def pedantic : Flag<["-", "--"], "pedantic">, Group<pedantic_Group>, Flags<[CC1Option]>;
-def pg : Flag<["-"], "pg">, HelpText<"Enable mcount instrumentation">, Flags<[CC1Option]>;
+def pedantic_errors : Flag<["-", "--"], "pedantic-errors">, Group<pedantic_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<DiagnosticOpts<"PedanticErrors">>;
+def pedantic : Flag<["-", "--"], "pedantic">, Group<pedantic_Group>, Flags<[CC1Option]>,
+ MarshallingInfoFlag<DiagnosticOpts<"Pedantic">>;
+def pg : Flag<["-"], "pg">, HelpText<"Enable mcount instrumentation">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<CodeGenOpts<"InstrumentForProfiling">>;
def pipe : Flag<["-", "--"], "pipe">,
HelpText<"Use pipes between commands, when possible">;
def prebind__all__twolevel__modules : Flag<["-"], "prebind_all_twolevel_modules">;
@@ -2735,7 +3414,8 @@ def preload : Flag<["-"], "preload">;
def print_file_name_EQ : Joined<["-", "--"], "print-file-name=">,
HelpText<"Print the full library path of <file>">, MetaVarName<"<file>">;
def print_ivar_layout : Flag<["-"], "print-ivar-layout">, Flags<[CC1Option]>,
- HelpText<"Enable Objective-C Ivar layout bitmap print trace">;
+ HelpText<"Enable Objective-C Ivar layout bitmap print trace">,
+ MarshallingInfoFlag<LangOpts<"ObjCGCBitmapPrint">>;
def print_libgcc_file_name : Flag<["-", "--"], "print-libgcc-file-name">,
HelpText<"Print the library path for the currently used compiler runtime "
"library (\"libgcc.a\" or \"libclang_rt.builtins.*.a\")">;
@@ -2757,23 +3437,25 @@ def print_targets : Flag<["-", "--"], "print-targets">,
HelpText<"Print the registered targets">;
def private__bundle : Flag<["-"], "private_bundle">;
def pthreads : Flag<["-"], "pthreads">;
-def pthread : Flag<["-"], "pthread">, Flags<[CC1Option]>,
- HelpText<"Support POSIX threads in generated code">;
-def no_pthread : Flag<["-"], "no-pthread">, Flags<[CC1Option]>;
+defm pthread : BoolOption<"", "pthread",
+ LangOpts<"POSIXThreads">, DefaultFalse,
+ PosFlag<SetTrue, [], "Support POSIX threads in generated code">,
+ NegFlag<SetFalse>, BothFlags<[CC1Option]>>;
def p : Flag<["-"], "p">;
-def pie : Flag<["-"], "pie">;
-def static_pie : Flag<["-"], "static-pie">;
+def pie : Flag<["-"], "pie">, Group<Link_Group>;
+def static_pie : Flag<["-"], "static-pie">, Group<Link_Group>;
def read__only__relocs : Separate<["-"], "read_only_relocs">;
def remap : Flag<["-"], "remap">;
-def rewrite_objc : Flag<["-"], "rewrite-objc">, Flags<[DriverOption,CC1Option]>,
+def rewrite_objc : Flag<["-"], "rewrite-objc">, Flags<[NoXarchOption,CC1Option]>,
HelpText<"Rewrite Objective-C source to C++">, Group<Action_Group>;
-def rewrite_legacy_objc : Flag<["-"], "rewrite-legacy-objc">, Flags<[DriverOption]>,
+def rewrite_legacy_objc : Flag<["-"], "rewrite-legacy-objc">, Flags<[NoXarchOption]>,
HelpText<"Rewrite Legacy Objective-C source to C++">;
-def rdynamic : Flag<["-"], "rdynamic">;
+def rdynamic : Flag<["-"], "rdynamic">, Group<Link_Group>;
def resource_dir : Separate<["-"], "resource-dir">,
- Flags<[DriverOption, CC1Option, CoreOption, HelpHidden]>,
- HelpText<"The directory which holds the compiler resource files">;
-def resource_dir_EQ : Joined<["-"], "resource-dir=">, Flags<[DriverOption, CoreOption]>,
+ Flags<[NoXarchOption, CC1Option, CoreOption, HelpHidden]>,
+ HelpText<"The directory which holds the compiler resource files">,
+ MarshallingInfoString<HeaderSearchOpts<"ResourceDir">>;
+def resource_dir_EQ : Joined<["-"], "resource-dir=">, Flags<[NoXarchOption, CoreOption]>,
Alias<resource_dir>;
def rpath : Separate<["-"], "rpath">, Flags<[LinkerInput]>, Group<Link_Group>;
def rtlib_EQ : Joined<["-", "--"], "rtlib=">,
@@ -2784,14 +3466,14 @@ def fno_rtlib_add_rpath: Flag<["-"], "fno-rtlib-add-rpath">, Flags<[NoArgumentUn
HelpText<"Do not add -rpath with architecture-specific resource directory to the linker flags">;
def r : Flag<["-"], "r">, Flags<[LinkerInput,NoArgumentUnused]>,
Group<Link_Group>;
-def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[CC1Option, DriverOption]>,
+def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[CC1Option, NoXarchOption]>,
HelpText<"Save intermediate compilation results.">;
-def save_temps : Flag<["-", "--"], "save-temps">, Flags<[DriverOption]>,
+def save_temps : Flag<["-", "--"], "save-temps">, Flags<[NoXarchOption]>,
Alias<save_temps_EQ>, AliasArgs<["cwd"]>,
HelpText<"Save intermediate compilation results">;
-def save_stats_EQ : Joined<["-", "--"], "save-stats=">, Flags<[DriverOption]>,
+def save_stats_EQ : Joined<["-", "--"], "save-stats=">, Flags<[NoXarchOption]>,
HelpText<"Save llvm statistics.">;
-def save_stats : Flag<["-", "--"], "save-stats">, Flags<[DriverOption]>,
+def save_stats : Flag<["-", "--"], "save-stats">, Flags<[NoXarchOption]>,
Alias<save_stats_EQ>, AliasArgs<["cwd"]>,
HelpText<"Save llvm statistics.">;
def via_file_asm : Flag<["-", "--"], "via-file-asm">, InternalDebugOpt,
@@ -2811,13 +3493,13 @@ def segs__read__only__addr : Separate<["-"], "segs_read_only_addr">;
def segs__read__write__addr : Separate<["-"], "segs_read_write_addr">;
def segs__read__ : Joined<["-"], "segs_read_">;
def shared_libgcc : Flag<["-"], "shared-libgcc">;
-def shared : Flag<["-", "--"], "shared">;
+def shared : Flag<["-", "--"], "shared">, Group<Link_Group>;
def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group<Link_Group>;
def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
def static_libgcc : Flag<["-"], "static-libgcc">;
def static_libstdcxx : Flag<["-"], "static-libstdc++">;
-def static : Flag<["-", "--"], "static">, Flags<[NoArgumentUnused]>;
+def static : Flag<["-", "--"], "static">, Group<Link_Group>, Flags<[NoArgumentUnused]>;
def std_default_EQ : Joined<["-"], "std-default=">;
def std_EQ : Joined<["-", "--"], "std=">, Flags<[CC1Option]>,
Group<CompileOnly_Group>, HelpText<"Language standard to compile for">,
@@ -2833,7 +3515,7 @@ def stdlib_EQ : Joined<["-", "--"], "stdlib=">, Flags<[CC1Option]>,
def stdlibxx_isystem : JoinedOrSeparate<["-"], "stdlib++-isystem">,
Group<clang_i_Group>,
HelpText<"Use directory as the C++ standard library include path">,
- Flags<[DriverOption]>, MetaVarName<"<directory>">;
+ Flags<[NoXarchOption]>, MetaVarName<"<directory>">;
def unwindlib_EQ : Joined<["-", "--"], "unwindlib=">, Flags<[CC1Option]>,
HelpText<"Unwind library to use">, Values<"libgcc,unwindlib,platform">;
def sub__library : JoinedOrSeparate<["-"], "sub_library">;
@@ -2849,20 +3531,22 @@ def no_system_header_prefix : Joined<["--"], "no-system-header-prefix=">,
"system header.">;
def : Separate<["--"], "no-system-header-prefix">, Alias<no_system_header_prefix>;
def s : Flag<["-"], "s">, Group<Link_Group>;
-def target : Joined<["--"], "target=">, Flags<[DriverOption, CoreOption]>,
+def target : Joined<["--"], "target=">, Flags<[NoXarchOption, CoreOption]>,
HelpText<"Generate code for the given target">;
def print_supported_cpus : Flag<["-", "--"], "print-supported-cpus">,
Group<CompileOnly_Group>, Flags<[CC1Option, CoreOption]>,
HelpText<"Print supported cpu models for the given target (if target is not specified,"
- " it will print the supported cpus for the default target)">;
+ " it will print the supported cpus for the default target)">,
+ MarshallingInfoFlag<FrontendOpts<"PrintSupportedCPUs">>;
def mcpu_EQ_QUESTION : Flag<["-"], "mcpu=?">, Alias<print_supported_cpus>;
def mtune_EQ_QUESTION : Flag<["-"], "mtune=?">, Alias<print_supported_cpus>;
-def gcc_toolchain : Joined<["--"], "gcc-toolchain=">, Flags<[DriverOption]>,
+def gcc_toolchain : Joined<["--"], "gcc-toolchain=">, Flags<[NoXarchOption]>,
HelpText<"Use the gcc toolchain at the given directory">;
def time : Flag<["-"], "time">,
HelpText<"Time individual commands">;
def traditional_cpp : Flag<["-", "--"], "traditional-cpp">, Flags<[CC1Option]>,
- HelpText<"Enable some traditional CPP emulation">;
+ HelpText<"Enable some traditional CPP emulation">,
+ MarshallingInfoFlag<LangOpts<"TraditionalCPP">>;
def traditional : Flag<["-", "--"], "traditional">;
def trigraphs : Flag<["-", "--"], "trigraphs">, Alias<ftrigraphs>,
HelpText<"Process trigraph sequences">;
@@ -2872,12 +3556,14 @@ def t : Flag<["-"], "t">, Group<Link_Group>;
def umbrella : Separate<["-"], "umbrella">;
def undefined : JoinedOrSeparate<["-"], "undefined">, Group<u_Group>;
def undef : Flag<["-"], "undef">, Group<u_Group>, Flags<[CC1Option]>,
- HelpText<"undef all system defines">;
+ HelpText<"undef all system defines">,
+ MarshallingInfoNegativeFlag<PreprocessorOpts<"UsePredefines">>;
def unexported__symbols__list : Separate<["-"], "unexported_symbols_list">;
def u : JoinedOrSeparate<["-"], "u">, Group<u_Group>;
def v : Flag<["-"], "v">, Flags<[CC1Option, CoreOption]>,
- HelpText<"Show commands to run and use verbose output">;
-def verify_debug_info : Flag<["--"], "verify-debug-info">, Flags<[DriverOption]>,
+ HelpText<"Show commands to run and use verbose output">,
+ MarshallingInfoFlag<HeaderSearchOpts<"Verbose">>;
+def verify_debug_info : Flag<["--"], "verify-debug-info">, Flags<[NoXarchOption]>,
HelpText<"Verify the binary representation of debug output">;
def weak_l : Joined<["-"], "weak-l">, Flags<[LinkerInput]>;
def weak__framework : Separate<["-"], "weak_framework">, Flags<[LinkerInput]>;
@@ -2885,27 +3571,32 @@ def weak__library : Separate<["-"], "weak_library">, Flags<[LinkerInput]>;
def weak__reference__mismatches : Separate<["-"], "weak_reference_mismatches">;
def whatsloaded : Flag<["-"], "whatsloaded">;
def whyload : Flag<["-"], "whyload">;
-def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">, Flags<[CC1Option]>;
-def x : JoinedOrSeparate<["-"], "x">, Flags<[DriverOption,CC1Option]>,
+def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">, Flags<[CC1Option]>,
+ MarshallingInfoFlag<DiagnosticOpts<"IgnoreWarnings">>;
+def x : JoinedOrSeparate<["-"], "x">, Flags<[NoXarchOption,CC1Option]>,
HelpText<"Treat subsequent input files as having type <language>">,
MetaVarName<"<language>">;
def y : Joined<["-"], "y">;
-defm integrated_as : OptOutFFlag<"integrated-as", "Enable the integrated assembler", "Disable the integrated assembler">;
+defm integrated_as : BoolFOption<"integrated-as",
+ CodeGenOpts<"DisableIntegratedAS">, DefaultFalse,
+ NegFlag<SetTrue, [CC1Option], "Disable">, PosFlag<SetFalse, [], "Enable">,
+ BothFlags<[], " the integrated assembler">>;
def fintegrated_cc1 : Flag<["-"], "fintegrated-cc1">,
- Flags<[CoreOption, DriverOption]>, Group<f_Group>,
+ Flags<[CoreOption, NoXarchOption]>, Group<f_Group>,
HelpText<"Run cc1 in-process">;
def fno_integrated_cc1 : Flag<["-"], "fno-integrated-cc1">,
- Flags<[CoreOption, DriverOption]>, Group<f_Group>,
+ Flags<[CoreOption, NoXarchOption]>, Group<f_Group>,
HelpText<"Spawn a separate process for each cc1">;
-def : Flag<["-"], "integrated-as">, Alias<fintegrated_as>, Flags<[DriverOption]>;
+def : Flag<["-"], "integrated-as">, Alias<fintegrated_as>, Flags<[NoXarchOption]>;
def : Flag<["-"], "no-integrated-as">, Alias<fno_integrated_as>,
- Flags<[CC1Option, DriverOption]>;
+ Flags<[CC1Option, NoXarchOption]>;
def working_directory : JoinedOrSeparate<["-"], "working-directory">, Flags<[CC1Option]>,
- HelpText<"Resolve file paths relative to the specified directory">;
+ HelpText<"Resolve file paths relative to the specified directory">,
+ MarshallingInfoString<FileSystemOpts<"WorkingDir">>;
def working_directory_EQ : Joined<["-"], "working-directory=">, Flags<[CC1Option]>,
Alias<working_directory>;
@@ -2917,10 +3608,10 @@ def _mhwdiv : Separate<["--"], "mhwdiv">, Alias<mhwdiv_EQ>;
def _CLASSPATH_EQ : Joined<["--"], "CLASSPATH=">, Alias<fclasspath_EQ>;
def _CLASSPATH : Separate<["--"], "CLASSPATH">, Alias<fclasspath_EQ>;
def _all_warnings : Flag<["--"], "all-warnings">, Alias<Wall>;
-def _analyzer_no_default_checks : Flag<["--"], "analyzer-no-default-checks">, Flags<[DriverOption]>;
-def _analyzer_output : JoinedOrSeparate<["--"], "analyzer-output">, Flags<[DriverOption]>,
+def _analyzer_no_default_checks : Flag<["--"], "analyzer-no-default-checks">, Flags<[NoXarchOption]>;
+def _analyzer_output : JoinedOrSeparate<["--"], "analyzer-output">, Flags<[NoXarchOption]>,
HelpText<"Static analyzer report output format (html|plist|plist-multi-file|plist-html|sarif|text).">;
-def _analyze : Flag<["--"], "analyze">, Flags<[DriverOption, CoreOption]>,
+def _analyze : Flag<["--"], "analyze">, Flags<[NoXarchOption, CoreOption]>,
HelpText<"Run the static analyzer">;
def _assemble : Flag<["--"], "assemble">, Alias<S>;
def _assert_EQ : Joined<["--"], "assert=">, Alias<A>;
@@ -2984,7 +3675,7 @@ def _output_EQ : Joined<["--"], "output=">, Alias<o>;
def _output : Separate<["--"], "output">, Alias<o>;
def _param : Separate<["--"], "param">, Group<CompileOnly_Group>;
def _param_EQ : Joined<["--"], "param=">, Alias<_param>;
-def _precompile : Flag<["--"], "precompile">, Flags<[DriverOption]>,
+def _precompile : Flag<["--"], "precompile">, Flags<[NoXarchOption]>,
Group<Action_Group>, HelpText<"Only precompile the input">;
def _prefix_EQ : Joined<["--"], "prefix=">, Alias<B>;
def _prefix : Separate<["--"], "prefix">, Alias<B>;
@@ -2998,10 +3689,11 @@ def _profile : Flag<["--"], "profile">, Alias<p>;
def _resource_EQ : Joined<["--"], "resource=">, Alias<fcompile_resource_EQ>;
def _resource : Separate<["--"], "resource">, Alias<fcompile_resource_EQ>;
def _rtlib : Separate<["--"], "rtlib">, Alias<rtlib_EQ>;
-def _serialize_diags : Separate<["-", "--"], "serialize-diagnostics">, Flags<[DriverOption]>,
+def _serialize_diags : Separate<["-", "--"], "serialize-diagnostics">, Flags<[NoXarchOption]>,
HelpText<"Serialize compiler diagnostics to a file">;
// We give --version different semantics from -version.
-def _version : Flag<["--"], "version">, Flags<[CoreOption, CC1Option]>,
+def _version : Flag<["--"], "version">,
+ Flags<[CoreOption, CC1Option, FC1Option, FlangOption]>,
HelpText<"Print version information">;
def _signed_char : Flag<["--"], "signed-char">, Alias<fsigned_char>;
def _std : Separate<["--"], "std">, Alias<std_EQ>;
@@ -3141,6 +3833,8 @@ def mavx512vpopcntdq : Flag<["-"], "mavx512vpopcntdq">, Group<m_x86_Features_Gro
def mno_avx512vpopcntdq : Flag<["-"], "mno-avx512vpopcntdq">, Group<m_x86_Features_Group>;
def mavx512vp2intersect : Flag<["-"], "mavx512vp2intersect">, Group<m_x86_Features_Group>;
def mno_avx512vp2intersect : Flag<["-"], "mno-avx512vp2intersect">, Group<m_x86_Features_Group>;
+def mavxvnni : Flag<["-"], "mavxvnni">, Group<m_x86_Features_Group>;
+def mno_avxvnni : Flag<["-"], "mno-avxvnni">, Group<m_x86_Features_Group>;
def madx : Flag<["-"], "madx">, Group<m_x86_Features_Group>;
def mno_adx : Flag<["-"], "mno-adx">, Group<m_x86_Features_Group>;
def maes : Flag<["-"], "maes">, Group<m_x86_Features_Group>;
@@ -3177,6 +3871,12 @@ def minvpcid : Flag<["-"], "minvpcid">, Group<m_x86_Features_Group>;
def mno_invpcid : Flag<["-"], "mno-invpcid">, Group<m_x86_Features_Group>;
def mgfni : Flag<["-"], "mgfni">, Group<m_x86_Features_Group>;
def mno_gfni : Flag<["-"], "mno-gfni">, Group<m_x86_Features_Group>;
+def mhreset : Flag<["-"], "mhreset">, Group<m_x86_Features_Group>;
+def mno_hreset : Flag<["-"], "mno-hreset">, Group<m_x86_Features_Group>;
+def mkl : Flag<["-"], "mkl">, Group<m_x86_Features_Group>;
+def mno_kl : Flag<["-"], "mno-kl">, Group<m_x86_Features_Group>;
+def mwidekl : Flag<["-"], "mwidekl">, Group<m_x86_Features_Group>;
+def mno_widekl : Flag<["-"], "mno-widekl">, Group<m_x86_Features_Group>;
def mlwp : Flag<["-"], "mlwp">, Group<m_x86_Features_Group>;
def mno_lwp : Flag<["-"], "mno-lwp">, Group<m_x86_Features_Group>;
def mlzcnt : Flag<["-"], "mlzcnt">, Group<m_x86_Features_Group>;
@@ -3223,6 +3923,8 @@ def mtbm : Flag<["-"], "mtbm">, Group<m_x86_Features_Group>;
def mno_tbm : Flag<["-"], "mno-tbm">, Group<m_x86_Features_Group>;
def mtsxldtrk : Flag<["-"], "mtsxldtrk">, Group<m_x86_Features_Group>;
def mno_tsxldtrk : Flag<["-"], "mno-tsxldtrk">, Group<m_x86_Features_Group>;
+def muintr : Flag<["-"], "muintr">, Group<m_x86_Features_Group>;
+def mno_uintr : Flag<["-"], "mno-uintr">, Group<m_x86_Features_Group>;
def mvaes : Flag<["-"], "mvaes">, Group<m_x86_Features_Group>;
def mno_vaes : Flag<["-"], "mno-vaes">, Group<m_x86_Features_Group>;
def mvpclmulqdq : Flag<["-"], "mvpclmulqdq">, Group<m_x86_Features_Group>;
@@ -3276,7 +3978,15 @@ defm : BooleanFFlag<"keep-inline-functions">, Group<clang_ignored_gcc_optimizati
def fprofile_dir : Joined<["-"], "fprofile-dir=">, Group<f_Group>;
-def fuse_ld_EQ : Joined<["-"], "fuse-ld=">, Group<f_Group>, Flags<[CoreOption]>;
+// The default value matches BinutilsVersion in MCAsmInfo.h.
+def fbinutils_version_EQ : Joined<["-"], "fbinutils-version=">,
+ MetaVarName<"<major.minor>">, Group<f_Group>, Flags<[CC1Option]>,
+ HelpText<"Produced object files can use all ELF features supported by this "
+ "binutils version and newer. If -fno-integrated-as is specified, the "
+ "generated assembly will consider GNU as support. 'none' means that all ELF "
+ "features can be used, regardless of binutils support. Defaults to 2.26.">;
+def fuse_ld_EQ : Joined<["-"], "fuse-ld=">, Group<f_Group>, Flags<[CoreOption, LinkOption]>;
+def ld_path_EQ : Joined<["--"], "ld-path=">, Group<Link_Group>;
defm align_labels : BooleanFFlag<"align-labels">, Group<clang_ignored_gcc_optimization_f_Group>;
def falign_labels_EQ : Joined<["-"], "falign-labels=">, Group<clang_ignored_gcc_optimization_f_Group>;
@@ -3292,7 +4002,6 @@ def fdiagnostics_show_location_EQ : Joined<["-"], "fdiagnostics-show-location=">
defm fcheck_new : BooleanFFlag<"check-new">, Group<clang_ignored_f_Group>;
defm caller_saves : BooleanFFlag<"caller-saves">, Group<clang_ignored_gcc_optimization_f_Group>;
defm reorder_blocks : BooleanFFlag<"reorder-blocks">, Group<clang_ignored_gcc_optimization_f_Group>;
-defm eliminate_unused_debug_types : BooleanFFlag<"eliminate-unused-debug-types">, Group<clang_ignored_f_Group>;
defm branch_count_reg : BooleanFFlag<"branch-count-reg">, Group<clang_ignored_gcc_optimization_f_Group>;
defm default_inline : BooleanFFlag<"default-inline">, Group<clang_ignored_gcc_optimization_f_Group>;
defm fat_lto_objects : BooleanFFlag<"fat-lto-objects">, Group<clang_ignored_gcc_optimization_f_Group>;
@@ -3319,8 +4028,9 @@ defm inline_small_functions : BooleanFFlag<"inline-small-functions">,
defm ipa_cp : BooleanFFlag<"ipa-cp">,
Group<clang_ignored_gcc_optimization_f_Group>;
defm ivopts : BooleanFFlag<"ivopts">, Group<clang_ignored_gcc_optimization_f_Group>;
-def fsemantic_interposition : Flag<["-"], "fsemantic-interposition">, Group<f_Group>, Flags<[CC1Option]>;
-def fno_semantic_interposition: Flag<["-"], "fno-semantic-interposition">, Group<f_Group>, Flags<[CC1Option]>;
+defm semantic_interposition : BoolFOption<"semantic-interposition",
+ LangOpts<"SemanticInterposition">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option]>, NegFlag<SetFalse>>;
defm non_call_exceptions : BooleanFFlag<"non-call-exceptions">, Group<clang_ignored_f_Group>;
defm peel_loops : BooleanFFlag<"peel-loops">, Group<clang_ignored_gcc_optimization_f_Group>;
defm permissive : BooleanFFlag<"permissive">, Group<clang_ignored_f_Group>;
@@ -3439,12 +4149,21 @@ defm underscoring : BooleanFFlag<"underscoring">, Group<gfortran_Group>;
defm whole_file : BooleanFFlag<"whole-file">, Group<gfortran_Group>;
// C++ SYCL options
-def fsycl : Flag<["-"], "fsycl">, Group<sycl_Group>, Flags<[CC1Option, CoreOption]>,
- HelpText<"Enable SYCL kernels compilation for device">;
-def fno_sycl : Flag<["-"], "fno-sycl">, Group<sycl_Group>, Flags<[CoreOption]>,
- HelpText<"Disable SYCL kernels compilation for device">;
+defm sycl : BoolOption<"f", "sycl",
+ LangOpts<"SYCL">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Enable">, NegFlag<SetFalse, [], "Disable">,
+ BothFlags<[CoreOption], " SYCL kernels compilation for device">>,
+ Group<sycl_Group>;
def sycl_std_EQ : Joined<["-"], "sycl-std=">, Group<sycl_Group>, Flags<[CC1Option, NoArgumentUnused, CoreOption]>,
- HelpText<"SYCL language standard to compile for.">, Values<"2017, 121, 1.2.1, sycl-1.2.1">;
+ HelpText<"SYCL language standard to compile for.">, Values<"2017,121,1.2.1,sycl-1.2.1">,
+ NormalizedValues<["SYCL_2017", "SYCL_2017", "SYCL_2017", "SYCL_2017"]>, NormalizedValuesScope<"LangOptions">,
+ MarshallingInfoString<LangOpts<"SYCLVersion">, "SYCL_None">, ShouldParseIf<fsycl.KeyPath>, AutoNormalizeEnum;
+
+//===----------------------------------------------------------------------===//
+// FlangOption and FC1 Options
+//===----------------------------------------------------------------------===//
+def test_io : Flag<["-"], "test-io">, Flags<[HelpHidden, FlangOption, FC1Option, FlangOnlyOption]>, Group<Action_Group>,
+ HelpText<"Run the InputOuputTest action. Use for development and testing only.">;
//===----------------------------------------------------------------------===//
// CC1 Options
@@ -3459,25 +4178,33 @@ let Flags = [CC1Option, NoDriverOption] in {
let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
def target_cpu : Separate<["-"], "target-cpu">,
- HelpText<"Target a specific cpu type">;
+ HelpText<"Target a specific cpu type">,
+ MarshallingInfoString<TargetOpts<"CPU">>;
+def tune_cpu : Separate<["-"], "tune-cpu">,
+ HelpText<"Tune for a specific cpu type">,
+ MarshallingInfoString<TargetOpts<"TuneCPU">>;
def target_feature : Separate<["-"], "target-feature">,
- HelpText<"Target specific attributes">;
+ HelpText<"Target specific attributes">,
+ MarshallingInfoStringVector<TargetOpts<"FeaturesAsWritten">>;
def triple : Separate<["-"], "triple">,
HelpText<"Specify target triple (e.g. i686-apple-darwin9)">,
- MarshallingInfoString<"TargetOpts->Triple", "llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple())", "std::string">,
- AlwaysEmit, Normalizer<"normalizeTriple">, DenormalizeString;
+ MarshallingInfoString<TargetOpts<"Triple">, "llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple())">,
+ AlwaysEmit, Normalizer<"normalizeTriple">;
def target_abi : Separate<["-"], "target-abi">,
- HelpText<"Target a particular ABI type">;
+ HelpText<"Target a particular ABI type">,
+ MarshallingInfoString<TargetOpts<"ABI">>;
def target_sdk_version_EQ : Joined<["-"], "target-sdk-version=">,
HelpText<"The version of target SDK used for compilation">;
}
def target_linker_version : Separate<["-"], "target-linker-version">,
- HelpText<"Target linker version">;
+ HelpText<"Target linker version">,
+ MarshallingInfoString<TargetOpts<"LinkerVersion">>;
def triple_EQ : Joined<["-"], "triple=">, Alias<triple>;
def mfpmath : Separate<["-"], "mfpmath">,
- HelpText<"Which unit to use for fp math">;
+ HelpText<"Which unit to use for fp math">,
+ MarshallingInfoString<TargetOpts<"FPMath">>;
def fpadding_on_unsigned_fixed_point : Flag<["-"], "fpadding-on-unsigned-fixed-point">,
HelpText<"Force each unsigned fixed point type to have an extra bit of padding to align their scales with those of signed fixed point types">;
@@ -3488,7 +4215,8 @@ def fno_padding_on_unsigned_fixed_point : Flag<["-"], "fno-padding-on-unsigned-f
//===----------------------------------------------------------------------===//
def analysis_UnoptimizedCFG : Flag<["-"], "unoptimized-cfg">,
- HelpText<"Generate unoptimized CFGs for all analyses">;
+ HelpText<"Generate unoptimized CFGs for all analyses">,
+ MarshallingInfoFlag<AnalyzerOpts<"UnoptimizedCFG">>;
def analysis_CFGAddImplicitDtors : Flag<["-"], "cfg-add-implicit-dtors">,
HelpText<"Add C++ implicit destructors to CFGs for all analyses">;
@@ -3511,24 +4239,33 @@ def analyzer_purge : Separate<["-"], "analyzer-purge">,
def analyzer_purge_EQ : Joined<["-"], "analyzer-purge=">, Alias<analyzer_purge>;
def analyzer_opt_analyze_headers : Flag<["-"], "analyzer-opt-analyze-headers">,
- HelpText<"Force the static analyzer to analyze functions defined in header files">;
+ HelpText<"Force the static analyzer to analyze functions defined in header files">,
+ MarshallingInfoFlag<AnalyzerOpts<"AnalyzeAll">>;
def analyzer_opt_analyze_nested_blocks : Flag<["-"], "analyzer-opt-analyze-nested-blocks">,
- HelpText<"Analyze the definitions of blocks in addition to functions">;
+ HelpText<"Analyze the definitions of blocks in addition to functions">,
+ MarshallingInfoFlag<AnalyzerOpts<"AnalyzeNestedBlocks">>;
def analyzer_display_progress : Flag<["-"], "analyzer-display-progress">,
- HelpText<"Emit verbose output about the analyzer's progress">;
+ HelpText<"Emit verbose output about the analyzer's progress">,
+ MarshallingInfoFlag<AnalyzerOpts<"AnalyzerDisplayProgress">>;
def analyze_function : Separate<["-"], "analyze-function">,
- HelpText<"Run analysis on specific function (for C++ include parameters in name)">;
+ HelpText<"Run analysis on specific function (for C++ include parameters in name)">,
+ MarshallingInfoString<AnalyzerOpts<"AnalyzeSpecificFunction">>;
def analyze_function_EQ : Joined<["-"], "analyze-function=">, Alias<analyze_function>;
def trim_egraph : Flag<["-"], "trim-egraph">,
- HelpText<"Only show error-related paths in the analysis graph">;
+ HelpText<"Only show error-related paths in the analysis graph">,
+ MarshallingInfoFlag<AnalyzerOpts<"TrimGraph">>;
def analyzer_viz_egraph_graphviz : Flag<["-"], "analyzer-viz-egraph-graphviz">,
- HelpText<"Display exploded graph using GraphViz">;
+ HelpText<"Display exploded graph using GraphViz">,
+ MarshallingInfoFlag<AnalyzerOpts<"visualizeExplodedGraphWithGraphViz">>;
def analyzer_dump_egraph : Separate<["-"], "analyzer-dump-egraph">,
- HelpText<"Dump exploded graph to the specified file">;
+ HelpText<"Dump exploded graph to the specified file">,
+ MarshallingInfoString<AnalyzerOpts<"DumpExplodedGraphTo">>;
def analyzer_dump_egraph_EQ : Joined<["-"], "analyzer-dump-egraph=">, Alias<analyzer_dump_egraph>;
def analyzer_inline_max_stack_depth : Separate<["-"], "analyzer-inline-max-stack-depth">,
- HelpText<"Bound on stack depth while inlining (4 by default)">;
+ HelpText<"Bound on stack depth while inlining (4 by default)">,
+ // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
+ MarshallingInfoStringInt<AnalyzerOpts<"InlineMaxStackDepth">, "5">;
def analyzer_inline_max_stack_depth_EQ : Joined<["-"], "analyzer-inline-max-stack-depth=">,
Alias<analyzer_inline_max_stack_depth>;
@@ -3537,12 +4274,15 @@ def analyzer_inlining_mode : Separate<["-"], "analyzer-inlining-mode">,
def analyzer_inlining_mode_EQ : Joined<["-"], "analyzer-inlining-mode=">, Alias<analyzer_inlining_mode>;
def analyzer_disable_retry_exhausted : Flag<["-"], "analyzer-disable-retry-exhausted">,
- HelpText<"Do not re-analyze paths leading to exhausted nodes with a different strategy (may decrease code coverage)">;
+ HelpText<"Do not re-analyze paths leading to exhausted nodes with a different strategy (may decrease code coverage)">,
+ MarshallingInfoFlag<AnalyzerOpts<"NoRetryExhausted">>;
def analyzer_max_loop : Separate<["-"], "analyzer-max-loop">,
- HelpText<"The maximum number of times the analyzer will go through a loop">;
+ HelpText<"The maximum number of times the analyzer will go through a loop">,
+ MarshallingInfoStringInt<AnalyzerOpts<"maxBlockVisitOnPath">, "4">;
def analyzer_stats : Flag<["-"], "analyzer-stats">,
- HelpText<"Print internal analyzer statistics.">;
+ HelpText<"Print internal analyzer statistics.">,
+ MarshallingInfoFlag<AnalyzerOpts<"PrintStats">>;
def analyzer_checker : Separate<["-"], "analyzer-checker">,
HelpText<"Choose analyzer checkers to enable">,
@@ -3567,192 +4307,256 @@ def analyzer_disable_checker_EQ : Joined<["-"], "analyzer-disable-checker=">,
Alias<analyzer_disable_checker>;
def analyzer_disable_all_checks : Flag<["-"], "analyzer-disable-all-checks">,
- HelpText<"Disable all static analyzer checks">;
+ HelpText<"Disable all static analyzer checks">,
+ MarshallingInfoFlag<AnalyzerOpts<"DisableAllCheckers">>;
def analyzer_checker_help : Flag<["-"], "analyzer-checker-help">,
- HelpText<"Display the list of analyzer checkers that are available">;
+ HelpText<"Display the list of analyzer checkers that are available">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerHelp">>;
def analyzer_checker_help_alpha : Flag<["-"], "analyzer-checker-help-alpha">,
HelpText<"Display the list of in development analyzer checkers. These "
"are NOT considered safe, they are unstable and will emit incorrect "
- "reports. Enable ONLY FOR DEVELOPMENT purposes">;
+ "reports. Enable ONLY FOR DEVELOPMENT purposes">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerHelpAlpha">>;
def analyzer_checker_help_developer : Flag<["-"], "analyzer-checker-help-developer">,
HelpText<"Display the list of developer-only checkers such as modeling "
- "and debug checkers">;
+ "and debug checkers">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerHelpDeveloper">>;
def analyzer_config_help : Flag<["-"], "analyzer-config-help">,
HelpText<"Display the list of -analyzer-config options. These are meant for "
- "development purposes only!">;
+ "development purposes only!">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowConfigOptionsList">>;
def analyzer_list_enabled_checkers : Flag<["-"], "analyzer-list-enabled-checkers">,
- HelpText<"Display the list of enabled analyzer checkers">;
+ HelpText<"Display the list of enabled analyzer checkers">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowEnabledCheckerList">>;
def analyzer_config : Separate<["-"], "analyzer-config">,
HelpText<"Choose analyzer options to enable">;
def analyzer_checker_option_help : Flag<["-"], "analyzer-checker-option-help">,
- HelpText<"Display the list of checker and package options">;
+ HelpText<"Display the list of checker and package options">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerOptionList">>;
def analyzer_checker_option_help_alpha : Flag<["-"], "analyzer-checker-option-help-alpha">,
HelpText<"Display the list of in development checker and package options. "
"These are NOT considered safe, they are unstable and will emit "
- "incorrect reports. Enable ONLY FOR DEVELOPMENT purposes">;
+ "incorrect reports. Enable ONLY FOR DEVELOPMENT purposes">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerOptionAlphaList">>;
def analyzer_checker_option_help_developer : Flag<["-"], "analyzer-checker-option-help-developer">,
HelpText<"Display the list of checker and package options meant for "
- "development purposes only">;
+ "development purposes only">,
+ MarshallingInfoFlag<AnalyzerOpts<"ShowCheckerOptionDeveloperList">>;
def analyzer_config_compatibility_mode : Separate<["-"], "analyzer-config-compatibility-mode">,
- HelpText<"Don't emit errors on invalid analyzer-config inputs">;
+ HelpText<"Don't emit errors on invalid analyzer-config inputs">,
+ Values<"true,false">, NormalizedValues<[[{false}], [{true}]]>,
+ MarshallingInfoString<AnalyzerOpts<"ShouldEmitErrorsOnInvalidConfigValue">, [{true}]>,
+ AutoNormalizeEnum;
def analyzer_config_compatibility_mode_EQ : Joined<["-"], "analyzer-config-compatibility-mode=">,
Alias<analyzer_config_compatibility_mode>;
def analyzer_werror : Flag<["-"], "analyzer-werror">,
- HelpText<"Emit analyzer results as errors rather than warnings">;
+ HelpText<"Emit analyzer results as errors rather than warnings">,
+ MarshallingInfoFlag<AnalyzerOpts<"AnalyzerWerror">>;
//===----------------------------------------------------------------------===//
// Migrator Options
//===----------------------------------------------------------------------===//
def migrator_no_nsalloc_error : Flag<["-"], "no-ns-alloc-error">,
- HelpText<"Do not error on use of NSAllocateCollectable/NSReallocateCollectable">;
+ HelpText<"Do not error on use of NSAllocateCollectable/NSReallocateCollectable">,
+ MarshallingInfoFlag<MigratorOpts<"NoNSAllocReallocError">>;
def migrator_no_finalize_removal : Flag<["-"], "no-finalize-removal">,
- HelpText<"Do not remove finalize method in gc mode">;
+ HelpText<"Do not remove finalize method in gc mode">,
+ MarshallingInfoFlag<MigratorOpts<"NoFinalizeRemoval">>;
//===----------------------------------------------------------------------===//
// CodeGen Options
//===----------------------------------------------------------------------===//
let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
-def debug_info_kind_EQ : Joined<["-"], "debug-info-kind=">;
+def debug_info_kind_EQ : Joined<["-"], "debug-info-kind=">,
+ Values<"line-tables-only,line-directives-only,constructor,limited,standalone,unused-types">,
+ NormalizedValuesScope<"codegenoptions">,
+ NormalizedValues<["DebugLineTablesOnly", "DebugDirectivesOnly", "DebugInfoConstructor",
+ "LimitedDebugInfo", "FullDebugInfo", "UnusedTypeInfo"]>,
+ MarshallingInfoString<CodeGenOpts<"DebugInfo">, "NoDebugInfo">, AutoNormalizeEnum;
def debug_info_macro : Flag<["-"], "debug-info-macro">,
- HelpText<"Emit macro debug information">;
+ HelpText<"Emit macro debug information">,
+ MarshallingInfoFlag<CodeGenOpts<"MacroDebugInfo">>;
def default_function_attr : Separate<["-"], "default-function-attr">,
- HelpText<"Apply given attribute to all functions">;
-def dwarf_version_EQ : Joined<["-"], "dwarf-version=">;
-def debugger_tuning_EQ : Joined<["-"], "debugger-tuning=">;
+ HelpText<"Apply given attribute to all functions">,
+ MarshallingInfoStringVector<CodeGenOpts<"DefaultFunctionAttrs">>;
+def dwarf_version_EQ : Joined<["-"], "dwarf-version=">,
+ MarshallingInfoStringInt<CodeGenOpts<"DwarfVersion">>;
+def debugger_tuning_EQ : Joined<["-"], "debugger-tuning=">,
+ Values<"gdb,lldb,sce">,
+ NormalizedValuesScope<"llvm::DebuggerKind">, NormalizedValues<["GDB", "LLDB", "SCE"]>,
+ MarshallingInfoString<CodeGenOpts<"DebuggerTuning">, "Default">, AutoNormalizeEnum;
def dwarf_debug_flags : Separate<["-"], "dwarf-debug-flags">,
- HelpText<"The string to embed in the Dwarf debug flags record.">;
+ HelpText<"The string to embed in the Dwarf debug flags record.">,
+ MarshallingInfoString<CodeGenOpts<"DwarfDebugFlags">>;
def record_command_line : Separate<["-"], "record-command-line">,
- HelpText<"The string to embed in the .LLVM.command.line section.">;
-def compress_debug_sections : Flag<["-", "--"], "compress-debug-sections">,
- HelpText<"DWARF debug sections compression">;
+ HelpText<"The string to embed in the .LLVM.command.line section.">,
+ MarshallingInfoString<CodeGenOpts<"RecordCommandLine">>;
def compress_debug_sections_EQ : Joined<["-", "--"], "compress-debug-sections=">,
- HelpText<"DWARF debug sections compression type">;
+ HelpText<"DWARF debug sections compression type">, Values<"none,zlib,zlib-gnu">,
+ NormalizedValuesScope<"llvm::DebugCompressionType">, NormalizedValues<["None", "Z", "GNU"]>,
+ MarshallingInfoString<CodeGenOpts<"CompressDebugSections">, "None">, AutoNormalizeEnum;
+def compress_debug_sections : Flag<["-", "--"], "compress-debug-sections">,
+ Alias<compress_debug_sections_EQ>, AliasArgs<["zlib"]>;
def mno_exec_stack : Flag<["-"], "mnoexecstack">,
- HelpText<"Mark the file as not needing an executable stack">;
+ HelpText<"Mark the file as not needing an executable stack">,
+ MarshallingInfoFlag<CodeGenOpts<"NoExecStack">>;
def massembler_no_warn : Flag<["-"], "massembler-no-warn">,
- HelpText<"Make assembler not emit warnings">;
+ HelpText<"Make assembler not emit warnings">,
+ MarshallingInfoFlag<CodeGenOpts<"NoWarn">>;
def massembler_fatal_warnings : Flag<["-"], "massembler-fatal-warnings">,
- HelpText<"Make assembler warnings fatal">;
+ HelpText<"Make assembler warnings fatal">,
+ MarshallingInfoFlag<CodeGenOpts<"FatalWarnings">>;
def mrelax_relocations : Flag<["--"], "mrelax-relocations">,
- HelpText<"Use relaxable elf relocations">;
+ HelpText<"Use relaxable elf relocations">,
+ MarshallingInfoFlag<CodeGenOpts<"RelaxELFRelocations">>;
def msave_temp_labels : Flag<["-"], "msave-temp-labels">,
HelpText<"Save temporary labels in the symbol table. "
"Note this may change .s semantics and shouldn't generally be used "
- "on compiler-generated code.">;
+ "on compiler-generated code.">,
+ MarshallingInfoFlag<CodeGenOpts<"SaveTempLabels">>;
def mrelocation_model : Separate<["-"], "mrelocation-model">,
HelpText<"The relocation model to use">, Values<"static,pic,ropi,rwpi,ropi-rwpi,dynamic-no-pic">,
NormalizedValuesScope<"llvm::Reloc">,
NormalizedValues<["Static", "PIC_", "ROPI", "RWPI", "ROPI_RWPI", "DynamicNoPIC"]>,
- MarshallingInfoString<"CodeGenOpts.RelocationModel", "PIC_", "Model">,
+ MarshallingInfoString<CodeGenOpts<"RelocationModel">, "PIC_">,
AutoNormalizeEnum;
def fno_math_builtin : Flag<["-"], "fno-math-builtin">,
- HelpText<"Disable implicit builtin knowledge of math functions">;
+ HelpText<"Disable implicit builtin knowledge of math functions">,
+ MarshallingInfoFlag<LangOpts<"NoMathBuiltin">>;
+def fuse_ctor_homing: Flag<["-"], "fuse-ctor-homing">,
+ HelpText<"Use constructor homing if we are using limited debug info already">;
}
def disable_llvm_verifier : Flag<["-"], "disable-llvm-verifier">,
- HelpText<"Don't run the LLVM IR verifier pass">;
+ HelpText<"Don't run the LLVM IR verifier pass">,
+ MarshallingInfoNegativeFlag<CodeGenOpts<"VerifyModule">>;
def disable_llvm_passes : Flag<["-"], "disable-llvm-passes">,
HelpText<"Use together with -emit-llvm to get pristine LLVM IR from the "
- "frontend by not running any LLVM passes at all">;
+ "frontend by not running any LLVM passes at all">,
+ MarshallingInfoFlag<CodeGenOpts<"DisableLLVMPasses">>;
def disable_llvm_optzns : Flag<["-"], "disable-llvm-optzns">,
Alias<disable_llvm_passes>;
def disable_lifetimemarkers : Flag<["-"], "disable-lifetime-markers">,
HelpText<"Disable lifetime-markers emission even when optimizations are "
- "enabled">;
+ "enabled">,
+ MarshallingInfoFlag<CodeGenOpts<"DisableLifetimeMarkers">>;
def disable_O0_optnone : Flag<["-"], "disable-O0-optnone">,
- HelpText<"Disable adding the optnone attribute to functions at O0">;
+ HelpText<"Disable adding the optnone attribute to functions at O0">,
+ MarshallingInfoFlag<CodeGenOpts<"DisableO0ImplyOptNone">>;
def disable_red_zone : Flag<["-"], "disable-red-zone">,
- HelpText<"Do not emit code that uses the red zone.">;
+ HelpText<"Do not emit code that uses the red zone.">,
+ MarshallingInfoFlag<CodeGenOpts<"DisableRedZone">>;
def dwarf_ext_refs : Flag<["-"], "dwarf-ext-refs">,
HelpText<"Generate debug info with external references to clang modules"
- " or precompiled headers">;
+ " or precompiled headers">,
+ MarshallingInfoFlag<CodeGenOpts<"DebugTypeExtRefs">>;
def dwarf_explicit_import : Flag<["-"], "dwarf-explicit-import">,
HelpText<"Generate explicit import from anonymous namespace to containing"
- " scope">;
+ " scope">,
+ MarshallingInfoFlag<CodeGenOpts<"DebugExplicitImport">>;
def debug_forward_template_params : Flag<["-"], "debug-forward-template-params">,
HelpText<"Emit complete descriptions of template parameters in forward"
- " declarations">;
+ " declarations">,
+ MarshallingInfoFlag<CodeGenOpts<"DebugFwdTemplateParams">>;
def fforbid_guard_variables : Flag<["-"], "fforbid-guard-variables">,
- HelpText<"Emit an error if a C++ static local initializer would need a guard variable">;
+ HelpText<"Emit an error if a C++ static local initializer would need a guard variable">,
+ MarshallingInfoFlag<CodeGenOpts<"ForbidGuardVariables">>;
def no_implicit_float : Flag<["-"], "no-implicit-float">,
- HelpText<"Don't generate implicit floating point instructions">;
+ HelpText<"Don't generate implicit floating point instructions">,
+ MarshallingInfoFlag<CodeGenOpts<"NoImplicitFloat">>;
def fdump_vtable_layouts : Flag<["-"], "fdump-vtable-layouts">,
- HelpText<"Dump the layouts of all vtables that will be emitted in a translation unit">;
+ HelpText<"Dump the layouts of all vtables that will be emitted in a translation unit">,
+ MarshallingInfoFlag<LangOpts<"DumpVTableLayouts">>;
def fmerge_functions : Flag<["-"], "fmerge-functions">,
- HelpText<"Permit merging of identical functions when optimizing.">;
-def femit_coverage_notes : Flag<["-"], "femit-coverage-notes">,
- HelpText<"Emit a gcov coverage notes file when compiling.">;
-def femit_coverage_data: Flag<["-"], "femit-coverage-data">,
- HelpText<"Instrument the program to emit gcov coverage data when run.">;
+ HelpText<"Permit merging of identical functions when optimizing.">,
+ MarshallingInfoFlag<CodeGenOpts<"MergeFunctions">>;
def coverage_data_file : Separate<["-"], "coverage-data-file">,
- HelpText<"Emit coverage data to this filename.">;
+ HelpText<"Emit coverage data to this filename.">,
+ MarshallingInfoString<CodeGenOpts<"CoverageDataFile">>,
+ ShouldParseIf<!strconcat(fprofile_arcs.KeyPath, "||", ftest_coverage.KeyPath)>;
def coverage_data_file_EQ : Joined<["-"], "coverage-data-file=">,
Alias<coverage_data_file>;
def coverage_notes_file : Separate<["-"], "coverage-notes-file">,
- HelpText<"Emit coverage notes to this filename.">;
+ HelpText<"Emit coverage notes to this filename.">,
+ MarshallingInfoString<CodeGenOpts<"CoverageNotesFile">>,
+ ShouldParseIf<!strconcat(fprofile_arcs.KeyPath, "||", ftest_coverage.KeyPath)>;
def coverage_notes_file_EQ : Joined<["-"], "coverage-notes-file=">,
Alias<coverage_notes_file>;
def coverage_version_EQ : Joined<["-"], "coverage-version=">,
HelpText<"Four-byte version string for gcov files.">;
-def test_coverage : Flag<["-"], "test-coverage">,
- HelpText<"Do not generate coverage files or remove coverage changes from IR">;
def dump_coverage_mapping : Flag<["-"], "dump-coverage-mapping">,
- HelpText<"Dump the coverage mapping records, for testing">;
+ HelpText<"Dump the coverage mapping records, for testing">,
+ MarshallingInfoFlag<CodeGenOpts<"DumpCoverageMapping">>;
def fuse_register_sized_bitfield_access: Flag<["-"], "fuse-register-sized-bitfield-access">,
- HelpText<"Use register sized accesses to bit-fields, when possible.">;
+ HelpText<"Use register sized accesses to bit-fields, when possible.">,
+ MarshallingInfoFlag<CodeGenOpts<"UseRegisterSizedBitfieldAccess">>;
def relaxed_aliasing : Flag<["-"], "relaxed-aliasing">,
- HelpText<"Turn off Type Based Alias Analysis">;
+ HelpText<"Turn off Type Based Alias Analysis">,
+ MarshallingInfoFlag<CodeGenOpts<"RelaxedAliasing">>;
def no_struct_path_tbaa : Flag<["-"], "no-struct-path-tbaa">,
- HelpText<"Turn off struct-path aware Type Based Alias Analysis">;
+ HelpText<"Turn off struct-path aware Type Based Alias Analysis">,
+ MarshallingInfoNegativeFlag<CodeGenOpts<"StructPathTBAA">>;
def new_struct_path_tbaa : Flag<["-"], "new-struct-path-tbaa">,
HelpText<"Enable enhanced struct-path aware Type Based Alias Analysis">;
def mdebug_pass : Separate<["-"], "mdebug-pass">,
- HelpText<"Enable additional debug output">;
+ HelpText<"Enable additional debug output">,
+ MarshallingInfoString<CodeGenOpts<"DebugPass">>;
def mframe_pointer_EQ : Joined<["-"], "mframe-pointer=">,
- HelpText<"Specify which frame pointers to retain (all, non-leaf, none).">, Values<"all,non-leaf,none">;
+ HelpText<"Specify which frame pointers to retain (all, non-leaf, none).">, Values<"all,non-leaf,none">,
+ NormalizedValuesScope<"CodeGenOptions::FramePointerKind">, NormalizedValues<["All", "NonLeaf", "None"]>,
+ MarshallingInfoString<CodeGenOpts<"FramePointer">, "None">, AutoNormalizeEnum;
def mdisable_tail_calls : Flag<["-"], "mdisable-tail-calls">,
- HelpText<"Disable tail call optimization, keeping the call stack accurate">;
+ HelpText<"Disable tail call optimization, keeping the call stack accurate">,
+ MarshallingInfoFlag<CodeGenOpts<"DisableTailCalls">>;
def menable_no_infinities : Flag<["-"], "menable-no-infs">,
- HelpText<"Allow optimization to assume there are no infinities.">;
+ HelpText<"Allow optimization to assume there are no infinities.">,
+ MarshallingInfoFlag<LangOpts<"NoHonorInfs">>, ImpliedByAnyOf<[ffinite_math_only.KeyPath]>;
def menable_no_nans : Flag<["-"], "menable-no-nans">,
- HelpText<"Allow optimization to assume there are no NaNs.">;
-def menable_unsafe_fp_math : Flag<["-"], "menable-unsafe-fp-math">,
- HelpText<"Allow unsafe floating-point math optimizations which may decrease "
- "precision">;
+ HelpText<"Allow optimization to assume there are no NaNs.">,
+ MarshallingInfoFlag<LangOpts<"NoHonorNaNs">>, ImpliedByAnyOf<[ffinite_math_only.KeyPath]>;
def mreassociate : Flag<["-"], "mreassociate">,
- HelpText<"Allow reassociation transformations for floating-point instructions">;
+ HelpText<"Allow reassociation transformations for floating-point instructions">,
+ MarshallingInfoFlag<LangOpts<"AllowFPReassoc">>, ImpliedByAnyOf<[menable_unsafe_fp_math.KeyPath]>;
def mabi_EQ_ieeelongdouble : Flag<["-"], "mabi=ieeelongdouble">,
- HelpText<"Use IEEE 754 quadruple-precision for long double">;
+ HelpText<"Use IEEE 754 quadruple-precision for long double">,
+ MarshallingInfoFlag<LangOpts<"PPCIEEELongDouble">>;
def mfloat_abi : Separate<["-"], "mfloat-abi">,
- HelpText<"The float ABI to use">;
+ HelpText<"The float ABI to use">,
+ MarshallingInfoString<CodeGenOpts<"FloatABI">>;
def mtp : Separate<["-"], "mtp">,
HelpText<"Mode for reading thread pointer">;
def mlimit_float_precision : Separate<["-"], "mlimit-float-precision">,
- HelpText<"Limit float precision to the given value">;
+ HelpText<"Limit float precision to the given value">,
+ MarshallingInfoString<CodeGenOpts<"LimitFloatPrecision">>;
def split_stacks : Flag<["-"], "split-stacks">,
- HelpText<"Try to use a split stack if possible.">;
+ HelpText<"Try to use a split stack if possible.">,
+ MarshallingInfoFlag<CodeGenOpts<"EnableSegmentedStacks">>;
def mregparm : Separate<["-"], "mregparm">,
- HelpText<"Limit the number of registers available for integer arguments">;
+ HelpText<"Limit the number of registers available for integer arguments">,
+ MarshallingInfoStringInt<CodeGenOpts<"NumRegisterParameters">>;
def msmall_data_limit : Separate<["-"], "msmall-data-limit">,
- HelpText<"Put global and static data smaller than the limit into a special section">;
+ HelpText<"Put global and static data smaller than the limit into a special section">,
+ MarshallingInfoStringInt<CodeGenOpts<"SmallDataLimit">>;
def munwind_tables : Flag<["-"], "munwind-tables">,
- HelpText<"Generate unwinding tables for all functions">;
+ HelpText<"Generate unwinding tables for all functions">,
+ MarshallingInfoFlag<CodeGenOpts<"UnwindTables">>;
def mconstructor_aliases : Flag<["-"], "mconstructor-aliases">,
- HelpText<"Emit complete constructors and destructors as aliases when possible">;
+ HelpText<"Emit complete constructors and destructors as aliases when possible">,
+ MarshallingInfoFlag<CodeGenOpts<"CXXCtorDtorAliases">>;
def mlink_bitcode_file : Separate<["-"], "mlink-bitcode-file">,
HelpText<"Link the given bitcode file before performing optimizations.">;
def mlink_builtin_bitcode : Separate<["-"], "mlink-builtin-bitcode">,
@@ -3761,87 +4565,121 @@ def mlink_builtin_bitcode : Separate<["-"], "mlink-builtin-bitcode">,
def mlink_cuda_bitcode : Separate<["-"], "mlink-cuda-bitcode">,
Alias<mlink_builtin_bitcode>;
def vectorize_loops : Flag<["-"], "vectorize-loops">,
- HelpText<"Run the Loop vectorization passes">;
+ HelpText<"Run the Loop vectorization passes">,
+ MarshallingInfoFlag<CodeGenOpts<"VectorizeLoop">>;
def vectorize_slp : Flag<["-"], "vectorize-slp">,
- HelpText<"Run the SLP vectorization passes">;
+ HelpText<"Run the SLP vectorization passes">,
+ MarshallingInfoFlag<CodeGenOpts<"VectorizeSLP">>;
def dependent_lib : Joined<["--"], "dependent-lib=">,
- HelpText<"Add dependent library">;
+ HelpText<"Add dependent library">,
+ MarshallingInfoStringVector<CodeGenOpts<"DependentLibraries">>;
def linker_option : Joined<["--"], "linker-option=">,
- HelpText<"Add linker option">;
+ HelpText<"Add linker option">,
+ MarshallingInfoStringVector<CodeGenOpts<"LinkerOptions">>;
def fsanitize_coverage_type : Joined<["-"], "fsanitize-coverage-type=">,
- HelpText<"Sanitizer coverage type">;
+ HelpText<"Sanitizer coverage type">,
+ MarshallingInfoStringInt<CodeGenOpts<"SanitizeCoverageType">>;
def fsanitize_coverage_indirect_calls
: Flag<["-"], "fsanitize-coverage-indirect-calls">,
- HelpText<"Enable sanitizer coverage for indirect calls">;
+ HelpText<"Enable sanitizer coverage for indirect calls">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageIndirectCalls">>;
def fsanitize_coverage_trace_bb
: Flag<["-"], "fsanitize-coverage-trace-bb">,
- HelpText<"Enable basic block tracing in sanitizer coverage">;
+ HelpText<"Enable basic block tracing in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTraceBB">>;
def fsanitize_coverage_trace_cmp
: Flag<["-"], "fsanitize-coverage-trace-cmp">,
- HelpText<"Enable cmp instruction tracing in sanitizer coverage">;
+ HelpText<"Enable cmp instruction tracing in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTraceCmp">>;
def fsanitize_coverage_trace_div
: Flag<["-"], "fsanitize-coverage-trace-div">,
- HelpText<"Enable div instruction tracing in sanitizer coverage">;
+ HelpText<"Enable div instruction tracing in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTraceDiv">>;
def fsanitize_coverage_trace_gep
: Flag<["-"], "fsanitize-coverage-trace-gep">,
- HelpText<"Enable gep instruction tracing in sanitizer coverage">;
+ HelpText<"Enable gep instruction tracing in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTraceGep">>;
def fsanitize_coverage_8bit_counters
: Flag<["-"], "fsanitize-coverage-8bit-counters">,
- HelpText<"Enable frequency counters in sanitizer coverage">;
+ HelpText<"Enable frequency counters in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverage8bitCounters">>;
def fsanitize_coverage_inline_8bit_counters
: Flag<["-"], "fsanitize-coverage-inline-8bit-counters">,
- HelpText<"Enable inline 8-bit counters in sanitizer coverage">;
+ HelpText<"Enable inline 8-bit counters in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageInline8bitCounters">>;
def fsanitize_coverage_inline_bool_flag
: Flag<["-"], "fsanitize-coverage-inline-bool-flag">,
- HelpText<"Enable inline bool flag in sanitizer coverage">;
+ HelpText<"Enable inline bool flag in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageInlineBoolFlag">>;
def fsanitize_coverage_pc_table
: Flag<["-"], "fsanitize-coverage-pc-table">,
- HelpText<"Create a table of coverage-instrumented PCs">;
+ HelpText<"Create a table of coverage-instrumented PCs">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoveragePCTable">>;
def fsanitize_coverage_trace_pc
: Flag<["-"], "fsanitize-coverage-trace-pc">,
- HelpText<"Enable PC tracing in sanitizer coverage">;
+ HelpText<"Enable PC tracing in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTracePC">>;
def fsanitize_coverage_trace_pc_guard
: Flag<["-"], "fsanitize-coverage-trace-pc-guard">,
- HelpText<"Enable PC tracing with guard in sanitizer coverage">;
+ HelpText<"Enable PC tracing with guard in sanitizer coverage">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTracePCGuard">>;
def fsanitize_coverage_no_prune
: Flag<["-"], "fsanitize-coverage-no-prune">,
- HelpText<"Disable coverage pruning (i.e. instrument all blocks/edges)">;
+ HelpText<"Disable coverage pruning (i.e. instrument all blocks/edges)">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageNoPrune">>;
def fsanitize_coverage_stack_depth
: Flag<["-"], "fsanitize-coverage-stack-depth">,
- HelpText<"Enable max stack depth tracing">;
+ HelpText<"Enable max stack depth tracing">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageStackDepth">>;
def fpatchable_function_entry_offset_EQ
: Joined<["-"], "fpatchable-function-entry-offset=">, MetaVarName<"<M>">,
- HelpText<"Generate M NOPs before function entry">;
+ HelpText<"Generate M NOPs before function entry">,
+ MarshallingInfoStringInt<CodeGenOpts<"PatchableFunctionEntryOffset">>;
def fprofile_instrument_EQ : Joined<["-"], "fprofile-instrument=">,
HelpText<"Enable PGO instrumentation. The accepted value is clang, llvm, "
- "or none">, Values<"none,clang,llvm">;
+ "or none">, Values<"none,clang,llvm,csllvm">,
+ NormalizedValuesScope<"CodeGenOptions">,
+ NormalizedValues<["ProfileNone", "ProfileClangInstr", "ProfileIRInstr", "ProfileCSIRInstr"]>,
+ MarshallingInfoString<CodeGenOpts<"ProfileInstr">, "ProfileNone">, AutoNormalizeEnum;
def fprofile_instrument_path_EQ : Joined<["-"], "fprofile-instrument-path=">,
HelpText<"Generate instrumented code to collect execution counts into "
- "<file> (overridden by LLVM_PROFILE_FILE env var)">;
+ "<file> (overridden by LLVM_PROFILE_FILE env var)">,
+ MarshallingInfoString<CodeGenOpts<"InstrProfileOutput">>;
def fprofile_instrument_use_path_EQ :
Joined<["-"], "fprofile-instrument-use-path=">,
- HelpText<"Specify the profile path in PGO use compilation">;
+ HelpText<"Specify the profile path in PGO use compilation">,
+ MarshallingInfoString<CodeGenOpts<"ProfileInstrumentUsePath">>;
def flto_visibility_public_std:
Flag<["-"], "flto-visibility-public-std">,
- HelpText<"Use public LTO visibility for classes in std and stdext namespaces">;
-def flto_unit: Flag<["-"], "flto-unit">,
- HelpText<"Emit IR to support LTO unit features (CFI, whole program vtable opt)">;
-def fno_lto_unit: Flag<["-"], "fno-lto-unit">;
-def fdebug_pass_manager : Flag<["-"], "fdebug-pass-manager">,
- HelpText<"Prints debug information for the new pass manager">;
-def fno_debug_pass_manager : Flag<["-"], "fno-debug-pass-manager">,
- HelpText<"Disables debug printing for the new pass manager">;
+ HelpText<"Use public LTO visibility for classes in std and stdext namespaces">,
+ MarshallingInfoFlag<CodeGenOpts<"LTOVisibilityPublicStd">>;
+defm lto_unit : BoolOption<"f", "lto-unit",
+ CodeGenOpts<"LTOUnit">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Emit IR to support LTO unit features (CFI, whole program vtable opt)">,
+ NegFlag<SetFalse>>;
+defm debug_pass_manager : BoolOption<"f", "debug-pass-manager",
+ CodeGenOpts<"DebugPassManager">, DefaultFalse,
+ PosFlag<SetTrue, [], "Prints debug information for the new pass manager">,
+ NegFlag<SetFalse, [], "Disables debug printing for the new pass manager">>;
+def fexperimental_debug_variable_locations : Flag<["-"],
+ "fexperimental-debug-variable-locations">,
+ HelpText<"Use experimental new value-tracking variable locations">,
+ MarshallingInfoFlag<CodeGenOpts<"ValueTrackingVariableLocations">>;
// The driver option takes the key as a parameter to the -msign-return-address=
// and -mbranch-protection= options, but CC1 has a separate option so we
// don't have to parse the parameter twice.
def msign_return_address_key_EQ : Joined<["-"], "msign-return-address-key=">,
Values<"a_key,b_key">;
-def mbranch_target_enforce : Flag<["-"], "mbranch-target-enforce">;
-def fno_dllexport_inlines : Flag<["-"], "fno-dllexport-inlines">;
+def mbranch_target_enforce : Flag<["-"], "mbranch-target-enforce">,
+ MarshallingInfoFlag<LangOpts<"BranchTargetEnforcement">>;
+def fno_dllexport_inlines : Flag<["-"], "fno-dllexport-inlines">,
+ MarshallingInfoNegativeFlag<LangOpts<"DllExportInlines">>;
def cfguard_no_checks : Flag<["-"], "cfguard-no-checks">,
- HelpText<"Emit Windows Control Flow Guard tables only (no checks)">;
+ HelpText<"Emit Windows Control Flow Guard tables only (no checks)">,
+ MarshallingInfoFlag<CodeGenOpts<"ControlFlowGuardNoChecks">>;
def cfguard : Flag<["-"], "cfguard">,
- HelpText<"Emit Windows Control Flow Guard tables and checks">;
+ HelpText<"Emit Windows Control Flow Guard tables and checks">,
+ MarshallingInfoFlag<CodeGenOpts<"ControlFlowGuard">>;
def fdenormal_fp_math_f32_EQ : Joined<["-"], "fdenormal-fp-math-f32=">,
Group<f_Group>;
@@ -3851,11 +4689,14 @@ def fdenormal_fp_math_f32_EQ : Joined<["-"], "fdenormal-fp-math-f32=">,
//===----------------------------------------------------------------------===//
def sys_header_deps : Flag<["-"], "sys-header-deps">,
- HelpText<"Include system headers in dependency output">;
+ HelpText<"Include system headers in dependency output">,
+ MarshallingInfoFlag<DependencyOutputOpts<"IncludeSystemHeaders">>;
def module_file_deps : Flag<["-"], "module-file-deps">,
- HelpText<"Include module files in dependency output">;
+ HelpText<"Include module files in dependency output">,
+ MarshallingInfoFlag<DependencyOutputOpts<"IncludeModuleFiles">>;
def header_include_file : Separate<["-"], "header-include-file">,
- HelpText<"Filename (or -) to write header include output to">;
+ HelpText<"Filename (or -) to write header include output to">,
+ MarshallingInfoString<DependencyOutputOpts<"HeaderIncludeOutputFile">>;
def show_includes : Flag<["--"], "show-includes">,
HelpText<"Print cl.exe style /showIncludes to stdout">;
@@ -3864,36 +4705,50 @@ def show_includes : Flag<["--"], "show-includes">,
//===----------------------------------------------------------------------===//
def diagnostic_log_file : Separate<["-"], "diagnostic-log-file">,
- HelpText<"Filename (or -) to log diagnostics to">;
+ HelpText<"Filename (or -) to log diagnostics to">,
+ MarshallingInfoString<DiagnosticOpts<"DiagnosticLogFile">>;
def diagnostic_serialized_file : Separate<["-"], "serialize-diagnostic-file">,
MetaVarName<"<filename>">,
HelpText<"File for serializing diagnostics in a binary format">;
def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
- HelpText<"Change diagnostic formatting to match IDE and command line tools">, Values<"clang,msvc,msvc-fallback,vi">;
+ HelpText<"Change diagnostic formatting to match IDE and command line tools">, Values<"clang,msvc,msvc-fallback,vi">,
+ NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", "MSVC", "MSVC", "Vi"]>,
+ MarshallingInfoString<DiagnosticOpts<"Format">, "Clang">, AutoNormalizeEnum;
def fdiagnostics_show_category : Separate<["-"], "fdiagnostics-show-category">,
- HelpText<"Print diagnostic category">, Values<"none,id,name">;
+ HelpText<"Print diagnostic category">, Values<"none,id,name">,
+ NormalizedValues<["0", "1", "2"]>,
+ MarshallingInfoString<DiagnosticOpts<"ShowCategories">, "0">, AutoNormalizeEnum;
def fno_diagnostics_use_presumed_location : Flag<["-"], "fno-diagnostics-use-presumed-location">,
- HelpText<"Ignore #line directives when displaying diagnostic locations">;
+ HelpText<"Ignore #line directives when displaying diagnostic locations">,
+ MarshallingInfoNegativeFlag<DiagnosticOpts<"ShowPresumedLoc">>;
def ftabstop : Separate<["-"], "ftabstop">, MetaVarName<"<N>">,
- HelpText<"Set the tab stop distance.">;
+ HelpText<"Set the tab stop distance.">,
+ MarshallingInfoStringInt<DiagnosticOpts<"TabStop">, "DiagnosticOptions::DefaultTabStop">;
def ferror_limit : Separate<["-"], "ferror-limit">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of errors to emit before stopping (0 = no limit).">;
+ HelpText<"Set the maximum number of errors to emit before stopping (0 = no limit).">,
+ MarshallingInfoStringInt<DiagnosticOpts<"ErrorLimit">>;
def fmacro_backtrace_limit : Separate<["-"], "fmacro-backtrace-limit">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of entries to print in a macro expansion backtrace (0 = no limit).">;
+ HelpText<"Set the maximum number of entries to print in a macro expansion backtrace (0 = no limit).">,
+ MarshallingInfoStringInt<DiagnosticOpts<"MacroBacktraceLimit">, "DiagnosticOptions::DefaultMacroBacktraceLimit">;
def ftemplate_backtrace_limit : Separate<["-"], "ftemplate-backtrace-limit">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of entries to print in a template instantiation backtrace (0 = no limit).">;
+ HelpText<"Set the maximum number of entries to print in a template instantiation backtrace (0 = no limit).">,
+ MarshallingInfoStringInt<DiagnosticOpts<"TemplateBacktraceLimit">, "DiagnosticOptions::DefaultTemplateBacktraceLimit">;
def fconstexpr_backtrace_limit : Separate<["-"], "fconstexpr-backtrace-limit">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of entries to print in a constexpr evaluation backtrace (0 = no limit).">;
+ HelpText<"Set the maximum number of entries to print in a constexpr evaluation backtrace (0 = no limit).">,
+ MarshallingInfoStringInt<DiagnosticOpts<"ConstexprBacktraceLimit">, "DiagnosticOptions::DefaultConstexprBacktraceLimit">;
def fspell_checking_limit : Separate<["-"], "fspell-checking-limit">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of times to perform spell checking on unrecognized identifiers (0 = no limit).">;
+ HelpText<"Set the maximum number of times to perform spell checking on unrecognized identifiers (0 = no limit).">,
+ MarshallingInfoStringInt<DiagnosticOpts<"SpellCheckingLimit">, "DiagnosticOptions::DefaultSpellCheckingLimit">;
def fcaret_diagnostics_max_lines :
Separate<["-"], "fcaret-diagnostics-max-lines">, MetaVarName<"<N>">,
- HelpText<"Set the maximum number of source lines to show in a caret diagnostic">;
+ HelpText<"Set the maximum number of source lines to show in a caret diagnostic">,
+ MarshallingInfoStringInt<DiagnosticOpts<"SnippetLineLimit">, "DiagnosticOptions::DefaultSnippetLineLimit">;
def verify_EQ : CommaJoined<["-"], "verify=">,
MetaVarName<"<prefixes>">,
HelpText<"Verify diagnostic output using comment directives that start with"
- " prefixes in the comma-separated sequence <prefixes>">;
+ " prefixes in the comma-separated sequence <prefixes>">,
+ MarshallingInfoStringVector<DiagnosticOpts<"VerifyPrefixes">>;
def verify : Flag<["-"], "verify">,
HelpText<"Equivalent to -verify=expected">;
def verify_ignore_unexpected : Flag<["-"], "verify-ignore-unexpected">,
@@ -3901,7 +4756,8 @@ def verify_ignore_unexpected : Flag<["-"], "verify-ignore-unexpected">,
def verify_ignore_unexpected_EQ : CommaJoined<["-"], "verify-ignore-unexpected=">,
HelpText<"Ignore unexpected diagnostic messages">;
def Wno_rewrite_macros : Flag<["-"], "Wno-rewrite-macros">,
- HelpText<"Silence ObjC rewriting warnings">;
+ HelpText<"Silence ObjC rewriting warnings">,
+ MarshallingInfoFlag<DiagnosticOpts<"NoRewriteMacros">>;
//===----------------------------------------------------------------------===//
// Frontend Options
@@ -3914,13 +4770,15 @@ def cc1as : Flag<["-"], "cc1as">;
def ast_merge : Separate<["-"], "ast-merge">,
MetaVarName<"<ast file>">,
- HelpText<"Merge the given AST file into the translation unit being compiled.">;
+ HelpText<"Merge the given AST file into the translation unit being compiled.">,
+ MarshallingInfoStringVector<FrontendOpts<"ASTMergeFiles">>;
def aux_target_cpu : Separate<["-"], "aux-target-cpu">,
HelpText<"Target a specific auxiliary cpu type">;
def aux_target_feature : Separate<["-"], "aux-target-feature">,
HelpText<"Target specific auxiliary attributes">;
def aux_triple : Separate<["-"], "aux-triple">,
- HelpText<"Auxiliary target triple.">;
+ HelpText<"Auxiliary target triple.">,
+ MarshallingInfoString<FrontendOpts<"AuxTriple">>;
def code_completion_at : Separate<["-"], "code-completion-at">,
MetaVarName<"<file>:<line>:<column>">,
HelpText<"Dump code-completion information at a location">;
@@ -3930,21 +4788,29 @@ def remap_file : Separate<["-"], "remap-file">,
def code_completion_at_EQ : Joined<["-"], "code-completion-at=">,
Alias<code_completion_at>;
def code_completion_macros : Flag<["-"], "code-completion-macros">,
- HelpText<"Include macros in code-completion results">;
+ HelpText<"Include macros in code-completion results">,
+ MarshallingInfoFlag<FrontendOpts<"CodeCompleteOpts.IncludeMacros">>;
def code_completion_patterns : Flag<["-"], "code-completion-patterns">,
- HelpText<"Include code patterns in code-completion results">;
+ HelpText<"Include code patterns in code-completion results">,
+ MarshallingInfoFlag<FrontendOpts<"CodeCompleteOpts.IncludeCodePatterns">>;
def no_code_completion_globals : Flag<["-"], "no-code-completion-globals">,
- HelpText<"Do not include global declarations in code-completion results.">;
+ HelpText<"Do not include global declarations in code-completion results.">,
+ MarshallingInfoNegativeFlag<FrontendOpts<"CodeCompleteOpts.IncludeGlobals">>;
def no_code_completion_ns_level_decls : Flag<["-"], "no-code-completion-ns-level-decls">,
- HelpText<"Do not include declarations inside namespaces (incl. global namespace) in the code-completion results.">;
+ HelpText<"Do not include declarations inside namespaces (incl. global namespace) in the code-completion results.">,
+ MarshallingInfoNegativeFlag<FrontendOpts<"CodeCompleteOpts.IncludeNamespaceLevelDecls">>;
def code_completion_brief_comments : Flag<["-"], "code-completion-brief-comments">,
- HelpText<"Include brief documentation comments in code-completion results.">;
+ HelpText<"Include brief documentation comments in code-completion results.">,
+ MarshallingInfoFlag<FrontendOpts<"CodeCompleteOpts.IncludeBriefComments">>;
def code_completion_with_fixits : Flag<["-"], "code-completion-with-fixits">,
- HelpText<"Include code completion results which require small fix-its.">;
+ HelpText<"Include code completion results which require small fix-its.">,
+ MarshallingInfoFlag<FrontendOpts<"CodeCompleteOpts.IncludeFixIts">>;
def disable_free : Flag<["-"], "disable-free">,
- HelpText<"Disable freeing of memory on exit">;
+ HelpText<"Disable freeing of memory on exit">,
+ MarshallingInfoFlag<FrontendOpts<"DisableFree">>;
def discard_value_names : Flag<["-"], "discard-value-names">,
- HelpText<"Discard value names in LLVM IR">;
+ HelpText<"Discard value names in LLVM IR">,
+ MarshallingInfoFlag<CodeGenOpts<"DiscardValueNames">>;
def load : Separate<["-"], "load">, MetaVarName<"<dsopath>">,
HelpText<"Load the named plugin (dynamic shared object)">;
def plugin : Separate<["-"], "plugin">, MetaVarName<"<name>">,
@@ -3953,29 +4819,37 @@ def plugin_arg : JoinedAndSeparate<["-"], "plugin-arg-">,
MetaVarName<"<name> <arg>">,
HelpText<"Pass <arg> to plugin <name>">;
def add_plugin : Separate<["-"], "add-plugin">, MetaVarName<"<name>">,
- HelpText<"Use the named plugin action in addition to the default action">;
+ HelpText<"Use the named plugin action in addition to the default action">,
+ MarshallingInfoStringVector<FrontendOpts<"AddPluginActions">>;
def ast_dump_filter : Separate<["-"], "ast-dump-filter">,
MetaVarName<"<dump_filter>">,
HelpText<"Use with -ast-dump or -ast-print to dump/print only AST declaration"
" nodes having a certain substring in a qualified name. Use"
- " -ast-list to list all filterable declaration node names.">;
+ " -ast-list to list all filterable declaration node names.">,
+ MarshallingInfoString<FrontendOpts<"ASTDumpFilter">>;
def fno_modules_global_index : Flag<["-"], "fno-modules-global-index">,
- HelpText<"Do not automatically generate or update the global module index">;
+ HelpText<"Do not automatically generate or update the global module index">,
+ MarshallingInfoNegativeFlag<FrontendOpts<"UseGlobalModuleIndex">>;
def fno_modules_error_recovery : Flag<["-"], "fno-modules-error-recovery">,
- HelpText<"Do not automatically import modules for error recovery">;
+ HelpText<"Do not automatically import modules for error recovery">,
+ MarshallingInfoNegativeFlag<LangOpts<"ModulesErrorRecovery">>;
def fmodule_map_file_home_is_cwd : Flag<["-"], "fmodule-map-file-home-is-cwd">,
HelpText<"Use the current working directory as the home directory of "
- "module maps specified by -fmodule-map-file=<FILE>">;
+ "module maps specified by -fmodule-map-file=<FILE>">,
+ MarshallingInfoFlag<HeaderSearchOpts<"ModuleMapFileHomeIsCwd">>;
def fmodule_feature : Separate<["-"], "fmodule-feature">,
MetaVarName<"<feature>">,
- HelpText<"Enable <feature> in module map requires declarations">;
+ HelpText<"Enable <feature> in module map requires declarations">,
+ MarshallingInfoStringVector<LangOpts<"ModuleFeatures">>;
def fmodules_embed_file_EQ : Joined<["-"], "fmodules-embed-file=">,
MetaVarName<"<file>">,
HelpText<"Embed the contents of the specified file into the module file "
- "being compiled.">;
+ "being compiled.">,
+ MarshallingInfoStringVector<FrontendOpts<"ModulesEmbedFiles">>;
def fmodules_embed_all_files : Joined<["-"], "fmodules-embed-all-files">,
HelpText<"Embed the contents of all files read by this compilation into "
- "the produced module file.">;
+ "the produced module file.">,
+ MarshallingInfoFlag<FrontendOpts<"ModulesEmbedAllFiles">>;
def fmodules_local_submodule_visibility :
Flag<["-"], "fmodules-local-submodule-visibility">,
HelpText<"Enforce name visibility rules across submodules of the same "
@@ -3983,14 +4857,17 @@ def fmodules_local_submodule_visibility :
def fmodules_codegen :
Flag<["-"], "fmodules-codegen">,
HelpText<"Generate code for uses of this module that assumes an explicit "
- "object file will be built for the module">;
+ "object file will be built for the module">,
+ MarshallingInfoFlag<LangOpts<"ModulesCodegen">>;
def fmodules_debuginfo :
Flag<["-"], "fmodules-debuginfo">,
HelpText<"Generate debug info for types in an object file built from this "
- "module and do not generate them elsewhere">;
+ "module and do not generate them elsewhere">,
+ MarshallingInfoFlag<LangOpts<"ModulesDebugInfo">>;
def fmodule_format_EQ : Joined<["-"], "fmodule-format=">,
HelpText<"Select the container format for clang modules and PCH. "
- "Supported options are 'raw' and 'obj'.">;
+ "Supported options are 'raw' and 'obj'.">,
+ MarshallingInfoString<HeaderSearchOpts<"ModuleFormat">, [{"raw"}]>;
def ftest_module_file_extension_EQ :
Joined<["-"], "ftest-module-file-extension=">,
HelpText<"introduce a module file extension for testing purposes. "
@@ -3999,16 +4876,17 @@ def fconcepts_ts : Flag<["-"], "fconcepts-ts">,
HelpText<"Enable C++ Extensions for Concepts. (deprecated - use -std=c++2a)">;
def fno_concept_satisfaction_caching : Flag<["-"],
"fno-concept-satisfaction-caching">,
- HelpText<"Disable satisfaction caching for C++2a Concepts.">;
-
-def frecovery_ast : Flag<["-"], "frecovery-ast">,
- HelpText<"Preserve expressions in AST rather than dropping them when "
- "encountering semantic errors">;
-def fno_recovery_ast : Flag<["-"], "fno-recovery-ast">;
-def frecovery_ast_type : Flag<["-"], "frecovery-ast-type">,
- HelpText<"Preserve the type for recovery expressions when possible "
- "(experimental)">;
-def fno_recovery_ast_type : Flag<["-"], "fno-recovery-ast-type">;
+ HelpText<"Disable satisfaction caching for C++2a Concepts.">,
+ MarshallingInfoNegativeFlag<LangOpts<"ConceptSatisfactionCaching">>;
+
+defm recovery_ast : BoolOption<"f", "recovery-ast",
+ LangOpts<"RecoveryAST">, DefaultTrue,
+ NegFlag<SetFalse>, PosFlag<SetTrue, [], "Preserve expressions in AST rather "
+ "than dropping them when encountering semantic errors">>;
+defm recovery_ast_type : BoolOption<"f", "recovery-ast-type",
+ LangOpts<"RecoveryASTType">, DefaultTrue,
+ NegFlag<SetFalse>, PosFlag<SetTrue, [], "Preserve the type for recovery "
+ "expressions when possible">>;
let Group = Action_Group in {
@@ -4046,11 +4924,13 @@ def ast_dump_all_EQ : Joined<["-"], "ast-dump-all=">,
HelpText<"Build ASTs and then debug dump them in the specified format, "
"forcing deserialization. Supported formats include: default, json">;
def ast_dump_decl_types : Flag<["-"], "ast-dump-decl-types">,
- HelpText<"Include declaration types in AST dumps">;
+ HelpText<"Include declaration types in AST dumps">,
+ MarshallingInfoFlag<FrontendOpts<"ASTDumpDeclTypes">>;
def templight_dump : Flag<["-"], "templight-dump">,
HelpText<"Dump templight information to stdout">;
def ast_dump_lookups : Flag<["-"], "ast-dump-lookups">,
- HelpText<"Build ASTs and then debug dump their name lookup tables">;
+ HelpText<"Build ASTs and then debug dump their name lookup tables">,
+ MarshallingInfoFlag<FrontendOpts<"ASTDumpLookups">>;
def ast_view : Flag<["-"], "ast-view">,
HelpText<"Build ASTs and view them with GraphViz">;
def emit_module : Flag<["-"], "emit-module">,
@@ -4067,8 +4947,6 @@ def emit_llvm_only : Flag<["-"], "emit-llvm-only">,
HelpText<"Build ASTs and convert to LLVM, discarding output">;
def emit_codegen_only : Flag<["-"], "emit-codegen-only">,
HelpText<"Generate machine code, but discard output">;
-def emit_obj : Flag<["-"], "emit-obj">,
- HelpText<"Emit native object files">;
def rewrite_test : Flag<["-"], "rewrite-test">,
HelpText<"Rewriter playground">;
def rewrite_macros : Flag<["-"], "rewrite-macros">,
@@ -4082,57 +4960,73 @@ def print_dependency_directives_minimized_source : Flag<["-"],
HelpText<"Print the output of the dependency directives source minimizer">;
}
-def emit_llvm_uselists : Flag<["-"], "emit-llvm-uselists">,
- HelpText<"Preserve order of LLVM use-lists when serializing">;
-def no_emit_llvm_uselists : Flag<["-"], "no-emit-llvm-uselists">,
- HelpText<"Don't preserve order of LLVM use-lists when serializing">;
+defm emit_llvm_uselists : BoolOption<"", "emit-llvm-uselists",
+ CodeGenOpts<"EmitLLVMUseLists">, DefaultFalse,
+ PosFlag<SetTrue, [], "Preserve">,
+ NegFlag<SetFalse, [], "Don't preserve">,
+ BothFlags<[], " order of LLVM use-lists when serializing">>;
def mt_migrate_directory : Separate<["-"], "mt-migrate-directory">,
- HelpText<"Directory for temporary files produced during ARC or ObjC migration">;
-def arcmt_check : Flag<["-"], "arcmt-check">,
- HelpText<"Check for ARC migration issues that need manual handling">;
-def arcmt_modify : Flag<["-"], "arcmt-modify">,
- HelpText<"Apply modifications to files to conform to ARC">;
-def arcmt_migrate : Flag<["-"], "arcmt-migrate">,
- HelpText<"Apply modifications and produces temporary files that conform to ARC">;
+ HelpText<"Directory for temporary files produced during ARC or ObjC migration">,
+ MarshallingInfoString<FrontendOpts<"MTMigrateDir">>;
+
+def arcmt_action_EQ : Joined<["-"], "arcmt-action=">, Flags<[CC1Option, NoDriverOption]>,
+ HelpText<"The ARC migration action to take">, Values<"check,modify,migrate">,
+ NormalizedValuesScope<"FrontendOptions">,
+ NormalizedValues<["ARCMT_Check", "ARCMT_Modify", "ARCMT_Migrate"]>,
+ MarshallingInfoString<FrontendOpts<"ARCMTAction">, "ARCMT_None">,
+ AutoNormalizeEnum;
def opt_record_file : Separate<["-"], "opt-record-file">,
- HelpText<"File name to use for YAML optimization record output">;
+ HelpText<"File name to use for YAML optimization record output">,
+ MarshallingInfoString<CodeGenOpts<"OptRecordFile">>;
def opt_record_passes : Separate<["-"], "opt-record-passes">,
HelpText<"Only record remark information for passes whose names match the given regular expression">;
def opt_record_format : Separate<["-"], "opt-record-format">,
HelpText<"The format used for serializing remarks (default: YAML)">;
def print_stats : Flag<["-"], "print-stats">,
- HelpText<"Print performance metrics and statistics">;
+ HelpText<"Print performance metrics and statistics">,
+ MarshallingInfoFlag<FrontendOpts<"ShowStats">>;
def stats_file : Joined<["-"], "stats-file=">,
- HelpText<"Filename to write statistics to">;
+ HelpText<"Filename to write statistics to">,
+ MarshallingInfoString<FrontendOpts<"StatsFile">>;
def fdump_record_layouts : Flag<["-"], "fdump-record-layouts">,
HelpText<"Dump record layout information">;
def fdump_record_layouts_simple : Flag<["-"], "fdump-record-layouts-simple">,
- HelpText<"Dump record layout information in a simple form used for testing">;
+ HelpText<"Dump record layout information in a simple form used for testing">,
+ MarshallingInfoFlag<LangOpts<"DumpRecordLayoutsSimple">>;
def fix_what_you_can : Flag<["-"], "fix-what-you-can">,
- HelpText<"Apply fix-it advice even in the presence of unfixable errors">;
+ HelpText<"Apply fix-it advice even in the presence of unfixable errors">,
+ MarshallingInfoFlag<FrontendOpts<"FixWhatYouCan">>;
def fix_only_warnings : Flag<["-"], "fix-only-warnings">,
- HelpText<"Apply fix-it advice only for warnings, not errors">;
+ HelpText<"Apply fix-it advice only for warnings, not errors">,
+ MarshallingInfoFlag<FrontendOpts<"FixOnlyWarnings">>;
def fixit_recompile : Flag<["-"], "fixit-recompile">,
- HelpText<"Apply fix-it changes and recompile">;
+ HelpText<"Apply fix-it changes and recompile">,
+ MarshallingInfoFlag<FrontendOpts<"FixAndRecompile">>;
def fixit_to_temp : Flag<["-"], "fixit-to-temporary">,
- HelpText<"Apply fix-it changes to temporary files">;
+ HelpText<"Apply fix-it changes to temporary files">,
+ MarshallingInfoFlag<FrontendOpts<"FixToTemporaries">>;
def foverride_record_layout_EQ : Joined<["-"], "foverride-record-layout=">,
- HelpText<"Override record layouts with those in the given file">;
+ HelpText<"Override record layouts with those in the given file">,
+ MarshallingInfoString<FrontendOpts<"OverrideRecordLayoutsFile">>;
def pch_through_header_EQ : Joined<["-"], "pch-through-header=">,
HelpText<"Stop PCH generation after including this file. When using a PCH, "
- "skip tokens until after this file is included.">;
+ "skip tokens until after this file is included.">,
+ MarshallingInfoString<PreprocessorOpts<"PCHThroughHeader">>;
def pch_through_hdrstop_create : Flag<["-"], "pch-through-hdrstop-create">,
- HelpText<"When creating a PCH, stop PCH generation after #pragma hdrstop.">;
+ HelpText<"When creating a PCH, stop PCH generation after #pragma hdrstop.">,
+ MarshallingInfoFlag<PreprocessorOpts<"PCHWithHdrStopCreate">>;
def pch_through_hdrstop_use : Flag<["-"], "pch-through-hdrstop-use">,
HelpText<"When using a PCH, skip tokens until after a #pragma hdrstop.">;
def fno_pch_timestamp : Flag<["-"], "fno-pch-timestamp">,
- HelpText<"Disable inclusion of timestamp in precompiled headers">;
+ HelpText<"Disable inclusion of timestamp in precompiled headers">,
+ MarshallingInfoNegativeFlag<FrontendOpts<"IncludeTimestamps">>;
def building_pch_with_obj : Flag<["-"], "building-pch-with-obj">,
- HelpText<"This compilation is part of building a PCH with corresponding object file.">;
+ HelpText<"This compilation is part of building a PCH with corresponding object file.">,
+ MarshallingInfoFlag<LangOpts<"BuildingPCHWithObjectFile">>;
def aligned_alloc_unavailable : Flag<["-"], "faligned-alloc-unavailable">,
HelpText<"Aligned allocation/deallocation functions are unavailable">;
@@ -4144,122 +5038,192 @@ def aligned_alloc_unavailable : Flag<["-"], "faligned-alloc-unavailable">,
let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
def version : Flag<["-"], "version">,
- HelpText<"Print the compiler version">;
+ HelpText<"Print the compiler version">,
+ MarshallingInfoFlag<FrontendOpts<"ShowVersion">>;
def main_file_name : Separate<["-"], "main-file-name">,
- HelpText<"Main file name to use for debug info and source if missing">;
+ HelpText<"Main file name to use for debug info and source if missing">,
+ MarshallingInfoString<CodeGenOpts<"MainFileName">>;
def split_dwarf_output : Separate<["-"], "split-dwarf-output">,
- HelpText<"File name to use for split dwarf debug info output">;
+ HelpText<"File name to use for split dwarf debug info output">,
+ MarshallingInfoString<CodeGenOpts<"SplitDwarfOutput">>;
}
def fblocks_runtime_optional : Flag<["-"], "fblocks-runtime-optional">,
- HelpText<"Weakly link in the blocks runtime">;
+ HelpText<"Weakly link in the blocks runtime">,
+ MarshallingInfoFlag<LangOpts<"BlocksRuntimeOptional">>;
def fexternc_nounwind : Flag<["-"], "fexternc-nounwind">,
- HelpText<"Assume all functions with C linkage do not unwind">;
+ HelpText<"Assume all functions with C linkage do not unwind">,
+ MarshallingInfoFlag<LangOpts<"ExternCNoUnwind">>;
def split_dwarf_file : Separate<["-"], "split-dwarf-file">,
- HelpText<"Name of the split dwarf debug info file to encode in the object file">;
+ HelpText<"Name of the split dwarf debug info file to encode in the object file">,
+ MarshallingInfoString<CodeGenOpts<"SplitDwarfFile">>;
def fno_wchar : Flag<["-"], "fno-wchar">,
HelpText<"Disable C++ builtin type wchar_t">;
def fconstant_string_class : Separate<["-"], "fconstant-string-class">,
MetaVarName<"<class name>">,
- HelpText<"Specify the class to use for constant Objective-C string objects.">;
+ HelpText<"Specify the class to use for constant Objective-C string objects.">,
+ MarshallingInfoString<LangOpts<"ObjCConstantStringClass">>;
def fobjc_arc_cxxlib_EQ : Joined<["-"], "fobjc-arc-cxxlib=">,
- HelpText<"Objective-C++ Automatic Reference Counting standard library kind">, Values<"libc++,libstdc++,none">;
+ HelpText<"Objective-C++ Automatic Reference Counting standard library kind">, Values<"libc++,libstdc++,none">,
+ NormalizedValues<["ARCXX_libcxx", "ARCXX_libstdcxx", "ARCXX_nolib"]>,
+ MarshallingInfoString<PreprocessorOpts<"ObjCXXARCStandardLibrary">, "ARCXX_nolib">, AutoNormalizeEnum;
def fobjc_runtime_has_weak : Flag<["-"], "fobjc-runtime-has-weak">,
HelpText<"The target Objective-C runtime supports ARC weak operations">;
def fobjc_dispatch_method_EQ : Joined<["-"], "fobjc-dispatch-method=">,
- HelpText<"Objective-C dispatch method to use">, Values<"legacy,non-legacy,mixed">;
+ HelpText<"Objective-C dispatch method to use">, Values<"legacy,non-legacy,mixed">,
+ NormalizedValuesScope<"CodeGenOptions">, NormalizedValues<["Legacy", "NonLegacy", "Mixed"]>,
+ MarshallingInfoString<CodeGenOpts<"ObjCDispatchMethod">, "Legacy">, AutoNormalizeEnum;
def disable_objc_default_synthesize_properties : Flag<["-"], "disable-objc-default-synthesize-properties">,
- HelpText<"disable the default synthesis of Objective-C properties">;
+ HelpText<"disable the default synthesis of Objective-C properties">,
+ MarshallingInfoNegativeFlag<LangOpts<"ObjCDefaultSynthProperties">>;
def fencode_extended_block_signature : Flag<["-"], "fencode-extended-block-signature">,
- HelpText<"enable extended encoding of block type signature">;
+ HelpText<"enable extended encoding of block type signature">,
+ MarshallingInfoFlag<LangOpts<"EncodeExtendedBlockSig">>;
def function_alignment : Separate<["-"], "function-alignment">,
- HelpText<"default alignment for functions">;
+ HelpText<"default alignment for functions">,
+ MarshallingInfoStringInt<LangOpts<"FunctionAlignment">>;
def pic_level : Separate<["-"], "pic-level">,
HelpText<"Value for __PIC__">;
def pic_is_pie : Flag<["-"], "pic-is-pie">,
- HelpText<"File is for a position independent executable">;
+ HelpText<"File is for a position independent executable">,
+ MarshallingInfoFlag<LangOpts<"PIE">>;
+def fhalf_no_semantic_interposition : Flag<["-"], "fhalf-no-semantic-interposition">,
+ HelpText<"Like -fno-semantic-interposition but don't use local aliases">,
+ MarshallingInfoFlag<LangOpts<"HalfNoSemanticInterposition">>;
def fno_validate_pch : Flag<["-"], "fno-validate-pch">,
- HelpText<"Disable validation of precompiled headers">;
+ HelpText<"Disable validation of precompiled headers">,
+ MarshallingInfoFlag<PreprocessorOpts<"DisablePCHOrModuleValidation">, "DisableValidationForModuleKind::None">,
+ Normalizer<"makeFlagToValueNormalizer(DisableValidationForModuleKind::All)">;
+def fallow_pcm_with_errors : Flag<["-"], "fallow-pcm-with-compiler-errors">,
+ HelpText<"Accept a PCM file that was created with compiler errors">,
+ MarshallingInfoFlag<FrontendOpts<"AllowPCMWithCompilerErrors">>;
def fallow_pch_with_errors : Flag<["-"], "fallow-pch-with-compiler-errors">,
- HelpText<"Accept a PCH file that was created with compiler errors">;
+ HelpText<"Accept a PCH file that was created with compiler errors">,
+ MarshallingInfoFlag<PreprocessorOpts<"AllowPCHWithCompilerErrors">>,
+ ImpliedByAnyOf<[fallow_pcm_with_errors.KeyPath]>;
def dump_deserialized_pch_decls : Flag<["-"], "dump-deserialized-decls">,
- HelpText<"Dump declarations that are deserialized from PCH, for testing">;
+ HelpText<"Dump declarations that are deserialized from PCH, for testing">,
+ MarshallingInfoFlag<PreprocessorOpts<"DumpDeserializedPCHDecls">>;
def error_on_deserialized_pch_decl : Separate<["-"], "error-on-deserialized-decl">,
HelpText<"Emit error if a specific declaration is deserialized from PCH, for testing">;
def error_on_deserialized_pch_decl_EQ : Joined<["-"], "error-on-deserialized-decl=">,
Alias<error_on_deserialized_pch_decl>;
def static_define : Flag<["-"], "static-define">,
- HelpText<"Should __STATIC__ be defined">;
+ HelpText<"Should __STATIC__ be defined">,
+ MarshallingInfoFlag<LangOpts<"Static">>;
def stack_protector : Separate<["-"], "stack-protector">,
- HelpText<"Enable stack protectors">;
+ HelpText<"Enable stack protectors">, Values<"0,1,2,3">,
+ NormalizedValuesScope<"LangOptions">,
+ NormalizedValues<["SSPOff", "SSPOn", "SSPStrong", "SSPReq"]>,
+ MarshallingInfoString<LangOpts<"StackProtector">, "SSPOff">, AutoNormalizeEnum;
def stack_protector_buffer_size : Separate<["-"], "stack-protector-buffer-size">,
- HelpText<"Lower bound for a buffer to be considered for stack protection">;
+ HelpText<"Lower bound for a buffer to be considered for stack protection">,
+ MarshallingInfoStringInt<CodeGenOpts<"SSPBufferSize">, "8">;
def fvisibility : Separate<["-"], "fvisibility">,
- HelpText<"Default type and symbol visibility">;
+ HelpText<"Default type and symbol visibility">,
+ MarshallingInfoVisibility<LangOpts<"ValueVisibilityMode">, "DefaultVisibility">;
def ftype_visibility : Separate<["-"], "ftype-visibility">,
- HelpText<"Default type visibility">;
+ HelpText<"Default type visibility">,
+ MarshallingInfoVisibility<LangOpts<"TypeVisibilityMode">, fvisibility.KeyPath>;
def fapply_global_visibility_to_externs : Flag<["-"], "fapply-global-visibility-to-externs">,
- HelpText<"Apply global symbol visibility to external declarations without an explicit visibility">;
+ HelpText<"Apply global symbol visibility to external declarations without an explicit visibility">,
+ MarshallingInfoFlag<LangOpts<"SetVisibilityForExternDecls">>;
def ftemplate_depth : Separate<["-"], "ftemplate-depth">,
- HelpText<"Maximum depth of recursive template instantiation">;
+ HelpText<"Maximum depth of recursive template instantiation">,
+ MarshallingInfoStringInt<LangOpts<"InstantiationDepth">, "1024">;
def foperator_arrow_depth : Separate<["-"], "foperator-arrow-depth">,
- HelpText<"Maximum number of 'operator->'s to call for a member access">;
+ HelpText<"Maximum number of 'operator->'s to call for a member access">,
+ MarshallingInfoStringInt<LangOpts<"ArrowDepth">, "256">;
def fconstexpr_depth : Separate<["-"], "fconstexpr-depth">,
- HelpText<"Maximum depth of recursive constexpr function calls">;
+ HelpText<"Maximum depth of recursive constexpr function calls">,
+ MarshallingInfoStringInt<LangOpts<"ConstexprCallDepth">, "512">;
def fconstexpr_steps : Separate<["-"], "fconstexpr-steps">,
- HelpText<"Maximum number of steps in constexpr function evaluation">;
+ HelpText<"Maximum number of steps in constexpr function evaluation">,
+ MarshallingInfoStringInt<LangOpts<"ConstexprStepLimit">, "1048576">;
def fbracket_depth : Separate<["-"], "fbracket-depth">,
- HelpText<"Maximum nesting level for parentheses, brackets, and braces">;
-def fconst_strings : Flag<["-"], "fconst-strings">,
- HelpText<"Use a const qualified type for string literals in C and ObjC">;
-def fno_const_strings : Flag<["-"], "fno-const-strings">,
- HelpText<"Don't use a const qualified type for string literals in C and ObjC">;
+ HelpText<"Maximum nesting level for parentheses, brackets, and braces">,
+ MarshallingInfoStringInt<LangOpts<"BracketDepth">, "256">;
+defm const_strings : BoolOption<"f", "const-strings",
+ LangOpts<"ConstStrings">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use">, NegFlag<SetFalse, [], "Don't use">,
+ BothFlags<[], " a const qualified type for string literals in C and ObjC">>;
def fno_bitfield_type_align : Flag<["-"], "fno-bitfield-type-align">,
- HelpText<"Ignore bit-field types when aligning structures">;
+ HelpText<"Ignore bit-field types when aligning structures">,
+ MarshallingInfoFlag<LangOpts<"NoBitFieldTypeAlign">>;
def ffake_address_space_map : Flag<["-"], "ffake-address-space-map">,
- HelpText<"Use a fake address space map; OpenCL testing purposes only">;
+ HelpText<"Use a fake address space map; OpenCL testing purposes only">,
+ MarshallingInfoFlag<LangOpts<"FakeAddressSpaceMap">>;
def faddress_space_map_mangling_EQ : Joined<["-"], "faddress-space-map-mangling=">, MetaVarName<"<yes|no|target>">,
- HelpText<"Set the mode for address space map based mangling; OpenCL testing purposes only">;
+ HelpText<"Set the mode for address space map based mangling; OpenCL testing purposes only">,
+ Values<"target,no,yes">, NormalizedValuesScope<"LangOptions">,
+ NormalizedValues<["ASMM_Target", "ASMM_Off", "ASMM_On"]>,
+ MarshallingInfoString<LangOpts<"AddressSpaceMapMangling">, "ASMM_Target">, AutoNormalizeEnum;
def funknown_anytype : Flag<["-"], "funknown-anytype">,
- HelpText<"Enable parser support for the __unknown_anytype type; for testing purposes only">;
+ HelpText<"Enable parser support for the __unknown_anytype type; for testing purposes only">,
+ MarshallingInfoFlag<LangOpts<"ParseUnknownAnytype">>;
def fdebugger_support : Flag<["-"], "fdebugger-support">,
- HelpText<"Enable special debugger support behavior">;
+ HelpText<"Enable special debugger support behavior">,
+ MarshallingInfoFlag<LangOpts<"DebuggerSupport">>;
def fdebugger_cast_result_to_id : Flag<["-"], "fdebugger-cast-result-to-id">,
- HelpText<"Enable casting unknown expression results to id">;
+ HelpText<"Enable casting unknown expression results to id">,
+ MarshallingInfoFlag<LangOpts<"DebuggerCastResultToId">>;
def fdebugger_objc_literal : Flag<["-"], "fdebugger-objc-literal">,
- HelpText<"Enable special debugger support for Objective-C subscripting and literals">;
+ HelpText<"Enable special debugger support for Objective-C subscripting and literals">,
+ MarshallingInfoFlag<LangOpts<"DebuggerObjCLiteral">>;
def fdeprecated_macro : Flag<["-"], "fdeprecated-macro">,
HelpText<"Defines the __DEPRECATED macro">;
def fno_deprecated_macro : Flag<["-"], "fno-deprecated-macro">,
HelpText<"Undefines the __DEPRECATED macro">;
def fobjc_subscripting_legacy_runtime : Flag<["-"], "fobjc-subscripting-legacy-runtime">,
HelpText<"Allow Objective-C array and dictionary subscripting in legacy runtime">;
+// TODO: Enforce values valid for MSVtorDispMode.
def vtordisp_mode_EQ : Joined<["-"], "vtordisp-mode=">,
- HelpText<"Control vtordisp placement on win32 targets">;
+ HelpText<"Control vtordisp placement on win32 targets">,
+ MarshallingInfoStringInt<LangOpts<"VtorDispMode">, "1">;
def fnative_half_type: Flag<["-"], "fnative-half-type">,
- HelpText<"Use the native half type for __fp16 instead of promoting to float">;
+ HelpText<"Use the native half type for __fp16 instead of promoting to float">,
+ MarshallingInfoFlag<LangOpts<"NativeHalfType">>,
+ ImpliedByAnyOf<[open_cl.KeyPath, render_script.KeyPath]>;
def fnative_half_arguments_and_returns : Flag<["-"], "fnative-half-arguments-and-returns">,
- HelpText<"Use the native __fp16 type for arguments and returns (and skip ABI-specific lowering)">;
+ HelpText<"Use the native __fp16 type for arguments and returns (and skip ABI-specific lowering)">,
+ MarshallingInfoFlag<LangOpts<"NativeHalfArgsAndReturns">>,
+ ImpliedByAnyOf<[open_cl.KeyPath, render_script.KeyPath]>;
def fallow_half_arguments_and_returns : Flag<["-"], "fallow-half-arguments-and-returns">,
- HelpText<"Allow function arguments and returns of type half">;
+ HelpText<"Allow function arguments and returns of type half">,
+ MarshallingInfoFlag<LangOpts<"HalfArgsAndReturns">>,
+ ImpliedByAnyOf<[fnative_half_arguments_and_returns.KeyPath]>;
def fdefault_calling_conv_EQ : Joined<["-"], "fdefault-calling-conv=">,
- HelpText<"Set default calling convention">, Values<"cdecl,fastcall,stdcall,vectorcall,regcall">;
+ HelpText<"Set default calling convention">, Values<"cdecl,fastcall,stdcall,vectorcall,regcall">,
+ NormalizedValuesScope<"LangOptions">,
+ NormalizedValues<["DCC_CDecl", "DCC_FastCall", "DCC_StdCall", "DCC_VectorCall", "DCC_RegCall"]>,
+ MarshallingInfoString<LangOpts<"DefaultCallingConv">, "DCC_None">, AutoNormalizeEnum;
+
+// These options cannot be marshalled, because they are used to set up the LangOptions defaults.
def finclude_default_header : Flag<["-"], "finclude-default-header">,
HelpText<"Include default header file for OpenCL">;
def fdeclare_opencl_builtins : Flag<["-"], "fdeclare-opencl-builtins">,
HelpText<"Add OpenCL builtin function declarations (experimental)">;
+
def fpreserve_vec3_type : Flag<["-"], "fpreserve-vec3-type">,
- HelpText<"Preserve 3-component vector type">;
+ HelpText<"Preserve 3-component vector type">,
+ MarshallingInfoFlag<CodeGenOpts<"PreserveVec3Type">>;
def fwchar_type_EQ : Joined<["-"], "fwchar-type=">,
- HelpText<"Select underlying type for wchar_t">, Values<"char,short,int">;
-def fsigned_wchar : Flag<["-"], "fsigned-wchar">,
- HelpText<"Use a signed type for wchar_t">;
-def fno_signed_wchar : Flag<["-"], "fno-signed-wchar">,
- HelpText<"Use an unsigned type for wchar_t">;
+ HelpText<"Select underlying type for wchar_t">, Values<"char,short,int">,
+ NormalizedValues<["1", "2", "4"]>,
+ MarshallingInfoString<LangOpts<"WCharSize">, "0">, AutoNormalizeEnum;
+defm signed_wchar : BoolOption<"f", "signed-wchar",
+ LangOpts<"WCharIsSigned">, DefaultTrue,
+ NegFlag<SetFalse, [CC1Option], "Use an unsigned">, PosFlag<SetTrue, [], "Use a signed">,
+ BothFlags<[], " type for wchar_t">>;
def fcompatibility_qualified_id_block_param_type_checking : Flag<["-"], "fcompatibility-qualified-id-block-type-checking">,
HelpText<"Allow using blocks with parameters of more specific type than "
- "the type system guarantees when a parameter is qualified id">;
+ "the type system guarantees when a parameter is qualified id">,
+ MarshallingInfoFlag<LangOpts<"CompatibilityQualifiedIdBlockParamTypeChecking">>;
+def fpass_by_value_is_noalias: Flag<["-"], "fpass-by-value-is-noalias">,
+ HelpText<"Allows assuming by-value parameters do not alias any other value. "
+ "Has no effect on non-trivially-copyable classes in C++.">, Group<f_Group>,
+ MarshallingInfoFlag<CodeGenOpts<"PassByValueIsNoAlias">>;
// FIXME: Remove these entirely once functionality/tests have been excised.
def fobjc_gc_only : Flag<["-"], "fobjc-gc-only">, Group<f_Group>,
@@ -4272,15 +5236,18 @@ def fobjc_gc : Flag<["-"], "fobjc-gc">, Group<f_Group>,
//===----------------------------------------------------------------------===//
def nostdsysteminc : Flag<["-"], "nostdsysteminc">,
- HelpText<"Disable standard system #include directories">;
+ HelpText<"Disable standard system #include directories">,
+ MarshallingInfoNegativeFlag<HeaderSearchOpts<"UseStandardSystemIncludes">>;
def fdisable_module_hash : Flag<["-"], "fdisable-module-hash">,
- HelpText<"Disable the module hash">;
+ HelpText<"Disable the module hash">,
+ MarshallingInfoFlag<HeaderSearchOpts<"DisableModuleHash">>;
def fmodules_hash_content : Flag<["-"], "fmodules-hash-content">,
- HelpText<"Enable hashing the content of a module file">;
+ HelpText<"Enable hashing the content of a module file">,
+ MarshallingInfoFlag<HeaderSearchOpts<"ModulesHashContent">>;
def fmodules_strict_context_hash : Flag<["-"], "fmodules-strict-context-hash">,
HelpText<"Enable hashing of all compiler options that could impact the "
"semantics of a module in an implicit build">,
- MarshallingInfoFlag<"HeaderSearchOpts->ModulesStrictContextHash", "false">;
+ MarshallingInfoFlag<HeaderSearchOpts<"ModulesStrictContextHash">>;
def c_isystem : JoinedOrSeparate<["-"], "c-isystem">, MetaVarName<"<directory>">,
HelpText<"Add directory to the C SYSTEM include search path">;
def objc_isystem : JoinedOrSeparate<["-"], "objc-isystem">,
@@ -4311,31 +5278,39 @@ def preamble_bytes_EQ : Joined<["-"], "preamble-bytes=">,
HelpText<"Assume that the precompiled header is a precompiled preamble "
"covering the first N bytes of the main file">;
def detailed_preprocessing_record : Flag<["-"], "detailed-preprocessing-record">,
- HelpText<"include a detailed record of preprocessing actions">;
+ HelpText<"include a detailed record of preprocessing actions">,
+ MarshallingInfoFlag<PreprocessorOpts<"DetailedRecord">>;
def setup_static_analyzer : Flag<["-"], "setup-static-analyzer">,
- HelpText<"Set up preprocessor for static analyzer (done automatically when static analyzer is run).">;
+ HelpText<"Set up preprocessor for static analyzer (done automatically when static analyzer is run).">,
+ MarshallingInfoFlag<PreprocessorOpts<"SetUpStaticAnalyzer">>;
def disable_pragma_debug_crash : Flag<["-"], "disable-pragma-debug-crash">,
- HelpText<"Disable any #pragma clang __debug that can lead to crashing behavior. This is meant for testing.">;
+ HelpText<"Disable any #pragma clang __debug that can lead to crashing behavior. This is meant for testing.">,
+ MarshallingInfoFlag<PreprocessorOpts<"DisablePragmaDebugCrash">>;
//===----------------------------------------------------------------------===//
// OpenCL Options
//===----------------------------------------------------------------------===//
def cl_ext_EQ : CommaJoined<["-"], "cl-ext=">,
- HelpText<"OpenCL only. Enable or disable OpenCL extensions. The argument is a comma-separated sequence of one or more extension names, each prefixed by '+' or '-'.">;
+ HelpText<"OpenCL only. Enable or disable OpenCL extensions. The argument is a comma-separated sequence of one or more extension names, each prefixed by '+' or '-'.">,
+ MarshallingInfoStringVector<TargetOpts<"OpenCLExtensionsAsWritten">>;
//===----------------------------------------------------------------------===//
// CUDA Options
//===----------------------------------------------------------------------===//
def fcuda_is_device : Flag<["-"], "fcuda-is-device">,
- HelpText<"Generate code for CUDA device">;
+ HelpText<"Generate code for CUDA device">,
+ MarshallingInfoFlag<LangOpts<"CUDAIsDevice">>;
def fcuda_include_gpubinary : Separate<["-"], "fcuda-include-gpubinary">,
- HelpText<"Incorporate CUDA device-side binary into host object file.">;
+ HelpText<"Incorporate CUDA device-side binary into host object file.">,
+ MarshallingInfoString<CodeGenOpts<"CudaGpuBinaryFileName">>;
def fcuda_allow_variadic_functions : Flag<["-"], "fcuda-allow-variadic-functions">,
- HelpText<"Allow variadic functions in CUDA device code.">;
+ HelpText<"Allow variadic functions in CUDA device code.">,
+ MarshallingInfoFlag<LangOpts<"CUDAAllowVariadicFunctions">>;
def fno_cuda_host_device_constexpr : Flag<["-"], "fno-cuda-host-device-constexpr">,
- HelpText<"Don't treat unattributed constexpr functions as __host__ __device__.">;
+ HelpText<"Don't treat unattributed constexpr functions as __host__ __device__.">,
+ MarshallingInfoNegativeFlag<LangOpts<"CUDAHostDeviceConstexpr">>;
//===----------------------------------------------------------------------===//
// OpenMP Options
@@ -4351,9 +5326,29 @@ def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">,
//===----------------------------------------------------------------------===//
def fsycl_is_device : Flag<["-"], "fsycl-is-device">,
- HelpText<"Generate code for SYCL device.">;
+ HelpText<"Generate code for SYCL device.">,
+ MarshallingInfoFlag<LangOpts<"SYCLIsDevice">>,
+ ShouldParseIf<fsycl.KeyPath>;
+
+} // let Flags = [CC1Option, NoDriverOption]
+
+defm cuda_approx_transcendentals : BoolFOption<"cuda-approx-transcendentals",
+ LangOpts<"CUDADeviceApproxTranscendentals">, DefaultFalse,
+ PosFlag<SetTrue, [CC1Option], "Use">, NegFlag<SetFalse, [], "Don't use">,
+ BothFlags<[], " approximate transcendental functions">>,
+ ShouldParseIf<fcuda_is_device.KeyPath>;
+
+//===----------------------------------------------------------------------===//
+// Frontend Options - cc1 + fc1
+//===----------------------------------------------------------------------===//
+let Flags = [CC1Option, FC1Option, NoDriverOption] in {
+let Group = Action_Group in {
+
+def emit_obj : Flag<["-"], "emit-obj">,
+ HelpText<"Emit native object files">;
-} // let Flags = [CC1Option]
+} // let Group = Action_Group
+} // let Flags = [CC1Option, FC1Option, NoDriverOption]
//===----------------------------------------------------------------------===//
// cc1as-only Options
@@ -4400,32 +5395,32 @@ def cl_ignored_Group : OptionGroup<"<clang-cl ignored options>">,
Group<cl_Group>;
class CLFlag<string name> : Option<["/", "-"], name, KIND_FLAG>,
- Group<cl_Group>, Flags<[CLOption, DriverOption]>;
+ Group<cl_Group>, Flags<[CLOption, NoXarchOption]>;
class CLCompileFlag<string name> : Option<["/", "-"], name, KIND_FLAG>,
- Group<cl_compile_Group>, Flags<[CLOption, DriverOption]>;
+ Group<cl_compile_Group>, Flags<[CLOption, NoXarchOption]>;
class CLIgnoredFlag<string name> : Option<["/", "-"], name, KIND_FLAG>,
- Group<cl_ignored_Group>, Flags<[CLOption, DriverOption]>;
+ Group<cl_ignored_Group>, Flags<[CLOption, NoXarchOption]>;
class CLJoined<string name> : Option<["/", "-"], name, KIND_JOINED>,
- Group<cl_Group>, Flags<[CLOption, DriverOption]>;
+ Group<cl_Group>, Flags<[CLOption, NoXarchOption]>;
class CLCompileJoined<string name> : Option<["/", "-"], name, KIND_JOINED>,
- Group<cl_compile_Group>, Flags<[CLOption, DriverOption]>;
+ Group<cl_compile_Group>, Flags<[CLOption, NoXarchOption]>;
class CLIgnoredJoined<string name> : Option<["/", "-"], name, KIND_JOINED>,
- Group<cl_ignored_Group>, Flags<[CLOption, DriverOption, HelpHidden]>;
+ Group<cl_ignored_Group>, Flags<[CLOption, NoXarchOption, HelpHidden]>;
class CLJoinedOrSeparate<string name> : Option<["/", "-"], name,
- KIND_JOINED_OR_SEPARATE>, Group<cl_Group>, Flags<[CLOption, DriverOption]>;
+ KIND_JOINED_OR_SEPARATE>, Group<cl_Group>, Flags<[CLOption, NoXarchOption]>;
class CLCompileJoinedOrSeparate<string name> : Option<["/", "-"], name,
KIND_JOINED_OR_SEPARATE>, Group<cl_compile_Group>,
- Flags<[CLOption, DriverOption]>;
+ Flags<[CLOption, NoXarchOption]>;
class CLRemainingArgsJoined<string name> : Option<["/", "-"], name,
- KIND_REMAINING_ARGS_JOINED>, Group<cl_Group>, Flags<[CLOption, DriverOption]>;
+ KIND_REMAINING_ARGS_JOINED>, Group<cl_Group>, Flags<[CLOption, NoXarchOption]>;
// Aliases:
// (We don't put any of these in cl_compile_Group as the options they alias are
@@ -4623,8 +5618,6 @@ def _SLASH_Zc_twoPhase_ : CLFlag<"Zc:twoPhase-">,
Alias<fdelayed_template_parsing>;
def _SLASH_Z7 : CLFlag<"Z7">,
HelpText<"Enable CodeView debug information in object files">;
-def _SLASH_Zd : CLFlag<"Zd">,
- HelpText<"Emit debug line number tables only">;
def _SLASH_Zi : CLFlag<"Zi">, Alias<_SLASH_Z7>,
HelpText<"Like /Z7">;
def _SLASH_Zp : CLJoined<"Zp">,
@@ -4642,6 +5635,9 @@ def _SLASH_openmp : CLFlag<"openmp">, HelpText<"Enable OpenMP support">,
def _SLASH_openmp_experimental : CLFlag<"openmp:experimental">,
HelpText<"Enable OpenMP support with experimental SIMD support">,
Alias<fopenmp>;
+def _SLASH_tune : CLCompileJoined<"tune:">,
+ HelpText<"Set CPU for optimization without affecting instruction set">,
+ Alias<mtune_EQ>;
// Non-aliases:
@@ -4667,6 +5663,7 @@ def _SLASH_FI : CLJoinedOrSeparate<"FI">,
def _SLASH_Fe : CLJoined<"Fe">,
HelpText<"Set output executable file name">,
MetaVarName<"<file or dir/>">;
+def _SLASH_Fe_COLON : CLJoined<"Fe:">, Alias<_SLASH_Fe>;
def _SLASH_Fi : CLCompileJoined<"Fi">,
HelpText<"Set preprocess output file name (with /P)">,
MetaVarName<"<file>">;
@@ -4687,13 +5684,13 @@ def _SLASH_LDd : CLFlag<"LDd">, HelpText<"Create debug DLL">;
def _SLASH_link : CLRemainingArgsJoined<"link">,
HelpText<"Forward options to the linker">, MetaVarName<"<options>">;
def _SLASH_MD : Option<["/", "-"], "MD", KIND_FLAG>, Group<_SLASH_M_Group>,
- Flags<[CLOption, DriverOption]>, HelpText<"Use DLL run-time">;
+ Flags<[CLOption, NoXarchOption]>, HelpText<"Use DLL run-time">;
def _SLASH_MDd : Option<["/", "-"], "MDd", KIND_FLAG>, Group<_SLASH_M_Group>,
- Flags<[CLOption, DriverOption]>, HelpText<"Use DLL debug run-time">;
+ Flags<[CLOption, NoXarchOption]>, HelpText<"Use DLL debug run-time">;
def _SLASH_MT : Option<["/", "-"], "MT", KIND_FLAG>, Group<_SLASH_M_Group>,
- Flags<[CLOption, DriverOption]>, HelpText<"Use static run-time">;
+ Flags<[CLOption, NoXarchOption]>, HelpText<"Use static run-time">;
def _SLASH_MTd : Option<["/", "-"], "MTd", KIND_FLAG>, Group<_SLASH_M_Group>,
- Flags<[CLOption, DriverOption]>, HelpText<"Use static debug run-time">;
+ Flags<[CLOption, NoXarchOption]>, HelpText<"Use static debug run-time">;
def _SLASH_o : CLJoinedOrSeparate<"o">,
HelpText<"Deprecated (set output file name); use /Fe or /Fe">,
MetaVarName<"<file or dir/>">;
@@ -4704,8 +5701,10 @@ def _SLASH_TC : CLCompileFlag<"TC">, HelpText<"Treat all source files as C">;
def _SLASH_Tp : CLCompileJoinedOrSeparate<"Tp">,
HelpText<"Treat <file> as C++ source file">, MetaVarName<"<file>">;
def _SLASH_TP : CLCompileFlag<"TP">, HelpText<"Treat all source files as C++">;
+def _SLASH_vctoolsdir : CLJoinedOrSeparate<"vctoolsdir">,
+ HelpText<"Path to the VCToolChain">, MetaVarName<"<dir>">;
def _SLASH_volatile_iso : Option<["/", "-"], "volatile:iso", KIND_FLAG>,
- Group<_SLASH_volatile_Group>, Flags<[CLOption, DriverOption]>,
+ Group<_SLASH_volatile_Group>, Flags<[CLOption, NoXarchOption]>,
HelpText<"Volatile loads and stores have standard semantics">;
def _SLASH_vmb : CLFlag<"vmb">,
HelpText<"Use a best-case representation method for member pointers">;
@@ -4720,7 +5719,7 @@ def _SLASH_vmv : CLFlag<"vmv">,
HelpText<"Set the default most-general representation to "
"virtual inheritance">;
def _SLASH_volatile_ms : Option<["/", "-"], "volatile:ms", KIND_FLAG>,
- Group<_SLASH_volatile_Group>, Flags<[CLOption, DriverOption]>,
+ Group<_SLASH_volatile_Group>, Flags<[CLOption, NoXarchOption]>,
HelpText<"Volatile loads and stores have acquire and release semantics">;
def _SLASH_clang : CLJoined<"clang:">,
HelpText<"Pass <arg> to the clang driver">, MetaVarName<"<arg>">;
diff --git a/contrib/llvm-project/clang/include/clang/Driver/SanitizerArgs.h b/contrib/llvm-project/clang/include/clang/Driver/SanitizerArgs.h
index 934dab808e82..ac2b817be1dc 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/SanitizerArgs.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/SanitizerArgs.h
@@ -55,13 +55,15 @@ class SanitizerArgs {
bool MinimalRuntime = false;
// True if cross-dso CFI support if provided by the system (i.e. Android).
bool ImplicitCfiRuntime = false;
+ bool NeedsMemProfRt = false;
- public:
+public:
/// Parses the sanitizer arguments from an argument list.
SanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args);
bool needsSharedRt() const { return SharedRuntime; }
+ bool needsMemProfRt() const { return NeedsMemProfRt; }
bool needsAsanRt() const { return Sanitizers.has(SanitizerKind::Address); }
bool needsHwasanRt() const {
return Sanitizers.has(SanitizerKind::HWAddress);
@@ -74,6 +76,7 @@ class SanitizerArgs {
!Sanitizers.has(SanitizerKind::Address) &&
!Sanitizers.has(SanitizerKind::HWAddress);
}
+ bool needsFuzzerInterceptors() const;
bool needsUbsanRt() const;
bool requiresMinimalRuntime() const { return MinimalRuntime; }
bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
diff --git a/contrib/llvm-project/clang/include/clang/Driver/ToolChain.h b/contrib/llvm-project/clang/include/clang/Driver/ToolChain.h
index 7495e08fe6e6..28c37a44e1eb 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/ToolChain.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/ToolChain.h
@@ -27,6 +27,7 @@
#include "llvm/Support/VersionTuple.h"
#include "llvm/Target/TargetOptions.h"
#include <cassert>
+#include <climits>
#include <memory>
#include <string>
#include <utility>
@@ -327,7 +328,14 @@ public:
/// Returns the linker path, respecting the -fuse-ld= argument to determine
/// the linker suffix or name.
- std::string GetLinkerPath() const;
+ /// If LinkerIsLLD is non-nullptr, it is set to true if the returned linker
+ /// is LLD. If it's set, it can be assumed that the linker is LLD built
+ /// at the same revision as clang, and clang can make assumptions about
+ /// LLD's supported flags, error output, etc.
+ /// If LinkerIsLLDDarwinNew is non-nullptr, it's set if the linker is
+ /// the new version in lld/MachO.
+ std::string GetLinkerPath(bool *LinkerIsLLD = nullptr,
+ bool *LinkerIsLLDDarwinNew = nullptr) const;
/// Returns the linker path for emitting a static library.
std::string GetStaticLibToolPath() const;
@@ -382,9 +390,10 @@ public:
virtual bool useRelaxRelocations() const;
/// GetDefaultStackProtectorLevel - Get the default stack protector level for
- /// this tool chain (0=off, 1=on, 2=strong, 3=all).
- virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
- return 0;
+ /// this tool chain.
+ virtual LangOptions::StackProtectorMode
+ GetDefaultStackProtectorLevel(bool KernelOrKext) const {
+ return LangOptions::SSPOff;
}
/// Get the default trivial automatic variable initialization.
@@ -419,10 +428,10 @@ public:
getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
FileType Type = ToolChain::FT_Static) const;
- std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
- StringRef Component,
- FileType Type = ToolChain::FT_Static,
- bool AddArch = true) const;
+ virtual std::string
+ getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component,
+ FileType Type = ToolChain::FT_Static,
+ bool AddArch = true) const;
// Returns target specific runtime path if it exists.
virtual Optional<std::string> getRuntimePath() const;
@@ -435,7 +444,7 @@ public:
std::string getArchSpecificLibPath() const;
// Returns <OSname> part of above.
- StringRef getOSLibName() const;
+ virtual StringRef getOSLibName() const;
/// needsProfileRT - returns true if instrumentation profile is on.
static bool needsProfileRT(const llvm::opt::ArgList &Args);
@@ -481,6 +490,11 @@ public:
// to the contrary.
virtual unsigned GetDefaultDwarfVersion() const { return 4; }
+ // Some toolchains may have different restrictions on the DWARF version and
+ // may need to adjust it. E.g. NVPTX may need to enforce DWARF2 even when host
+ // compilation uses DWARF5.
+ virtual unsigned getMaxDwarfVersion() const { return UINT_MAX; }
+
// True if the driver should assume "-fstandalone-debug"
// in the absence of an option specifying otherwise,
// provided that debugging was requested in the first place.
diff --git a/contrib/llvm-project/clang/include/clang/Driver/XRayArgs.h b/contrib/llvm-project/clang/include/clang/Driver/XRayArgs.h
index 2f055e5c6d7d..6ed99a127669 100644
--- a/contrib/llvm-project/clang/include/clang/Driver/XRayArgs.h
+++ b/contrib/llvm-project/clang/include/clang/Driver/XRayArgs.h
@@ -32,6 +32,8 @@ class XRayArgs {
bool XRayRT = true;
bool XRayIgnoreLoops = false;
bool XRayFunctionIndex;
+ int XRayFunctionGroups = 1;
+ int XRaySelectedFunctionGroup = 0;
public:
/// Parses the XRay arguments from an argument list.
diff --git a/contrib/llvm-project/clang/include/clang/Edit/EditedSource.h b/contrib/llvm-project/clang/include/clang/Edit/EditedSource.h
index 60072f6758b1..ab76b0d719b0 100644
--- a/contrib/llvm-project/clang/include/clang/Edit/EditedSource.h
+++ b/contrib/llvm-project/clang/include/clang/Edit/EditedSource.h
@@ -62,7 +62,7 @@ class EditedSource {
}
};
- llvm::DenseMap<unsigned, SmallVector<MacroArgUse, 2>> ExpansionToArgMap;
+ llvm::DenseMap<SourceLocation, SmallVector<MacroArgUse, 2>> ExpansionToArgMap;
SmallVector<std::pair<SourceLocation, MacroArgUse>, 2>
CurrCommitMacroArgExps;
diff --git a/contrib/llvm-project/clang/include/clang/Format/Format.h b/contrib/llvm-project/clang/include/clang/Format/Format.h
index 3549ec9eee0e..96c2a74e97db 100755
--- a/contrib/llvm-project/clang/include/clang/Format/Format.h
+++ b/contrib/llvm-project/clang/include/clang/Format/Format.h
@@ -56,7 +56,7 @@ struct FormatStyle {
int AccessModifierOffset;
/// Different styles for aligning after open brackets.
- enum BracketAlignmentStyle {
+ enum BracketAlignmentStyle : unsigned char {
/// Align parameters on the open bracket, e.g.:
/// \code
/// someLongFunction(argument1,
@@ -84,10 +84,23 @@ struct FormatStyle {
/// brackets.
BracketAlignmentStyle AlignAfterOpenBracket;
- /// \brief If ``true``, aligns consecutive C/C++ preprocessor macros.
+ /// Styles for alignment of consecutive tokens. Tokens can be assignment signs
+ /// (see
+ /// ``AlignConsecutiveAssignments``), bitfield member separators (see
+ /// ``AlignConsecutiveBitFields``), names in declarations (see
+ /// ``AlignConsecutiveDeclarations``) or macro definitions (see
+ /// ``AlignConsecutiveMacros``).
+ enum AlignConsecutiveStyle {
+ ACS_None,
+ ACS_Consecutive,
+ ACS_AcrossEmptyLines,
+ ACS_AcrossComments,
+ ACS_AcrossEmptyLinesAndComments
+ };
+
+ /// Style of aligning consecutive macro definitions.
///
- /// This will align C/C++ preprocessor macros of consecutive lines.
- /// Will result in formattings like
+ /// ``Consecutive`` will result in formattings like:
/// \code
/// #define SHORT_NAME 42
/// #define LONGER_NAME 0x007f
@@ -95,43 +108,274 @@ struct FormatStyle {
/// #define foo(x) (x * x)
/// #define bar(y, z) (y + z)
/// \endcode
- bool AlignConsecutiveMacros;
-
- /// If ``true``, aligns consecutive assignments.
///
- /// This will align the assignment operators of consecutive lines. This
- /// will result in formattings like
+ /// Possible values:
+ ///
+ /// * ``ACS_None`` (in configuration: ``None``)
+ /// Do not align macro definitions on consecutive lines.
+ ///
+ /// * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ /// Align macro definitions on consecutive lines. This will result in
+ /// formattings like:
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ ///
+ /// #define foo(x) (x * x)
+ /// /* some comment */
+ /// #define bar(y, z) (y + z)
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ /// Same as ACS_Consecutive, but also spans over empty lines, e.g.
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ ///
+ /// #define foo(x) (x * x)
+ /// /* some comment */
+ /// #define bar(y, z) (y + z)
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments, e.g.
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ ///
+ /// #define foo(x) (x * x)
+ /// /* some comment */
+ /// #define bar(y, z) (y + z)
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLinesAndComments``
+ /// (in configuration: ``AcrossEmptyLinesAndComments``)
+ ///
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments and empty lines, e.g.
+ /// \code
+ /// #define SHORT_NAME 42
+ /// #define LONGER_NAME 0x007f
+ /// #define EVEN_LONGER_NAME (2)
+ ///
+ /// #define foo(x) (x * x)
+ /// /* some comment */
+ /// #define bar(y, z) (y + z)
+ /// \endcode
+ AlignConsecutiveStyle AlignConsecutiveMacros;
+
+ /// Style of aligning consecutive assignments.
+ ///
+ /// ``Consecutive`` will result in formattings like:
/// \code
- /// int aaaa = 12;
- /// int b = 23;
- /// int ccc = 23;
- /// \endcode
- bool AlignConsecutiveAssignments;
-
- /// If ``true``, aligns consecutive bitfield members.
- ///
- /// This will align the bitfield separators of consecutive lines. This
- /// will result in formattings like
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ /// \endcode
+ ///
+ /// Possible values:
+ ///
+ /// * ``ACS_None`` (in configuration: ``None``)
+ /// Do not align assignments on consecutive lines.
+ ///
+ /// * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ /// Align assignments on consecutive lines. This will result in
+ /// formattings like:
+ /// \code
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ /// Same as ACS_Consecutive, but also spans over empty lines, e.g.
+ /// \code
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments, e.g.
+ /// \code
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLinesAndComments``
+ /// (in configuration: ``AcrossEmptyLinesAndComments``)
+ ///
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments and empty lines, e.g.
+ /// \code
+ /// int a = 1;
+ /// int somelongname = 2;
+ /// double c = 3;
+ ///
+ /// int d = 3;
+ /// /* A comment. */
+ /// double e = 4;
+ /// \endcode
+ AlignConsecutiveStyle AlignConsecutiveAssignments;
+
+ /// Style of aligning consecutive bit field.
+ ///
+ /// ``Consecutive`` will align the bitfield separators of consecutive lines.
+ /// This will result in formattings like:
/// \code
/// int aaaa : 1;
/// int b : 12;
/// int ccc : 8;
/// \endcode
- bool AlignConsecutiveBitFields;
-
- /// If ``true``, aligns consecutive declarations.
///
- /// This will align the declaration names of consecutive lines. This
- /// will result in formattings like
+ /// Possible values:
+ ///
+ /// * ``ACS_None`` (in configuration: ``None``)
+ /// Do not align bit fields on consecutive lines.
+ ///
+ /// * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ /// Align bit fields on consecutive lines. This will result in
+ /// formattings like:
+ /// \code
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ ///
+ /// int d : 2;
+ /// /* A comment. */
+ /// int ee : 3;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ /// Same as ACS_Consecutive, but also spans over empty lines, e.g.
+ /// \code
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ ///
+ /// int d : 2;
+ /// /* A comment. */
+ /// int ee : 3;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments, e.g.
+ /// \code
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ ///
+ /// int d : 2;
+ /// /* A comment. */
+ /// int ee : 3;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLinesAndComments``
+ /// (in configuration: ``AcrossEmptyLinesAndComments``)
+ ///
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments and empty lines, e.g.
+ /// \code
+ /// int aaaa : 1;
+ /// int b : 12;
+ /// int ccc : 8;
+ ///
+ /// int d : 2;
+ /// /* A comment. */
+ /// int ee : 3;
+ /// \endcode
+ AlignConsecutiveStyle AlignConsecutiveBitFields;
+
+ /// Style of aligning consecutive declarations.
+ ///
+ /// ``Consecutive`` will align the declaration names of consecutive lines.
+ /// This will result in formattings like:
/// \code
/// int aaaa = 12;
/// float b = 23;
- /// std::string ccc = 23;
- /// \endcode
- bool AlignConsecutiveDeclarations;
+ /// std::string ccc;
+ /// \endcode
+ ///
+ /// Possible values:
+ ///
+ /// * ``ACS_None`` (in configuration: ``None``)
+ /// Do not align bit declarations on consecutive lines.
+ ///
+ /// * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ /// Align declarations on consecutive lines. This will result in
+ /// formattings like:
+ /// \code
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ ///
+ /// int a = 42;
+ /// /* A comment. */
+ /// bool c = false;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ /// Same as ACS_Consecutive, but also spans over empty lines, e.g.
+ /// \code
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ ///
+ /// int a = 42;
+ /// /* A comment. */
+ /// bool c = false;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments, e.g.
+ /// \code
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ ///
+ /// int a = 42;
+ /// /* A comment. */
+ /// bool c = false;
+ /// \endcode
+ ///
+ /// * ``ACS_AcrossEmptyLinesAndComments``
+ /// (in configuration: ``AcrossEmptyLinesAndComments``)
+ ///
+ /// Same as ACS_Consecutive, but also spans over lines only containing
+ /// comments and empty lines, e.g.
+ /// \code
+ /// int aaaa = 12;
+ /// float b = 23;
+ /// std::string ccc;
+ ///
+ /// int a = 42;
+ /// /* A comment. */
+ /// bool c = false;
+ /// \endcode
+ AlignConsecutiveStyle AlignConsecutiveDeclarations;
/// Different styles for aligning escaped newlines.
- enum EscapedNewlineAlignmentStyle {
+ enum EscapedNewlineAlignmentStyle : unsigned char {
/// Don't align escaped newlines.
/// \code
/// #define A \
@@ -165,7 +409,7 @@ struct FormatStyle {
EscapedNewlineAlignmentStyle AlignEscapedNewlines;
/// Different styles for aligning operands.
- enum OperandAlignmentStyle {
+ enum OperandAlignmentStyle : unsigned char {
/// Do not align operands of binary and ternary expressions.
/// The wrapped lines are indented ``ContinuationIndentWidth`` spaces from
/// the start of the line.
@@ -275,7 +519,7 @@ struct FormatStyle {
/// Different styles for merging short blocks containing at most one
/// statement.
- enum ShortBlockStyle {
+ enum ShortBlockStyle : unsigned char {
/// Never merge blocks into a single line.
/// \code
/// while (true) {
@@ -320,7 +564,7 @@ struct FormatStyle {
/// Different styles for merging short functions containing at most one
/// statement.
- enum ShortFunctionStyle {
+ enum ShortFunctionStyle : unsigned char {
/// Never merge functions into a single line.
SFS_None,
/// Only merge functions defined inside a class. Same as "inline",
@@ -371,7 +615,7 @@ struct FormatStyle {
ShortFunctionStyle AllowShortFunctionsOnASingleLine;
/// Different styles for handling short if lines
- enum ShortIfStyle {
+ enum ShortIfStyle : unsigned char {
/// Never put short ifs on the same line.
/// \code
/// if (a)
@@ -405,7 +649,7 @@ struct FormatStyle {
/// Different styles for merging short lambdas containing at most one
/// statement.
- enum ShortLambdaStyle {
+ enum ShortLambdaStyle : unsigned char {
/// Never merge lambdas into a single line.
SLS_None,
/// Only merge empty lambdas.
@@ -442,7 +686,7 @@ struct FormatStyle {
/// Different ways to break after the function definition return type.
/// This option is **deprecated** and is retained for backwards compatibility.
- enum DefinitionReturnTypeBreakingStyle {
+ enum DefinitionReturnTypeBreakingStyle : unsigned char {
/// Break after return type automatically.
/// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
DRTBS_None,
@@ -454,7 +698,7 @@ struct FormatStyle {
/// Different ways to break after the function definition or
/// declaration return type.
- enum ReturnTypeBreakingStyle {
+ enum ReturnTypeBreakingStyle : unsigned char {
/// Break after return type automatically.
/// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
/// \code
@@ -545,7 +789,7 @@ struct FormatStyle {
bool AlwaysBreakBeforeMultilineStrings;
/// Different ways to break after the template declaration.
- enum BreakTemplateDeclarationsStyle {
+ enum BreakTemplateDeclarationsStyle : unsigned char {
/// Do not force break before declaration.
/// ``PenaltyBreakTemplateDeclaration`` is taken into account.
/// \code
@@ -583,6 +827,24 @@ struct FormatStyle {
/// The template declaration breaking style to use.
BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
+ /// A vector of strings that should be interpreted as attributes/qualifiers
+ /// instead of identifiers. This can be useful for language extensions or
+ /// static analyzer annotations.
+ ///
+ /// For example:
+ /// \code
+ /// x = (char *__capability)&y;
+ /// int function(void) __ununsed;
+ /// void only_writes_to_buffer(char *__output buffer);
+ /// \endcode
+ ///
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// AttributeMacros: ['__capability', '__output', '__ununsed']
+ /// \endcode
+ ///
+ std::vector<std::string> AttributeMacros;
+
/// If ``false``, a function call's arguments will either be all on the
/// same line or will have one line each.
/// \code
@@ -602,7 +864,7 @@ struct FormatStyle {
bool BinPackArguments;
/// The style of inserting trailing commas into container literals.
- enum TrailingCommaStyle {
+ enum TrailingCommaStyle : unsigned char {
/// Do not insert trailing commas.
TCS_None,
/// Insert trailing commas in container literals that were wrapped over
@@ -646,7 +908,7 @@ struct FormatStyle {
/// The style of wrapping parameters on the same line (bin-packed) or
/// on one line each.
- enum BinPackStyle {
+ enum BinPackStyle : unsigned char {
/// Automatically determine parameter bin-packing behavior.
BPS_Auto,
/// Always bin-pack parameters.
@@ -656,7 +918,7 @@ struct FormatStyle {
};
/// The style of breaking before or after binary operators.
- enum BinaryOperatorStyle {
+ enum BinaryOperatorStyle : unsigned char {
/// Break after operators.
/// \code
/// LooooooooooongType loooooooooooooooooooooongVariable =
@@ -699,166 +961,430 @@ struct FormatStyle {
BinaryOperatorStyle BreakBeforeBinaryOperators;
/// Different ways to attach braces to their surrounding context.
- enum BraceBreakingStyle {
+ enum BraceBreakingStyle : unsigned char {
/// Always attach braces to surrounding context.
/// \code
- /// try {
- /// foo();
- /// } catch () {
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i) {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
/// }
- /// void foo() { bar(); }
- /// class foo {};
- /// if (foo()) {
- /// } else {
+ ///
+ /// void foo(bool b) {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int { A, B };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Attach,
/// Like ``Attach``, but break before braces on function, namespace and
/// class definitions.
/// \code
- /// try {
- /// foo();
- /// } catch () {
- /// }
- /// void foo() { bar(); }
- /// class foo
+ /// namespace N
/// {
+ /// enum E {
+ /// E1,
+ /// E2,
/// };
- /// if (foo()) {
- /// } else {
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int { A, B };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Linux,
/// Like ``Attach``, but break before braces on enum, function, and record
/// definitions.
/// \code
- /// try {
- /// foo();
- /// } catch () {
- /// }
- /// void foo() { bar(); }
- /// class foo
+ /// namespace N {
+ /// enum E
/// {
+ /// E1,
+ /// E2,
/// };
- /// if (foo()) {
- /// } else {
+ ///
+ /// class C
+ /// {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int { A, B };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Mozilla,
/// Like ``Attach``, but break before function definitions, ``catch``, and
/// ``else``.
/// \code
- /// try {
- /// foo();
- /// }
- /// catch () {
- /// }
- /// void foo() { bar(); }
- /// class foo {
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
/// };
- /// if (foo()) {
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
/// }
- /// else {
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// }
+ /// else {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int { A, B };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Stroustrup,
/// Always break before braces.
/// \code
- /// try
+ /// namespace N
/// {
- /// foo();
- /// }
- /// catch ()
+ /// enum E
/// {
- /// }
- /// void foo() { bar(); }
- /// class foo
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
/// {
+ /// public:
+ /// C();
/// };
- /// if (foo())
+ ///
+ /// bool baz(int i)
/// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
/// }
- /// else
+ ///
+ /// void foo(bool b)
/// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int
- /// {
- /// A,
- /// B
- /// };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Allman,
/// Like ``Allman`` but always indent braces and line up code with braces.
/// \code
- /// try
+ /// namespace N
/// {
- /// foo();
- /// }
- /// catch ()
+ /// enum E
/// {
- /// }
- /// void foo() { bar(); }
- /// class foo
+ /// E1,
+ /// E2,
+ /// };
+ ///
+ /// class C
/// {
+ /// public:
+ /// C();
/// };
- /// if (foo())
+ ///
+ /// bool baz(int i)
/// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
/// }
- /// else
+ ///
+ /// void foo(bool b)
/// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
/// }
- /// enum X : int
- /// {
- /// A,
- /// B
- /// };
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_Whitesmiths,
/// Always break before braces and add an extra level of indentation to
/// braces of control statements, not to those of class, function
/// or other definitions.
/// \code
- /// try
- /// {
- /// foo();
- /// }
- /// catch ()
- /// {
- /// }
- /// void foo() { bar(); }
- /// class foo
+ /// namespace N
+ /// {
+ /// enum E
/// {
+ /// E1,
+ /// E2,
/// };
- /// if (foo())
- /// {
- /// }
- /// else
- /// {
- /// }
- /// enum X : int
+ ///
+ /// class C
/// {
- /// A,
- /// B
+ /// public:
+ /// C();
/// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try
+ /// {
+ /// do
+ /// {
+ /// switch (i)
+ /// {
+ /// case 1:
+ /// {
+ /// foobar();
+ /// break;
+ /// }
+ /// default:
+ /// {
+ /// break;
+ /// }
+ /// }
+ /// }
+ /// while (--i);
+ /// return true;
+ /// }
+ /// catch (...)
+ /// {
+ /// handleError();
+ /// return false;
+ /// }
+ /// }
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b)
+ /// {
+ /// baz(2);
+ /// }
+ /// else
+ /// {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_GNU,
/// Like ``Attach``, but break before functions.
/// \code
- /// try {
- /// foo();
- /// } catch () {
- /// }
- /// void foo() { bar(); }
- /// class foo {
+ /// namespace N {
+ /// enum E {
+ /// E1,
+ /// E2,
/// };
- /// if (foo()) {
- /// } else {
+ ///
+ /// class C {
+ /// public:
+ /// C();
+ /// };
+ ///
+ /// bool baz(int i)
+ /// {
+ /// try {
+ /// do {
+ /// switch (i) {
+ /// case 1: {
+ /// foobar();
+ /// break;
+ /// }
+ /// default: {
+ /// break;
+ /// }
+ /// }
+ /// } while (--i);
+ /// return true;
+ /// } catch (...) {
+ /// handleError();
+ /// return false;
+ /// }
/// }
- /// enum X : int { A, B };
+ ///
+ /// void foo(bool b)
+ /// {
+ /// if (b) {
+ /// baz(2);
+ /// } else {
+ /// baz(5);
+ /// }
+ /// }
+ ///
+ /// void bar() { foo(true); }
+ /// } // namespace N
/// \endcode
BS_WebKit,
/// Configure each individual brace in `BraceWrapping`.
@@ -869,7 +1395,7 @@ struct FormatStyle {
BraceBreakingStyle BreakBeforeBraces;
/// Different ways to wrap braces after control statements.
- enum BraceWrappingAfterControlStatementStyle {
+ enum BraceWrappingAfterControlStatementStyle : unsigned char {
/// Never wrap braces after a control statement.
/// \code
/// if (foo()) {
@@ -1142,6 +1668,17 @@ struct FormatStyle {
/// \endcode
BraceWrappingFlags BraceWrapping;
+ /// If ``true``, concept will be placed on a new line.
+ /// \code
+ /// true:
+ /// template<typename T>
+ /// concept ...
+ ///
+ /// false:
+ /// template<typename T> concept ...
+ /// \endcode
+ bool BreakBeforeConceptDeclarations;
+
/// If ``true``, ternary operators will be placed after line breaks.
/// \code
/// true:
@@ -1157,7 +1694,7 @@ struct FormatStyle {
bool BreakBeforeTernaryOperators;
/// Different ways to break initializers.
- enum BreakConstructorInitializersStyle {
+ enum BreakConstructorInitializersStyle : unsigned char {
/// Break constructor initializers before the colon and after the commas.
/// \code
/// Constructor()
@@ -1224,7 +1761,7 @@ struct FormatStyle {
std::string CommentPragmas;
/// Different ways to break inheritance list.
- enum BreakInheritanceListStyle {
+ enum BreakInheritanceListStyle : unsigned char {
/// Break inheritance list before the colon and after the commas.
/// \code
/// class Foo
@@ -1348,6 +1885,68 @@ struct FormatStyle {
/// Disables formatting completely.
bool DisableFormat;
+ /// Different styles for empty line before access modifiers.
+ enum EmptyLineBeforeAccessModifierStyle : unsigned char {
+ /// Remove all empty lines before access modifiers.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ /// protected:
+ /// int j;
+ /// /* comment */
+ /// public:
+ /// foo() {}
+ /// private:
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_Never,
+ /// Keep existing empty lines before access modifiers.
+ ELBAMS_Leave,
+ /// Add empty line only when access modifier starts a new logical block.
+ /// Logical block is a group of one or more member fields or functions.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ ///
+ /// protected:
+ /// int j;
+ /// /* comment */
+ /// public:
+ /// foo() {}
+ ///
+ /// private:
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_LogicalBlock,
+ /// Always add empty line before access modifiers unless access modifier
+ /// is at the start of struct or class definition.
+ /// \code
+ /// struct foo {
+ /// private:
+ /// int i;
+ ///
+ /// protected:
+ /// int j;
+ /// /* comment */
+ ///
+ /// public:
+ /// foo() {}
+ ///
+ /// private:
+ ///
+ /// protected:
+ /// };
+ /// \endcode
+ ELBAMS_Always,
+ };
+
+ /// Defines in which cases to put empty line before access modifiers.
+ EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
+
/// If ``true``, clang-format detects whether function calls and
/// definitions are formatted with one parameter per line.
///
@@ -1425,15 +2024,20 @@ struct FormatStyle {
/// For example: TESTSUITE
std::vector<std::string> NamespaceMacros;
- /// A vector of macros which are whitespace-sensitive and shouldn't be
- /// touched.
+ /// A vector of macros which are whitespace-sensitive and should not
+ /// be touched.
///
/// These are expected to be macros of the form:
/// \code
/// STRINGIZE(...)
/// \endcode
///
- /// For example: STRINGIZE
+ /// In the .clang-format configuration file, this can be configured like:
+ /// \code{.yaml}
+ /// WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
+ /// \endcode
+ ///
+ /// For example: BOOST_PP_STRINGIZE
std::vector<std::string> WhitespaceSensitiveMacros;
tooling::IncludeStyle IncludeStyle;
@@ -1495,7 +2099,7 @@ struct FormatStyle {
bool IndentGotoLabels;
/// Options for indenting preprocessor directives.
- enum PPDirectiveIndentStyle {
+ enum PPDirectiveIndentStyle : unsigned char {
/// Does not indent any directives.
/// \code
/// #if FOO
@@ -1529,7 +2133,7 @@ struct FormatStyle {
PPDirectiveIndentStyle IndentPPDirectives;
/// Indents extern blocks
- enum IndentExternBlockStyle {
+ enum IndentExternBlockStyle : unsigned char {
/// Backwards compatible with AfterExternBlock's indenting.
/// \code
/// IndentExternBlock: AfterExternBlock
@@ -1567,6 +2171,24 @@ struct FormatStyle {
/// IndentExternBlockStyle is the type of indenting of extern blocks.
IndentExternBlockStyle IndentExternBlock;
+ /// Indent the requires clause in a template
+ /// \code
+ /// true:
+ /// template <typename It>
+ /// requires Iterator<It>
+ /// void sort(It begin, It end) {
+ /// //....
+ /// }
+ ///
+ /// false:
+ /// template <typename It>
+ /// requires Iterator<It>
+ /// void sort(It begin, It end) {
+ /// //....
+ /// }
+ /// \endcode
+ bool IndentRequires;
+
/// The number of columns to use for indentation.
/// \code
/// IndentWidth: 3
@@ -1595,10 +2217,12 @@ struct FormatStyle {
/// A vector of prefixes ordered by the desired groups for Java imports.
///
- /// Each group is separated by a newline. Static imports will also follow the
- /// same grouping convention above all non-static imports. One group's prefix
- /// can be a subset of another - the longest prefix is always matched. Within
- /// a group, the imports are ordered lexicographically.
+ /// One group's prefix can be a subset of another - the longest prefix is
+ /// always matched. Within a group, the imports are ordered lexicographically.
+ /// Static imports are grouped separately and follow the same group rules.
+ /// By default, static imports are placed before non-static imports,
+ /// but this behavior is changed by another option,
+ /// ``SortJavaStaticImport``.
///
/// In the .clang-format configuration file, this can be configured like
/// in the following yaml example. This will result in imports being
@@ -1626,7 +2250,7 @@ struct FormatStyle {
/// Quotation styles for JavaScript strings. Does not affect template
/// strings.
- enum JavaScriptQuoteStyle {
+ enum JavaScriptQuoteStyle : unsigned char {
/// Leave string quotes as they are.
/// \code{.js}
/// string1 = "foo";
@@ -1681,7 +2305,7 @@ struct FormatStyle {
/// When stored in a configuration file, specifies the language, that the
/// configuration targets. When passed to the ``reformat()`` function, enables
/// syntax features specific to the language.
- enum LanguageKind {
+ enum LanguageKind : unsigned char {
/// Do not use.
LK_None,
/// Should be used for C, C++.
@@ -1754,7 +2378,7 @@ struct FormatStyle {
unsigned MaxEmptyLinesToKeep;
/// Different ways to indent namespace contents.
- enum NamespaceIndentationKind {
+ enum NamespaceIndentationKind : unsigned char {
/// Don't indent in namespaces.
/// \code
/// namespace out {
@@ -1837,7 +2461,7 @@ struct FormatStyle {
bool ObjCSpaceAfterProperty;
/// Break parameters list into lines when there is nested block
- /// parameters in a fuction call.
+ /// parameters in a function call.
/// \code
/// false:
/// - (void)_aMethod
@@ -1888,8 +2512,12 @@ struct FormatStyle {
/// line.
unsigned PenaltyReturnTypeOnItsOwnLine;
+ /// Penalty for each character of whitespace indentation
+ /// (counted relative to leading non-whitespace column).
+ unsigned PenaltyIndentedWhitespace;
+
/// The ``&`` and ``*`` alignment style.
- enum PointerAlignmentStyle {
+ enum PointerAlignmentStyle : unsigned char {
/// Align pointer to the left.
/// \code
/// int* a;
@@ -1993,6 +2621,29 @@ struct FormatStyle {
/// \endcode
bool SortIncludes;
+ /// Position for Java Static imports.
+ enum SortJavaStaticImportOptions : unsigned char {
+ /// Static imports are placed before non-static imports.
+ /// \code{.java}
+ /// import static org.example.function1;
+ ///
+ /// import org.example.ClassA;
+ /// \endcode
+ SJSIO_Before,
+ /// Static imports are placed after non-static imports.
+ /// \code{.java}
+ /// import org.example.ClassA;
+ ///
+ /// import static org.example.function1;
+ /// \endcode
+ SJSIO_After,
+ };
+
+ /// When sorting Java imports, by default static imports are placed before
+ /// non-static imports. If ``JavaStaticImportAfterImport`` is ``After``,
+ /// static imports are placed after non-static imports.
+ SortJavaStaticImportOptions SortJavaStaticImport;
+
/// If ``true``, clang-format will sort using declarations.
///
/// The order of using declarations is defined as follows:
@@ -2030,6 +2681,38 @@ struct FormatStyle {
/// \endcode
bool SpaceAfterTemplateKeyword;
+ /// Different ways to put a space before opening parentheses.
+ enum SpaceAroundPointerQualifiersStyle : unsigned char {
+ /// Don't ensure spaces around pointer qualifiers and use PointerAlignment
+ /// instead.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const* x = NULL; vs. void *const *x = NULL;
+ /// \endcode
+ SAPQ_Default,
+ /// Ensure that there is a space before pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const* x = NULL; vs. void * const *x = NULL;
+ /// \endcode
+ SAPQ_Before,
+ /// Ensure that there is a space after pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const * x = NULL; vs. void *const *x = NULL;
+ /// \endcode
+ SAPQ_After,
+ /// Ensure that there is a space both before and after pointer qualifiers.
+ /// \code
+ /// PointerAlignment: Left PointerAlignment: Right
+ /// void* const * x = NULL; vs. void * const *x = NULL;
+ /// \endcode
+ SAPQ_Both,
+ };
+
+ /// Defines in which cases to put a space before or after pointer qualifiers
+ SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers;
+
/// If ``false``, spaces will be removed before assignment operators.
/// \code
/// true: false:
@@ -2038,6 +2721,15 @@ struct FormatStyle {
/// \endcode
bool SpaceBeforeAssignmentOperators;
+ /// If ``false``, spaces will be removed before case colon.
+ /// \code
+ /// true: false
+ /// switch (x) { vs. switch (x) {
+ /// case 1 : break; case 1: break;
+ /// } }
+ /// \endcode
+ bool SpaceBeforeCaseColon;
+
/// If ``true``, a space will be inserted before a C++11 braced list
/// used to initialize an object (after the preceding identifier or type).
/// \code
@@ -2065,7 +2757,7 @@ struct FormatStyle {
bool SpaceBeforeInheritanceColon;
/// Different ways to put a space before opening parentheses.
- enum SpaceBeforeParensOptions {
+ enum SpaceBeforeParensOptions : unsigned char {
/// Never put a space before opening parentheses.
/// \code
/// void f() {
@@ -2228,6 +2920,34 @@ struct FormatStyle {
/// \endcode
bool SpaceBeforeSquareBrackets;
+ /// Styles for adding spacing around ``:`` in bitfield definitions.
+ enum BitFieldColonSpacingStyle : unsigned char {
+ /// Add one space on each side of the ``:``
+ /// \code
+ /// unsigned bf : 2;
+ /// \endcode
+ BFCS_Both,
+ /// Add no space around the ``:`` (except when needed for
+ /// ``AlignConsecutiveBitFields``).
+ /// \code
+ /// unsigned bf:2;
+ /// \endcode
+ BFCS_None,
+ /// Add space before the ``:`` only
+ /// \code
+ /// unsigned bf :2;
+ /// \endcode
+ BFCS_Before,
+ /// Add space after the ``:`` only (space may be added before if
+ /// needed for ``AlignConsecutiveBitFields``).
+ /// \code
+ /// unsigned bf: 2;
+ /// \endcode
+ BFCS_After
+ };
+ /// The BitFieldColonSpacingStyle to use for bitfields.
+ BitFieldColonSpacingStyle BitFieldColonSpacing;
+
/// Supported language standards for parsing and formatting C++ constructs.
/// \code
/// Latest: vector<set<int>>
@@ -2236,7 +2956,7 @@ struct FormatStyle {
///
/// The correct way to spell a specific language version is e.g. ``c++11``.
/// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
- enum LanguageStandard {
+ enum LanguageStandard : unsigned char {
/// Parse and format as C++03.
/// ``Cpp03`` is a deprecated alias for ``c++03``
LS_Cpp03, // c++03
@@ -2262,11 +2982,27 @@ struct FormatStyle {
/// \endcode
LanguageStandard Standard;
+ /// Macros which are ignored in front of a statement, as if they were an
+ /// attribute. So that they are not parsed as identifier, for example for Qts
+ /// emit.
+ /// \code
+ /// AlignConsecutiveDeclarations: true
+ /// StatementAttributeLikeMacros: []
+ /// unsigned char data = 'x';
+ /// emit signal(data); // This is parsed as variable declaration.
+ ///
+ /// AlignConsecutiveDeclarations: true
+ /// StatementAttributeLikeMacros: [emit]
+ /// unsigned char data = 'x';
+ /// emit signal(data); // Now it's fine again.
+ /// \endcode
+ std::vector<std::string> StatementAttributeLikeMacros;
+
/// The number of columns used for tab stops.
unsigned TabWidth;
/// Different ways to use tab in formatting.
- enum UseTabStyle {
+ enum UseTabStyle : unsigned char {
/// Never use tab.
UT_Never,
/// Use tabs only for indentation.
@@ -2295,6 +3031,7 @@ struct FormatStyle {
AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
AlignConsecutiveBitFields == R.AlignConsecutiveBitFields &&
AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
+ AlignConsecutiveMacros == R.AlignConsecutiveMacros &&
AlignEscapedNewlines == R.AlignEscapedNewlines &&
AlignOperands == R.AlignOperands &&
AlignTrailingComments == R.AlignTrailingComments &&
@@ -2318,10 +3055,12 @@ struct FormatStyle {
R.AlwaysBreakBeforeMultilineStrings &&
AlwaysBreakTemplateDeclarations ==
R.AlwaysBreakTemplateDeclarations &&
+ AttributeMacros == R.AttributeMacros &&
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
BreakBeforeBraces == R.BreakBeforeBraces &&
+ BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations &&
BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
BreakConstructorInitializers == R.BreakConstructorInitializers &&
CompactNamespaces == R.CompactNamespaces &&
@@ -2338,6 +3077,7 @@ struct FormatStyle {
DeriveLineEnding == R.DeriveLineEnding &&
DerivePointerAlignment == R.DerivePointerAlignment &&
DisableFormat == R.DisableFormat &&
+ EmptyLineBeforeAccessModifier == R.EmptyLineBeforeAccessModifier &&
ExperimentalAutoDetectBinPacking ==
R.ExperimentalAutoDetectBinPacking &&
FixNamespaceComments == R.FixNamespaceComments &&
@@ -2353,7 +3093,8 @@ struct FormatStyle {
IndentGotoLabels == R.IndentGotoLabels &&
IndentPPDirectives == R.IndentPPDirectives &&
IndentExternBlock == R.IndentExternBlock &&
- IndentWidth == R.IndentWidth && Language == R.Language &&
+ IndentRequires == R.IndentRequires && IndentWidth == R.IndentWidth &&
+ Language == R.Language &&
IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
JavaImportGroups == R.JavaImportGroups &&
JavaScriptQuotes == R.JavaScriptQuotes &&
@@ -2383,15 +3124,18 @@ struct FormatStyle {
R.PenaltyBreakTemplateDeclaration &&
PointerAlignment == R.PointerAlignment &&
RawStringFormats == R.RawStringFormats &&
+ SortJavaStaticImport == R.SortJavaStaticImport &&
SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
+ SpaceBeforeCaseColon == R.SpaceBeforeCaseColon &&
SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
SpaceBeforeCtorInitializerColon ==
R.SpaceBeforeCtorInitializerColon &&
SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
SpaceBeforeParens == R.SpaceBeforeParens &&
+ SpaceAroundPointerQualifiers == R.SpaceAroundPointerQualifiers &&
SpaceBeforeRangeBasedForLoopColon ==
R.SpaceBeforeRangeBasedForLoopColon &&
SpaceInEmptyBlock == R.SpaceInEmptyBlock &&
@@ -2404,9 +3148,12 @@ struct FormatStyle {
SpacesInParentheses == R.SpacesInParentheses &&
SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
- Standard == R.Standard && TabWidth == R.TabWidth &&
- StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
- UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;
+ BitFieldColonSpacing == R.BitFieldColonSpacing &&
+ Standard == R.Standard &&
+ StatementAttributeLikeMacros == R.StatementAttributeLikeMacros &&
+ StatementMacros == R.StatementMacros && TabWidth == R.TabWidth &&
+ UseTab == R.UseTab && UseCRLF == R.UseCRLF &&
+ TypenameMacros == R.TypenameMacros;
}
llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
@@ -2444,7 +3191,9 @@ struct FormatStyle {
private:
FormatStyleSet StyleSet;
- friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
+ friend std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
+ FormatStyle *Style,
+ bool AllowUnknownOptions);
};
/// Returns a format style complying with the LLVM coding standards:
@@ -2499,7 +3248,19 @@ bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
///
/// When ``BasedOnStyle`` is not present, options not present in the YAML
/// document, are retained in \p Style.
-std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
+///
+/// If AllowUnknownOptions is true, no errors are emitted if unknown
+/// format options are occured.
+std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
+ FormatStyle *Style,
+ bool AllowUnknownOptions = false);
+
+/// Like above but accepts an unnamed buffer.
+inline std::error_code parseConfiguration(StringRef Config, FormatStyle *Style,
+ bool AllowUnknownOptions = false) {
+ return parseConfiguration(llvm::MemoryBufferRef(Config, "YAML"), Style,
+ AllowUnknownOptions);
+}
/// Gets configuration in a YAML string.
std::string configurationAsText(const FormatStyle &Style);
@@ -2636,6 +3397,9 @@ extern const char *DefaultFallbackStyle;
/// language if the filename isn't sufficient.
/// \param[in] FS The underlying file system, in which the file resides. By
/// default, the file system is the real file system.
+/// \param[in] AllowUnknownOptions If true, unknown format options only
+/// emit a warning. If false, errors are emitted on unknown format
+/// options.
///
/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
@@ -2643,7 +3407,8 @@ extern const char *DefaultFallbackStyle;
llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyle,
StringRef Code = "",
- llvm::vfs::FileSystem *FS = nullptr);
+ llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false);
// Guesses the language from the ``FileName`` and ``Code`` to be formatted.
// Defaults to FormatStyle::LK_Cpp.
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/ASTUnit.h b/contrib/llvm-project/clang/include/clang/Frontend/ASTUnit.h
index 50ab86ebad97..6cf9f3ff936f 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/ASTUnit.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/ASTUnit.h
@@ -688,14 +688,15 @@ public:
/// lifetime is expected to extend past that of the returned ASTUnit.
///
/// \returns - The initialized ASTUnit or null if the AST failed to load.
- static std::unique_ptr<ASTUnit> LoadFromASTFile(
- const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
- WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
- const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
- bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
- CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
- bool AllowPCHWithCompilerErrors = false,
- bool UserFilesAreVolatile = false);
+ static std::unique_ptr<ASTUnit>
+ LoadFromASTFile(const std::string &Filename,
+ const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad,
+ IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+ const FileSystemOptions &FileSystemOpts,
+ bool UseDebugInfo = false, bool OnlyLocalDecls = false,
+ CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
+ bool AllowASTWithCompilerErrors = false,
+ bool UserFilesAreVolatile = false);
private:
/// Helper function for \c LoadFromCompilerInvocation() and
@@ -756,7 +757,6 @@ public:
CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
unsigned PrecompilePreambleAfterNParses = 0,
bool CacheCodeCompletionResults = false,
- bool IncludeBriefCommentsInCodeCompletion = false,
bool UserFilesAreVolatile = false,
std::unique_ptr<ASTUnit> *ErrAST = nullptr);
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/CompilerInstance.h b/contrib/llvm-project/clang/include/clang/Frontend/CompilerInstance.h
index cb935becaef1..57632f8770f0 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/CompilerInstance.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/CompilerInstance.h
@@ -50,6 +50,7 @@ class Preprocessor;
class Sema;
class SourceManager;
class TargetInfo;
+enum class DisableValidationForModuleKind;
/// CompilerInstance - Helper class for managing a single instance of the Clang
/// compiler.
@@ -171,11 +172,6 @@ class CompilerInstance : public ModuleLoader {
}
};
- /// If the output doesn't support seeking (terminal, pipe). we switch
- /// the stream to a buffer_ostream. These are the buffer and the original
- /// stream.
- std::unique_ptr<llvm::raw_fd_ostream> NonSeekStream;
-
/// The list of active output files.
std::list<OutputFile> OutputFiles;
@@ -582,11 +578,6 @@ public:
/// @name Output Files
/// {
- /// addOutputFile - Add an output file onto the list of tracked output files.
- ///
- /// \param OutFile - The output file info.
- void addOutputFile(OutputFile &&OutFile);
-
/// clearOutputFiles - Clear the output file list. The underlying output
/// streams must have been closed beforehand.
///
@@ -649,23 +640,27 @@ public:
/// and replace any existing one with it.
void createPreprocessor(TranslationUnitKind TUKind);
- std::string getSpecificModuleCachePath();
+ std::string getSpecificModuleCachePath(StringRef ModuleHash);
+ std::string getSpecificModuleCachePath() {
+ return getSpecificModuleCachePath(getInvocation().getModuleHash());
+ }
/// Create the AST context.
void createASTContext();
/// Create an external AST source to read a PCH file and attach it to the AST
/// context.
- void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
- bool AllowPCHWithCompilerErrors,
- void *DeserializationListener,
- bool OwnDeserializationListener);
+ void createPCHExternalASTSource(
+ StringRef Path, DisableValidationForModuleKind DisableValidation,
+ bool AllowPCHWithCompilerErrors, void *DeserializationListener,
+ bool OwnDeserializationListener);
/// Create an external AST source to read a PCH file.
///
/// \return - The new object on success, or null on failure.
static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
- StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
+ StringRef Path, StringRef Sysroot,
+ DisableValidationForModuleKind DisableValidation,
bool AllowPCHWithCompilerErrors, Preprocessor &PP,
InMemoryModuleCache &ModuleCache, ASTContext &Context,
const PCHContainerReader &PCHContainerRdr,
@@ -695,25 +690,29 @@ public:
/// Create the default output file (from the invocation's options) and add it
/// to the list of tracked output files.
///
- /// The files created by this function always use temporary files to write to
- /// their result (that is, the data is written to a temporary file which will
- /// atomically replace the target output on success).
+ /// The files created by this are usually removed on signal, and, depending
+ /// on FrontendOptions, may also use a temporary file (that is, the data is
+ /// written to a temporary file which will atomically replace the target
+ /// output on success). If a client (like libclang) needs to disable
+ /// RemoveFileOnSignal, temporary files will be forced on.
///
/// \return - Null on error.
std::unique_ptr<raw_pwrite_stream>
createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
- StringRef Extension = "");
+ StringRef Extension = "",
+ bool RemoveFileOnSignal = true,
+ bool CreateMissingDirectories = false);
- /// Create a new output file and add it to the list of tracked output files,
- /// optionally deriving the output path name.
+ /// Create a new output file, optionally deriving the output path name, and
+ /// add it to the list of tracked output files.
///
/// \return - Null on error.
std::unique_ptr<raw_pwrite_stream>
createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
- StringRef BaseInput, StringRef Extension, bool UseTemporary,
- bool CreateMissingDirectories = false);
+ bool UseTemporary, bool CreateMissingDirectories = false);
- /// Create a new output file, optionally deriving the output path name.
+private:
+ /// Create a new output file and add it to the list of tracked output files.
///
/// If \p OutputPath is empty, then createOutputFile will derive an output
/// path location as \p BaseInput, with any suffix removed, and \p Extension
@@ -722,10 +721,6 @@ public:
/// renamed to \p OutputPath in the end.
///
/// \param OutputPath - If given, the path to the output file.
- /// \param Error [out] - On failure, the error.
- /// \param BaseInput - If \p OutputPath is empty, the input path name to use
- /// for deriving the output path.
- /// \param Extension - The extension to use for derived output names.
/// \param Binary - The mode to open the file in.
/// \param RemoveFileOnSignal - Whether the file should be registered with
/// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
@@ -734,17 +729,12 @@ public:
/// OutputPath in the end.
/// \param CreateMissingDirectories - When \p UseTemporary is true, create
/// missing directories in the output path.
- /// \param ResultPathName [out] - If given, the result path name will be
- /// stored here on success.
- /// \param TempPathName [out] - If given, the temporary file path name
- /// will be stored here on success.
- std::unique_ptr<raw_pwrite_stream>
- createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
- bool RemoveFileOnSignal, StringRef BaseInput,
- StringRef Extension, bool UseTemporary,
- bool CreateMissingDirectories, std::string *ResultPathName,
- std::string *TempPathName);
+ Expected<std::unique_ptr<raw_pwrite_stream>>
+ createOutputFileImpl(StringRef OutputPath, bool Binary,
+ bool RemoveFileOnSignal, bool UseTemporary,
+ bool CreateMissingDirectories);
+public:
std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
/// }
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h b/contrib/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h
index c723fc084c85..0d83a228c301 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h
@@ -176,11 +176,12 @@ public:
/// \param Opts - The LangOptions object to set up.
/// \param IK - The input language.
/// \param T - The target triple.
- /// \param PPOpts - The PreprocessorOptions affected.
+ /// \param Includes - The affected list of included files.
/// \param LangStd - The input language standard.
- static void setLangDefaults(LangOptions &Opts, InputKind IK,
- const llvm::Triple &T, PreprocessorOptions &PPOpts,
- LangStandard::Kind LangStd = LangStandard::lang_unspecified);
+ static void
+ setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T,
+ std::vector<std::string> &Includes,
+ LangStandard::Kind LangStd = LangStandard::lang_unspecified);
/// Retrieve a module hash string that is suitable for uniquely
/// identifying the conditions under which the module was built.
@@ -246,6 +247,19 @@ private:
/// \returns - True if parsing was successful, false otherwise
bool parseSimpleArgs(const llvm::opt::ArgList &Args,
DiagnosticsEngine &Diags);
+
+ /// Parse command line options that map to LangOptions.
+ static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+ InputKind IK, const llvm::Triple &T,
+ std::vector<std::string> &Includes,
+ DiagnosticsEngine &Diags);
+
+ /// Parse command line options that map to CodeGenOptions.
+ static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
+ InputKind IK, DiagnosticsEngine &Diags,
+ const llvm::Triple &T,
+ const std::string &OutputFile,
+ const LangOptions &LangOptsRef);
};
IntrusiveRefCntPtr<llvm::vfs::FileSystem>
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/FrontendAction.h b/contrib/llvm-project/clang/include/clang/Frontend/FrontendAction.h
index c9f9f080c141..319b3bc62cc4 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/FrontendAction.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/FrontendAction.h
@@ -145,7 +145,7 @@ public:
assert(!CurrentInput.isEmpty() && "No current file!");
return CurrentInput.isFile()
? CurrentInput.getFile()
- : CurrentInput.getBuffer()->getBufferIdentifier();
+ : CurrentInput.getBuffer().getBufferIdentifier();
}
InputKind getCurrentFileKind() const {
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h b/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h
index 9ca2bfda2138..25ca95980806 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h
@@ -117,6 +117,8 @@ protected:
}
bool hasASTFileSupport() const override { return false; }
+
+ bool shouldEraseOutputFiles() override;
};
class GenerateInterfaceStubsAction : public ASTFrontendAction {
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/FrontendOptions.h b/contrib/llvm-project/clang/include/clang/Frontend/FrontendOptions.h
index b2be33032c08..223c1e05d053 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/FrontendOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/FrontendOptions.h
@@ -188,7 +188,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.
- const llvm::MemoryBuffer *Buffer = nullptr;
+ llvm::Optional<llvm::MemoryBufferRef> Buffer;
/// The kind of input, e.g., C source, AST file, LLVM IR.
InputKind Kind;
@@ -200,16 +200,16 @@ public:
FrontendInputFile() = default;
FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false)
: File(File.str()), Kind(Kind), IsSystem(IsSystem) {}
- FrontendInputFile(const llvm::MemoryBuffer *Buffer, InputKind Kind,
+ FrontendInputFile(llvm::MemoryBufferRef Buffer, InputKind Kind,
bool IsSystem = false)
: Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) {}
InputKind getKind() const { return Kind; }
bool isSystem() const { return IsSystem; }
- bool isEmpty() const { return File.empty() && Buffer == nullptr; }
+ bool isEmpty() const { return File.empty() && Buffer == None; }
bool isFile() const { return !isBuffer(); }
- bool isBuffer() const { return Buffer != nullptr; }
+ bool isBuffer() const { return Buffer != None; }
bool isPreprocessed() const { return Kind.isPreprocessed(); }
StringRef getFile() const {
@@ -217,9 +217,9 @@ public:
return File;
}
- const llvm::MemoryBuffer *getBuffer() const {
+ llvm::MemoryBufferRef getBuffer() const {
assert(isBuffer());
- return Buffer;
+ return *Buffer;
}
};
@@ -239,9 +239,6 @@ public:
/// Show frontend performance metrics and statistics.
unsigned ShowStats : 1;
- /// Show timers for individual actions.
- unsigned ShowTimers : 1;
-
/// print the supported cpus for the current target
unsigned PrintSupportedCPUs : 1;
@@ -303,6 +300,9 @@ public:
/// When using -emit-module, treat the modulemap as a system module.
unsigned IsSystemModule : 1;
+ /// Output (and read) PCM files regardless of compiler errors.
+ unsigned AllowPCMWithCompilerErrors : 1;
+
CodeCompleteOptions CodeCompleteOpts;
/// Specifies the output format of the AST.
@@ -450,14 +450,15 @@ public:
public:
FrontendOptions()
: DisableFree(false), RelocatablePCH(false), ShowHelp(false),
- ShowStats(false), ShowTimers(false), TimeTrace(false),
- ShowVersion(false), FixWhatYouCan(false), FixOnlyWarnings(false),
- FixAndRecompile(false), FixToTemporaries(false),
- ARCMTMigrateEmitARCErrors(false), SkipFunctionBodies(false),
- UseGlobalModuleIndex(true), GenerateGlobalModuleIndex(true),
- ASTDumpDecls(false), ASTDumpLookups(false),
- BuildingImplicitModule(false), ModulesEmbedAllFiles(false),
- IncludeTimestamps(true), UseTemporary(true), TimeTraceGranularity(500) {}
+ ShowStats(false), TimeTrace(false), ShowVersion(false),
+ FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
+ FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
+ SkipFunctionBodies(false), UseGlobalModuleIndex(true),
+ GenerateGlobalModuleIndex(true), ASTDumpDecls(false),
+ ASTDumpLookups(false), BuildingImplicitModule(false),
+ ModulesEmbedAllFiles(false), IncludeTimestamps(true),
+ UseTemporary(true), AllowPCMWithCompilerErrors(false),
+ TimeTraceGranularity(500) {}
/// getInputKindForExtension - Return the appropriate input kind for a file
/// extension. For example, "c" would return Language::C.
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h b/contrib/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h
index 0f7e9d895a00..bb7fd97fe5df 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h
@@ -26,6 +26,7 @@
namespace llvm {
class MemoryBuffer;
+class MemoryBufferRef;
namespace vfs {
class FileSystem;
}
@@ -40,7 +41,7 @@ class PCHContainerOperations;
/// Runs lexer to compute suggested preamble bounds.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts,
- const llvm::MemoryBuffer *Buffer,
+ const llvm::MemoryBufferRef &Buffer,
unsigned MaxLines);
class PreambleCallbacks;
@@ -104,8 +105,8 @@ public:
/// Check whether PrecompiledPreamble can be reused for the new contents(\p
/// MainFileBuffer) of the main file.
bool CanReuse(const CompilerInvocation &Invocation,
- const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
- llvm::vfs::FileSystem *VFS) const;
+ const llvm::MemoryBufferRef &MainFileBuffer,
+ PreambleBounds Bounds, llvm::vfs::FileSystem &VFS) const;
/// Changes options inside \p CI to use PCH from this preamble. Also remaps
/// main file to \p MainFileBuffer and updates \p VFS to ensure the preamble
@@ -216,7 +217,7 @@ private:
static PreambleFileHash createForFile(off_t Size, time_t ModTime);
static PreambleFileHash
- createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
+ createForMemoryBuffer(const llvm::MemoryBufferRef &Buffer);
friend bool operator==(const PreambleFileHash &LHS,
const PreambleFileHash &RHS) {
diff --git a/contrib/llvm-project/clang/include/clang/Frontend/Utils.h b/contrib/llvm-project/clang/include/clang/Frontend/Utils.h
index b5834921b9ed..da2d79af2eba 100644
--- a/contrib/llvm-project/clang/include/clang/Frontend/Utils.h
+++ b/contrib/llvm-project/clang/include/clang/Frontend/Utils.h
@@ -23,6 +23,7 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Option/OptSpecifier.h"
+#include "llvm/Support/FileCollector.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <cstdint>
#include <memory>
@@ -151,9 +152,8 @@ class ModuleDependencyCollector : public DependencyCollector {
bool HasErrors = false;
llvm::StringSet<> Seen;
llvm::vfs::YAMLVFSWriter VFSWriter;
- llvm::StringMap<std::string> SymLinkMap;
+ llvm::FileCollector::PathCanonicalizer Canonicalizer;
- bool getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result);
std::error_code copyToRoot(StringRef Src, StringRef Dst = {});
public:
@@ -227,10 +227,6 @@ std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine(
// Frontend timing utils
-/// If the user specifies the -ftime-report argument on an Clang command line
-/// then the value of this boolean will be true, otherwise false.
-extern bool FrontendTimesIsEnabled;
-
} // namespace clang
#endif // LLVM_CLANG_FRONTEND_UTILS_H
diff --git a/contrib/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h b/contrib/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h
new file mode 100644
index 000000000000..20cf8fbdad96
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h
@@ -0,0 +1,129 @@
+//===--- SerializablePathCollection.h -- Index of paths ---------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_INDEX_SerializablePathCollection_H
+#define LLVM_CLANG_INDEX_SerializablePathCollection_H
+
+#include "clang/Basic/FileManager.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator.h"
+
+#include <string>
+#include <vector>
+
+namespace clang {
+namespace index {
+
+/// Pool of strings
+class StringPool {
+ llvm::SmallString<512> Buffer;
+
+public:
+ struct StringOffsetSize {
+ std::size_t Offset;
+ std::size_t Size;
+
+ StringOffsetSize(size_t Offset, size_t Size) : Offset(Offset), Size(Size) {}
+ };
+
+ StringOffsetSize add(StringRef Str);
+ StringRef getBuffer() const { return Buffer; }
+};
+
+/// Pool of filesystem paths backed by a StringPool
+class PathPool {
+public:
+ /// Special root directory of a filesystem path.
+ enum class RootDirKind {
+ Regular = 0,
+ CurrentWorkDir = 1,
+ SysRoot = 2,
+ };
+
+ struct DirPath {
+ RootDirKind Root;
+ StringPool::StringOffsetSize Path;
+
+ DirPath(RootDirKind Root, const StringPool::StringOffsetSize &Path)
+ : Root(Root), Path(Path) {}
+ };
+
+ struct FilePath {
+ DirPath Dir;
+ StringPool::StringOffsetSize Filename;
+
+ FilePath(const DirPath &Dir, const StringPool::StringOffsetSize &Filename)
+ : Dir(Dir), Filename(Filename) {}
+ };
+
+ /// \returns index of the newly added file in FilePaths.
+ size_t addFilePath(RootDirKind Root, const StringPool::StringOffsetSize &Dir,
+ StringRef Filename);
+
+ /// \returns offset in Paths and size of newly added directory.
+ StringPool::StringOffsetSize addDirPath(StringRef Dir);
+
+ llvm::ArrayRef<FilePath> getFilePaths() const;
+
+ StringRef getPaths() const;
+
+private:
+ StringPool Paths;
+ std::vector<FilePath> FilePaths;
+};
+
+/// Stores file paths and produces serialization-friendly representation.
+class SerializablePathCollection {
+ std::string WorkDir;
+ std::string SysRoot;
+
+ PathPool Paths;
+ llvm::DenseMap<const clang::FileEntry *, std::size_t> UniqueFiles;
+ llvm::StringMap<PathPool::DirPath, llvm::BumpPtrAllocator> UniqueDirs;
+
+public:
+ const StringPool::StringOffsetSize WorkDirPath;
+ const StringPool::StringOffsetSize SysRootPath;
+ const StringPool::StringOffsetSize OutputFilePath;
+
+ SerializablePathCollection(llvm::StringRef CurrentWorkDir,
+ llvm::StringRef SysRoot,
+ llvm::StringRef OutputFile);
+
+ /// \returns buffer containing all the paths.
+ llvm::StringRef getPathsBuffer() const { return Paths.getPaths(); }
+
+ /// \returns file paths (no directories) backed by buffer exposed in
+ /// getPathsBuffer.
+ ArrayRef<PathPool::FilePath> getFilePaths() const {
+ return Paths.getFilePaths();
+ }
+
+ /// Stores path to \p FE if it hasn't been stored yet.
+ /// \returns index to array exposed by getPathsBuffer().
+ size_t tryStoreFilePath(const clang::FileEntry &FE);
+
+private:
+ /// Stores \p Path if it is non-empty.
+ /// Warning: this method doesn't check for uniqueness.
+ /// \returns offset of \p Path value begin in buffer with stored paths.
+ StringPool::StringOffsetSize storePath(llvm::StringRef Path);
+
+ /// Stores \p dirStr path if it hasn't been stored yet.
+ PathPool::DirPath tryStoreDirPath(llvm::StringRef dirStr);
+};
+
+} // namespace index
+} // namespace clang
+
+#endif // LLVM_CLANG_INDEX_SerializablePathCollection_H
diff --git a/contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h b/contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h
index 28c57dbe3b8e..93d6ea72270a 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h
@@ -183,6 +183,9 @@ class HeaderSearch {
/// a system header.
std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
+ /// The hash used for module cache paths.
+ std::string ModuleHash;
+
/// The path to the module cache.
std::string ModuleCachePath;
@@ -319,11 +322,17 @@ public:
return {};
}
+ /// Set the hash to use for module cache paths.
+ void setModuleHash(StringRef Hash) { ModuleHash = std::string(Hash); }
+
/// Set the path to the module cache.
void setModuleCachePath(StringRef CachePath) {
ModuleCachePath = std::string(CachePath);
}
+ /// Retrieve the module hash.
+ StringRef getModuleHash() const { return ModuleHash; }
+
/// Retrieve the path to the module cache.
StringRef getModuleCachePath() const { return ModuleCachePath; }
@@ -512,6 +521,15 @@ public:
std::string getPrebuiltModuleFileName(StringRef ModuleName,
bool FileMapOnly = false);
+ /// Retrieve the name of the prebuilt module file that should be used
+ /// to load the given module.
+ ///
+ /// \param Module The module whose module file name will be returned.
+ ///
+ /// \returns The name of the module file that corresponds to this module,
+ /// or an empty string if this module does not correspond to any module file.
+ std::string getPrebuiltImplicitModuleFileName(Module *Module);
+
/// Retrieve the name of the (to-be-)cached module file that should
/// be used to load a module with the given name.
///
@@ -614,6 +632,22 @@ private:
Module *lookupModule(StringRef ModuleName, StringRef SearchName,
bool AllowExtraModuleMapSearch = false);
+ /// Retrieve the name of the (to-be-)cached module file that should
+ /// be used to load a module with the given name.
+ ///
+ /// \param ModuleName The module whose module file name will be returned.
+ ///
+ /// \param ModuleMapPath A path that when combined with \c ModuleName
+ /// uniquely identifies this module. See Module::ModuleMap.
+ ///
+ /// \param CachePath A path to the module cache.
+ ///
+ /// \returns The name of the module file that corresponds to this module,
+ /// or an empty string if this module does not correspond to any module file.
+ std::string getCachedModuleFileNameImpl(StringRef ModuleName,
+ StringRef ModuleMapPath,
+ StringRef CachePath);
+
/// Retrieve a module with the given name, which may be part of the
/// given framework.
///
diff --git a/contrib/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h b/contrib/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h
index 3af49e175395..42f3cff8c57a 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h
@@ -142,6 +142,10 @@ public:
/// file.
unsigned ModuleMapFileHomeIsCwd : 1;
+ /// Also search for prebuilt implicit modules in the prebuilt module cache
+ /// path.
+ unsigned EnablePrebuiltImplicitModules : 1;
+
/// The interval (in seconds) between pruning operations.
///
/// This operation is expensive, because it requires Clang to walk through
@@ -217,8 +221,9 @@ public:
HeaderSearchOptions(StringRef _Sysroot = "/")
: Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(false),
ImplicitModuleMaps(false), ModuleMapFileHomeIsCwd(false),
- UseBuiltinIncludes(true), UseStandardSystemIncludes(true),
- UseStandardCXXIncludes(true), UseLibcxx(false), Verbose(false),
+ EnablePrebuiltImplicitModules(false), UseBuiltinIncludes(true),
+ UseStandardSystemIncludes(true), UseStandardCXXIncludes(true),
+ UseLibcxx(false), Verbose(false),
ModulesValidateOncePerBuildSession(false),
ModulesValidateSystemHeaders(false),
ValidateASTInputFilesContent(false), UseDebugInfo(false),
diff --git a/contrib/llvm-project/clang/include/clang/Lex/Lexer.h b/contrib/llvm-project/clang/include/clang/Lex/Lexer.h
index 97a222f4a703..a291520ae5ca 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/Lexer.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/Lexer.h
@@ -27,7 +27,7 @@
namespace llvm {
-class MemoryBuffer;
+class MemoryBufferRef;
} // namespace llvm
@@ -128,6 +128,10 @@ class Lexer : public PreprocessorLexer {
bool HasLeadingEmptyMacro;
+ // NewLinePtr - A pointer to new line character '\n' being lexed. For '\r\n',
+ // it also points to '\n.'
+ const char *NewLinePtr;
+
// CurrentConflictMarkerState - The kind of conflict marker we are handling.
ConflictMarkerKind CurrentConflictMarkerState;
@@ -138,7 +142,7 @@ public:
/// with the specified preprocessor managing the lexing process. This lexer
/// assumes that the associated file buffer and Preprocessor objects will
/// outlive it, so it doesn't take ownership of either of them.
- Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP);
+ Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile, Preprocessor &PP);
/// Lexer constructor - Create a new raw lexer object. This object is only
/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
@@ -149,7 +153,7 @@ public:
/// Lexer constructor - Create a new raw lexer object. This object is only
/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
/// text range will outlive it, so it doesn't take ownership of it.
- Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
+ Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
const SourceManager &SM, const LangOptions &LangOpts);
Lexer(const Lexer &) = delete;
diff --git a/contrib/llvm-project/clang/include/clang/Lex/ModuleMap.h b/contrib/llvm-project/clang/include/clang/Lex/ModuleMap.h
index 5b164039080b..6827408f10a3 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/ModuleMap.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/ModuleMap.h
@@ -14,6 +14,7 @@
#ifndef LLVM_CLANG_LEX_MODULEMAP_H
#define LLVM_CLANG_LEX_MODULEMAP_H
+#include "clang/Basic/FileEntry.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
@@ -37,7 +38,6 @@ namespace clang {
class DiagnosticsEngine;
class DirectoryEntry;
-class FileEntry;
class FileManager;
class HeaderSearch;
class SourceManager;
@@ -328,10 +328,9 @@ private:
/// \param NeedsFramework If M is not a framework but a missing header would
/// be found in case M was, set it to true. False otherwise.
/// \return The resolved file, if any.
- const FileEntry *findHeader(Module *M,
- const Module::UnresolvedHeaderDirective &Header,
- SmallVectorImpl<char> &RelativePathName,
- bool &NeedsFramework);
+ Optional<FileEntryRef>
+ findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
+ SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
/// Resolve the given header directive.
///
@@ -649,12 +648,12 @@ public:
/// Sets the umbrella header of the given module to the given
/// header.
- void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
+ void setUmbrellaHeader(Module *Mod, FileEntryRef UmbrellaHeader,
Twine NameAsWritten);
/// Sets the umbrella directory of the given module to the given
/// directory.
- void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
+ void setUmbrellaDir(Module *Mod, DirectoryEntryRef UmbrellaDir,
Twine NameAsWritten);
/// Adds this header to the given module.
diff --git a/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h b/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h
index 5cd017fa925f..68139cb24b31 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h
@@ -67,6 +67,7 @@ class CodeCompletionHandler;
class CommentHandler;
class DirectoryEntry;
class DirectoryLookup;
+class EmptylineHandler;
class ExternalPreprocessorSource;
class FileEntry;
class FileManager;
@@ -256,6 +257,9 @@ class Preprocessor {
/// with this preprocessor.
std::vector<CommentHandler *> CommentHandlers;
+ /// Empty line handler.
+ EmptylineHandler *Emptyline = nullptr;
+
/// True if we want to ignore EOF token and continue later on (thus
/// avoid tearing the Lexer and etc. down).
bool IncrementalProcessing = false;
@@ -419,6 +423,9 @@ class Preprocessor {
/// The number of (LexLevel 0) preprocessor tokens.
unsigned TokenCount = 0;
+ /// Preprocess every token regardless of LexLevel.
+ bool PreprocessToken = false;
+
/// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens
/// warning, or zero for unlimited.
unsigned MaxTokens = 0;
@@ -1038,6 +1045,8 @@ public:
OnToken = std::move(F);
}
+ void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
+
bool isMacroDefined(StringRef Id) {
return isMacroDefined(&Identifiers.get(Id));
}
@@ -1214,6 +1223,11 @@ public:
/// Install empty handlers for all pragmas (making them ignored).
void IgnorePragmas();
+ /// Set empty line handler.
+ void setEmptylineHandler(EmptylineHandler *Handler) { Emptyline = Handler; }
+
+ EmptylineHandler *getEmptylineHandler() const { return Emptyline; }
+
/// Add the specified comment handler to the preprocessor.
void addCommentHandler(CommentHandler *Handler);
@@ -2385,6 +2399,16 @@ public:
virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
};
+/// Abstract base class that describes a handler that will receive
+/// source ranges for empty lines encountered in the source file.
+class EmptylineHandler {
+public:
+ virtual ~EmptylineHandler();
+
+ // The handler handles empty lines.
+ virtual void HandleEmptyline(SourceRange Range) = 0;
+};
+
/// Registry of pragma handlers added by plugins
using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>;
diff --git a/contrib/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h b/contrib/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
index 893b7ba7a9f5..1a0d5ed57b28 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
@@ -23,8 +23,7 @@ using PreprocessorSkippedRangeMapping = llvm::DenseMap<unsigned, unsigned>;
/// The datastructure that holds the mapping between the active memory buffers
/// and the individual skip mappings.
using ExcludedPreprocessorDirectiveSkipMapping =
- llvm::DenseMap<const llvm::MemoryBuffer *,
- const PreprocessorSkippedRangeMapping *>;
+ llvm::DenseMap<const char *, const PreprocessorSkippedRangeMapping *>;
} // end namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h b/contrib/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h
index c551f87e0d7b..7f024989bf9b 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h
@@ -9,6 +9,7 @@
#ifndef LLVM_CLANG_LEX_PREPROCESSOROPTIONS_H_
#define LLVM_CLANG_LEX_PREPROCESSOROPTIONS_H_
+#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/LLVM.h"
#include "clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h"
#include "llvm/ADT/StringRef.h"
@@ -40,6 +41,24 @@ enum ObjCXXARCStandardLibraryKind {
ARCXX_libstdcxx
};
+/// Whether to disable the normal validation performed on precompiled
+/// headers and module files when they are loaded.
+enum class DisableValidationForModuleKind {
+ /// Perform validation, don't disable it.
+ None = 0,
+
+ /// Disable validation for a precompiled header and the modules it depends on.
+ PCH = 0x1,
+
+ /// Disable validation for module files.
+ Module = 0x2,
+
+ /// Disable validation for all kinds.
+ All = PCH | Module,
+
+ LLVM_MARK_AS_BITMASK_ENUM(Module)
+};
+
/// PreprocessorOptions - This class is used for passing the various options
/// used in preprocessor initialization to InitializePreprocessor().
class PreprocessorOptions {
@@ -79,9 +98,10 @@ public:
/// Headers that will be converted to chained PCHs in memory.
std::vector<std::string> ChainedIncludes;
- /// When true, disables most of the normal validation performed on
- /// precompiled headers.
- bool DisablePCHValidation = false;
+ /// Whether to disable most of the normal validation performed on
+ /// precompiled headers and module files.
+ DisableValidationForModuleKind DisablePCHOrModuleValidation =
+ DisableValidationForModuleKind::None;
/// When true, a PCH with compiler errors will not be rejected.
bool AllowPCHWithCompilerErrors = false;
diff --git a/contrib/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h b/contrib/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h
index 989e0ac703c9..119f02201fc6 100644
--- a/contrib/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h
+++ b/contrib/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h
@@ -39,17 +39,14 @@ namespace clang {
assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned "
"outside an ISO C/C++ variadic "
"macro definition!");
- assert(
- !Ident__VA_OPT__ ||
- (Ident__VA_OPT__->isPoisoned() && "__VA_OPT__ should be poisoned!"));
+ assert(Ident__VA_OPT__->isPoisoned() && "__VA_OPT__ should be poisoned!");
}
/// Client code should call this function just before the Preprocessor is
/// about to Lex tokens from the definition of a variadic (ISO C/C++) macro.
void enterScope() {
Ident__VA_ARGS__->setIsPoisoned(false);
- if (Ident__VA_OPT__)
- Ident__VA_OPT__->setIsPoisoned(false);
+ Ident__VA_OPT__->setIsPoisoned(false);
}
/// Client code should call this function as soon as the Preprocessor has
@@ -58,8 +55,7 @@ namespace clang {
/// (might be explicitly called, and then reinvoked via the destructor).
void exitScope() {
Ident__VA_ARGS__->setIsPoisoned(true);
- if (Ident__VA_OPT__)
- Ident__VA_OPT__->setIsPoisoned(true);
+ Ident__VA_OPT__->setIsPoisoned(true);
}
~VariadicMacroScopeGuard() { exitScope(); }
diff --git a/contrib/llvm-project/clang/include/clang/Parse/Parser.h b/contrib/llvm-project/clang/include/clang/Parse/Parser.h
index e809d87b59a0..02aab3b43be0 100644
--- a/contrib/llvm-project/clang/include/clang/Parse/Parser.h
+++ b/contrib/llvm-project/clang/include/clang/Parse/Parser.h
@@ -48,7 +48,6 @@ namespace clang {
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
- class ObjCTypeParameter;
struct OMPTraitProperty;
struct OMPTraitSelector;
struct OMPTraitSet;
@@ -202,7 +201,8 @@ class Parser : public CodeCompletionHandler {
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
- std::unique_ptr<PragmaHandler> STDCFENVHandler;
+ std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
+ std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
@@ -701,10 +701,6 @@ private:
/// #pragma ms_struct...
void HandlePragmaMSStruct();
- /// Handle the annotation token produced for
- /// #pragma comment...
- void HandlePragmaMSComment();
-
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
@@ -746,6 +742,10 @@ private:
void HandlePragmaFEnvAccess();
/// Handle the annotation token produced for
+ /// #pragma STDC FENV_ROUND...
+ void HandlePragmaFEnvRound();
+
+ /// Handle the annotation token produced for
/// #pragma float_control
void HandlePragmaFloatControl();
@@ -1045,6 +1045,25 @@ private:
/// was successful.
bool expectIdentifier();
+ /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
+ enum class CompoundToken {
+ /// A '(' '{' beginning a statement-expression.
+ StmtExprBegin,
+ /// A '}' ')' ending a statement-expression.
+ StmtExprEnd,
+ /// A '[' '[' beginning a C++11 or C2x attribute.
+ AttrBegin,
+ /// A ']' ']' ending a C++11 or C2x attribute.
+ AttrEnd,
+ /// A '::' '*' forming a C++ pointer-to-member declaration.
+ MemberPtr,
+ };
+
+ /// Check that a compound operator was written in a "sensible" way, and warn
+ /// if not.
+ void checkCompoundToken(SourceLocation FirstTokLoc,
+ tok::TokenKind FirstTokKind, CompoundToken Op);
+
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
@@ -1343,7 +1362,7 @@ private:
void ParseLexedMethodDeclarations() override;
- Parser* Self;
+ Parser *Self;
/// Method - The method declaration.
Decl *Method;
@@ -1710,7 +1729,6 @@ private:
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
- void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
@@ -1800,14 +1818,12 @@ private:
ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
ExprResult ParseUnaryExprOrTypeTraitExpression();
ExprResult ParseBuiltinPrimaryExpression();
- ExprResult ParseUniqueStableNameExpression();
ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
- typedef SmallVector<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
@@ -2556,12 +2572,11 @@ private:
bool TrySkipAttributes();
public:
- TypeResult ParseTypeName(SourceRange *Range = nullptr,
- DeclaratorContext Context
- = DeclaratorContext::TypeNameContext,
- AccessSpecifier AS = AS_none,
- Decl **OwnedType = nullptr,
- ParsedAttributes *Attrs = nullptr);
+ TypeResult
+ ParseTypeName(SourceRange *Range = nullptr,
+ DeclaratorContext Context = DeclaratorContext::TypeName,
+ AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
+ ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
@@ -2780,6 +2795,14 @@ private:
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
+ void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
+ SourceLocation AttrNameLoc,
+ ParsedAttributes &Attrs,
+ SourceLocation *EndLoc,
+ IdentifierInfo *ScopeName,
+ SourceLocation ScopeLoc,
+ ParsedAttr::Syntax Syntax);
+
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
@@ -3074,12 +3097,20 @@ private:
/// Parse a `match` clause for an '#pragma omp declare variant'. Return true
/// if there was an error.
- bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI);
+ bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
+ OMPTraitInfo *ParentTI);
/// Parse clauses for '#pragma omp declare variant'.
void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
SourceLocation Loc);
+ /// Parse 'omp [begin] assume[s]' directive.
+ void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
+ SourceLocation Loc);
+
+ /// Parse 'omp end assumes' directive.
+ void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
+
/// Parse clauses for '#pragma omp declare target'.
DeclGroupPtrTy ParseOMPDeclareTargetClauses();
/// Parse '#pragma omp end declare target'.
@@ -3221,6 +3252,9 @@ public:
MapTypeModifiers;
SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
MapTypeModifiersLoc;
+ SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
+ MotionModifiers;
+ SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
bool IsMapTypeImplicit = false;
SourceLocation ExtraModifierLoc;
};
@@ -3272,8 +3306,6 @@ private:
NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
bool isTypeConstraintAnnotation();
bool TryAnnotateTypeConstraint();
- NamedDecl *
- ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
diff --git a/contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h b/contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h
index 7293784f894b..87646ab95025 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -992,9 +992,6 @@ inline bool operator>=(const CodeCompletionResult &X,
return !(X < Y);
}
-raw_ostream &operator<<(raw_ostream &OS,
- const CodeCompletionString &CCS);
-
/// Abstract interface for a consumer of code-completion
/// information.
class CodeCompleteConsumer {
diff --git a/contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h b/contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h
index 0a22b5af7c64..3b16295941e4 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h
@@ -249,25 +249,12 @@ public:
static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
- // Import type specifier width enumeration and constants.
- typedef TypeSpecifierWidth TSW;
- static const TSW TSW_unspecified = clang::TSW_unspecified;
- static const TSW TSW_short = clang::TSW_short;
- static const TSW TSW_long = clang::TSW_long;
- static const TSW TSW_longlong = clang::TSW_longlong;
-
enum TSC {
TSC_unspecified,
TSC_imaginary,
TSC_complex
};
- // Import type specifier sign enumeration and constants.
- typedef TypeSpecifierSign TSS;
- static const TSS TSS_unspecified = clang::TSS_unspecified;
- static const TSS TSS_signed = clang::TSS_signed;
- static const TSS TSS_unsigned = clang::TSS_unsigned;
-
// Import type specifier type enumeration and constants.
typedef TypeSpecifierType TST;
static const TST TST_unspecified = clang::TST_unspecified;
@@ -342,7 +329,7 @@ private:
unsigned SCS_extern_in_linkage_spec : 1;
// type-specifier
- /*TSW*/unsigned TypeSpecWidth : 2;
+ /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2;
/*TSC*/unsigned TypeSpecComplex : 2;
/*TSS*/unsigned TypeSpecSign : 2;
/*TST*/unsigned TypeSpecType : 6;
@@ -434,15 +421,18 @@ public:
DeclSpec(AttributeFactory &attrFactory)
: StorageClassSpec(SCS_unspecified),
ThreadStorageClassSpec(TSCS_unspecified),
- SCS_extern_in_linkage_spec(false), TypeSpecWidth(TSW_unspecified),
- TypeSpecComplex(TSC_unspecified), TypeSpecSign(TSS_unspecified),
+ SCS_extern_in_linkage_spec(false),
+ TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
+ TypeSpecComplex(TSC_unspecified),
+ TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
- TypeQualifiers(TQ_unspecified),
- FS_inline_specified(false), FS_forceinline_specified(false),
- FS_virtual_specified(false), FS_noreturn_specified(false),
- Friend_specified(false), ConstexprSpecifier(CSK_unspecified),
+ TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
+ FS_forceinline_specified(false), FS_virtual_specified(false),
+ FS_noreturn_specified(false), Friend_specified(false),
+ ConstexprSpecifier(
+ static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
ObjCQualifiers(nullptr) {}
@@ -476,9 +466,13 @@ public:
}
// type-specifier
- TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
+ TypeSpecifierWidth getTypeSpecWidth() const {
+ return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
+ }
TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
- TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
+ TypeSpecifierSign getTypeSpecSign() const {
+ return static_cast<TypeSpecifierSign>(TypeSpecSign);
+ }
TST getTypeSpecType() const { return (TST)TypeSpecType; }
bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
@@ -540,9 +534,9 @@ public:
static const char *getSpecifierName(DeclSpec::TST T,
const PrintingPolicy &Policy);
static const char *getSpecifierName(DeclSpec::TQ Q);
- static const char *getSpecifierName(DeclSpec::TSS S);
+ static const char *getSpecifierName(TypeSpecifierSign S);
static const char *getSpecifierName(DeclSpec::TSC C);
- static const char *getSpecifierName(DeclSpec::TSW W);
+ static const char *getSpecifierName(TypeSpecifierWidth W);
static const char *getSpecifierName(DeclSpec::SCS S);
static const char *getSpecifierName(DeclSpec::TSCS S);
static const char *getSpecifierName(ConstexprSpecKind C);
@@ -626,9 +620,9 @@ public:
/// Return true if any type-specifier has been found.
bool hasTypeSpecifier() const {
return getTypeSpecType() != DeclSpec::TST_unspecified ||
- getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
+ getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
- getTypeSpecSign() != DeclSpec::TSS_unspecified;
+ getTypeSpecSign() != TypeSpecifierSign::Unspecified;
}
/// Return a bitmask of which flavors of specifiers this
@@ -659,12 +653,13 @@ public:
const PrintingPolicy &Policy);
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID);
- bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
- unsigned &DiagID, const PrintingPolicy &Policy);
+ bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
+ const char *&PrevSpec, unsigned &DiagID,
+ const PrintingPolicy &Policy);
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
- bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
- unsigned &DiagID);
+ bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
+ const char *&PrevSpec, unsigned &DiagID);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
@@ -762,11 +757,11 @@ public:
SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
bool hasConstexprSpecifier() const {
- return ConstexprSpecifier != CSK_unspecified;
+ return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
}
void ClearConstexprSpec() {
- ConstexprSpecifier = CSK_unspecified;
+ ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
ConstexprLoc = SourceLocation();
}
@@ -972,7 +967,7 @@ public:
/// Different operators have different numbers of tokens in their name,
/// up to three. Any remaining source locations in this array will be
/// set to an invalid value for operators with fewer than three tokens.
- unsigned SymbolLocations[3];
+ SourceLocation SymbolLocations[3];
};
/// Anonymous union that holds extra data associated with the
@@ -1035,7 +1030,6 @@ public:
/// Determine what kind of name we have.
UnqualifiedIdKind getKind() const { return Kind; }
- void setKind(UnqualifiedIdKind kind) { Kind = kind; }
/// Specify that this unqualified-id was parsed as an identifier.
///
@@ -1151,6 +1145,16 @@ public:
StartLocation = EndLocation = TemplateLoc;
}
+ /// Specify that this unqualified-id is an implicit 'self'
+ /// parameter.
+ ///
+ /// \param Id the identifier.
+ void setImplicitSelfParam(const IdentifierInfo *Id) {
+ Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
+ Identifier = const_cast<IdentifierInfo *>(Id);
+ StartLocation = EndLocation = SourceLocation();
+ }
+
/// Return the source range that covers this unqualified-id.
SourceRange getSourceRange() const LLVM_READONLY {
return SourceRange(StartLocation, EndLocation);
@@ -1167,6 +1171,8 @@ typedef SmallVector<Token, 4> CachedTokens;
///
/// This is intended to be a small value object.
struct DeclaratorChunk {
+ DeclaratorChunk() {};
+
enum {
Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
} Kind;
@@ -1189,19 +1195,19 @@ struct DeclaratorChunk {
unsigned TypeQuals : 5;
/// The location of the const-qualifier, if any.
- unsigned ConstQualLoc;
+ SourceLocation ConstQualLoc;
/// The location of the volatile-qualifier, if any.
- unsigned VolatileQualLoc;
+ SourceLocation VolatileQualLoc;
/// The location of the restrict-qualifier, if any.
- unsigned RestrictQualLoc;
+ SourceLocation RestrictQualLoc;
/// The location of the _Atomic-qualifier, if any.
- unsigned AtomicQualLoc;
+ SourceLocation AtomicQualLoc;
/// The location of the __unaligned-qualifier, if any.
- unsigned UnalignedQualLoc;
+ SourceLocation UnalignedQualLoc;
void destroy() {
}
@@ -1296,13 +1302,13 @@ struct DeclaratorChunk {
unsigned HasTrailingReturnType : 1;
/// The location of the left parenthesis in the source.
- unsigned LParenLoc;
+ SourceLocation LParenLoc;
/// When isVariadic is true, the location of the ellipsis in the source.
- unsigned EllipsisLoc;
+ SourceLocation EllipsisLoc;
/// The location of the right parenthesis in the source.
- unsigned RParenLoc;
+ SourceLocation RParenLoc;
/// NumParams - This is the number of formal parameters specified by the
/// declarator.
@@ -1316,17 +1322,17 @@ struct DeclaratorChunk {
/// The location of the ref-qualifier, if any.
///
/// If this is an invalid location, there is no ref-qualifier.
- unsigned RefQualifierLoc;
+ SourceLocation RefQualifierLoc;
/// The location of the 'mutable' qualifer in a lambda-declarator, if
/// any.
- unsigned MutableLoc;
+ SourceLocation MutableLoc;
/// The beginning location of the exception specification, if any.
- unsigned ExceptionSpecLocBeg;
+ SourceLocation ExceptionSpecLocBeg;
/// The end location of the exception specification, if any.
- unsigned ExceptionSpecLocEnd;
+ SourceLocation ExceptionSpecLocEnd;
/// Params - This is a pointer to a new[]'d array of ParamInfo objects that
/// describe the parameters specified by this function declarator. null if
@@ -1363,6 +1369,10 @@ struct DeclaratorChunk {
/// type specified.
UnionParsedType TrailingReturnType;
+ /// If HasTrailingReturnType is true, this is the location of the trailing
+ /// return type.
+ SourceLocation TrailingReturnTypeLoc;
+
/// Reset the parameter list to having zero parameters.
///
/// This is used in various places for error recovery.
@@ -1409,24 +1419,18 @@ struct DeclaratorChunk {
/// by the parameter type definitions.
bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
- SourceLocation getLParenLoc() const {
- return SourceLocation::getFromRawEncoding(LParenLoc);
- }
+ SourceLocation getLParenLoc() const { return LParenLoc; }
- SourceLocation getEllipsisLoc() const {
- return SourceLocation::getFromRawEncoding(EllipsisLoc);
- }
+ SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
- SourceLocation getRParenLoc() const {
- return SourceLocation::getFromRawEncoding(RParenLoc);
- }
+ SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getExceptionSpecLocBeg() const {
- return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
+ return ExceptionSpecLocBeg;
}
SourceLocation getExceptionSpecLocEnd() const {
- return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
+ return ExceptionSpecLocEnd;
}
SourceRange getExceptionSpecRange() const {
@@ -1434,9 +1438,7 @@ struct DeclaratorChunk {
}
/// Retrieve the location of the ref-qualifier, if any.
- SourceLocation getRefQualifierLoc() const {
- return SourceLocation::getFromRawEncoding(RefQualifierLoc);
- }
+ SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
/// Retrieve the location of the 'const' qualifier.
SourceLocation getConstQualifierLoc() const {
@@ -1457,9 +1459,7 @@ struct DeclaratorChunk {
}
/// Retrieve the location of the 'mutable' qualifier, if any.
- SourceLocation getMutableLoc() const {
- return SourceLocation::getFromRawEncoding(MutableLoc);
- }
+ SourceLocation getMutableLoc() const { return MutableLoc; }
/// Determine whether this function declaration contains a
/// ref-qualifier.
@@ -1498,7 +1498,16 @@ struct DeclaratorChunk {
bool hasTrailingReturnType() const { return HasTrailingReturnType; }
/// Get the trailing-return-type for this function declarator.
- ParsedType getTrailingReturnType() const { return TrailingReturnType; }
+ ParsedType getTrailingReturnType() const {
+ assert(HasTrailingReturnType);
+ return TrailingReturnType;
+ }
+
+ /// Get the trailing-return-type location for this function declarator.
+ SourceLocation getTrailingReturnTypeLoc() const {
+ assert(HasTrailingReturnType);
+ return TrailingReturnTypeLoc;
+ }
};
struct BlockPointerTypeInfo {
@@ -1514,7 +1523,7 @@ struct DeclaratorChunk {
/// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
unsigned TypeQuals : 5;
/// Location of the '*' token.
- unsigned StarLoc;
+ SourceLocation StarLoc;
// CXXScopeSpec has a constructor, so it can't be a direct member.
// So we need some pointer-aligned storage and a bit of trickery.
alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
@@ -1574,12 +1583,13 @@ struct DeclaratorChunk {
DeclaratorChunk I;
I.Kind = Pointer;
I.Loc = Loc;
+ new (&I.Ptr) PointerTypeInfo;
I.Ptr.TypeQuals = TypeQuals;
- I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
- I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
- I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
- I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
- I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
+ I.Ptr.ConstQualLoc = ConstQualLoc;
+ I.Ptr.VolatileQualLoc = VolatileQualLoc;
+ I.Ptr.RestrictQualLoc = RestrictQualLoc;
+ I.Ptr.AtomicQualLoc = AtomicQualLoc;
+ I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
return I;
}
@@ -1633,6 +1643,8 @@ struct DeclaratorChunk {
Declarator &TheDeclarator,
TypeResult TrailingReturnType =
TypeResult(),
+ SourceLocation TrailingReturnTypeLoc =
+ SourceLocation(),
DeclSpec *MethodQualifiers = nullptr);
/// Return a DeclaratorChunk for a block.
@@ -1663,7 +1675,8 @@ struct DeclaratorChunk {
I.Kind = MemberPointer;
I.Loc = SS.getBeginLoc();
I.EndLoc = EndLoc;
- I.Mem.StarLoc = StarLoc.getRawEncoding();
+ new (&I.Mem) MemberPointerTypeInfo;
+ I.Mem.StarLoc = StarLoc;
I.Mem.TypeQuals = TypeQuals;
new (I.Mem.ScopeMem) CXXScopeSpec(SS);
return I;
@@ -1738,44 +1751,43 @@ public:
/// Described the kind of function definition (if any) provided for
/// a function.
-enum FunctionDefinitionKind {
- FDK_Declaration,
- FDK_Definition,
- FDK_Defaulted,
- FDK_Deleted
+enum class FunctionDefinitionKind {
+ Declaration,
+ Definition,
+ Defaulted,
+ Deleted
};
enum class DeclaratorContext {
- FileContext, // File scope declaration.
- PrototypeContext, // Within a function prototype.
- ObjCResultContext, // An ObjC method result type.
- ObjCParameterContext,// An ObjC method parameter type.
- KNRTypeListContext, // K&R type definition list for formals.
- TypeNameContext, // Abstract declarator for types.
- FunctionalCastContext, // Type in a C++ functional cast expression.
- MemberContext, // Struct/Union field.
- BlockContext, // Declaration within a block in a function.
- ForContext, // Declaration within first part of a for loop.
- InitStmtContext, // Declaration within optional init stmt of if/switch.
- ConditionContext, // Condition declaration in a C++ if/switch/while/for.
- TemplateParamContext,// Within a template parameter list.
- CXXNewContext, // C++ new-expression.
- CXXCatchContext, // C++ catch exception-declaration
- ObjCCatchContext, // Objective-C catch exception-declaration
- BlockLiteralContext, // Block literal declarator.
- LambdaExprContext, // Lambda-expression declarator.
- LambdaExprParameterContext, // Lambda-expression parameter declarator.
- ConversionIdContext, // C++ conversion-type-id.
- TrailingReturnContext, // C++11 trailing-type-specifier.
- TrailingReturnVarContext, // C++11 trailing-type-specifier for variable.
- TemplateArgContext, // Any template argument (in template argument list).
- TemplateTypeArgContext, // Template type argument (in default argument).
- AliasDeclContext, // C++11 alias-declaration.
- AliasTemplateContext, // C++11 alias-declaration template.
- RequiresExprContext // C++2a requires-expression.
+ File, // File scope declaration.
+ Prototype, // Within a function prototype.
+ ObjCResult, // An ObjC method result type.
+ ObjCParameter, // An ObjC method parameter type.
+ KNRTypeList, // K&R type definition list for formals.
+ TypeName, // Abstract declarator for types.
+ FunctionalCast, // Type in a C++ functional cast expression.
+ Member, // Struct/Union field.
+ Block, // Declaration within a block in a function.
+ ForInit, // Declaration within first part of a for loop.
+ SelectionInit, // Declaration within optional init stmt of if/switch.
+ Condition, // Condition declaration in a C++ if/switch/while/for.
+ TemplateParam, // Within a template parameter list.
+ CXXNew, // C++ new-expression.
+ CXXCatch, // C++ catch exception-declaration
+ ObjCCatch, // Objective-C catch exception-declaration
+ BlockLiteral, // Block literal declarator.
+ LambdaExpr, // Lambda-expression declarator.
+ LambdaExprParameter, // Lambda-expression parameter declarator.
+ ConversionId, // C++ conversion-type-id.
+ TrailingReturn, // C++11 trailing-type-specifier.
+ TrailingReturnVar, // C++11 trailing-type-specifier for variable.
+ TemplateArg, // Any template argument (in template argument list).
+ TemplateTypeArg, // Template type argument (in default argument).
+ AliasDecl, // C++11 alias-declaration.
+ AliasTemplate, // C++11 alias-declaration template.
+ RequiresExpr // C++2a requires-expression.
};
-
/// Information about one declarator, including the parsed type
/// information and the identifier.
///
@@ -1835,6 +1847,9 @@ private:
/// Indicates whether the InlineParams / InlineBindings storage has been used.
unsigned InlineStorageUsed : 1;
+ /// Indicates whether this declarator has an initializer.
+ unsigned HasInitializer : 1;
+
/// Attrs - Attributes.
ParsedAttributes Attrs;
@@ -1879,11 +1894,12 @@ public:
Declarator(const DeclSpec &ds, DeclaratorContext C)
: DS(ds), Range(ds.getSourceRange()), Context(C),
InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
- GroupingParens(false), FunctionDefinition(FDK_Declaration),
+ GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
+ FunctionDefinitionKind::Declaration)),
Redeclaration(false), Extension(false), ObjCIvar(false),
ObjCWeakProperty(false), InlineStorageUsed(false),
- Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr),
- TrailingRequiresClause(nullptr),
+ HasInitializer(false), Attrs(ds.getAttributePool().getFactory()),
+ AsmLabel(nullptr), TrailingRequiresClause(nullptr),
InventedTemplateParameterList(nullptr) {}
~Declarator() {
@@ -1919,10 +1935,10 @@ public:
DeclaratorContext getContext() const { return Context; }
bool isPrototypeContext() const {
- return (Context == DeclaratorContext::PrototypeContext ||
- Context == DeclaratorContext::ObjCParameterContext ||
- Context == DeclaratorContext::ObjCResultContext ||
- Context == DeclaratorContext::LambdaExprParameterContext);
+ return (Context == DeclaratorContext::Prototype ||
+ Context == DeclaratorContext::ObjCParameter ||
+ Context == DeclaratorContext::ObjCResult ||
+ Context == DeclaratorContext::LambdaExprParameter);
}
/// Get the source range that spans this declarator.
@@ -1966,6 +1982,7 @@ public:
Attrs.clear();
AsmLabel = nullptr;
InlineStorageUsed = false;
+ HasInitializer = false;
ObjCIvar = false;
ObjCWeakProperty = false;
CommaLoc = SourceLocation();
@@ -1977,35 +1994,35 @@ public:
/// parameter lists.
bool mayOmitIdentifier() const {
switch (Context) {
- case DeclaratorContext::FileContext:
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::MemberContext:
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
- case DeclaratorContext::ConditionContext:
+ case DeclaratorContext::File:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::Member:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
+ case DeclaratorContext::Condition:
return false;
- case DeclaratorContext::TypeNameContext:
- case DeclaratorContext::FunctionalCastContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TemplateArgContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::TrailingReturnVarContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::TypeName:
+ case DeclaratorContext::FunctionalCast:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TemplateArg:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::TrailingReturnVar:
+ case DeclaratorContext::RequiresExpr:
return true;
}
llvm_unreachable("unknown context kind!");
@@ -2016,35 +2033,35 @@ public:
/// typenames.
bool mayHaveIdentifier() const {
switch (Context) {
- case DeclaratorContext::FileContext:
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::MemberContext:
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
- case DeclaratorContext::ConditionContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::File:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::Member:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
+ case DeclaratorContext::Condition:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::RequiresExpr:
return true;
- case DeclaratorContext::TypeNameContext:
- case DeclaratorContext::FunctionalCastContext:
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TemplateArgContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::TrailingReturnVarContext:
+ case DeclaratorContext::TypeName:
+ case DeclaratorContext::FunctionalCast:
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TemplateArg:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::TrailingReturnVar:
return false;
}
llvm_unreachable("unknown context kind!");
@@ -2053,41 +2070,41 @@ public:
/// Return true if the context permits a C++17 decomposition declarator.
bool mayHaveDecompositionDeclarator() const {
switch (Context) {
- case DeclaratorContext::FileContext:
+ case DeclaratorContext::File:
// FIXME: It's not clear that the proposal meant to allow file-scope
// structured bindings, but it does.
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
- case DeclaratorContext::ConditionContext:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
+ case DeclaratorContext::Condition:
return true;
- case DeclaratorContext::MemberContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::Member:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::RequiresExpr:
// Maybe one day...
return false;
// These contexts don't allow any kind of non-abstract declarator.
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::TypeNameContext:
- case DeclaratorContext::FunctionalCastContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TemplateArgContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::TrailingReturnVarContext:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::TypeName:
+ case DeclaratorContext::FunctionalCast:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TemplateArg:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::TrailingReturnVar:
return false;
}
llvm_unreachable("unknown context kind!");
@@ -2102,7 +2119,7 @@ public:
return false;
if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
- Context != DeclaratorContext::FileContext)
+ Context != DeclaratorContext::File)
return false;
// Special names can't have direct initializers.
@@ -2110,40 +2127,40 @@ public:
return false;
switch (Context) {
- case DeclaratorContext::FileContext:
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
- case DeclaratorContext::TrailingReturnVarContext:
+ case DeclaratorContext::File:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
+ case DeclaratorContext::TrailingReturnVar:
return true;
- case DeclaratorContext::ConditionContext:
+ case DeclaratorContext::Condition:
// This may not be followed by a direct initializer, but it can't be a
// function declaration either, and we'd prefer to perform a tentative
// parse in order to produce the right diagnostic.
return true;
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::MemberContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::TypeNameContext:
- case DeclaratorContext::FunctionalCastContext: // FIXME
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TemplateArgContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::Member:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::TypeName:
+ case DeclaratorContext::FunctionalCast: // FIXME
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TemplateArg:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::RequiresExpr:
return false;
}
llvm_unreachable("unknown context kind!");
@@ -2337,35 +2354,35 @@ public:
return false;
switch (Context) {
- case DeclaratorContext::FileContext:
- case DeclaratorContext::MemberContext:
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
+ case DeclaratorContext::File:
+ case DeclaratorContext::Member:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
return true;
- case DeclaratorContext::ConditionContext:
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::TypeNameContext:
- case DeclaratorContext::FunctionalCastContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TemplateArgContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::TrailingReturnVarContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::Condition:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::TypeName:
+ case DeclaratorContext::FunctionalCast:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TemplateArg:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::TrailingReturnVar:
+ case DeclaratorContext::RequiresExpr:
return false;
}
llvm_unreachable("unknown context kind!");
@@ -2375,38 +2392,38 @@ public:
/// expression could appear.
bool isExpressionContext() const {
switch (Context) {
- case DeclaratorContext::FileContext:
- case DeclaratorContext::KNRTypeListContext:
- case DeclaratorContext::MemberContext:
+ case DeclaratorContext::File:
+ case DeclaratorContext::KNRTypeList:
+ case DeclaratorContext::Member:
// FIXME: sizeof(...) permits an expression.
- case DeclaratorContext::TypeNameContext:
-
- case DeclaratorContext::FunctionalCastContext:
- case DeclaratorContext::AliasDeclContext:
- case DeclaratorContext::AliasTemplateContext:
- case DeclaratorContext::PrototypeContext:
- case DeclaratorContext::LambdaExprParameterContext:
- case DeclaratorContext::ObjCParameterContext:
- case DeclaratorContext::ObjCResultContext:
- case DeclaratorContext::TemplateParamContext:
- case DeclaratorContext::CXXNewContext:
- case DeclaratorContext::CXXCatchContext:
- case DeclaratorContext::ObjCCatchContext:
- case DeclaratorContext::BlockLiteralContext:
- case DeclaratorContext::LambdaExprContext:
- case DeclaratorContext::ConversionIdContext:
- case DeclaratorContext::TrailingReturnContext:
- case DeclaratorContext::TrailingReturnVarContext:
- case DeclaratorContext::TemplateTypeArgContext:
- case DeclaratorContext::RequiresExprContext:
+ case DeclaratorContext::TypeName:
+
+ case DeclaratorContext::FunctionalCast:
+ case DeclaratorContext::AliasDecl:
+ case DeclaratorContext::AliasTemplate:
+ case DeclaratorContext::Prototype:
+ case DeclaratorContext::LambdaExprParameter:
+ case DeclaratorContext::ObjCParameter:
+ case DeclaratorContext::ObjCResult:
+ case DeclaratorContext::TemplateParam:
+ case DeclaratorContext::CXXNew:
+ case DeclaratorContext::CXXCatch:
+ case DeclaratorContext::ObjCCatch:
+ case DeclaratorContext::BlockLiteral:
+ case DeclaratorContext::LambdaExpr:
+ case DeclaratorContext::ConversionId:
+ case DeclaratorContext::TrailingReturn:
+ case DeclaratorContext::TrailingReturnVar:
+ case DeclaratorContext::TemplateTypeArg:
+ case DeclaratorContext::RequiresExpr:
return false;
- case DeclaratorContext::BlockContext:
- case DeclaratorContext::ForContext:
- case DeclaratorContext::InitStmtContext:
- case DeclaratorContext::ConditionContext:
- case DeclaratorContext::TemplateArgContext:
+ case DeclaratorContext::Block:
+ case DeclaratorContext::ForInit:
+ case DeclaratorContext::SelectionInit:
+ case DeclaratorContext::Condition:
+ case DeclaratorContext::TemplateArg:
return true;
}
@@ -2448,6 +2465,8 @@ public:
/// \brief Sets a trailing requires clause for this declarator.
void setTrailingRequiresClause(Expr *TRC) {
TrailingRequiresClause = TRC;
+
+ SetRangeEnd(TRC->getEndLoc());
}
/// \brief Sets a trailing requires clause for this declarator.
@@ -2551,20 +2570,23 @@ public:
void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
- FunctionDefinition = Val;
+ FunctionDefinition = static_cast<unsigned>(Val);
}
bool isFunctionDefinition() const {
- return getFunctionDefinitionKind() != FDK_Declaration;
+ return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
}
FunctionDefinitionKind getFunctionDefinitionKind() const {
return (FunctionDefinitionKind)FunctionDefinition;
}
+ void setHasInitializer(bool Val = true) { HasInitializer = Val; }
+ bool hasInitializer() const { return HasInitializer; }
+
/// Returns true if this declares a real member and not a friend.
bool isFirstDeclarationOfMember() {
- return getContext() == DeclaratorContext::MemberContext &&
+ return getContext() == DeclaratorContext::Member &&
!getDeclSpec().isFriendSpecified();
}
@@ -2586,8 +2608,7 @@ struct FieldDeclarator {
Declarator D;
Expr *BitfieldSize;
explicit FieldDeclarator(const DeclSpec &DS)
- : D(DS, DeclaratorContext::MemberContext),
- BitfieldSize(nullptr) {}
+ : D(DS, DeclaratorContext::Member), BitfieldSize(nullptr) {}
};
/// Represents a C++11 virt-specifier-seq.
diff --git a/contrib/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h b/contrib/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h
index 929db5dfce23..50abcc421d45 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h
@@ -57,21 +57,16 @@ public:
/// The target is the base class.
enum BaseNonce { Base };
- AccessedEntity(PartialDiagnostic::StorageAllocator &Allocator,
- MemberNonce _,
- CXXRecordDecl *NamingClass,
- DeclAccessPair FoundDecl,
- QualType BaseObjectType)
+ AccessedEntity(PartialDiagnostic::DiagStorageAllocator &Allocator,
+ MemberNonce _, CXXRecordDecl *NamingClass,
+ DeclAccessPair FoundDecl, QualType BaseObjectType)
: Access(FoundDecl.getAccess()), IsMember(true),
Target(FoundDecl.getDecl()), NamingClass(NamingClass),
- BaseObjectType(BaseObjectType), Diag(0, Allocator) {
- }
+ BaseObjectType(BaseObjectType), Diag(0, Allocator) {}
- AccessedEntity(PartialDiagnostic::StorageAllocator &Allocator,
- BaseNonce _,
- CXXRecordDecl *BaseClass,
- CXXRecordDecl *DerivedClass,
- AccessSpecifier Access)
+ AccessedEntity(PartialDiagnostic::DiagStorageAllocator &Allocator,
+ BaseNonce _, CXXRecordDecl *BaseClass,
+ CXXRecordDecl *DerivedClass, AccessSpecifier Access)
: Access(Access), IsMember(false), Target(BaseClass),
NamingClass(DerivedClass), Diag(0, Allocator) {}
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Designator.h b/contrib/llvm-project/clang/include/clang/Sema/Designator.h
index 05f661151263..84837bfeba5b 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Designator.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Designator.h
@@ -39,22 +39,24 @@ public:
FieldDesignator, ArrayDesignator, ArrayRangeDesignator
};
private:
+ Designator() {};
+
DesignatorKind Kind;
struct FieldDesignatorInfo {
const IdentifierInfo *II;
- unsigned DotLoc;
- unsigned NameLoc;
+ SourceLocation DotLoc;
+ SourceLocation NameLoc;
};
struct ArrayDesignatorInfo {
Expr *Index;
- unsigned LBracketLoc;
- mutable unsigned RBracketLoc;
+ SourceLocation LBracketLoc;
+ mutable SourceLocation RBracketLoc;
};
struct ArrayRangeDesignatorInfo {
Expr *Start, *End;
- unsigned LBracketLoc, EllipsisLoc;
- mutable unsigned RBracketLoc;
+ SourceLocation LBracketLoc, EllipsisLoc;
+ mutable SourceLocation RBracketLoc;
};
union {
@@ -77,12 +79,12 @@ public:
SourceLocation getDotLoc() const {
assert(isFieldDesignator() && "Invalid accessor");
- return SourceLocation::getFromRawEncoding(FieldInfo.DotLoc);
+ return FieldInfo.DotLoc;
}
SourceLocation getFieldLoc() const {
assert(isFieldDesignator() && "Invalid accessor");
- return SourceLocation::getFromRawEncoding(FieldInfo.NameLoc);
+ return FieldInfo.NameLoc;
}
Expr *getArrayIndex() const {
@@ -103,32 +105,33 @@ public:
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
- return SourceLocation::getFromRawEncoding(ArrayInfo.LBracketLoc);
+ return ArrayInfo.LBracketLoc;
else
- return SourceLocation::getFromRawEncoding(ArrayRangeInfo.LBracketLoc);
+ return ArrayRangeInfo.LBracketLoc;
}
SourceLocation getRBracketLoc() const {
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
- return SourceLocation::getFromRawEncoding(ArrayInfo.RBracketLoc);
+ return ArrayInfo.RBracketLoc;
else
- return SourceLocation::getFromRawEncoding(ArrayRangeInfo.RBracketLoc);
+ return ArrayRangeInfo.RBracketLoc;
}
SourceLocation getEllipsisLoc() const {
assert(isArrayRangeDesignator() && "Invalid accessor");
- return SourceLocation::getFromRawEncoding(ArrayRangeInfo.EllipsisLoc);
+ return ArrayRangeInfo.EllipsisLoc;
}
static Designator getField(const IdentifierInfo *II, SourceLocation DotLoc,
SourceLocation NameLoc) {
Designator D;
D.Kind = FieldDesignator;
+ new (&D.FieldInfo) FieldDesignatorInfo;
D.FieldInfo.II = II;
- D.FieldInfo.DotLoc = DotLoc.getRawEncoding();
- D.FieldInfo.NameLoc = NameLoc.getRawEncoding();
+ D.FieldInfo.DotLoc = DotLoc;
+ D.FieldInfo.NameLoc = NameLoc;
return D;
}
@@ -136,9 +139,10 @@ public:
SourceLocation LBracketLoc) {
Designator D;
D.Kind = ArrayDesignator;
+ new (&D.ArrayInfo) ArrayDesignatorInfo;
D.ArrayInfo.Index = Index;
- D.ArrayInfo.LBracketLoc = LBracketLoc.getRawEncoding();
- D.ArrayInfo.RBracketLoc = 0;
+ D.ArrayInfo.LBracketLoc = LBracketLoc;
+ D.ArrayInfo.RBracketLoc = SourceLocation();
return D;
}
@@ -148,11 +152,12 @@ public:
SourceLocation EllipsisLoc) {
Designator D;
D.Kind = ArrayRangeDesignator;
+ new (&D.ArrayRangeInfo) ArrayRangeDesignatorInfo;
D.ArrayRangeInfo.Start = Start;
D.ArrayRangeInfo.End = End;
- D.ArrayRangeInfo.LBracketLoc = LBracketLoc.getRawEncoding();
- D.ArrayRangeInfo.EllipsisLoc = EllipsisLoc.getRawEncoding();
- D.ArrayRangeInfo.RBracketLoc = 0;
+ D.ArrayRangeInfo.LBracketLoc = LBracketLoc;
+ D.ArrayRangeInfo.EllipsisLoc = EllipsisLoc;
+ D.ArrayRangeInfo.RBracketLoc = SourceLocation();
return D;
}
@@ -160,9 +165,9 @@ public:
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
- ArrayInfo.RBracketLoc = RBracketLoc.getRawEncoding();
+ ArrayInfo.RBracketLoc = RBracketLoc;
else
- ArrayRangeInfo.RBracketLoc = RBracketLoc.getRawEncoding();
+ ArrayRangeInfo.RBracketLoc = RBracketLoc;
}
/// ClearExprs - Null out any expression references, which prevents
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Initialization.h b/contrib/llvm-project/clang/include/clang/Sema/Initialization.h
index ca9e0a198cb9..dcdfa3c3cf64 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Initialization.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Initialization.h
@@ -55,6 +55,9 @@ public:
/// The entity being initialized is a function parameter.
EK_Parameter,
+ /// The entity being initialized is a non-type template parameter.
+ EK_TemplateParameter,
+
/// The entity being initialized is the result of a function call.
EK_Result,
@@ -145,7 +148,7 @@ private:
/// location of the 'return', 'throw', or 'new' keyword,
/// respectively. When Kind == EK_Temporary, the location where
/// the temporary is being created.
- unsigned Location;
+ SourceLocation Location;
/// Whether the entity being initialized may end up using the
/// named return value optimization (NRVO).
@@ -171,11 +174,12 @@ private:
IdentifierInfo *VarID;
/// The source location at which the capture occurs.
- unsigned Location;
+ SourceLocation Location;
};
union {
- /// When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
+ /// When Kind == EK_Variable, EK_Member, EK_Binding, or
+ /// EK_TemplateParameter, the variable, binding, or template parameter.
VD Variable;
/// When Kind == EK_RelatedResult, the ObjectiveC method where
@@ -205,7 +209,7 @@ private:
struct C Capture;
};
- InitializedEntity() = default;
+ InitializedEntity() {};
/// Create the initialization entity for a variable.
InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
@@ -217,7 +221,8 @@ private:
InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
bool NRVO = false)
: Kind(Kind), Type(Type) {
- LocAndNRVO.Location = Loc.getRawEncoding();
+ new (&LocAndNRVO) LN;
+ LocAndNRVO.Location = Loc;
LocAndNRVO.NRVO = NRVO;
}
@@ -234,8 +239,9 @@ private:
/// Create the initialization entity for a lambda capture.
InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
: Kind(EK_LambdaCapture), Type(FieldType) {
+ new (&Capture) C;
Capture.VarID = VarID;
- Capture.Location = Loc.getRawEncoding();
+ Capture.Location = Loc;
}
public:
@@ -281,6 +287,17 @@ public:
return Entity;
}
+ /// Create the initialization entity for a template parameter.
+ static InitializedEntity
+ InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param) {
+ InitializedEntity Entity;
+ Entity.Kind = EK_TemplateParameter;
+ Entity.Type = T;
+ Entity.Parent = nullptr;
+ Entity.Variable = {Param, false, false};
+ return Entity;
+ }
+
/// Create the initialization entity for the result of a function.
static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
QualType Type, bool NRVO) {
@@ -441,6 +458,10 @@ public:
getKind() == EK_Parameter_CF_Audited);
}
+ bool isParamOrTemplateParamKind() const {
+ return isParameterKind() || getKind() == EK_TemplateParameter;
+ }
+
/// Determine whether this initialization consumes the
/// parameter.
bool isParameterConsumed() const {
@@ -482,14 +503,14 @@ public:
/// the result of a function call.
SourceLocation getReturnLoc() const {
assert(getKind() == EK_Result && "No 'return' location!");
- return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
+ return LocAndNRVO.Location;
}
/// Determine the location of the 'throw' keyword when initializing
/// an exception object.
SourceLocation getThrowLoc() const {
assert(getKind() == EK_Exception && "No 'throw' location!");
- return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
+ return LocAndNRVO.Location;
}
/// If this is an array, vector, or complex number element, get the
@@ -518,7 +539,7 @@ public:
/// field from a captured variable in a lambda.
SourceLocation getCaptureLoc() const {
assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
- return SourceLocation::getFromRawEncoding(Capture.Location);
+ return Capture.Location;
}
void setParameterCFAudited() {
@@ -821,6 +842,9 @@ public:
/// Perform a qualification conversion, producing an lvalue.
SK_QualificationConversionLValue,
+ /// Perform a function reference conversion, see [dcl.init.ref]p4.
+ SK_FunctionReferenceConversion,
+
/// Perform a conversion adding _Atomic to a type.
SK_AtomicConversion,
@@ -1204,17 +1228,6 @@ public:
/// constructor.
bool isConstructorInitialization() const;
- /// Returns whether the last step in this initialization sequence is a
- /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
- ///
- /// If this function returns true, *isInitializerConstant will be set to
- /// describe whether *Initializer was a constant expression. If
- /// *isInitializerConstant is set to true, *ConstantValue will be set to the
- /// evaluated value of *Initializer.
- bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
- bool *isInitializerConstant,
- APValue *ConstantValue) const;
-
/// Add a new step in the initialization that resolves the address
/// of an overloaded function to a specific function declaration.
///
@@ -1269,6 +1282,10 @@ public:
void AddQualificationConversionStep(QualType Ty,
ExprValueKind Category);
+ /// Add a new step that performs a function reference conversion to the
+ /// given type.
+ void AddFunctionReferenceConversionStep(QualType Ty);
+
/// Add a new step that performs conversion from non-atomic to atomic
/// type.
void AddAtomicConversionStep(QualType Ty);
@@ -1336,10 +1353,6 @@ public:
/// from a zero constant.
void AddOCLZeroOpaqueTypeStep(QualType T);
- /// Add a step to initialize by zero types defined in the
- /// cl_intel_device_side_avc_motion_estimation OpenCL extension
- void AddOCLIntelSubgroupAVCZeroInitStep(QualType T);
-
/// Add steps to unwrap a initializer list for a reference around a
/// single element and rewrap it at the end.
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
diff --git a/contrib/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h b/contrib/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h
index e94dd5d46871..b54a6283d640 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h
@@ -153,8 +153,6 @@ public:
/// Retrieve the module that corresponds to the given module ID.
Module *getModule(unsigned ID) override;
- bool DeclIsFromPCHWithObjectFile(const Decl *D) override;
-
/// Perform layout on the given record.
///
/// This routine allows the external AST source to provide an specific
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Overload.h b/contrib/llvm-project/clang/include/clang/Sema/Overload.h
index 5023525aa41b..5be6a618711c 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Overload.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Overload.h
@@ -160,6 +160,9 @@ class Sema;
/// Vector conversions
ICK_Vector_Conversion,
+ /// Arm SVE Vector conversions
+ ICK_SVE_Vector_Conversion,
+
/// A vector splat from an arithmetic type
ICK_Vector_Splat,
@@ -1048,6 +1051,9 @@ class Sema;
void destroyCandidates();
+ /// Whether diagnostics should be deferred.
+ bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
+
public:
OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
OperatorRewriteInfo RewriteInfo = {})
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Ownership.h b/contrib/llvm-project/clang/include/clang/Sema/Ownership.h
index 7c7b1d35c9fd..5c7b010ed736 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Ownership.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Ownership.h
@@ -133,14 +133,13 @@ namespace llvm {
namespace clang {
// Basic
- class DiagnosticBuilder;
-
- // Determines whether the low bit of the result pointer for the
- // given UID is always zero. If so, ActionResult will use that bit
- // for it's "invalid" flag.
- template<class Ptr>
- struct IsResultPtrLowBitFree {
- static const bool value = false;
+class StreamingDiagnostic;
+
+// Determines whether the low bit of the result pointer for the
+// given UID is always zero. If so, ActionResult will use that bit
+// for it's "invalid" flag.
+template <class Ptr> struct IsResultPtrLowBitFree {
+ static const bool value = false;
};
/// ActionResult - This structure is used while parsing/acting on
@@ -280,8 +279,12 @@ namespace clang {
inline StmtResult StmtError() { return StmtResult(true); }
inline TypeResult TypeError() { return TypeResult(true); }
- inline ExprResult ExprError(const DiagnosticBuilder&) { return ExprError(); }
- inline StmtResult StmtError(const DiagnosticBuilder&) { return StmtError(); }
+ inline ExprResult ExprError(const StreamingDiagnostic &) {
+ return ExprError();
+ }
+ inline StmtResult StmtError(const StreamingDiagnostic &) {
+ return StmtError();
+ }
inline ExprResult ExprEmpty() { return ExprResult(false); }
inline StmtResult StmtEmpty() { return StmtResult(false); }
diff --git a/contrib/llvm-project/clang/include/clang/Sema/ParsedAttr.h b/contrib/llvm-project/clang/include/clang/Sema/ParsedAttr.h
index 21e030fe5134..43c21faaece9 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/ParsedAttr.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/ParsedAttr.h
@@ -606,6 +606,10 @@ public:
return LangAS::opencl_constant;
case ParsedAttr::AT_OpenCLGlobalAddressSpace:
return LangAS::opencl_global;
+ case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
+ return LangAS::opencl_global_device;
+ case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
+ return LangAS::opencl_global_host;
case ParsedAttr::AT_OpenCLLocalAddressSpace:
return LangAS::opencl_local;
case ParsedAttr::AT_OpenCLPrivateAddressSpace:
@@ -1019,7 +1023,8 @@ enum AttributeArgumentNType {
AANT_ArgumentIntOrBool,
AANT_ArgumentIntegerConstant,
AANT_ArgumentString,
- AANT_ArgumentIdentifier
+ AANT_ArgumentIdentifier,
+ AANT_ArgumentConstantExpr,
};
/// These constants match the enumerated choices of
@@ -1040,32 +1045,43 @@ enum AttributeDeclKind {
ExpectedFunctionWithProtoType,
};
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const ParsedAttr &At) {
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const ParsedAttr &At) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(At.getAttrName()),
DiagnosticsEngine::ak_identifierinfo);
return DB;
}
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const ParsedAttr &At) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(At.getAttrName()),
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const ParsedAttr *At) {
+ DB.AddTaggedVal(reinterpret_cast<intptr_t>(At->getAttrName()),
DiagnosticsEngine::ak_identifierinfo);
- return PD;
+ return DB;
}
-inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
- const ParsedAttr *At) {
- DB.AddTaggedVal(reinterpret_cast<intptr_t>(At->getAttrName()),
+/// AttributeCommonInfo has a non-explicit constructor which takes an
+/// SourceRange as its only argument, this constructor has many uses so making
+/// it explicit is hard. This constructor causes ambiguity with
+/// DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, SourceRange R).
+/// We use SFINAE to disable any conversion and remove any ambiguity.
+template <typename ACI,
+ typename std::enable_if_t<
+ std::is_same<ACI, AttributeCommonInfo>::value, int> = 0>
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const ACI &CI) {
+ DB.AddTaggedVal(reinterpret_cast<intptr_t>(CI.getAttrName()),
DiagnosticsEngine::ak_identifierinfo);
return DB;
}
-inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
- const ParsedAttr *At) {
- PD.AddTaggedVal(reinterpret_cast<intptr_t>(At->getAttrName()),
+template <typename ACI,
+ typename std::enable_if_t<
+ std::is_same<ACI, AttributeCommonInfo>::value, int> = 0>
+inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
+ const ACI* CI) {
+ DB.AddTaggedVal(reinterpret_cast<intptr_t>(CI->getAttrName()),
DiagnosticsEngine::ak_identifierinfo);
- return PD;
+ return DB;
}
} // namespace clang
diff --git a/contrib/llvm-project/clang/include/clang/Sema/ScopeInfo.h b/contrib/llvm-project/clang/include/clang/Sema/ScopeInfo.h
index f0f9cb9e40ae..8ec74cafeeca 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/ScopeInfo.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/ScopeInfo.h
@@ -127,6 +127,9 @@ public:
/// Whether there is a fallthrough statement in this function.
bool HasFallthroughStmt : 1;
+ /// Whether this function uses constrained floating point intrinsics
+ bool UsesFPIntrin : 1;
+
/// Whether we make reference to a declaration that could be
/// unavailable.
bool HasPotentialAvailabilityViolations : 1;
@@ -369,7 +372,8 @@ public:
: Kind(SK_Function), HasBranchProtectedScope(false),
HasBranchIntoScope(false), HasIndirectGoto(false),
HasDroppedStmt(false), HasOMPDeclareReductionCombiner(false),
- HasFallthroughStmt(false), HasPotentialAvailabilityViolations(false),
+ HasFallthroughStmt(false), UsesFPIntrin(false),
+ HasPotentialAvailabilityViolations(false),
ObjCShouldCallSuper(false), ObjCIsDesignatedInit(false),
ObjCWarnForNoDesignatedInitChain(false), ObjCIsSecondaryInit(false),
ObjCWarnForNoInitDelegation(false), NeedsCoroutineSuspends(true),
@@ -431,6 +435,10 @@ public:
HasFallthroughStmt = true;
}
+ void setUsesFPIntrin() {
+ UsesFPIntrin = true;
+ }
+
void setHasCXXTry(SourceLocation TryLoc) {
setHasBranchProtectedScope();
FirstCXXTryLoc = TryLoc;
@@ -841,6 +849,11 @@ public:
/// Source range covering the explicit template parameter list (if it exists).
SourceRange ExplicitTemplateParamsRange;
+ /// The requires-clause immediately following the explicit template parameter
+ /// list, if any. (Note that there may be another requires-clause included as
+ /// part of the lambda-declarator.)
+ ExprResult RequiresClause;
+
/// If this is a generic lambda, and the template parameter
/// list has been created (from the TemplateParams) then store
/// a reference to it (cache it to avoid reconstructing it).
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Sema.h b/contrib/llvm-project/clang/include/clang/Sema/Sema.h
index 1b5e389501c3..2530a2776373 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Sema.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Sema.h
@@ -58,8 +58,8 @@
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
-#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
@@ -455,11 +455,7 @@ public:
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
-
- void Act(SourceLocation PragmaLocation,
- PragmaClangSectionAction Action,
- StringLiteral* Name);
- };
+ };
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
@@ -477,6 +473,108 @@ public:
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
+ // #pragma pack and align.
+ class AlignPackInfo {
+ public:
+ // `Native` represents default align mode, which may vary based on the
+ // platform.
+ enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
+
+ // #pragma pack info constructor
+ AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
+ : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
+ assert(Num == PackNumber && "The pack number has been truncated.");
+ }
+
+ // #pragma align info constructor
+ AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
+ : PackAttr(false), AlignMode(M),
+ PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
+
+ explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
+
+ AlignPackInfo() : AlignPackInfo(Native, false) {}
+
+ // When a AlignPackInfo itself cannot be used, this returns an 32-bit
+ // integer encoding for it. This should only be passed to
+ // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
+ static uint32_t getRawEncoding(const AlignPackInfo &Info) {
+ std::uint32_t Encoding{};
+ if (Info.IsXLStack())
+ Encoding |= IsXLMask;
+
+ Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
+
+ if (Info.IsPackAttr())
+ Encoding |= PackAttrMask;
+
+ Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
+
+ return Encoding;
+ }
+
+ static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
+ bool IsXL = static_cast<bool>(Encoding & IsXLMask);
+ AlignPackInfo::Mode M =
+ static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
+ int PackNumber = (Encoding & PackNumMask) >> 4;
+
+ if (Encoding & PackAttrMask)
+ return AlignPackInfo(M, PackNumber, IsXL);
+
+ return AlignPackInfo(M, IsXL);
+ }
+
+ bool IsPackAttr() const { return PackAttr; }
+
+ bool IsAlignAttr() const { return !PackAttr; }
+
+ Mode getAlignMode() const { return AlignMode; }
+
+ unsigned getPackNumber() const { return PackNumber; }
+
+ bool IsPackSet() const {
+ // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
+ // attriute on a decl.
+ return PackNumber != UninitPackVal && PackNumber != 0;
+ }
+
+ bool IsXLStack() const { return XLStack; }
+
+ bool operator==(const AlignPackInfo &Info) const {
+ return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
+ std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
+ Info.XLStack);
+ }
+
+ bool operator!=(const AlignPackInfo &Info) const {
+ return !(*this == Info);
+ }
+
+ private:
+ /// \brief True if this is a pragma pack attribute,
+ /// not a pragma align attribute.
+ bool PackAttr;
+
+ /// \brief The alignment mode that is in effect.
+ Mode AlignMode;
+
+ /// \brief The pack number of the stack.
+ unsigned char PackNumber;
+
+ /// \brief True if it is a XL #pragma align/pack stack.
+ bool XLStack;
+
+ /// \brief Uninitialized pack value.
+ static constexpr unsigned char UninitPackVal = -1;
+
+ // Masks to encode and decode an AlignPackInfo.
+ static constexpr uint32_t IsXLMask{0x0000'0001};
+ static constexpr uint32_t AlignModeMask{0x0000'0006};
+ static constexpr uint32_t PackAttrMask{0x00000'0008};
+ static constexpr uint32_t PackNumMask{0x0000'01F0};
+ };
+
template<typename ValueType>
struct PragmaStack {
struct Slot {
@@ -569,17 +667,14 @@ public:
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispMode> VtorDispStack;
- // #pragma pack.
- // Sentinel to represent when the stack is set to mac68k alignment.
- static const unsigned kMac68kAlignmentSentinel = ~0U;
- PragmaStack<unsigned> PackStack;
- // The current #pragma pack values and locations at each #include.
- struct PackIncludeState {
- unsigned CurrentValue;
+ PragmaStack<AlignPackInfo> AlignPackStack;
+ // The current #pragma align/pack values and locations at each #include.
+ struct AlignPackIncludeState {
+ AlignPackInfo CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
- SmallVector<PackIncludeState, 8> PackIncludeStack;
+ SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
@@ -587,13 +682,13 @@ public:
PragmaStack<StringLiteral *> CodeSegStack;
// This stack tracks the current state of Sema.CurFPFeatures.
- PragmaStack<unsigned> FpPragmaStack;
+ PragmaStack<FPOptionsOverride> FpPragmaStack;
FPOptionsOverride CurFPFeatureOverrides() {
FPOptionsOverride result;
if (!FpPragmaStack.hasValue()) {
result = FPOptionsOverride();
} else {
- result = FPOptionsOverride(FpPragmaStack.CurrentValue);
+ result = FpPragmaStack.CurrentValue;
}
return result;
}
@@ -1076,10 +1171,6 @@ public:
/// have been declared.
bool GlobalNewDeleteDeclared;
- /// A flag to indicate that we're in a context that permits abstract
- /// references to fields. This is really a
- bool AllowAbstractFieldReference;
-
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
@@ -1138,9 +1229,6 @@ public:
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
- /// Whether we are in a decltype expression.
- bool IsDecltype;
-
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
@@ -1405,12 +1493,12 @@ public:
S.CurFPFeatures = OldFPFeaturesState;
S.FpPragmaStack.CurrentValue = OldOverrides;
}
- unsigned getOverrides() { return OldOverrides; }
+ FPOptionsOverride getOverrides() { return OldOverrides; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
- unsigned OldOverrides;
+ FPOptionsOverride OldOverrides;
};
void addImplicitTypedef(StringRef Name, QualType T);
@@ -1462,41 +1550,41 @@ public:
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
- /// class that emits diagnostics. SemaDiagnosticBuilder is
+ /// class that emits diagnostics. ImmediateDiagBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
- class SemaDiagnosticBuilder : public DiagnosticBuilder {
+ class ImmediateDiagBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
- SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
- : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
+ ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
+ : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
+ ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
+ : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
- // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
+ // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
// in that case anwyay.
- SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
+ ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
- ~SemaDiagnosticBuilder() {
+ ~ImmediateDiagBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
- // Otherwise, we need to emit the diagnostic. First flush the underlying
- // DiagnosticBuilder data, and clear the diagnostic builder itself so it
- // won't emit the diagnostic in its own destructor.
+ // Otherwise, we need to emit the diagnostic. First clear the diagnostic
+ // builder itself so it won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
- FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
@@ -1504,27 +1592,161 @@ public:
}
/// Teach operator<< to produce an object of the correct type.
- template<typename T>
- friend const SemaDiagnosticBuilder &operator<<(
- const SemaDiagnosticBuilder &Diag, const T &Value) {
+ template <typename T>
+ friend const ImmediateDiagBuilder &
+ operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
+
+ // It is necessary to limit this to rvalue reference to avoid calling this
+ // function with a bitfield lvalue argument since non-const reference to
+ // bitfield is not allowed.
+ template <typename T, typename = typename std::enable_if<
+ !std::is_lvalue_reference<T>::value>::type>
+ const ImmediateDiagBuilder &operator<<(T &&V) const {
+ const DiagnosticBuilder &BaseDiag = *this;
+ BaseDiag << std::move(V);
+ return *this;
+ }
};
+ /// A generic diagnostic builder for errors which may or may not be deferred.
+ ///
+ /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
+ /// which are not allowed to appear inside __device__ functions and are
+ /// allowed to appear in __host__ __device__ functions only if the host+device
+ /// function is never codegen'ed.
+ ///
+ /// To handle this, we use the notion of "deferred diagnostics", where we
+ /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
+ ///
+ /// This class lets you emit either a regular diagnostic, a deferred
+ /// diagnostic, or no diagnostic at all, according to an argument you pass to
+ /// its constructor, thus simplifying the process of creating these "maybe
+ /// deferred" diagnostics.
+ class SemaDiagnosticBuilder {
+ public:
+ enum Kind {
+ /// Emit no diagnostics.
+ K_Nop,
+ /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
+ K_Immediate,
+ /// Emit the diagnostic immediately, and, if it's a warning or error, also
+ /// emit a call stack showing how this function can be reached by an a
+ /// priori known-emitted function.
+ K_ImmediateWithCallStack,
+ /// Create a deferred diagnostic, which is emitted only if the function
+ /// it's attached to is codegen'ed. Also emit a call stack as with
+ /// K_ImmediateWithCallStack.
+ K_Deferred
+ };
+
+ SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
+ FunctionDecl *Fn, Sema &S);
+ SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
+ SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
+ ~SemaDiagnosticBuilder();
+
+ bool isImmediate() const { return ImmediateDiag.hasValue(); }
+
+ /// Convertible to bool: True if we immediately emitted an error, false if
+ /// we didn't emit an error or we created a deferred error.
+ ///
+ /// Example usage:
+ ///
+ /// if (SemaDiagnosticBuilder(...) << foo << bar)
+ /// return ExprError();
+ ///
+ /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
+ /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
+ operator bool() const { return isImmediate(); }
+
+ template <typename T>
+ friend const SemaDiagnosticBuilder &
+ operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
+ if (Diag.ImmediateDiag.hasValue())
+ *Diag.ImmediateDiag << Value;
+ else if (Diag.PartialDiagId.hasValue())
+ Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
+ << Value;
+ return Diag;
+ }
+
+ // It is necessary to limit this to rvalue reference to avoid calling this
+ // function with a bitfield lvalue argument since non-const reference to
+ // bitfield is not allowed.
+ template <typename T, typename = typename std::enable_if<
+ !std::is_lvalue_reference<T>::value>::type>
+ const SemaDiagnosticBuilder &operator<<(T &&V) const {
+ if (ImmediateDiag.hasValue())
+ *ImmediateDiag << std::move(V);
+ else if (PartialDiagId.hasValue())
+ S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
+ return *this;
+ }
+
+ friend const SemaDiagnosticBuilder &
+ operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
+ if (Diag.ImmediateDiag.hasValue())
+ PD.Emit(*Diag.ImmediateDiag);
+ else if (Diag.PartialDiagId.hasValue())
+ Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
+ return Diag;
+ }
+
+ void AddFixItHint(const FixItHint &Hint) const {
+ if (ImmediateDiag.hasValue())
+ ImmediateDiag->AddFixItHint(Hint);
+ else if (PartialDiagId.hasValue())
+ S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
+ }
+
+ friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
+ return ExprError();
+ }
+ friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
+ return StmtError();
+ }
+ operator ExprResult() const { return ExprError(); }
+ operator StmtResult() const { return StmtError(); }
+ operator TypeResult() const { return TypeError(); }
+ operator DeclResult() const { return DeclResult(true); }
+ operator MemInitResult() const { return MemInitResult(true); }
+
+ private:
+ Sema &S;
+ SourceLocation Loc;
+ unsigned DiagID;
+ FunctionDecl *Fn;
+ bool ShowCallStack;
+
+ // 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;
+ };
+
+ /// Is the last error level diagnostic immediate. This is used to determined
+ /// whether the next info diagnostic should be immediate.
+ bool IsLastErrorImmediate = true;
+
/// Emit a diagnostic.
- SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
- DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
- return SemaDiagnosticBuilder(DB, *this, DiagID);
- }
+ SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
+ bool DeferHint = false);
/// Emit a partial diagnostic.
- SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
+ SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
+ bool DeferHint = false);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
+ /// Whether uncompilable error has occurred. This includes error happens
+ /// in deferred diagnostics.
+ bool hasUncompilableErrorOccurred() const;
+
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
@@ -1834,6 +2056,16 @@ public:
}
};
+ /// Do a check to make sure \p Name looks like a legal argument for the
+ /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
+ /// is invalid for the given declaration.
+ ///
+ /// \p AL is used to provide caret diagnostics in case of a malformed name.
+ ///
+ /// \returns true if the name is a valid swift name for \p D, false otherwise.
+ bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
+ const ParsedAttr &AL, bool IsAsync);
+
/// A derivative of BoundTypeDiagnoser for which the diagnostic's type
/// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
/// For example, a diagnostic with no other parameters would generally have
@@ -1912,6 +2144,12 @@ public:
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
+ // When loading a non-modular PCH files, this is used to restore module
+ // visibility.
+ void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
+ VisibleModules.setVisible(Mod, ImportLoc);
+ }
+
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return D->isUnconditionallyVisible() || isVisibleSlow(D);
@@ -2000,6 +2238,16 @@ public:
return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
}
+ /// Get the type of expression E, triggering instantiation to complete the
+ /// type if necessary -- that is, if the expression refers to a templated
+ /// static data member of incomplete array type.
+ ///
+ /// May still return an incomplete type if instantiation was not possible or
+ /// if the type is incomplete for a different reason. Use
+ /// RequireCompleteExprType instead if a diagnostic is expected for an
+ /// incomplete expression type.
+ QualType getCompletedType(Expr *E);
+
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
TypeDiagnoser &Diagnoser);
@@ -2111,9 +2359,11 @@ public:
/// resolved. ActOnNameClassifiedAsDependentNonType should be called to
/// convert the result to an expression.
NC_DependentNonType,
- /// The name was classified as a non-type, and an expression representing
- /// that name has been formed.
- NC_ContextIndependentExpr,
+ /// The name was classified as an overload set, and an expression
+ /// representing that overload set has been formed.
+ /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
+ /// expression referencing the overload set.
+ NC_OverloadSet,
/// The name was classified as a template whose specializations are types.
NC_TypeTemplate,
/// The name was classified as a variable template name.
@@ -2150,8 +2400,8 @@ public:
return NameClassification(NC_Unknown);
}
- static NameClassification ContextIndependentExpr(ExprResult E) {
- NameClassification Result(NC_ContextIndependentExpr);
+ static NameClassification OverloadSet(ExprResult E) {
+ NameClassification Result(NC_OverloadSet);
Result.Expr = E;
return Result;
}
@@ -2203,7 +2453,7 @@ public:
NameClassificationKind getKind() const { return Kind; }
ExprResult getExpression() const {
- assert(Kind == NC_ContextIndependentExpr);
+ assert(Kind == NC_OverloadSet);
return Expr;
}
@@ -2283,6 +2533,8 @@ public:
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken);
+ /// Act on the result of classifying a name as an overload set.
+ ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
@@ -2519,6 +2771,7 @@ public:
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
+ ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
@@ -2658,12 +2911,6 @@ public:
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
- /// We've found a use of a template specialization that would select a
- /// partial specialization. Check that the partial specialization is visible,
- /// and diagnose if not.
- void checkPartialSpecializationVisibility(SourceLocation Loc,
- NamedDecl *Spec);
-
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
@@ -3049,6 +3296,8 @@ public:
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
+ SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
+ StringRef Name);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
@@ -3060,6 +3309,9 @@ public:
Decl *D, const WebAssemblyImportNameAttr &AL);
WebAssemblyImportModuleAttr *mergeImportModuleAttr(
Decl *D, const WebAssemblyImportModuleAttr &AL);
+ EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
+ EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
+ const EnforceTCBLeafAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
@@ -3178,6 +3430,8 @@ public:
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
+ bool IsStringInit(Expr *Init, const ArrayType *AT);
+
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
@@ -3203,14 +3457,15 @@ public:
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
- CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
+ CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
- APValue &Value, CCEKind CCE);
+ APValue &Value, CCEKind CCE,
+ NamedDecl *Dest = nullptr);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
@@ -3516,6 +3771,9 @@ public:
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
+ void AddOverloadedCallCandidates(
+ LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
+ ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
// An enum used to represent the different possible results of building a
// range-based for loop.
@@ -3546,6 +3804,12 @@ public:
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
+ ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
+ NestedNameSpecifierLoc NNSLoc,
+ DeclarationNameInfo DNI,
+ const UnresolvedSetImpl &Fns,
+ bool PerformADL = true);
+
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
@@ -3571,11 +3835,11 @@ public:
SourceLocation RLoc,
Expr *Base,Expr *Idx);
- ExprResult
- BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
- SourceLocation LParenLoc,
- MultiExprArg Args,
- SourceLocation RParenLoc);
+ ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
+ SourceLocation LParenLoc,
+ MultiExprArg Args,
+ SourceLocation RParenLoc,
+ bool AllowRecovery = false);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
@@ -3723,7 +3987,7 @@ public:
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
- LOLR_StringTemplate
+ LOLR_StringTemplatePack,
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
@@ -3797,6 +4061,7 @@ public:
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupBuiltin(LookupResult &R);
+ void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
@@ -3812,7 +4077,6 @@ public:
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
- QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
@@ -3831,12 +4095,11 @@ public:
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
- LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
- ArrayRef<QualType> ArgTys,
- bool AllowRaw,
- bool AllowTemplate,
- bool AllowStringTemplate,
- bool DiagnoseMissing);
+ LiteralOperatorLookupResult
+ LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
+ bool AllowRaw, bool AllowTemplate,
+ bool AllowStringTemplate, bool DiagnoseMissing,
+ StringLiteral *StringLit = nullptr);
bool isKnownName(StringRef name);
/// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
@@ -4313,6 +4576,7 @@ public:
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
+ void ActOnAfterCompoundStatementLeadingPragmas();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
@@ -4367,16 +4631,17 @@ public:
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
- Stmt *InitStmt,
- ConditionResult Cond, Stmt *ThenVal,
- SourceLocation ElseLoc, Stmt *ElseVal);
+ SourceLocation LParenLoc, Stmt *InitStmt,
+ ConditionResult Cond, SourceLocation RParenLoc,
+ Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
- Stmt *InitStmt,
- ConditionResult Cond, Stmt *ThenVal,
- SourceLocation ElseLoc, Stmt *ElseVal);
+ SourceLocation LParenLoc, Stmt *InitStmt,
+ ConditionResult Cond, SourceLocation RParenLoc,
+ Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
- Stmt *InitStmt,
- ConditionResult Cond);
+ SourceLocation LParenLoc, Stmt *InitStmt,
+ ConditionResult Cond,
+ SourceLocation RParenLoc);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
@@ -4791,6 +5056,8 @@ public:
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
+ bool DiagnoseDependentMemberLookup(LookupResult &R);
+
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
@@ -4842,11 +5109,10 @@ public:
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
- ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
- SourceLocation TemplateKWLoc,
- LookupResult &R,
- const TemplateArgumentListInfo *TemplateArgs,
- const Scope *S);
+ ExprResult BuildPossibleImplicitMemberExpr(
+ const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
+ const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
+ UnresolvedLookupExpr *AsULE = nullptr);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
@@ -4889,15 +5155,6 @@ public:
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
- ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand);
- ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E);
- ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
- SourceLocation LParen,
- SourceLocation RParen, ParsedType Ty);
- ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
- SourceLocation LParen,
- SourceLocation RParen, Expr *E);
-
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
@@ -5093,7 +5350,8 @@ public:
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
- bool IsExecConfig = false);
+ bool IsExecConfig = false,
+ bool AllowRecovery = false);
enum class AtomicArgumentOrder { API, AST };
ExprResult
BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
@@ -5159,6 +5417,8 @@ public:
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
+ void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
+ UnresolvedSetImpl &Functions);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
@@ -5548,45 +5808,6 @@ public:
}
};
- /// Determine what sort of exception specification a defaulted
- /// copy constructor of a class will have.
- ImplicitExceptionSpecification
- ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
- CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification a defaulted
- /// default constructor of a class will have, and whether the parameter
- /// will be const.
- ImplicitExceptionSpecification
- ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification a defaulted
- /// copy assignment operator of a class will have, and whether the
- /// parameter will be const.
- ImplicitExceptionSpecification
- ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification a defaulted move
- /// constructor of a class will have.
- ImplicitExceptionSpecification
- ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification a defaulted move
- /// assignment operator of a class will have.
- ImplicitExceptionSpecification
- ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification a defaulted
- /// destructor of a class will have.
- ImplicitExceptionSpecification
- ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
-
- /// Determine what sort of exception specification an inheriting
- /// constructor of a class will have.
- ImplicitExceptionSpecification
- ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
- CXXConstructorDecl *CD);
-
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
@@ -5839,11 +6060,12 @@ public:
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
- ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
+ ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
- ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
+ ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
+ SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
@@ -6336,7 +6558,7 @@ public:
/// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
- Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
+ Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
@@ -6385,7 +6607,8 @@ public:
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
- SourceLocation RAngleLoc);
+ SourceLocation RAngleLoc,
+ ExprResult RequiresClause);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
@@ -6437,7 +6660,8 @@ public:
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
- getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
+ getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
+ CallingConv CC);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
@@ -6582,14 +6806,6 @@ public:
DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
bool First = true);
- /// \brief Emit diagnostics explaining why a constraint expression was deemed
- /// unsatisfied because it was ill-formed.
- void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
- StringRef Diagnostic);
-
- void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
- SourceLocation New);
-
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
@@ -7107,9 +7323,9 @@ public:
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
- NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
- bool AllowFunctionTemplates = true,
- bool AllowDependent = true);
+ static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
+ bool AllowFunctionTemplates = true,
+ bool AllowDependent = true);
enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
/// Whether and why a template name is required in this lookup.
@@ -7220,6 +7436,8 @@ public:
NonTypeTemplateParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
+ bool RequireStructuralType(QualType T, SourceLocation Loc);
+
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
@@ -7327,11 +7545,17 @@ public:
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
+ /// Get the specialization of the given variable template corresponding to
+ /// the specified argument list, or a null-but-valid result if the arguments
+ /// are dependent.
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
+ /// Form a reference to the specialization of the given variable template
+ /// corresponding to the specified argument list, or a null-but-valid result
+ /// if the arguments are dependent.
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
@@ -7745,11 +7969,17 @@ public:
/// Lambda expression.
UPPC_Lambda,
- /// Block expression,
+ /// Block expression.
UPPC_Block,
- /// A type constraint,
- UPPC_TypeConstraint
+ /// A type constraint.
+ UPPC_TypeConstraint,
+
+ // A requirement in a requires-expression.
+ UPPC_Requirement,
+
+ // A requires-clause.
+ UPPC_RequiresClause,
};
/// Diagnose unexpanded parameter packs.
@@ -7788,6 +8018,15 @@ public:
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
+ /// If the given requirees-expression contains an unexpanded reference to one
+ /// of its own parameter packs, diagnose the error.
+ ///
+ /// \param RE The requiress-expression that is being checked for unexpanded
+ /// parameter packs.
+ ///
+ /// \returns true if an error occurred, false otherwise.
+ bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
+
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
@@ -9072,6 +9311,8 @@ public:
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
+ void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
+
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
@@ -9127,7 +9368,7 @@ public:
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
- SourceLocation PointOfInstantiation, void *InsertPos,
+ SourceLocation PointOfInstantiation,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
@@ -9142,10 +9383,6 @@ public:
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
- VarDecl *getVarTemplateSpecialization(
- VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
- const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
-
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
@@ -9596,14 +9833,14 @@ public:
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
- enum class PragmaPackDiagnoseKind {
+ enum class PragmaAlignPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
- void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
- SourceLocation IncludeLoc);
- void DiagnoseUnterminatedPragmaPack();
+ void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
+ SourceLocation IncludeLoc);
+ void DiagnoseUnterminatedPragmaAlignPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
@@ -9632,9 +9869,8 @@ public:
PSK_CodeSeg,
};
- bool UnifySection(StringRef SectionName,
- int SectionFlags,
- DeclaratorDecl *TheDecl);
+ bool UnifySection(StringRef SectionName, int SectionFlags,
+ NamedDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
@@ -9719,7 +9955,11 @@ public:
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
- /// Called to set rounding mode for floating point operations.
+ /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
+ void ActOnPragmaFPExceptions(SourceLocation Loc,
+ LangOptions::FPExceptionModeKind);
+
+ /// Called to set constant rounding mode for floating point operations.
void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
/// Called to set exception behavior for floating point operations.
@@ -9732,9 +9972,6 @@ public:
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
- /// FreePackedContext - Deallocate and null out PackContext.
- void FreePackedContext();
-
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
@@ -9811,6 +10048,10 @@ public:
/// declaration.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
+ /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
+ void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
+ StringRef Annot, MutableArrayRef<Expr *> Args);
+
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
@@ -9938,7 +10179,7 @@ public:
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
- unsigned DeclareTargetNestingLevel = 0;
+ SmallVector<SourceLocation, 4> DeclareTargetNesting;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
@@ -9989,26 +10230,40 @@ private:
OMPDeclareVariantScope(OMPTraitInfo &TI);
};
+ /// Return the OMPTraitInfo for the surrounding scope, if any.
+ OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
+ return OMPDeclareVariantScopes.empty() ? nullptr
+ : OMPDeclareVariantScopes.back().TI;
+ }
+
/// The current `omp begin/end declare variant` scopes.
SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
+ /// The current `omp begin/end assumes` scopes.
+ SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
+
+ /// All `omp assumes` we encountered so far.
+ SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
+
+public:
/// The declarator \p D defines a function in the scope \p S which is nested
/// in an `omp begin/end declare variant` scope. In this method we create a
/// declaration for \p D and rename \p D according to the OpenMP context
- /// selector of the surrounding scope.
- FunctionDecl *
- ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
- Declarator &D);
+ /// selector of the surrounding scope. Return all base functions in \p Bases.
+ void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
+ Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
+ SmallVectorImpl<FunctionDecl *> &Bases);
- /// Register \p FD as specialization of \p BaseFD in the current `omp
- /// begin/end declare variant` scope.
+ /// Register \p D as specialization of all base functions in \p Bases in the
+ /// current `omp begin/end declare variant` scope.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
- FunctionDecl *FD, FunctionDecl *BaseFD);
+ Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
-public:
+ /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
+ void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
- /// Can we exit a scope at the moment.
- bool isInOpenMPDeclareVariantScope() {
+ /// Can we exit an OpenMP declare variant scope at the moment.
+ bool isInOpenMPDeclareVariantScope() const {
return !OMPDeclareVariantScopes.empty();
}
@@ -10124,6 +10379,22 @@ public:
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
+
+ /// Called on well-formed '#pragma omp [begin] assume[s]'.
+ void ActOnOpenMPAssumesDirective(SourceLocation Loc,
+ OpenMPDirectiveKind DKind,
+ ArrayRef<StringRef> Assumptions,
+ bool SkippedClauses);
+
+ /// Check if there is an active global `omp begin assumes` directive.
+ bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
+
+ /// Check if there is an active global `omp assumes` directive.
+ bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
+
+ /// Called on well-formed '#pragma omp end assumes'.
+ void ActOnOpenMPEndAssumesDirective();
+
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
@@ -10160,19 +10431,18 @@ public:
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
- OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
+ DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
+ Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
- void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
- Scope *S, QualType MapperType,
- SourceLocation StartLoc,
- DeclarationName VN);
- /// Called at the end of '#pragma omp declare mapper'.
- DeclGroupPtrTy
- ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
- ArrayRef<OMPClause *> ClauseList);
+ ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
+ QualType MapperType,
+ SourceLocation StartLoc,
+ DeclarationName VN);
+ bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
+ const ValueDecl *getOpenMPDeclareMapperVarName() const;
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
@@ -10199,7 +10469,7 @@ public:
SourceLocation Loc);
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
- return DeclareTargetNestingLevel > 0;
+ return !DeclareTargetNesting.empty();
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
@@ -10718,7 +10988,9 @@ public:
DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
- SourceLocation ExtraModifierLoc);
+ SourceLocation ExtraModifierLoc,
+ ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
+ ArrayRef<SourceLocation> MotionModifiersLoc);
/// Called on well-formed 'inclusive' clause.
OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
@@ -10855,15 +11127,20 @@ public:
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
- ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
- DeclarationNameInfo &MapperId,
- const OMPVarListLocTy &Locs,
+ ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
+ ArrayRef<SourceLocation> MotionModifiersLoc,
+ CXXScopeSpec &MapperIdScopeSpec,
+ DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
+ ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
- OMPClause *ActOnOpenMPFromClause(
- ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
- DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
- ArrayRef<Expr *> UnresolvedMappers = llvm::None);
+ OMPClause *
+ ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
+ ArrayRef<SourceLocation> MotionModifiersLoc,
+ CXXScopeSpec &MapperIdScopeSpec,
+ DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
+ ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
+ ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
@@ -11189,10 +11466,6 @@ public:
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
- AssignmentAction Action,
- bool AllowExplicit,
- ImplicitConversionSequence& ICS);
- ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
@@ -11306,6 +11579,8 @@ public:
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign);
+ bool isValidSveBitcast(QualType srcType, QualType destType);
+
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
@@ -11552,9 +11827,17 @@ public:
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
- virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
- virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
- virtual ~VerifyICEDiagnoser() { }
+ virtual SemaDiagnosticBuilder
+ diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
+ virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
+ SourceLocation Loc) = 0;
+ virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
+ virtual ~VerifyICEDiagnoser() {}
+ };
+
+ enum AllowFoldKind {
+ NoFold,
+ AllowFold,
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
@@ -11562,12 +11845,17 @@ public:
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
- bool AllowFold = true);
+ AllowFoldKind CanFold = NoFold);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
- bool AllowFold = true);
+ AllowFoldKind CanFold = NoFold);
ExprResult VerifyIntegerConstantExpression(Expr *E,
- llvm::APSInt *Result = nullptr);
+ llvm::APSInt *Result = nullptr,
+ AllowFoldKind CanFold = NoFold);
+ ExprResult VerifyIntegerConstantExpression(Expr *E,
+ AllowFoldKind CanFold = NoFold) {
+ return VerifyIntegerConstantExpression(E, nullptr, CanFold);
+ }
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
@@ -11619,84 +11907,11 @@ public:
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
- /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
- /// deferred.
- ///
- /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
- /// which are not allowed to appear inside __device__ functions and are
- /// allowed to appear in __host__ __device__ functions only if the host+device
- /// function is never codegen'ed.
- ///
- /// To handle this, we use the notion of "deferred diagnostics", where we
- /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
- ///
- /// This class lets you emit either a regular diagnostic, a deferred
- /// diagnostic, or no diagnostic at all, according to an argument you pass to
- /// its constructor, thus simplifying the process of creating these "maybe
- /// deferred" diagnostics.
- class DeviceDiagBuilder {
- public:
- enum Kind {
- /// Emit no diagnostics.
- K_Nop,
- /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
- K_Immediate,
- /// Emit the diagnostic immediately, and, if it's a warning or error, also
- /// emit a call stack showing how this function can be reached by an a
- /// priori known-emitted function.
- K_ImmediateWithCallStack,
- /// Create a deferred diagnostic, which is emitted only if the function
- /// it's attached to is codegen'ed. Also emit a call stack as with
- /// K_ImmediateWithCallStack.
- K_Deferred
- };
-
- DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
- FunctionDecl *Fn, Sema &S);
- DeviceDiagBuilder(DeviceDiagBuilder &&D);
- DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
- ~DeviceDiagBuilder();
-
- /// Convertible to bool: True if we immediately emitted an error, false if
- /// we didn't emit an error or we created a deferred error.
- ///
- /// Example usage:
- ///
- /// if (DeviceDiagBuilder(...) << foo << bar)
- /// return ExprError();
- ///
- /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
- /// want to use these instead of creating a DeviceDiagBuilder yourself.
- operator bool() const { return ImmediateDiag.hasValue(); }
-
- template <typename T>
- friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
- const T &Value) {
- if (Diag.ImmediateDiag.hasValue())
- *Diag.ImmediateDiag << Value;
- else if (Diag.PartialDiagId.hasValue())
- Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
- << Value;
- return Diag;
- }
-
- private:
- Sema &S;
- SourceLocation Loc;
- unsigned DiagID;
- FunctionDecl *Fn;
- bool ShowCallStack;
-
- // Invariant: At most one of these Optionals has a value.
- // FIXME: Switch these to a Variant once that exists.
- llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
- llvm::Optional<unsigned> PartialDiagId;
- };
-
- /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
- /// is "used as device code".
+ /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
+ /// context is "used as device code".
///
- /// - If CurContext is a __host__ function, does not emit any diagnostics.
+ /// - If CurContext is a __host__ function, does not emit any diagnostics
+ /// unless \p EmitOnBothSides is true.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
@@ -11709,15 +11924,16 @@ public:
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
- DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
+ SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
+ unsigned DiagID);
- /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
- /// is "used as host code".
+ /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
+ /// context is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
- DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
+ SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
- /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
+ /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
@@ -11732,9 +11948,10 @@ public:
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
- DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
+ SemaDiagnosticBuilder
+ diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
- /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
+ /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// - If CurContext is a `declare target` function or it is known that the
@@ -11747,13 +11964,20 @@ public:
/// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
- DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
-
- DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
+ SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
+ unsigned DiagID, FunctionDecl *FD);
+
+ SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
+ FunctionDecl *FD = nullptr);
+ SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
+ const PartialDiagnostic &PD,
+ FunctionDecl *FD = nullptr) {
+ return targetDiag(Loc, PD.getDiagID(), FD) << PD;
+ }
/// Check if the expression is allowed to be used in expressions for the
/// offloading devices.
- void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc);
+ void checkDeviceDecl(ValueDecl *D, SourceLocation Loc);
enum CUDAFunctionTarget {
CFT_Device,
@@ -12156,7 +12380,6 @@ private:
bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
ArrayRef<int> ArgNums);
- bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum);
bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
ArrayRef<int> ArgNums);
@@ -12170,6 +12393,7 @@ private:
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
+ bool SemaBuiltinComplex(CallExpr *TheCall);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
@@ -12208,6 +12432,9 @@ private:
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
+ bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc);
+
+ bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
// Matrix builtin handling.
ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
@@ -12265,6 +12492,8 @@ private:
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
+ void CheckFreeArguments(const CallExpr *E);
+
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
@@ -12302,6 +12531,8 @@ private:
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
+ void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee);
+
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
@@ -12357,6 +12588,7 @@ private:
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
+ IdentifierInfo *Ident__Nullable_result = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
@@ -12380,6 +12612,7 @@ public:
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
+ bool isCFError(RecordDecl *D);
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
@@ -12521,7 +12754,7 @@ public:
ConstructorDestructor,
BuiltinFunction
};
- /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
+ /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurLexicalContext is a kernel function or it is known that the
@@ -12539,7 +12772,8 @@ public:
/// if (!S.Context.getTargetInfo().hasFloat128Type() &&
/// S.getLangOpts().SYCLIsDevice)
/// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
- DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
+ SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
+ unsigned DiagID);
/// Check whether we're allowed to call Callee from the current context.
///
@@ -12617,6 +12851,13 @@ struct LateParsedTemplate {
/// The template function declaration to be late parsed.
Decl *D;
};
+
+template <>
+void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
+ PragmaMsStackAction Action,
+ llvm::StringRef StackSlotLabel,
+ AlignPackInfo Value);
+
} // end namespace clang
namespace llvm {
@@ -12636,7 +12877,7 @@ template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
- FDL.Loc.getRawEncoding());
+ FDL.Loc.getHashValue());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
diff --git a/contrib/llvm-project/clang/include/clang/Sema/Template.h b/contrib/llvm-project/clang/include/clang/Sema/Template.h
index 91d175fdd050..0dcaf565591b 100644
--- a/contrib/llvm-project/clang/include/clang/Sema/Template.h
+++ b/contrib/llvm-project/clang/include/clang/Sema/Template.h
@@ -600,7 +600,7 @@ enum class TemplateSubstitutionKind : char {
TagDecl *NewDecl);
Decl *VisitVarTemplateSpecializationDecl(
- VarTemplateDecl *VarTemplate, VarDecl *FromVar, void *InsertPos,
+ VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentListInfo &TemplateArgsInfo,
ArrayRef<TemplateArgument> Converted,
VarTemplateSpecializationDecl *PrevDecl = nullptr);
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h b/contrib/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h
index c6f9f1d1a08f..e9fc202f8d1d 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h
@@ -681,8 +681,8 @@ public:
MODULAR_CODEGEN_DECLS = 60,
- /// Record code for \#pragma pack options.
- PACK_PRAGMA_OPTIONS = 61,
+ /// Record code for \#pragma align/pack options.
+ ALIGN_PACK_PRAGMA_OPTIONS = 61,
/// The stack of open #ifs/#ifdefs recorded in a preamble.
PP_CONDITIONAL_STACK = 62,
@@ -1080,6 +1080,9 @@ public:
// \brief SVE types with auto numeration
#define SVE_TYPE(Name, Id, SingletonId) PREDEF_TYPE_##Id##_ID,
#include "clang/Basic/AArch64SVEACLETypes.def"
+ // \brief PowerPC MMA types with auto numeration
+#define PPC_VECTOR_TYPE(Name, Id, Size) PREDEF_TYPE_##Id##_ID,
+#include "clang/Basic/PPCTypes.def"
};
/// The number of predefined type IDs that are reserved for
@@ -1281,6 +1284,9 @@ public:
/// A MSGuidDecl record.
DECL_MS_GUID,
+ /// A TemplateParamObjectDecl record.
+ DECL_TEMPLATE_PARAM_OBJECT,
+
/// A VarDecl record.
DECL_VAR,
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ASTReader.h b/contrib/llvm-project/clang/include/clang/Serialization/ASTReader.h
index a80366f0ee04..d0d2a68114c7 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ASTReader.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ASTReader.h
@@ -23,8 +23,10 @@
#include "clang/Lex/ExternalPreprocessorSource.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/PreprocessingRecord.h"
+#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
+#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ContinuousRangeMap.h"
#include "clang/Serialization/ModuleFile.h"
@@ -440,6 +442,9 @@ private:
/// imported from. For non-module AST types it should be invalid.
SourceLocation CurrentImportLoc;
+ /// The module kind that is currently deserializing.
+ Optional<ModuleKind> CurrentDeserializingModuleKind;
+
/// The global module index, if loaded.
std::unique_ptr<GlobalModuleIndex> GlobalIndex;
@@ -858,10 +863,10 @@ private:
SourceLocation PointersToMembersPragmaLocation;
/// The pragma float_control state.
- Optional<unsigned> FpPragmaCurrentValue;
+ Optional<FPOptionsOverride> FpPragmaCurrentValue;
SourceLocation FpPragmaCurrentLocation;
struct FpPragmaStackEntry {
- unsigned Value;
+ FPOptionsOverride Value;
SourceLocation Location;
SourceLocation PushLocation;
StringRef SlotLabel;
@@ -869,17 +874,17 @@ private:
llvm::SmallVector<FpPragmaStackEntry, 2> FpPragmaStack;
llvm::SmallVector<std::string, 2> FpPragmaStrings;
- /// The pragma pack state.
- Optional<unsigned> PragmaPackCurrentValue;
- SourceLocation PragmaPackCurrentLocation;
- struct PragmaPackStackEntry {
- unsigned Value;
+ /// The pragma align/pack state.
+ Optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue;
+ SourceLocation PragmaAlignPackCurrentLocation;
+ struct PragmaAlignPackStackEntry {
+ Sema::AlignPackInfo Value;
SourceLocation Location;
SourceLocation PushLocation;
StringRef SlotLabel;
};
- llvm::SmallVector<PragmaPackStackEntry, 2> PragmaPackStack;
- llvm::SmallVector<std::string, 2> PragmaPackStrings;
+ llvm::SmallVector<PragmaAlignPackStackEntry, 2> PragmaAlignPackStack;
+ llvm::SmallVector<std::string, 2> PragmaAlignPackStrings;
/// The OpenCL extension settings.
OpenCLOptions OpenCLExtensions;
@@ -900,8 +905,9 @@ private:
/// Delete expressions to analyze at the end of translation unit.
SmallVector<uint64_t, 8> DelayedDeleteExprs;
- // A list of late parsed template function data.
- SmallVector<uint64_t, 1> LateParsedTemplates;
+ // A list of late parsed template function data with their module files.
+ SmallVector<std::pair<ModuleFile *, SmallVector<uint64_t, 1>>, 4>
+ LateParsedTemplates;
/// The IDs of all decls to be checked for deferred diags.
///
@@ -929,8 +935,8 @@ private:
std::string isysroot;
/// Whether to disable the normal validation performed on precompiled
- /// headers when they are loaded.
- bool DisableValidation;
+ /// headers and module files when they are loaded.
+ DisableValidationForModuleKind DisableValidationKind;
/// Whether to accept an AST file with compiler errors.
bool AllowASTWithCompilerErrors;
@@ -1213,6 +1219,8 @@ private:
llvm::DenseMap<const Decl *, bool> DefinitionSource;
+ bool shouldDisableValidationForFile(const serialization::ModuleFile &M) const;
+
/// Reads a statement from the specified cursor.
Stmt *ReadStmtFromStream(ModuleFile &F);
@@ -1449,8 +1457,6 @@ private:
void Error(StringRef Msg) const;
void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
- void Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
- unsigned Select) const;
void Error(llvm::Error &&Err) const;
public:
@@ -1473,9 +1479,9 @@ public:
/// user. This is only used with relocatable PCH files. If non-NULL,
/// a relocatable PCH file will use the default path "/".
///
- /// \param DisableValidation If true, the AST reader will suppress most
+ /// \param DisableValidationKind If set, the AST reader will suppress most
/// of its regular consistency checking, allowing the use of precompiled
- /// headers that cannot be determined to be compatible.
+ /// headers and module files that cannot be determined to be compatible.
///
/// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
/// AST file the was created out of an AST with compiler errors,
@@ -1496,7 +1502,9 @@ public:
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
- StringRef isysroot = "", bool DisableValidation = false,
+ StringRef isysroot = "",
+ DisableValidationForModuleKind DisableValidationKind =
+ DisableValidationForModuleKind::None,
bool AllowASTWithCompilerErrors = false,
bool AllowConfigurationMismatch = false,
bool ValidateSystemInputs = false,
@@ -2085,8 +2093,6 @@ public:
/// Note: overrides method in ExternalASTSource
Module *getModule(unsigned ID) override;
- bool DeclIsFromPCHWithObjectFile(const Decl *D) override;
-
/// Retrieve the module file with a given local ID within the specified
/// ModuleFile.
ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
@@ -2120,6 +2126,11 @@ public:
/// Read the contents of a CXXCtorInitializer array.
CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
+ /// Read a AlignPackInfo from raw form.
+ Sema::AlignPackInfo ReadAlignPackInfo(uint32_t Raw) const {
+ return Sema::AlignPackInfo::getFromRawEncoding(Raw);
+ }
+
/// Read a source location from raw form and return it in its
/// originating module file's source location space.
SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h b/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h
index 7248e6fa6c21..b85609bf4e05 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h
@@ -24,6 +24,7 @@
namespace clang {
class OMPTraitInfo;
+class OMPChildren;
/// An object for streaming information from a record.
class ASTRecordReader
@@ -266,6 +267,9 @@ public:
/// Read an OpenMP clause, advancing Idx.
OMPClause *readOMPClause();
+ /// Read an OpenMP children, advancing Idx.
+ void readOMPChildren(OMPChildren *Data);
+
/// Read a source location, advancing Idx.
SourceLocation readSourceLocation() {
return Reader->ReadSourceLocation(*F, Record, Idx);
@@ -277,7 +281,7 @@ public:
}
/// Read an arbitrary constant value, advancing Idx.
- APValue readAPValue();
+ // APValue readAPValue(); (inherited)
/// Read an integral value, advancing Idx.
// llvm::APInt readAPInt(); (inherited)
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h b/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h
index 491207c9de90..0dc69bd3f3bd 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h
@@ -55,13 +55,14 @@ class ASTRecordWriter
public:
/// Construct a ASTRecordWriter that uses the default encoding scheme.
- ASTRecordWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
- : Writer(&Writer), Record(&Record) {}
+ ASTRecordWriter(ASTWriter &W, ASTWriter::RecordDataImpl &Record)
+ : DataStreamBasicWriter(W.getASTContext()), Writer(&W), Record(&Record) {}
/// Construct a ASTRecordWriter that uses the same encoding scheme as another
/// ASTRecordWriter.
ASTRecordWriter(ASTRecordWriter &Parent, ASTWriter::RecordDataImpl &Record)
- : Writer(Parent.Writer), Record(&Record) {}
+ : DataStreamBasicWriter(Parent.getASTContext()), Writer(Parent.Writer),
+ Record(&Record) {}
/// Copying an ASTRecordWriter is almost certainly a bug.
ASTRecordWriter(const ASTRecordWriter &) = delete;
@@ -165,7 +166,7 @@ public:
void AddAPFloat(const llvm::APFloat &Value);
/// Emit an APvalue.
- void AddAPValue(const APValue &Value);
+ void AddAPValue(const APValue &Value) { writeAPValue(Value); }
/// Emit a reference to an identifier.
void AddIdentifierRef(const IdentifierInfo *II) {
@@ -266,11 +267,17 @@ public:
void AddCXXDefinitionData(const CXXRecordDecl *D);
+ /// Emit information about the initializer of a VarDecl.
+ void AddVarDeclInit(const VarDecl *VD);
+
/// Write an OMPTraitInfo object.
void writeOMPTraitInfo(const OMPTraitInfo *TI);
void writeOMPClause(OMPClause *C);
+ /// Writes data related to the OpenMP directives.
+ void writeOMPChildren(OMPChildren *Data);
+
/// Emit a string.
void AddString(StringRef Str) {
return Writer->AddString(Str, *Record);
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ASTWriter.h b/contrib/llvm-project/clang/include/clang/Serialization/ASTWriter.h
index 7a6664af65d8..12073a38a77a 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ASTWriter.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ASTWriter.h
@@ -19,6 +19,7 @@
#include "clang/AST/Type.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
+#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaConsumer.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ASTDeserializationListener.h"
@@ -555,6 +556,11 @@ public:
bool IncludeTimestamps = true);
~ASTWriter() override;
+ ASTContext &getASTContext() const {
+ assert(Context && "requested AST context when not writing AST");
+ return *Context;
+ }
+
const LangOptions &getLangOpts() const;
/// Get a timestamp for output into the AST file. The actual timestamp
@@ -584,6 +590,10 @@ public:
/// Emit a token.
void AddToken(const Token &Tok, RecordDataImpl &Record);
+ /// Emit a AlignPackInfo.
+ void AddAlignPackInfo(const Sema::AlignPackInfo &Info,
+ RecordDataImpl &Record);
+
/// Emit a source location.
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ModuleFile.h b/contrib/llvm-project/clang/include/clang/Serialization/ModuleFile.h
index cec29da69372..a641a26661ae 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ModuleFile.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ModuleFile.h
@@ -67,13 +67,13 @@ class InputFile {
OutOfDate = 2,
NotFound = 3
};
- llvm::PointerIntPair<const FileEntry *, 2, unsigned> Val;
+ llvm::PointerIntPair<const FileEntryRef::MapEntry *, 2, unsigned> Val;
public:
InputFile() = default;
- InputFile(const FileEntry *File,
- bool isOverridden = false, bool isOutOfDate = false) {
+ InputFile(FileEntryRef File, bool isOverridden = false,
+ bool isOutOfDate = false) {
assert(!(isOverridden && isOutOfDate) &&
"an overridden cannot be out-of-date");
unsigned intVal = 0;
@@ -81,7 +81,7 @@ public:
intVal = Overridden;
else if (isOutOfDate)
intVal = OutOfDate;
- Val.setPointerAndInt(File, intVal);
+ Val.setPointerAndInt(&File.getMapEntry(), intVal);
}
static InputFile getNotFound() {
@@ -90,7 +90,11 @@ public:
return File;
}
- const FileEntry *getFile() const { return Val.getPointer(); }
+ OptionalFileEntryRefDegradesToFileEntryPtr getFile() const {
+ if (auto *P = Val.getPointer())
+ return FileEntryRef(*P);
+ return None;
+ }
bool isOverridden() const { return Val.getInt() == Overridden; }
bool isOutOfDate() const { return Val.getInt() == OutOfDate; }
bool isNotFound() const { return Val.getInt() == NotFound; }
@@ -155,14 +159,11 @@ public:
/// Whether timestamps are included in this module file.
bool HasTimestamps = false;
- /// Whether the PCH has a corresponding object file.
- bool PCHHasObjectFile = false;
-
/// Whether the top-level module has been read from the AST file.
bool DidReadTopLevelSubmodule = false;
/// The file entry for the module file.
- const FileEntry *File = nullptr;
+ OptionalFileEntryRefDegradesToFileEntryPtr File;
/// The signature of the module file, which may be used instead of the size
/// and modification time to identify this particular file.
diff --git a/contrib/llvm-project/clang/include/clang/Serialization/ModuleManager.h b/contrib/llvm-project/clang/include/clang/Serialization/ModuleManager.h
index 15ddb9875ff1..7081eedad4b4 100644
--- a/contrib/llvm-project/clang/include/clang/Serialization/ModuleManager.h
+++ b/contrib/llvm-project/clang/include/clang/Serialization/ModuleManager.h
@@ -307,10 +307,8 @@ public:
/// \returns True if a file exists but does not meet the size/
/// modification time criteria, false if the file is either available and
/// suitable, or is missing.
- bool lookupModuleFile(StringRef FileName,
- off_t ExpectedSize,
- time_t ExpectedModTime,
- const FileEntry *&File);
+ bool lookupModuleFile(StringRef FileName, off_t ExpectedSize,
+ time_t ExpectedModTime, Optional<FileEntryRef> &File);
/// View the graphviz representation of the module graph.
void viewGraph();
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index cbd925400328..444b00d73f0b 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -349,6 +349,8 @@ let ParentPackage = APIModeling in {
def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
HelpText<"Improve modeling of the C standard library functions">,
+ // Uninitialized value check is a mandatory dependency. This Checker asserts
+ // that arguments are always initialized.
Dependencies<[CallAndMessageModeling]>,
CheckerOptions<[
CmdLineOption<Boolean,
@@ -538,7 +540,7 @@ def StdCLibraryFunctionArgsChecker : Checker<"StdCLibraryFunctionArgs">,
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
Dependencies<[StdCLibraryFunctionsChecker]>,
- WeakDependencies<[NonNullParamChecker]>,
+ WeakDependencies<[CallAndMessageChecker, NonNullParamChecker, StreamChecker]>,
Documentation<NotDocumented>;
} // end "alpha.unix"
@@ -1476,8 +1478,8 @@ def LiveVariablesDumper : Checker<"DumpLiveVars">,
HelpText<"Print results of live variable analysis">,
Documentation<NotDocumented>;
-def LiveStatementsDumper : Checker<"DumpLiveStmts">,
- HelpText<"Print results of live statement analysis">,
+def LiveExpressionsDumper : Checker<"DumpLiveExprs">,
+ HelpText<"Print results of live expression analysis">,
Documentation<NotDocumented>;
def CFGViewer : Checker<"ViewCFG">,
@@ -1654,6 +1656,10 @@ def NoUncountedMemberChecker : Checker<"NoUncountedMemberChecker">,
HelpText<"Check for no uncounted member variables.">,
Documentation<HasDocumentation>;
+def UncountedLambdaCapturesChecker : Checker<"UncountedLambdaCapturesChecker">,
+ HelpText<"Check uncounted lambda captures.">,
+ Documentation<HasDocumentation>;
+
} // end webkit
let ParentPackage = WebKitAlpha in {
@@ -1662,4 +1668,8 @@ def UncountedCallArgsChecker : Checker<"UncountedCallArgsChecker">,
HelpText<"Check uncounted call arguments.">,
Documentation<HasDocumentation>;
+def UncountedLocalVarsChecker : Checker<"UncountedLocalVarsChecker">,
+ HelpText<"Check uncounted local variables.">,
+ Documentation<HasDocumentation>;
+
} // end alpha.webkit
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
index d2df24a6e21b..ccf35e0a81ec 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -14,6 +14,7 @@
#ifndef LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
#define LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
+#include "clang/Analysis/PathDiagnostic.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/Optional.h"
@@ -177,23 +178,23 @@ public:
/// description in a formatted manner. If \p MinLineWidth is set to 0, no line
/// breaks are introduced for the description.
///
- /// Format, depending whether the option name's length is less then
- /// \p OptionWidth:
+ /// Format, depending whether the option name's length is less than
+ /// \p EntryWidth:
///
/// <padding>EntryName<padding>Description
/// <---------padding--------->Description
/// <---------padding--------->Description
///
- /// <padding>VeryVeryLongOptionName
+ /// <padding>VeryVeryLongEntryName
/// <---------padding--------->Description
/// <---------padding--------->Description
- /// ^~~~~~~~ InitialPad
- /// ^~~~~~~~~~~~~~~~~~~~~~~~~~ EntryWidth
+ /// ^~~~~~~~~InitialPad
+ /// ^~~~~~~~~~~~~~~~~~EntryWidth
/// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MinLineWidth
- static void printFormattedEntry(
- llvm::raw_ostream &Out,
- std::pair<StringRef, StringRef> EntryDescPair,
- size_t EntryWidth, size_t InitialPad, size_t MinLineWidth = 0);
+ static void printFormattedEntry(llvm::raw_ostream &Out,
+ std::pair<StringRef, StringRef> EntryDescPair,
+ size_t InitialPad, size_t EntryWidth,
+ size_t MinLineWidth = 0);
/// Pairs of checker/package name and enable/disable.
std::vector<std::pair<std::string, bool>> CheckersAndPackages;
@@ -255,11 +256,10 @@ public:
unsigned NoRetryExhausted : 1;
/// Emit analyzer warnings as errors.
- unsigned AnalyzerWerror : 1;
+ bool AnalyzerWerror : 1;
/// The inlining stack depth limit.
- // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
- unsigned InlineMaxStackDepth = 5;
+ unsigned InlineMaxStackDepth;
/// The mode of function selection used during inlining.
AnalysisInliningMode InliningMode = NoRedundancy;
@@ -390,6 +390,16 @@ public:
///
/// \sa CXXMemberInliningMode
bool mayInlineCXXMemberFunction(CXXInlineableMemberKind K) const;
+
+ ento::PathDiagnosticConsumerOptions getDiagOpts() const {
+ return {FullCompilerInvocation,
+ ShouldDisplayMacroExpansions,
+ ShouldSerializeStats,
+ ShouldWriteStableReportFilename,
+ AnalyzerWerror,
+ ShouldApplyFixIts,
+ ShouldDisplayCheckerNameForText};
+ }
};
using AnalyzerOptionsRef = IntrusiveRefCntPtr<AnalyzerOptions>;
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
index 365b1ff1bfe3..58a88f452ed9 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -53,7 +53,7 @@ public:
/// Note that this function does *not* get run on the very last node
/// of the report, as the PathDiagnosticPiece associated with the
/// last node should be unique.
- /// Use {@code getEndPath} to customize the note associated with the report
+ /// Use \ref getEndPath to customize the note associated with the report
/// end instead.
///
/// The last parameter can be used to register a new visitor with the given
@@ -373,7 +373,7 @@ public:
class FalsePositiveRefutationBRVisitor final : public BugReporterVisitor {
private:
/// Holds the constraints in a given path
- ConstraintRangeTy Constraints;
+ ConstraintMap Constraints;
public:
FalsePositiveRefutationBRVisitor();
@@ -390,7 +390,6 @@ public:
bool OverwriteConstraintsOnExistingSyms);
};
-
/// The visitor detects NoteTags and displays the event notes they contain.
class TagVisitor : public BugReporterVisitor {
public:
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/IssueHash.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/IssueHash.h
deleted file mode 100644
index 38d5f847fc29..000000000000
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/IssueHash.h
+++ /dev/null
@@ -1,50 +0,0 @@
-//===---------- IssueHash.h - Generate identification hashes ----*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-#ifndef LLVM_CLANG_STATICANALYZER_CORE_ISSUE_HASH_H
-#define LLVM_CLANG_STATICANALYZER_CORE_ISSUE_HASH_H
-
-#include "llvm/ADT/SmallString.h"
-
-namespace clang {
-class Decl;
-class SourceManager;
-class FullSourceLoc;
-class LangOptions;
-
-/// Get an MD5 hash to help identify bugs.
-///
-/// This function returns a hash that helps identify bugs within a source file.
-/// This identification can be utilized to diff diagnostic results on different
-/// snapshots of a projects, or maintain a database of suppressed diagnotics.
-///
-/// The hash contains the normalized text of the location associated with the
-/// diagnostic. Normalization means removing the whitespaces. The associated
-/// location is the either the last location of a diagnostic path or a uniqueing
-/// location. The bugtype and the name of the checker is also part of the hash.
-/// The last component is the string representation of the enclosing declaration
-/// of the associated location.
-///
-/// In case a new hash is introduced, the old one should still be maintained for
-/// a while. One should not introduce a new hash for every change, it is
-/// possible to introduce experimental hashes that may change in the future.
-/// Such hashes should be marked as experimental using a comment in the plist
-/// files.
-llvm::SmallString<32> GetIssueHash(const SourceManager &SM,
- FullSourceLoc &IssueLoc,
- llvm::StringRef CheckerName,
- llvm::StringRef BugType, const Decl *D,
- const LangOptions &LangOpts);
-
-/// Get the string representation of issue hash. See GetIssueHash() for
-/// more information.
-std::string GetIssueString(const SourceManager &SM, FullSourceLoc &IssueLoc,
- llvm::StringRef CheckerName, llvm::StringRef BugType,
- const Decl *D, const LangOptions &LangOpts);
-} // namespace clang
-
-#endif
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
index 8601966c91e5..f40f88eb32ff 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
@@ -13,6 +13,8 @@
#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHDIAGNOSTICCONSUMERS_H
#define LLVM_CLANG_STATICANALYZER_CORE_PATHDIAGNOSTICCONSUMERS_H
+#include "clang/Analysis/PathDiagnostic.h"
+
#include <string>
#include <vector>
@@ -30,8 +32,9 @@ class PathDiagnosticConsumer;
typedef std::vector<PathDiagnosticConsumer*> PathDiagnosticConsumers;
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
- void CREATEFN(AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C, \
- const std::string &Prefix, const Preprocessor &PP, \
+ void CREATEFN(PathDiagnosticConsumerOptions Diagopts, \
+ PathDiagnosticConsumers &C, const std::string &Prefix, \
+ const Preprocessor &PP, \
const cross_tu::CrossTranslationUnitContext &CTU);
#include "clang/StaticAnalyzer/Core/Analyses.def"
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
index a001c0dc7030..142b1ab11750 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -79,11 +79,11 @@ public:
};
class PointerToMemberData : public llvm::FoldingSetNode {
- const DeclaratorDecl *D;
+ const NamedDecl *D;
llvm::ImmutableList<const CXXBaseSpecifier *> L;
public:
- PointerToMemberData(const DeclaratorDecl *D,
+ PointerToMemberData(const NamedDecl *D,
llvm::ImmutableList<const CXXBaseSpecifier *> L)
: D(D), L(L) {}
@@ -92,11 +92,11 @@ public:
iterator begin() const { return L.begin(); }
iterator end() const { return L.end(); }
- static void Profile(llvm::FoldingSetNodeID& ID, const DeclaratorDecl *D,
+ static void Profile(llvm::FoldingSetNodeID &ID, const NamedDecl *D,
llvm::ImmutableList<const CXXBaseSpecifier *> L);
- void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, D, L); }
- const DeclaratorDecl *getDeclaratorDecl() const {return D;}
+ void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, D, L); }
+ const NamedDecl *getDeclaratorDecl() const { return D; }
llvm::ImmutableList<const CXXBaseSpecifier *> getCXXBaseList() const {
return L;
@@ -236,9 +236,9 @@ public:
const LazyCompoundValData *getLazyCompoundValData(const StoreRef &store,
const TypedValueRegion *region);
- const PointerToMemberData *getPointerToMemberData(
- const DeclaratorDecl *DD,
- llvm::ImmutableList<const CXXBaseSpecifier *> L);
+ const PointerToMemberData *
+ getPointerToMemberData(const NamedDecl *ND,
+ llvm::ImmutableList<const CXXBaseSpecifier *> L);
llvm::ImmutableList<SVal> getEmptySValList() {
return SValListFactory.getEmptyList();
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index a2a98c558a4b..060fff1a7407 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -225,7 +225,7 @@ public:
/// Returns the expression whose value will be the result of this call.
/// May be null.
- const Expr *getOriginExpr() const {
+ virtual const Expr *getOriginExpr() const {
return Origin.dyn_cast<const Expr *>();
}
@@ -530,7 +530,7 @@ protected:
}
public:
- virtual const CallExpr *getOriginExpr() const {
+ const CallExpr *getOriginExpr() const override {
return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
}
@@ -543,9 +543,7 @@ public:
}
Kind getKind() const override { return CE_Function; }
- virtual StringRef getKindAsString() const override {
- return "SimpleFunctionCall";
- }
+ StringRef getKindAsString() const override { return "SimpleFunctionCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_Function;
@@ -570,7 +568,7 @@ protected:
RegionAndSymbolInvalidationTraits *ETraits) const override;
public:
- virtual const CallExpr *getOriginExpr() const {
+ const CallExpr *getOriginExpr() const override {
return cast<CallExpr>(CallEvent::getOriginExpr());
}
@@ -653,7 +651,7 @@ public:
ArrayRef<ParmVarDecl *> parameters() const override;
Kind getKind() const override { return CE_Block; }
- virtual StringRef getKindAsString() const override { return "BlockCall"; }
+ StringRef getKindAsString() const override { return "BlockCall"; }
static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; }
};
@@ -708,7 +706,7 @@ protected:
void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
public:
- virtual const CXXMemberCallExpr *getOriginExpr() const {
+ const CXXMemberCallExpr *getOriginExpr() const override {
return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
}
@@ -727,7 +725,7 @@ public:
RuntimeDefinition getRuntimeDefinition() const override;
Kind getKind() const override { return CE_CXXMember; }
- virtual StringRef getKindAsString() const override { return "CXXMemberCall"; }
+ StringRef getKindAsString() const override { return "CXXMemberCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_CXXMember;
@@ -752,7 +750,7 @@ protected:
}
public:
- virtual const CXXOperatorCallExpr *getOriginExpr() const {
+ const CXXOperatorCallExpr *getOriginExpr() const override {
return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
}
@@ -767,9 +765,7 @@ public:
const Expr *getCXXThisExpr() const override;
Kind getKind() const override { return CE_CXXMemberOperator; }
- virtual StringRef getKindAsString() const override {
- return "CXXMemberOperatorCall";
- }
+ StringRef getKindAsString() const override { return "CXXMemberOperatorCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_CXXMemberOperator;
@@ -838,9 +834,7 @@ public:
}
Kind getKind() const override { return CE_CXXDestructor; }
- virtual StringRef getKindAsString() const override {
- return "CXXDestructorCall";
- }
+ StringRef getKindAsString() const override { return "CXXDestructorCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_CXXDestructor;
@@ -898,7 +892,7 @@ protected:
void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
public:
- virtual const CXXConstructExpr *getOriginExpr() const {
+ const CXXConstructExpr *getOriginExpr() const override {
return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
}
@@ -913,9 +907,7 @@ public:
}
Kind getKind() const override { return CE_CXXConstructor; }
- virtual StringRef getKindAsString() const override {
- return "CXXConstructorCall";
- }
+ StringRef getKindAsString() const override { return "CXXConstructorCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_CXXConstructor;
@@ -959,7 +951,7 @@ protected:
}
public:
- virtual const CXXInheritedCtorInitExpr *getOriginExpr() const {
+ const CXXInheritedCtorInitExpr *getOriginExpr() const override {
return cast<CXXInheritedCtorInitExpr>(AnyFunctionCall::getOriginExpr());
}
@@ -986,14 +978,14 @@ public:
return getInheritingConstructor()->getArg(Index);
}
- virtual SVal getArgSVal(unsigned Index) const override {
+ SVal getArgSVal(unsigned Index) const override {
return getState()->getSVal(
getArgExpr(Index),
getInheritingStackFrame()->getParent()->getStackFrame());
}
Kind getKind() const override { return CE_CXXInheritedConstructor; }
- virtual StringRef getKindAsString() const override {
+ StringRef getKindAsString() const override {
return "CXXInheritedConstructorCall";
}
@@ -1017,7 +1009,7 @@ protected:
void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
public:
- virtual const CXXNewExpr *getOriginExpr() const {
+ const CXXNewExpr *getOriginExpr() const override {
return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
}
@@ -1058,9 +1050,7 @@ public:
}
Kind getKind() const override { return CE_CXXAllocator; }
- virtual StringRef getKindAsString() const override {
- return "CXXAllocatorCall";
- }
+ StringRef getKindAsString() const override { return "CXXAllocatorCall"; }
static bool classof(const CallEvent *CE) {
return CE->getKind() == CE_CXXAllocator;
@@ -1091,7 +1081,7 @@ protected:
}
public:
- virtual const CXXDeleteExpr *getOriginExpr() const {
+ const CXXDeleteExpr *getOriginExpr() const override {
return cast<CXXDeleteExpr>(AnyFunctionCall::getOriginExpr());
}
@@ -1107,9 +1097,7 @@ public:
}
Kind getKind() const override { return CE_CXXDeallocator; }
- virtual StringRef getKindAsString() const override {
- return "CXXDeallocatorCall";
- }
+ StringRef getKindAsString() const override { return "CXXDeallocatorCall"; }
static bool classof(const CallEvent *CE) {
return CE->getKind() == CE_CXXDeallocator;
@@ -1153,7 +1141,7 @@ protected:
Selector Sel) const;
public:
- virtual const ObjCMessageExpr *getOriginExpr() const {
+ const ObjCMessageExpr *getOriginExpr() const override {
return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
}
@@ -1230,9 +1218,7 @@ public:
ArrayRef<ParmVarDecl*> parameters() const override;
Kind getKind() const override { return CE_ObjCMessage; }
- virtual StringRef getKindAsString() const override {
- return "ObjCMethodCall";
- }
+ StringRef getKindAsString() const override { return "ObjCMethodCall"; }
static bool classof(const CallEvent *CA) {
return CA->getKind() == CE_ObjCMessage;
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
index 8fd7f52585b8..54572bd81f20 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -301,6 +301,26 @@ public:
IsPrunable);
}
+ /// A shorthand version of getNoteTag that accepts a lambda with stream for
+ /// note.
+ ///
+ /// @param Cb Callback with 'BugReport &' and 'llvm::raw_ostream &'.
+ /// @param IsPrunable Whether the note is prunable. It allows BugReporter
+ /// to omit the note from the report if it would make the displayed
+ /// bug path significantly shorter.
+ const NoteTag *getNoteTag(
+ std::function<void(PathSensitiveBugReport &BR, llvm::raw_ostream &OS)> &&Cb,
+ bool IsPrunable = false) {
+ return getNoteTag(
+ [Cb](PathSensitiveBugReport &BR) -> std::string {
+ llvm::SmallString<128> Str;
+ llvm::raw_svector_ostream OS(Str);
+ Cb(BR, OS);
+ return std::string(OS.str());
+ },
+ IsPrunable);
+ }
+
/// Returns the word that should be used to refer to the declaration
/// in the report.
StringRef getDeclDescription(const Decl *D);
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index cdfe986355c5..582a56cbee1e 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -869,6 +869,23 @@ private:
void handleConstructor(const Expr *E, ExplodedNode *Pred,
ExplodedNodeSet &Dst);
+public:
+ /// Note whether this loop has any more iteratios to model. These methods are
+ /// essentially an interface for a GDM trait. Further reading in
+ /// ExprEngine::VisitObjCForCollectionStmt().
+ LLVM_NODISCARD static ProgramStateRef
+ setWhetherHasMoreIteration(ProgramStateRef State,
+ const ObjCForCollectionStmt *O,
+ const LocationContext *LC, bool HasMoreIteraton);
+
+ LLVM_NODISCARD static ProgramStateRef
+ removeIterationState(ProgramStateRef State, const ObjCForCollectionStmt *O,
+ const LocationContext *LC);
+
+ LLVM_NODISCARD static bool hasMoreIteration(ProgramStateRef State,
+ const ObjCForCollectionStmt *O,
+ const LocationContext *LC);
+private:
/// Store the location of a C++ object corresponding to a statement
/// until the statement is actually encountered. For example, if a DeclStmt
/// has CXXConstructExpr as its initializer, the object would be considered
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
index a42eebd7d4e8..bc5d5f57cd68 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
@@ -126,6 +126,8 @@ public:
RangeSet Intersect(BasicValueFactory &BV, Factory &F,
const RangeSet &Other) const;
RangeSet Negate(BasicValueFactory &BV, Factory &F) const;
+ RangeSet Delete(BasicValueFactory &BV, Factory &F,
+ const llvm::APSInt &Point) const;
void print(raw_ostream &os) const;
@@ -134,15 +136,8 @@ public:
}
};
-class ConstraintRange {};
-using ConstraintRangeTy = llvm::ImmutableMap<SymbolRef, RangeSet>;
-
-template <>
-struct ProgramStateTrait<ConstraintRange>
- : public ProgramStatePartialTrait<ConstraintRangeTy> {
- static void *GDMIndex();
-};
-
+using ConstraintMap = llvm::ImmutableMap<SymbolRef, RangeSet>;
+ConstraintMap getConstraintMap(ProgramStateRef State);
class RangedConstraintManager : public SimpleConstraintManager {
public:
@@ -169,8 +164,8 @@ public:
protected:
/// Assume a constraint between a symbolic expression and a concrete integer.
virtual ProgramStateRef assumeSymRel(ProgramStateRef State, SymbolRef Sym,
- BinaryOperator::Opcode op,
- const llvm::APSInt &Int);
+ BinaryOperator::Opcode op,
+ const llvm::APSInt &Int);
//===------------------------------------------------------------------===//
// Interface that subclasses must implement.
@@ -218,8 +213,9 @@ private:
static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment);
};
-} // end GR namespace
+} // namespace ento
+} // namespace clang
-} // end clang namespace
+REGISTER_FACTORY_WITH_PROGRAMSTATE(ConstraintMap)
#endif
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
index 6a0f5f10874e..07fc73a670f3 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
@@ -122,8 +122,7 @@ public:
// this method tries to get the interpretation (the actual value) from
// the solver, which is currently not cached.
- llvm::SMTExprRef Exp =
- SMTConv::fromData(Solver, SD->getSymbolID(), Ty, Ctx.getTypeSize(Ty));
+ llvm::SMTExprRef Exp = SMTConv::fromData(Solver, Ctx, SD);
Solver->reset();
addStateConstraints(State);
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
index bdebe238829e..2d0f169260a4 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -319,11 +319,16 @@ public:
}
/// Construct an SMTSolverRef from a SymbolData.
- static inline llvm::SMTExprRef fromData(llvm::SMTSolverRef &Solver,
- const SymbolID ID, const QualType &Ty,
- uint64_t BitWidth) {
- llvm::Twine Name = "$" + llvm::Twine(ID);
- return Solver->mkSymbol(Name.str().c_str(), mkSort(Solver, Ty, BitWidth));
+ static inline llvm::SMTExprRef
+ fromData(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const SymbolData *Sym) {
+ const SymbolID ID = Sym->getSymbolID();
+ const QualType Ty = Sym->getType();
+ const uint64_t BitWidth = Ctx.getTypeSize(Ty);
+
+ llvm::SmallString<16> Str;
+ llvm::raw_svector_ostream OS(Str);
+ OS << Sym->getKindStr() << ID;
+ return Solver->mkSymbol(Str.c_str(), mkSort(Solver, Ty, BitWidth));
}
// Wrapper to generate SMTSolverRef from SymbolCast data.
@@ -422,8 +427,7 @@ public:
if (RetTy)
*RetTy = Sym->getType();
- return fromData(Solver, SD->getSymbolID(), Sym->getType(),
- Ctx.getTypeSize(Sym->getType()));
+ return fromData(Solver, Ctx, SD);
}
if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) {
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index 35ebefdc00d6..4ea85f9730bb 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -233,7 +233,7 @@ public:
const LocationContext *LCtx,
unsigned count);
- DefinedSVal getMemberPointer(const DeclaratorDecl *DD);
+ DefinedSVal getMemberPointer(const NamedDecl *ND);
DefinedSVal getFunctionPointer(const FunctionDecl *func);
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index 1abe29782088..bb295ab591d4 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -80,7 +80,7 @@ public:
#define ABSTRACT_SVAL_WITH_KIND(Id, Parent) Id ## Kind,
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.def"
};
- enum { BaseBits = 2, BaseMask = 0x3 };
+ enum { BaseBits = 2, BaseMask = 0b11 };
protected:
const void *Data = nullptr;
@@ -116,7 +116,7 @@ public:
unsigned getRawKind() const { return Kind; }
BaseKind getBaseKind() const { return (BaseKind) (Kind & BaseMask); }
- unsigned getSubKind() const { return (Kind & ~BaseMask) >> BaseBits; }
+ unsigned getSubKind() const { return Kind >> BaseBits; }
// This method is required for using SVal in a FoldingSetNode. It
// extracts a unique signature for this SVal object.
@@ -182,12 +182,6 @@ public:
/// should continue to the base regions if the region is not symbolic.
SymbolRef getAsSymbol(bool IncludeBaseRegions = false) const;
- /// getAsSymbolicExpression - If this Sval wraps a symbolic expression then
- /// return that expression. Otherwise return NULL.
- const SymExpr *getAsSymbolicExpression() const;
-
- const SymExpr *getAsSymExpr() const;
-
const MemRegion *getAsRegion() const;
/// printJson - Pretty-prints in JSON format.
@@ -526,7 +520,7 @@ class PointerToMember : public NonLoc {
public:
using PTMDataType =
- llvm::PointerUnion<const DeclaratorDecl *, const PointerToMemberData *>;
+ llvm::PointerUnion<const NamedDecl *, const PointerToMemberData *>;
const PTMDataType getPTMData() const {
return PTMDataType::getFromOpaqueValue(const_cast<void *>(Data));
@@ -534,7 +528,7 @@ public:
bool isNullMemberPointer() const;
- const DeclaratorDecl *getDecl() const;
+ const NamedDecl *getDecl() const;
template<typename AdjustedDecl>
const AdjustedDecl *getDeclAs() const {
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
index abfcd1d80faa..2f4ac6ba5f97 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
@@ -126,6 +126,9 @@ protected:
public:
~SymbolData() override = default;
+ /// Get a string representation of the kind of the region.
+ virtual StringRef getKindStr() const = 0;
+
SymbolID getSymbolID() const { return Sym; }
unsigned computeComplexity() const override {
diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
index 390ced8c29f8..c71cb88f5574 100644
--- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -59,6 +59,8 @@ public:
Profile(profile, R);
}
+ StringRef getKindStr() const override;
+
void dumpToStream(raw_ostream &os) const override;
const MemRegion *getOriginRegion() const override { return getRegion(); }
@@ -99,6 +101,8 @@ public:
QualType getType() const override;
+ StringRef getKindStr() const override;
+
void dumpToStream(raw_ostream &os) const override;
static void Profile(llvm::FoldingSetNodeID& profile, const Stmt *S,
@@ -141,6 +145,8 @@ public:
QualType getType() const override;
+ StringRef getKindStr() const override;
+
void dumpToStream(raw_ostream &os) const override;
const MemRegion *getOriginRegion() const override { return getRegion(); }
@@ -177,6 +183,8 @@ public:
QualType getType() const override;
+ StringRef getKindStr() const override;
+
void dumpToStream(raw_ostream &os) const override;
static void Profile(llvm::FoldingSetNodeID& profile, const SubRegion *R) {
@@ -226,6 +234,8 @@ public:
QualType getType() const override;
+ StringRef getKindStr() const override;
+
void dumpToStream(raw_ostream &os) const override;
static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
@@ -529,7 +539,7 @@ public:
bool isLive(SymbolRef sym);
bool isLiveRegion(const MemRegion *region);
- bool isLive(const Stmt *ExprVal, const LocationContext *LCtx) const;
+ bool isLive(const Expr *ExprVal, const LocationContext *LCtx) const;
bool isLive(const VarRegion *VR, bool includeStoreBindings = false) const;
/// Unconditionally marks a symbol as live.
diff --git a/contrib/llvm-project/clang/include/clang/Testing/TestClangConfig.h b/contrib/llvm-project/clang/include/clang/Testing/TestClangConfig.h
index eefa36dc2ebb..5d6be4f65d0a 100644
--- a/contrib/llvm-project/clang/include/clang/Testing/TestClangConfig.h
+++ b/contrib/llvm-project/clang/include/clang/Testing/TestClangConfig.h
@@ -51,6 +51,8 @@ struct TestClangConfig {
return Language == Lang_CXX17 || Language == Lang_CXX20;
}
+ bool isCXX20OrLater() const { return Language == Lang_CXX20; }
+
bool supportsCXXDynamicExceptionSpecification() const {
return Language == Lang_CXX03 || Language == Lang_CXX11 ||
Language == Lang_CXX14;
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h b/contrib/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h
index b28a8a6d6e51..44af236347b3 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h
@@ -43,10 +43,10 @@ namespace tooling {
/// Specifies the working directory and command of a compilation.
struct CompileCommand {
CompileCommand() = default;
- CompileCommand(Twine Directory, Twine Filename,
- std::vector<std::string> CommandLine, Twine Output)
+ CompileCommand(const Twine &Directory, const Twine &Filename,
+ std::vector<std::string> CommandLine, const Twine &Output)
: Directory(Directory.str()), Filename(Filename.str()),
- CommandLine(std::move(CommandLine)), Output(Output.str()){}
+ CommandLine(std::move(CommandLine)), Output(Output.str()) {}
/// The working directory the command was executed from.
std::string Directory;
@@ -180,18 +180,24 @@ public:
/// \param Argv Points to the command line arguments.
/// \param ErrorMsg Contains error text if the function returns null pointer.
/// \param Directory The base directory used in the FixedCompilationDatabase.
- static std::unique_ptr<FixedCompilationDatabase> loadFromCommandLine(
- int &Argc, const char *const *Argv, std::string &ErrorMsg,
- Twine Directory = ".");
+ static std::unique_ptr<FixedCompilationDatabase>
+ loadFromCommandLine(int &Argc, const char *const *Argv, std::string &ErrorMsg,
+ const Twine &Directory = ".");
- /// Reads flags from the given file, one-per line.
+ /// Reads flags from the given file, one-per-line.
/// Returns nullptr and sets ErrorMessage if we can't read the file.
static std::unique_ptr<FixedCompilationDatabase>
loadFromFile(StringRef Path, std::string &ErrorMsg);
+ /// Reads flags from the given buffer, one-per-line.
+ /// Directory is the command CWD, typically the parent of compile_flags.txt.
+ static std::unique_ptr<FixedCompilationDatabase>
+ loadFromBuffer(StringRef Directory, StringRef Data, std::string &ErrorMsg);
+
/// Constructs a compilation data base from a specified directory
/// and command line.
- FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine);
+ FixedCompilationDatabase(const Twine &Directory,
+ ArrayRef<std::string> CommandLine);
/// Returns the given compile command.
///
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h b/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
index 18374ad46a9c..02fb2875671a 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -40,8 +40,6 @@ private:
const IncludeStyle Style;
bool IsMainFile;
std::string FileName;
- // This refers to a substring in FileName.
- StringRef FileStem;
SmallVector<llvm::Regex, 4> CategoryRegexs;
};
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h b/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
index 2648297724e1..4caaf4121f15 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
@@ -60,8 +60,11 @@ struct IncludeStyle {
int Priority;
/// The custom priority to sort before grouping.
int SortPriority;
+ /// If the regular expression is case sensitive.
+ bool RegexIsCaseSensitive;
bool operator==(const IncludeCategory &Other) const {
- return Regex == Other.Regex && Priority == Other.Priority;
+ return Regex == Other.Regex && Priority == Other.Priority &&
+ RegexIsCaseSensitive == Other.RegexIsCaseSensitive;
}
};
@@ -84,13 +87,16 @@ struct IncludeStyle {
/// (https://llvm.org/docs/CodingStandards.html#include-style). However, you
/// can also assign negative priorities if you have certain headers that
/// always need to be first.
- ///
+ ///
/// There is a third and optional field ``SortPriority`` which can used while
- /// ``IncludeBloks = IBS_Regroup`` to define the priority in which ``#includes``
- /// should be ordered, and value of ``Priority`` defines the order of
- /// ``#include blocks`` and also enables to group ``#includes`` of different
- /// priority for order.``SortPriority`` is set to the value of ``Priority``
- /// as default if it is not assigned.
+ /// ``IncludeBlocks = IBS_Regroup`` to define the priority in which
+ /// ``#includes`` should be ordered. The value of ``Priority`` defines the
+ /// order of ``#include blocks`` and also allows the grouping of ``#includes``
+ /// of different priority. ``SortPriority`` is set to the value of
+ /// ``Priority`` as default if it is not assigned.
+ ///
+ /// Each regular expression can be marked as case sensitive with the field
+ /// ``CaseSensitive``, per default it is not.
///
/// To configure this in the .clang-format file, use:
/// \code{.yaml}
@@ -98,6 +104,7 @@ struct IncludeStyle {
/// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
/// Priority: 2
/// SortPriority: 2
+ /// CaseSensitive: true
/// - Regex: '^(<|"(gtest|gmock|isl|json)/)'
/// Priority: 3
/// - Regex: '<[[:alnum:].]+>'
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Core/Lookup.h b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Lookup.h
index 02b561c14f29..448bc422c4e7 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Core/Lookup.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Lookup.h
@@ -10,8 +10,8 @@
//
//===----------------------------------------------------------------------===//
-#ifndef LLVM_CLANG_TOOLING_CORE_LOOKUP_H
-#define LLVM_CLANG_TOOLING_CORE_LOOKUP_H
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H
+#define LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
@@ -47,4 +47,4 @@ std::string replaceNestedName(const NestedNameSpecifier *Use,
} // end namespace tooling
} // end namespace clang
-#endif // LLVM_CLANG_TOOLING_CORE_LOOKUP_H
+#endif // LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
index 5271a54075ea..e0da9469deb5 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
@@ -77,7 +77,7 @@ private:
/// might operate on.
ASTContext *AST = nullptr;
/// The allocator for diagnostics.
- PartialDiagnostic::StorageAllocator DiagStorage;
+ PartialDiagnostic::DiagStorageAllocator DiagStorage;
// FIXME: Remove when memoized.
std::unique_ptr<SelectedASTNode> ASTNodeSelection;
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
index 3b903cb822f3..c4bfaa9cc377 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
@@ -69,17 +69,18 @@ public:
OccurrenceKind getKind() const { return Kind; }
ArrayRef<SourceRange> getNameRanges() const {
- if (MultipleRanges) {
- return llvm::makeArrayRef(MultipleRanges.get(),
- RangeOrNumRanges.getBegin().getRawEncoding());
- }
- return RangeOrNumRanges;
+ if (MultipleRanges)
+ return llvm::makeArrayRef(MultipleRanges.get(), NumRanges);
+ return SingleRange;
}
private:
OccurrenceKind Kind;
std::unique_ptr<SourceRange[]> MultipleRanges;
- SourceRange RangeOrNumRanges;
+ union {
+ SourceRange SingleRange;
+ unsigned NumRanges;
+ };
};
using SymbolOccurrences = std::vector<SymbolOccurrence>;
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h
index b7ad50c941d1..3c8dd8ceed09 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h
@@ -19,15 +19,40 @@ namespace clang {
namespace syntax {
/// Build a syntax tree for the main file.
-syntax::TranslationUnit *buildSyntaxTree(Arena &A,
- const clang::TranslationUnitDecl &TU);
+/// This usually covers the whole TranslationUnitDecl, but can be restricted by
+/// the ASTContext's traversal scope.
+syntax::TranslationUnit *buildSyntaxTree(Arena &A, ASTContext &Context);
// Create syntax trees from subtrees not backed by the source code.
-clang::syntax::Leaf *createPunctuation(clang::syntax::Arena &A,
- clang::tok::TokenKind K);
-clang::syntax::EmptyStatement *createEmptyStatement(clang::syntax::Arena &A);
+// Synthesis of Leafs
+/// Create `Leaf` from token with `Spelling` and assert it has the desired
+/// `TokenKind`.
+syntax::Leaf *createLeaf(syntax::Arena &A, tok::TokenKind K,
+ StringRef Spelling);
+/// Infer the token spelling from its `TokenKind`, then create `Leaf` from
+/// this token
+syntax::Leaf *createLeaf(syntax::Arena &A, tok::TokenKind K);
+
+// Synthesis of Trees
+/// Creates the concrete syntax node according to the specified `NodeKind` `K`.
+/// Returns it as a pointer to the base class `Tree`.
+syntax::Tree *
+createTree(syntax::Arena &A,
+ ArrayRef<std::pair<syntax::Node *, syntax::NodeRole>> Children,
+ syntax::NodeKind K);
+
+// Synthesis of Syntax Nodes
+syntax::EmptyStatement *createEmptyStatement(syntax::Arena &A);
+
+/// Creates a completely independent copy of `N` with its macros expanded.
+///
+/// The copy is:
+/// * Detached, i.e. `Parent == NextSibling == nullptr` and
+/// `Role == Detached`.
+/// * Synthesized, i.e. `Original == false`.
+syntax::Node *deepCopyExpandingMacros(syntax::Arena &A, const syntax::Node *N);
} // namespace syntax
} // namespace clang
#endif
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h
index d97b127638bb..edb6d4d4381d 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h
@@ -35,76 +35,17 @@ namespace syntax {
/// blocks of enumerator constants must correspond to the inheritance hierarchy
/// of syntax::Node.
enum class NodeKind : uint16_t {
- Leaf,
- TranslationUnit,
-
- // Expressions.
- UnknownExpression,
- PrefixUnaryOperatorExpression,
- PostfixUnaryOperatorExpression,
- BinaryOperatorExpression,
- ParenExpression,
- IntegerLiteralExpression,
- CharacterLiteralExpression,
- FloatingLiteralExpression,
- StringLiteralExpression,
- BoolLiteralExpression,
- CxxNullPtrExpression,
- IntegerUserDefinedLiteralExpression,
- FloatUserDefinedLiteralExpression,
- CharUserDefinedLiteralExpression,
- StringUserDefinedLiteralExpression,
- IdExpression,
-
- // Statements.
- UnknownStatement,
- DeclarationStatement,
- EmptyStatement,
- SwitchStatement,
- CaseStatement,
- DefaultStatement,
- IfStatement,
- ForStatement,
- WhileStatement,
- ContinueStatement,
- BreakStatement,
- ReturnStatement,
- RangeBasedForStatement,
- ExpressionStatement,
- CompoundStatement,
-
- // Declarations.
- UnknownDeclaration,
- EmptyDeclaration,
- StaticAssertDeclaration,
- LinkageSpecificationDeclaration,
- SimpleDeclaration,
- TemplateDeclaration,
- ExplicitTemplateInstantiation,
- NamespaceDefinition,
- NamespaceAliasDefinition,
- UsingNamespaceDirective,
- UsingDeclaration,
- TypeAliasDeclaration,
-
- // Declarators.
- SimpleDeclarator,
- ParenDeclarator,
-
- ArraySubscript,
- TrailingReturnType,
- ParametersAndQualifiers,
- MemberPointer,
- NestedNameSpecifier,
- NameSpecifier,
- UnqualifiedId
+#define CONCRETE_NODE(Kind, Base) Kind,
+#include "clang/Tooling/Syntax/Nodes.inc"
};
/// For debugging purposes.
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, NodeKind K);
+raw_ostream &operator<<(raw_ostream &OS, NodeKind K);
/// A relation between a parent and child node, e.g. 'left-hand-side of
/// a binary expression'. Used for implementing accessors.
///
+/// In general `NodeRole`s should be named the same as their accessors.
+///
/// Some roles describe parent/child relations that occur multiple times in
/// language grammar. We define only one role to describe all instances of such
/// recurring relations. For example, grammar for both "if" and "while"
@@ -115,12 +56,6 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, NodeKind K);
/// opening paren), we define a role for this token and use it across all
/// grammar rules with the same requirement. Names of such reusable roles end
/// with a ~Token or a ~Keyword suffix.
-///
-/// Some roles are assigned only to child nodes of one specific parent syntax
-/// node type. Names of such roles start with the name of the parent syntax tree
-/// node type. For example, a syntax node with a role
-/// BinaryOperatorExpression_leftHandSide can only appear as a child of a
-/// BinaryOperatorExpression node.
enum class NodeRole : uint8_t {
// Roles common to multiple node kinds.
/// A node without a parent
@@ -135,84 +70,61 @@ enum class NodeRole : uint8_t {
IntroducerKeyword,
/// A token that represents a literal, e.g. 'nullptr', '1', 'true', etc.
LiteralToken,
- /// Tokens or Keywords
+ /// Tokens or Keywords.
ArrowToken,
ExternKeyword,
+ TemplateKeyword,
/// An inner statement for those that have only a single child of kind
/// statement, e.g. loop body for while, for, etc; inner statement for case,
/// default, etc.
BodyStatement,
+ /// List API roles.
+ ListElement,
+ ListDelimiter,
// Roles specific to particular node kinds.
- OperatorExpression_operatorToken,
- UnaryOperatorExpression_operand,
- BinaryOperatorExpression_leftHandSide,
- BinaryOperatorExpression_rightHandSide,
- CaseStatement_value,
- IfStatement_thenStatement,
- IfStatement_elseKeyword,
- IfStatement_elseStatement,
- ReturnStatement_value,
- ExpressionStatement_expression,
- CompoundStatement_statement,
- StaticAssertDeclaration_condition,
- StaticAssertDeclaration_message,
- SimpleDeclaration_declarator,
- TemplateDeclaration_declaration,
- ExplicitTemplateInstantiation_declaration,
- ArraySubscript_sizeExpression,
- TrailingReturnType_declarator,
- ParametersAndQualifiers_parameter,
- ParametersAndQualifiers_trailingReturn,
- IdExpression_id,
- IdExpression_qualifier,
- NestedNameSpecifier_specifier,
- ParenExpression_subExpression
+ OperatorToken,
+ Operand,
+ LeftHandSide,
+ RightHandSide,
+ ReturnValue,
+ CaseValue,
+ ThenStatement,
+ ElseKeyword,
+ ElseStatement,
+ Expression,
+ Statement,
+ Condition,
+ Message,
+ Declarator,
+ Declaration,
+ Size,
+ Parameters,
+ TrailingReturn,
+ UnqualifiedId,
+ Qualifier,
+ SubExpression,
+ Object,
+ AccessToken,
+ Member,
+ Callee,
+ Arguments,
+ Declarators
};
/// For debugging purposes.
-llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, NodeRole R);
+raw_ostream &operator<<(raw_ostream &OS, NodeRole R);
-class SimpleDeclarator;
-
-/// A root node for a translation unit. Parent is always null.
-class TranslationUnit final : public Tree {
-public:
- TranslationUnit() : Tree(NodeKind::TranslationUnit) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::TranslationUnit;
- }
-};
-
-/// A base class for all expressions. Note that expressions are not statements,
-/// even though they are in clang.
-class Expression : public Tree {
-public:
- Expression(NodeKind K) : Tree(K) {}
- static bool classof(const Node *N) {
- return NodeKind::UnknownExpression <= N->kind() &&
- N->kind() <= NodeKind::UnknownExpression;
- }
-};
-
-/// A sequence of these specifiers make a `nested-name-specifier`.
-/// e.g. the `std::` or `vector<int>::` in `std::vector<int>::size`.
-class NameSpecifier final : public Tree {
-public:
- NameSpecifier() : Tree(NodeKind::NameSpecifier) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::NameSpecifier;
- }
-};
+#include "clang/Tooling/Syntax/NodeClasses.inc"
/// Models a `nested-name-specifier`. C++ [expr.prim.id.qual]
/// e.g. the `std::vector<int>::` in `std::vector<int>::size`.
-class NestedNameSpecifier final : public Tree {
+class NestedNameSpecifier final : public List {
public:
- NestedNameSpecifier() : Tree(NodeKind::NestedNameSpecifier) {}
- static bool classof(const Node *N) {
- return N->kind() <= NodeKind::NestedNameSpecifier;
- }
- std::vector<syntax::NameSpecifier *> specifiers();
+ NestedNameSpecifier() : List(NodeKind::NestedNameSpecifier) {}
+ static bool classof(const Node *N);
+ std::vector<NameSpecifier *> getSpecifiers();
+ std::vector<List::ElementAndDelimiter<syntax::NameSpecifier>>
+ getSpecifiersAndDoubleColons();
};
/// Models an `unqualified-id`. C++ [expr.prim.id.unqual]
@@ -220,28 +132,7 @@ public:
class UnqualifiedId final : public Tree {
public:
UnqualifiedId() : Tree(NodeKind::UnqualifiedId) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UnqualifiedId;
- }
-};
-
-/// Models an `id-expression`, e.g. `std::vector<int>::size`.
-/// C++ [expr.prim.id]
-/// id-expression:
-/// unqualified-id
-/// qualified-id
-/// qualified-id:
-/// nested-name-specifier template_opt unqualified-id
-class IdExpression final : public Expression {
-public:
- IdExpression() : Expression(NodeKind::IdExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::IdExpression;
- }
- syntax::NestedNameSpecifier *qualifier();
- // TODO after expose `id-expression` from `DependentScopeDeclRefExpr`:
- // Add accessor for `template_opt`.
- syntax::UnqualifiedId *unqualifiedId();
+ static bool classof(const Node *N);
};
/// An expression of an unknown kind, i.e. one not currently handled by the
@@ -249,162 +140,29 @@ public:
class UnknownExpression final : public Expression {
public:
UnknownExpression() : Expression(NodeKind::UnknownExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UnknownExpression;
- }
-};
-
-/// Models a parenthesized expression `(E)`. C++ [expr.prim.paren]
-/// e.g. `(3 + 2)` in `a = 1 + (3 + 2);`
-class ParenExpression final : public Expression {
-public:
- ParenExpression() : Expression(NodeKind::ParenExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ParenExpression;
- }
- syntax::Leaf *openParen();
- syntax::Expression *subExpression();
- syntax::Leaf *closeParen();
+ static bool classof(const Node *N);
};
-/// Expression for integer literals. C++ [lex.icon]
-class IntegerLiteralExpression final : public Expression {
+/// Models arguments of a function call.
+/// call-arguments:
+/// delimited_list(expression, ',')
+/// Note: This construct is a simplification of the grammar rule for
+/// `expression-list`, that is used in the definition of `call-expression`
+class CallArguments final : public List {
public:
- IntegerLiteralExpression() : Expression(NodeKind::IntegerLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::IntegerLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for character literals. C++ [lex.ccon]
-class CharacterLiteralExpression final : public Expression {
-public:
- CharacterLiteralExpression()
- : Expression(NodeKind::CharacterLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::CharacterLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for floating-point literals. C++ [lex.fcon]
-class FloatingLiteralExpression final : public Expression {
-public:
- FloatingLiteralExpression()
- : Expression(NodeKind::FloatingLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::FloatingLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for string-literals. C++ [lex.string]
-class StringLiteralExpression final : public Expression {
-public:
- StringLiteralExpression() : Expression(NodeKind::StringLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::StringLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for boolean literals. C++ [lex.bool]
-class BoolLiteralExpression final : public Expression {
-public:
- BoolLiteralExpression() : Expression(NodeKind::BoolLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::BoolLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for the `nullptr` literal. C++ [lex.nullptr]
-class CxxNullPtrExpression final : public Expression {
-public:
- CxxNullPtrExpression() : Expression(NodeKind::CxxNullPtrExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::CxxNullPtrExpression;
- }
- syntax::Leaf *nullPtrKeyword();
-};
-
-/// Expression for user-defined literal. C++ [lex.ext]
-/// user-defined-literal:
-/// user-defined-integer-literal
-/// user-defined-floating-point-literal
-/// user-defined-string-literal
-/// user-defined-character-literal
-class UserDefinedLiteralExpression : public Expression {
-public:
- UserDefinedLiteralExpression(NodeKind K) : Expression(K) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::IntegerUserDefinedLiteralExpression ||
- N->kind() == NodeKind::FloatUserDefinedLiteralExpression ||
- N->kind() == NodeKind::CharUserDefinedLiteralExpression ||
- N->kind() == NodeKind::StringUserDefinedLiteralExpression;
- }
- syntax::Leaf *literalToken();
-};
-
-/// Expression for user-defined-integer-literal. C++ [lex.ext]
-class IntegerUserDefinedLiteralExpression final
- : public UserDefinedLiteralExpression {
-public:
- IntegerUserDefinedLiteralExpression()
- : UserDefinedLiteralExpression(
- NodeKind::IntegerUserDefinedLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::IntegerUserDefinedLiteralExpression;
- }
-};
-
-/// Expression for user-defined-floating-point-literal. C++ [lex.ext]
-class FloatUserDefinedLiteralExpression final
- : public UserDefinedLiteralExpression {
-public:
- FloatUserDefinedLiteralExpression()
- : UserDefinedLiteralExpression(
- NodeKind::FloatUserDefinedLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::FloatUserDefinedLiteralExpression;
- }
-};
-
-/// Expression for user-defined-character-literal. C++ [lex.ext]
-class CharUserDefinedLiteralExpression final
- : public UserDefinedLiteralExpression {
-public:
- CharUserDefinedLiteralExpression()
- : UserDefinedLiteralExpression(
- NodeKind::CharUserDefinedLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::CharUserDefinedLiteralExpression;
- }
-};
-
-/// Expression for user-defined-string-literal. C++ [lex.ext]
-class StringUserDefinedLiteralExpression final
- : public UserDefinedLiteralExpression {
-public:
- StringUserDefinedLiteralExpression()
- : UserDefinedLiteralExpression(
- NodeKind::StringUserDefinedLiteralExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::StringUserDefinedLiteralExpression;
- }
+ CallArguments() : List(NodeKind::CallArguments) {}
+ static bool classof(const Node *N);
+ std::vector<Expression *> getArguments();
+ std::vector<List::ElementAndDelimiter<Expression>> getArgumentsAndCommas();
};
/// An abstract class for prefix and postfix unary operators.
class UnaryOperatorExpression : public Expression {
public:
UnaryOperatorExpression(NodeKind K) : Expression(K) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::PrefixUnaryOperatorExpression ||
- N->kind() == NodeKind::PostfixUnaryOperatorExpression;
- }
- syntax::Leaf *operatorToken();
- syntax::Expression *operand();
+ static bool classof(const Node *N);
+ Leaf *getOperatorToken();
+ Expression *getOperand();
};
/// <operator> <operand>
@@ -420,9 +178,7 @@ class PrefixUnaryOperatorExpression final : public UnaryOperatorExpression {
public:
PrefixUnaryOperatorExpression()
: UnaryOperatorExpression(NodeKind::PrefixUnaryOperatorExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::PrefixUnaryOperatorExpression;
- }
+ static bool classof(const Node *N);
};
/// <operand> <operator>
@@ -434,9 +190,7 @@ class PostfixUnaryOperatorExpression final : public UnaryOperatorExpression {
public:
PostfixUnaryOperatorExpression()
: UnaryOperatorExpression(NodeKind::PostfixUnaryOperatorExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::PostfixUnaryOperatorExpression;
- }
+ static bool classof(const Node *N);
};
/// <lhs> <operator> <rhs>
@@ -449,12 +203,10 @@ public:
class BinaryOperatorExpression final : public Expression {
public:
BinaryOperatorExpression() : Expression(NodeKind::BinaryOperatorExpression) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::BinaryOperatorExpression;
- }
- syntax::Expression *lhs();
- syntax::Leaf *operatorToken();
- syntax::Expression *rhs();
+ static bool classof(const Node *N);
+ Expression *getLhs();
+ Leaf *getOperatorToken();
+ Expression *getRhs();
};
/// An abstract node for C++ statements, e.g. 'while', 'if', etc.
@@ -462,10 +214,7 @@ public:
class Statement : public Tree {
public:
Statement(NodeKind K) : Tree(K) {}
- static bool classof(const Node *N) {
- return NodeKind::UnknownStatement <= N->kind() &&
- N->kind() <= NodeKind::CompoundStatement;
- }
+ static bool classof(const Node *N);
};
/// A statement of an unknown kind, i.e. one not currently handled by the syntax
@@ -473,61 +222,49 @@ public:
class UnknownStatement final : public Statement {
public:
UnknownStatement() : Statement(NodeKind::UnknownStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UnknownStatement;
- }
+ static bool classof(const Node *N);
};
/// E.g. 'int a, b = 10;'
class DeclarationStatement final : public Statement {
public:
DeclarationStatement() : Statement(NodeKind::DeclarationStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::DeclarationStatement;
- }
+ static bool classof(const Node *N);
};
/// The no-op statement, i.e. ';'.
class EmptyStatement final : public Statement {
public:
EmptyStatement() : Statement(NodeKind::EmptyStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::EmptyStatement;
- }
+ static bool classof(const Node *N);
};
/// switch (<cond>) <body>
class SwitchStatement final : public Statement {
public:
SwitchStatement() : Statement(NodeKind::SwitchStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::SwitchStatement;
- }
- syntax::Leaf *switchKeyword();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getSwitchKeyword();
+ Statement *getBody();
};
/// case <value>: <body>
class CaseStatement final : public Statement {
public:
CaseStatement() : Statement(NodeKind::CaseStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::CaseStatement;
- }
- syntax::Leaf *caseKeyword();
- syntax::Expression *value();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getCaseKeyword();
+ Expression *getCaseValue();
+ Statement *getBody();
};
/// default: <body>
class DefaultStatement final : public Statement {
public:
DefaultStatement() : Statement(NodeKind::DefaultStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::DefaultStatement;
- }
- syntax::Leaf *defaultKeyword();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getDefaultKeyword();
+ Statement *getBody();
};
/// if (cond) <then-statement> else <else-statement>
@@ -535,55 +272,45 @@ public:
class IfStatement final : public Statement {
public:
IfStatement() : Statement(NodeKind::IfStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::IfStatement;
- }
- syntax::Leaf *ifKeyword();
- syntax::Statement *thenStatement();
- syntax::Leaf *elseKeyword();
- syntax::Statement *elseStatement();
+ static bool classof(const Node *N);
+ Leaf *getIfKeyword();
+ Statement *getThenStatement();
+ Leaf *getElseKeyword();
+ Statement *getElseStatement();
};
/// for (<init>; <cond>; <increment>) <body>
class ForStatement final : public Statement {
public:
ForStatement() : Statement(NodeKind::ForStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ForStatement;
- }
- syntax::Leaf *forKeyword();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getForKeyword();
+ Statement *getBody();
};
/// while (<cond>) <body>
class WhileStatement final : public Statement {
public:
WhileStatement() : Statement(NodeKind::WhileStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::WhileStatement;
- }
- syntax::Leaf *whileKeyword();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getWhileKeyword();
+ Statement *getBody();
};
/// continue;
class ContinueStatement final : public Statement {
public:
ContinueStatement() : Statement(NodeKind::ContinueStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ContinueStatement;
- }
- syntax::Leaf *continueKeyword();
+ static bool classof(const Node *N);
+ Leaf *getContinueKeyword();
};
/// break;
class BreakStatement final : public Statement {
public:
BreakStatement() : Statement(NodeKind::BreakStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::BreakStatement;
- }
- syntax::Leaf *breakKeyword();
+ static bool classof(const Node *N);
+ Leaf *getBreakKeyword();
};
/// return <expr>;
@@ -591,22 +318,18 @@ public:
class ReturnStatement final : public Statement {
public:
ReturnStatement() : Statement(NodeKind::ReturnStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ReturnStatement;
- }
- syntax::Leaf *returnKeyword();
- syntax::Expression *value();
+ static bool classof(const Node *N);
+ Leaf *getReturnKeyword();
+ Expression *getReturnValue();
};
/// for (<decl> : <init>) <body>
class RangeBasedForStatement final : public Statement {
public:
RangeBasedForStatement() : Statement(NodeKind::RangeBasedForStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::RangeBasedForStatement;
- }
- syntax::Leaf *forKeyword();
- syntax::Statement *body();
+ static bool classof(const Node *N);
+ Leaf *getForKeyword();
+ Statement *getBody();
};
/// Expression in a statement position, e.g. functions calls inside compound
@@ -614,23 +337,19 @@ public:
class ExpressionStatement final : public Statement {
public:
ExpressionStatement() : Statement(NodeKind::ExpressionStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ExpressionStatement;
- }
- syntax::Expression *expression();
+ static bool classof(const Node *N);
+ Expression *getExpression();
};
/// { statement1; statement2; … }
class CompoundStatement final : public Statement {
public:
CompoundStatement() : Statement(NodeKind::CompoundStatement) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::CompoundStatement;
- }
- syntax::Leaf *lbrace();
+ static bool classof(const Node *N);
+ Leaf *getLbrace();
/// FIXME: use custom iterator instead of 'vector'.
- std::vector<syntax::Statement *> statements();
- syntax::Leaf *rbrace();
+ std::vector<Statement *> getStatements();
+ Leaf *getRbrace();
};
/// A declaration that can appear at the top-level. Note that this does *not*
@@ -640,28 +359,21 @@ public:
class Declaration : public Tree {
public:
Declaration(NodeKind K) : Tree(K) {}
- static bool classof(const Node *N) {
- return NodeKind::UnknownDeclaration <= N->kind() &&
- N->kind() <= NodeKind::TypeAliasDeclaration;
- }
+ static bool classof(const Node *N);
};
/// Declaration of an unknown kind, e.g. not yet supported in syntax trees.
class UnknownDeclaration final : public Declaration {
public:
UnknownDeclaration() : Declaration(NodeKind::UnknownDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UnknownDeclaration;
- }
+ static bool classof(const Node *N);
};
/// A semicolon in the top-level context. Does not declare anything.
class EmptyDeclaration final : public Declaration {
public:
EmptyDeclaration() : Declaration(NodeKind::EmptyDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::EmptyDeclaration;
- }
+ static bool classof(const Node *N);
};
/// static_assert(<condition>, <message>)
@@ -669,11 +381,9 @@ public:
class StaticAssertDeclaration final : public Declaration {
public:
StaticAssertDeclaration() : Declaration(NodeKind::StaticAssertDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::StaticAssertDeclaration;
- }
- syntax::Expression *condition();
- syntax::Expression *message();
+ static bool classof(const Node *N);
+ Expression *getCondition();
+ Expression *getMessage();
};
/// extern <string-literal> declaration
@@ -682,9 +392,16 @@ class LinkageSpecificationDeclaration final : public Declaration {
public:
LinkageSpecificationDeclaration()
: Declaration(NodeKind::LinkageSpecificationDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::LinkageSpecificationDeclaration;
- }
+ static bool classof(const Node *N);
+};
+
+class DeclaratorList final : public List {
+public:
+ DeclaratorList() : List(NodeKind::DeclaratorList) {}
+ static bool classof(const Node *N);
+ std::vector<SimpleDeclarator *> getDeclarators();
+ std::vector<List::ElementAndDelimiter<syntax::SimpleDeclarator>>
+ getDeclaratorsAndCommas();
};
/// Groups multiple declarators (e.g. variables, typedefs, etc.) together. All
@@ -693,22 +410,18 @@ public:
class SimpleDeclaration final : public Declaration {
public:
SimpleDeclaration() : Declaration(NodeKind::SimpleDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::SimpleDeclaration;
- }
+ static bool classof(const Node *N);
/// FIXME: use custom iterator instead of 'vector'.
- std::vector<syntax::SimpleDeclarator *> declarators();
+ std::vector<SimpleDeclarator *> getDeclarators();
};
/// template <template-parameters> <declaration>
class TemplateDeclaration final : public Declaration {
public:
TemplateDeclaration() : Declaration(NodeKind::TemplateDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::TemplateDeclaration;
- }
- syntax::Leaf *templateKeyword();
- syntax::Declaration *declaration();
+ static bool classof(const Node *N);
+ Leaf *getTemplateKeyword();
+ Declaration *getDeclaration();
};
/// template <declaration>
@@ -720,21 +433,17 @@ class ExplicitTemplateInstantiation final : public Declaration {
public:
ExplicitTemplateInstantiation()
: Declaration(NodeKind::ExplicitTemplateInstantiation) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ExplicitTemplateInstantiation;
- }
- syntax::Leaf *templateKeyword();
- syntax::Leaf *externKeyword();
- syntax::Declaration *declaration();
+ static bool classof(const Node *N);
+ Leaf *getTemplateKeyword();
+ Leaf *getExternKeyword();
+ Declaration *getDeclaration();
};
/// namespace <name> { <decls> }
class NamespaceDefinition final : public Declaration {
public:
NamespaceDefinition() : Declaration(NodeKind::NamespaceDefinition) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::NamespaceDefinition;
- }
+ static bool classof(const Node *N);
};
/// namespace <name> = <namespace-reference>
@@ -742,18 +451,14 @@ class NamespaceAliasDefinition final : public Declaration {
public:
NamespaceAliasDefinition()
: Declaration(NodeKind::NamespaceAliasDefinition) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::NamespaceAliasDefinition;
- }
+ static bool classof(const Node *N);
};
/// using namespace <name>
class UsingNamespaceDirective final : public Declaration {
public:
UsingNamespaceDirective() : Declaration(NodeKind::UsingNamespaceDirective) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UsingNamespaceDirective;
- }
+ static bool classof(const Node *N);
};
/// using <scope>::<name>
@@ -761,18 +466,14 @@ public:
class UsingDeclaration final : public Declaration {
public:
UsingDeclaration() : Declaration(NodeKind::UsingDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::UsingDeclaration;
- }
+ static bool classof(const Node *N);
};
/// using <name> = <type>
class TypeAliasDeclaration final : public Declaration {
public:
TypeAliasDeclaration() : Declaration(NodeKind::TypeAliasDeclaration) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::TypeAliasDeclaration;
- }
+ static bool classof(const Node *N);
};
/// Covers a name, an initializer and a part of the type outside declaration
@@ -790,10 +491,7 @@ public:
class Declarator : public Tree {
public:
Declarator(NodeKind K) : Tree(K) {}
- static bool classof(const Node *N) {
- return NodeKind::SimpleDeclarator <= N->kind() &&
- N->kind() <= NodeKind::ParenDeclarator;
- }
+ static bool classof(const Node *N);
};
/// A top-level declarator without parentheses. See comment of Declarator for
@@ -801,9 +499,7 @@ public:
class SimpleDeclarator final : public Declarator {
public:
SimpleDeclarator() : Declarator(NodeKind::SimpleDeclarator) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::SimpleDeclarator;
- }
+ static bool classof(const Node *N);
};
/// Declarator inside parentheses.
@@ -812,11 +508,9 @@ public:
class ParenDeclarator final : public Declarator {
public:
ParenDeclarator() : Declarator(NodeKind::ParenDeclarator) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ParenDeclarator;
- }
- syntax::Leaf *lparen();
- syntax::Leaf *rparen();
+ static bool classof(const Node *N);
+ Leaf *getLparen();
+ Leaf *getRparen();
};
/// Array size specified inside a declarator.
@@ -826,13 +520,11 @@ public:
class ArraySubscript final : public Tree {
public:
ArraySubscript() : Tree(NodeKind::ArraySubscript) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ArraySubscript;
- }
+ static bool classof(const Node *N);
// TODO: add an accessor for the "static" keyword.
- syntax::Leaf *lbracket();
- syntax::Expression *sizeExpression();
- syntax::Leaf *rbracket();
+ Leaf *getLbracket();
+ Expression *getSize();
+ Leaf *getRbracket();
};
/// Trailing return type after the parameter list, including the arrow token.
@@ -840,12 +532,23 @@ public:
class TrailingReturnType final : public Tree {
public:
TrailingReturnType() : Tree(NodeKind::TrailingReturnType) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::TrailingReturnType;
- }
+ static bool classof(const Node *N);
// TODO: add accessors for specifiers.
- syntax::Leaf *arrowToken();
- syntax::SimpleDeclarator *declarator();
+ Leaf *getArrowToken();
+ // FIXME: This should be a `type-id` following the grammar. Fix this once we
+ // have a representation of `type-id`s.
+ SimpleDeclarator *getDeclarator();
+};
+
+/// Models a `parameter-declaration-list` which appears within
+/// `parameters-and-qualifiers`. See C++ [dcl.fct]
+class ParameterDeclarationList final : public List {
+public:
+ ParameterDeclarationList() : List(NodeKind::ParameterDeclarationList) {}
+ static bool classof(const Node *N);
+ std::vector<SimpleDeclaration *> getParameterDeclarations();
+ std::vector<List::ElementAndDelimiter<syntax::SimpleDeclaration>>
+ getParametersAndCommas();
};
/// Parameter list for a function type and a trailing return type, if the
@@ -862,14 +565,11 @@ public:
class ParametersAndQualifiers final : public Tree {
public:
ParametersAndQualifiers() : Tree(NodeKind::ParametersAndQualifiers) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::ParametersAndQualifiers;
- }
- syntax::Leaf *lparen();
- /// FIXME: use custom iterator instead of 'vector'.
- std::vector<syntax::SimpleDeclaration *> parameters();
- syntax::Leaf *rparen();
- syntax::TrailingReturnType *trailingReturn();
+ static bool classof(const Node *N);
+ Leaf *getLparen();
+ ParameterDeclarationList *getParameters();
+ Leaf *getRparen();
+ TrailingReturnType *getTrailingReturn();
};
/// Member pointer inside a declarator
@@ -877,11 +577,19 @@ public:
class MemberPointer final : public Tree {
public:
MemberPointer() : Tree(NodeKind::MemberPointer) {}
- static bool classof(const Node *N) {
- return N->kind() == NodeKind::MemberPointer;
- }
+ static bool classof(const Node *N);
};
+#define CONCRETE_NODE(Kind, Base) \
+ inline bool Kind::classof(const Node *N) { \
+ return N->getKind() == NodeKind::Kind; \
+ }
+#define ABSTRACT_NODE(Kind, Base, First, Last) \
+ inline bool Kind::classof(const Node *N) { \
+ return N->getKind() >= NodeKind::First && N->getKind() <= NodeKind::Last; \
+ }
+#include "clang/Tooling/Syntax/Nodes.inc"
+
} // namespace syntax
} // namespace clang
#endif
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td
new file mode 100644
index 000000000000..765710e3e72e
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td
@@ -0,0 +1,296 @@
+//===- Nodes.td - Node types in the Syntax Tree grammar -------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines concrete nodes in the syntax tree.
+// The archetypes they fall into (Sequence, List etc) are defined in Syntax.td.
+//
+// The C++ classes for the archetypes themselves are written by hand, and the
+// concrete node classes will be generated. Migration to TableGen is not
+// complete, so currently there is a mix of generated and hand-authored code.
+//
+//===----------------------------------------------------------------------===//
+
+include "clang/Tooling/Syntax/Syntax.td"
+
+def TranslationUnit : Unconstrained {
+ let documentation = [{
+ A root node for a translation unit. Parent is always null.
+ }];
+}
+
+def UnqualifiedId : External<Tree> {}
+
+// Lists
+def List : External<Tree> {}
+def DeclaratorList : External<List> {}
+def ParameterDeclarationList : External<List> {}
+def CallArguments : External<List> {}
+def NestedNameSpecifier : External<List> {}
+
+def Expression : Alternatives {
+ let documentation = [{
+ A base class for all expressions. Note that expressions are not statements,
+ even though they are in clang.
+ }];
+}
+def UnknownExpression : External<Expression> {}
+def UnaryOperatorExpression : External<Tree> {}
+def PrefixUnaryOperatorExpression : External<UnaryOperatorExpression> {}
+def PostfixUnaryOperatorExpression : External<UnaryOperatorExpression> {}
+def BinaryOperatorExpression : External<Expression> {}
+def ParenExpression : Sequence<Expression> {
+ let documentation = [{
+ Models a parenthesized expression `(E)`. C++ [expr.prim.paren]
+ e.g. `(3 + 2)` in `a = 1 + (3 + 2);`
+ }];
+ let children = [
+ Role<"OpenParen", Token<"l_paren">>,
+ Role<"SubExpression", Expression>,
+ Role<"CloseParen", Token<"r_paren">>,
+ ];
+}
+def LiteralExpression : Alternatives<Expression> {
+ let documentation = [{
+ Expression for literals. C++ [lex.literal]
+ }];
+}
+def IntegerLiteralExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for integer literals. C++ [lex.icon]
+ }];
+ let children = [
+ Role<"LiteralToken", Token<"numeric_constant">>,
+ ];
+}
+defvar AnyCharacterLiteral = AnyToken<[
+ "char_constant", "wide_char_constant", "utf8_char_constant",
+ "utf16_char_constant", "utf32_char_constant"
+]>;
+def CharacterLiteralExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for character literals. C++ [lex.ccon]
+ }];
+ let children = [
+ Role<"LiteralToken", AnyCharacterLiteral>,
+ ];
+}
+def FloatingLiteralExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for floating-point literals. C++ [lex.fcon]
+ }];
+ let children = [
+ Role<"LiteralToken", Token<"numeric_constant">>,
+ ];
+}
+defvar AnyStringLiteral = AnyToken<[
+ "string_literal", "wide_string_literal", "utf8_string_literal",
+ "utf16_string_literal", "utf32_string_literal"
+]>;
+def StringLiteralExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for string-literals. C++ [lex.string]
+ }];
+ // FIXME: string literals may consist of multiple tokens.
+ // These are merged in phase 6, but tokens are captured after phase 4.
+ // The child here should be a list of literal tokens instead.
+ let children = [
+ Role<"LiteralToken", AnyStringLiteral>,
+ ];
+}
+def BoolLiteralExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for boolean literals. C++ [lex.bool]
+ }];
+ let children = [
+ Role<"LiteralToken", AnyToken<["kw_false","kw_true"]>>,
+ ];
+}
+def CxxNullPtrExpression : Sequence<LiteralExpression> {
+ let documentation = [{
+ Expression for the `nullptr` literal. C++ [lex.nullptr]
+ }];
+ let children = [
+ Role<"LiteralToken", Keyword<"nullptr">>,
+ ];
+}
+def UserDefinedLiteralExpression : Alternatives<LiteralExpression> {
+ let documentation = [{
+ Expression for user-defined literal. C++ [lex.ext]
+ user-defined-literal:
+ user-defined-integer-literal
+ user-defined-floating-point-literal
+ user-defined-string-literal
+ user-defined-character-literal
+ }];
+}
+def IntegerUserDefinedLiteralExpression : Sequence<UserDefinedLiteralExpression> {
+ let documentation = [{
+ Expression for user-defined-integer-literal. C++ [lex.ext]
+ }];
+ let children = [
+ Role<"LiteralToken", Keyword<"numeric_constant">>,
+ ];
+}
+def FloatUserDefinedLiteralExpression : Sequence<UserDefinedLiteralExpression> {
+ let documentation = [{
+ Expression for user-defined-floating-point-literal. C++ [lex.ext]
+ }];
+ let children = [
+ Role<"LiteralToken", Keyword<"numeric_constant">>,
+ ];
+}
+def CharUserDefinedLiteralExpression : Sequence<UserDefinedLiteralExpression> {
+ let documentation = [{
+ Expression for user-defined-character-literal. C++ [lex.ext]
+ }];
+ let children = [
+ Role<"LiteralToken", AnyCharacterLiteral>,
+ ];
+}
+def StringUserDefinedLiteralExpression : Sequence<UserDefinedLiteralExpression> {
+ let documentation = [{
+ Expression for user-defined-string-literal. C++ [lex.ext]
+ }];
+ let children = [
+ Role<"LiteralToken", AnyStringLiteral>,
+ ];
+}
+def IdExpression : Sequence<Expression> {
+ let documentation = [{
+ Models an `id-expression`, e.g. `std::vector<int>::size`.
+ C++ [expr.prim.id]
+ id-expression:
+ unqualified-id
+ qualified-id
+ qualified-id:
+ nested-name-specifier template_opt unqualified-id
+ }];
+ let children = [
+ Role<"Qualifier", Optional<NestedNameSpecifier>>,
+ Role<"TemplateKeyword", Optional<Keyword<"template">>>,
+ Role<"UnqualifiedId", UnqualifiedId>,
+ ];
+}
+def MemberExpression : Sequence<Expression> {
+ let documentation = [{
+ Models a class member access. C++ [expr.ref]
+ member-expression:
+ expression -> template_opt id-expression
+ expression . template_opt id-expression
+ e.g. `x.a`, `xp->a`
+
+ Note: An implicit member access inside a class, i.e. `a` instead of
+ `this->a`, is an `id-expression`.
+ }];
+ let children = [
+ Role<"Object", Expression>,
+ Role<"AccessToken", AnyToken<["period","arrow"]>>,
+ Role<"TemplateKeyword", Optional<Keyword<"template">>>,
+ Role<"Member", IdExpression>,
+ ];
+}
+def ThisExpression : Sequence<Expression> {
+ let documentation = [{
+ Models a this expression `this`. C++ [expr.prim.this]
+ }];
+ let children = [
+ Role<"IntroducerKeyword", Keyword<"this">>,
+ ];
+}
+def CallExpression : Sequence<Expression> {
+ let documentation = [{
+ A function call. C++ [expr.call]
+ call-expression:
+ expression '(' call-arguments ')'
+ e.g `f(1, '2')` or `this->Base::f()`
+ }];
+ let children = [
+ Role<"Callee", Expression>,
+ Role<"OpenParen", Token<"l_paren">>,
+ Role<"Arguments", CallArguments>,
+ Role<"CloseParen", Token<"r_paren">>,
+ ];
+}
+
+// Statements.
+def Statement : External<Tree> {}
+def UnknownStatement : External<Statement> {}
+def DeclarationStatement : External<Statement> {}
+def EmptyStatement : External<Statement> {}
+def SwitchStatement : External<Statement> {}
+def CaseStatement : External<Statement> {}
+def DefaultStatement : External<Statement> {}
+def IfStatement : External<Statement> {}
+def ForStatement : External<Statement> {}
+def WhileStatement : External<Statement> {}
+def ContinueStatement : External<Statement> {}
+def BreakStatement : External<Statement> {}
+def ReturnStatement : External<Statement> {}
+def RangeBasedForStatement : External<Statement> {}
+def ExpressionStatement : External<Statement> {}
+def CompoundStatement : External<Statement> {}
+
+// Declarations.
+def Declaration : External<Tree> {}
+def UnknownDeclaration : External<Declaration> {}
+def EmptyDeclaration : External<Declaration> {}
+def StaticAssertDeclaration : External<Declaration> {}
+def LinkageSpecificationDeclaration : External<Declaration> {}
+def SimpleDeclaration : External<Declaration> {}
+def TemplateDeclaration : External<Declaration> {}
+def ExplicitTemplateInstantiation : External<Declaration> {}
+def NamespaceDefinition : External<Declaration> {}
+def NamespaceAliasDefinition : External<Declaration> {}
+def UsingNamespaceDirective : External<Declaration> {}
+def UsingDeclaration : External<Declaration> {}
+def TypeAliasDeclaration : External<Declaration> {}
+
+// Declarators.
+def Declarator : External<Tree> {}
+def SimpleDeclarator : External<Declarator> {}
+def ParenDeclarator : External<Declarator> {}
+
+def ArraySubscript : External<Tree> {}
+def TrailingReturnType : External<Tree> {}
+def ParametersAndQualifiers : External<Tree> {}
+def MemberPointer : External<Tree> {}
+
+// Name Specifiers.
+def NameSpecifier : Alternatives {
+ let documentation = [{
+ A sequence of these specifiers make a `nested-name-specifier`.
+ e.g. the `std` or `vector<int>` in `std::vector<int>::size`.
+ }];
+}
+def GlobalNameSpecifier : Unconstrained<NameSpecifier> {
+ let documentation = [{
+ The global namespace name specifier, this specifier doesn't correspond to a
+ token instead an absence of tokens before a `::` characterizes it, in
+ `::std::vector<int>` it would be characterized by the absence of a token
+ before the first `::`
+ }];
+}
+def DecltypeNameSpecifier : Unconstrained<NameSpecifier> {
+ let documentation = [{
+ A name specifier holding a decltype, of the form: `decltype ( expression ) `
+ e.g. the `decltype(s)` in `decltype(s)::size`.
+ }];
+}
+def IdentifierNameSpecifier : Unconstrained<NameSpecifier> {
+ let documentation = [{
+ A identifier name specifier, of the form `identifier`
+ e.g. the `std` in `std::vector<int>::size`.
+ }];
+}
+def SimpleTemplateNameSpecifier : Unconstrained<NameSpecifier> {
+ let documentation = [{
+ A name specifier with a simple-template-id, of the form `template_opt
+ identifier < template-args >` e.g. the `vector<int>` in
+ `std::vector<int>::size`.
+ }];
+}
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td
new file mode 100644
index 000000000000..2da0c1452b86
--- /dev/null
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td
@@ -0,0 +1,85 @@
+//===- Syntax.td - TableGen metamodel for syntax::Node hierarchy ----------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// The tree representation of the is C++ syntax is quite regular.
+//
+// There are 4 archetypes of nodes in the syntax tree:
+// - Leaves, owning exactly one token. (syntax::Leaf)
+// - Sequences, with a fixed list of children that should appear in order.
+// The concrete node defines a Role sequence which identifies the children.
+// The type of child in each role is also constrained.
+// - Lists, with children in alternating Element/Delimiter roles. (syntax::List)
+// The concrete node defines the element type, delimiters are always leaves.
+// - Alternatives, where several different node types are allowed.
+// These are modeled as abstract types with inheritance (e.g. Declaration).
+//
+// This file defines TableGen classes modelling these archetypes.
+// The concrete nodes are defined in terms of these classes in Nodes.td.
+//
+// The C++ classes for the archetypes themselves are written by hand, and the
+// concrete node classes will be generated. Migration to TableGen is not
+// complete, so currently there is a mix of generated and hand-authored code.
+//
+//===----------------------------------------------------------------------===//
+
+// Syntax is any constraint on constructs that can appear somewhere.
+class Syntax;
+class Optional<Syntax inner_> : Syntax { Syntax inner = inner_; }
+class AnyToken<list<string> kinds_> : Syntax { list<string> kinds = kinds_; }
+class Token<string kind_> : AnyToken<[kind_]>;
+class Keyword<string kw> : Token<!strconcat("kw_", kw)>;
+
+// Defs derived from NodeType correspond to syntax tree node types.
+// NodeType is also a syntax constraint: one node of this type.
+class NodeType : Syntax {
+ // The NodeType that this node is derived from in the Node class hierarchy.
+ NodeType base = ?;
+ // Documentation for this Node subclass.
+ string documentation;
+}
+
+// A node type which is defined in Nodes.h rather than by generated code.
+// We merely specify the inheritance hierarchy here.
+class External<NodeType base_> : NodeType { let base = base_; }
+
+// Special nodes defined here.
+def Node : External<?> {}
+def Leaf : External<Node> {}
+def Tree : External<Node> {}
+
+// An abstract node type which merely serves as a base for more specific types.
+//
+// This corresponds to an alternative rule in the grammar, such as:
+// Statement = IfStatement | ForStatement | ...
+// Statement is modeled using Alternatives, and IfStatement.base is Statement.
+class Alternatives<NodeType base_ = Tree> : NodeType { let base = base_; }
+
+// A node type which may contain anything and has no specific accessors.
+// These are generally placeholders for a more precise implementation.
+class Unconstrained<NodeType base_ = Tree> : NodeType { let base = base_; }
+
+class Role<string role_, Syntax syntax_> {
+ string role = role_;
+ Syntax syntax = syntax_;
+}
+
+// A node which contains a fixed sequence of children in a particular order.
+//
+// Each child is characterized by a role (unique within the sequence), and
+// has an allowed base type for the node.
+// The role sequence and role/type match are enforced invariants of the class.
+//
+// We also record whether the child is required to be present, and which tokens
+// are permitted (for Leaf nodes). These invariants are not enforced.
+class Sequence<NodeType base_ = Tree> : NodeType {
+ let base = base_;
+ // Children must be Role or have a default role derived from the NodeType.
+ list<Role> children;
+}
+
+// FIXME: add list archetype.
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h
index a7f9369ddfff..98320bd54d6f 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h
@@ -275,6 +275,10 @@ public:
/// macro expands to.
llvm::Optional<Expansion>
expansionStartingAt(const syntax::Token *Spelled) const;
+ /// Returns all expansions (partially) expanded from the specified tokens.
+ /// This is the expansions whose Spelled range intersects \p Spelled.
+ std::vector<Expansion>
+ expansionsOverlapping(llvm::ArrayRef<syntax::Token> Spelled) const;
/// Lexed tokens of a file before preprocessing. E.g. for the following input
/// #define DECL(name) int name = 10
@@ -352,6 +356,12 @@ private:
mappingStartingBeforeSpelled(const MarkedFile &F,
const syntax::Token *Spelled);
+ /// Convert a private Mapping to a public Expansion.
+ Expansion makeExpansion(const MarkedFile &, const Mapping &) const;
+ /// Returns the file that the Spelled tokens are taken from.
+ /// Asserts that they are non-empty, from a tracked file, and in-bounds.
+ const MarkedFile &fileForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const;
+
/// Token stream produced after preprocessing, conceputally this captures the
/// same stream as 'clang -E' (excluding the preprocessor directives like
/// #file, etc.).
@@ -428,7 +438,7 @@ private:
/// the stack) and not when they end (when we pop a macro from the stack).
/// To workaround this limitation, we rely on source location information
/// stored in this map.
- using PPExpansions = llvm::DenseMap</*SourceLocation*/ int, SourceLocation>;
+ using PPExpansions = llvm::DenseMap<SourceLocation, SourceLocation>;
class Builder;
class CollectPPExpansions;
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h
index bc581004c46e..b92e92305417 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h
@@ -28,8 +28,10 @@
#include "clang/Tooling/Syntax/Tokens.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/iterator.h"
#include "llvm/Support/Allocator.h"
#include <cstdint>
+#include <iterator>
namespace clang {
namespace syntax {
@@ -39,26 +41,28 @@ namespace syntax {
class Arena {
public:
Arena(SourceManager &SourceMgr, const LangOptions &LangOpts,
- TokenBuffer Tokens);
+ const TokenBuffer &Tokens);
- const SourceManager &sourceManager() const { return SourceMgr; }
- const LangOptions &langOptions() const { return LangOpts; }
+ const SourceManager &getSourceManager() const { return SourceMgr; }
+ const LangOptions &getLangOptions() const { return LangOpts; }
- const TokenBuffer &tokenBuffer() const;
- llvm::BumpPtrAllocator &allocator() { return Allocator; }
+ const TokenBuffer &getTokenBuffer() const;
+ llvm::BumpPtrAllocator &getAllocator() { return Allocator; }
+private:
/// Add \p Buffer to the underlying source manager, tokenize it and store the
- /// resulting tokens. Useful when there is a need to materialize tokens that
- /// were not written in user code.
- std::pair<FileID, llvm::ArrayRef<syntax::Token>>
+ /// resulting tokens. Used exclusively in `FactoryImpl` to materialize tokens
+ /// that were not written in user code.
+ std::pair<FileID, ArrayRef<Token>>
lexBuffer(std::unique_ptr<llvm::MemoryBuffer> Buffer);
+ friend class FactoryImpl;
private:
SourceManager &SourceMgr;
const LangOptions &LangOpts;
- TokenBuffer Tokens;
+ const TokenBuffer &Tokens;
/// IDs and storage for additional tokenized files.
- llvm::DenseMap<FileID, std::vector<syntax::Token>> ExtraTokens;
+ llvm::DenseMap<FileID, std::vector<Token>> ExtraTokens;
/// Keeps all the allocated nodes and their intermediate data structures.
llvm::BumpPtrAllocator Allocator;
};
@@ -74,13 +78,23 @@ enum class NodeRole : uint8_t;
/// A node in a syntax tree. Each node is either a Leaf (representing tokens) or
/// a Tree (representing language constructrs).
class Node {
-public:
+protected:
/// Newly created nodes are detached from a tree, parent and sibling links are
/// set when the node is added as a child to another one.
Node(NodeKind Kind);
+ /// Nodes are allocated on Arenas; the destructor is never called.
+ ~Node() = default;
- NodeKind kind() const { return static_cast<NodeKind>(Kind); }
- NodeRole role() const { return static_cast<NodeRole>(Role); }
+public:
+ /// Nodes cannot simply be copied without violating tree invariants.
+ Node(const Node &) = delete;
+ Node &operator=(const Node &) = delete;
+ /// Idiomatically, nodes are allocated on an Arena and never moved.
+ Node(Node &&) = delete;
+ Node &operator=(Node &&) = delete;
+
+ NodeKind getKind() const { return static_cast<NodeKind>(Kind); }
+ NodeRole getRole() const { return static_cast<NodeRole>(Role); }
/// Whether the node is detached from a tree, i.e. does not have a parent.
bool isDetached() const;
@@ -99,16 +113,18 @@ public:
/// modifiable.
bool canModify() const { return CanModify; }
- const Tree *parent() const { return Parent; }
- Tree *parent() { return Parent; }
+ const Tree *getParent() const { return Parent; }
+ Tree *getParent() { return Parent; }
- const Node *nextSibling() const { return NextSibling; }
- Node *nextSibling() { return NextSibling; }
+ const Node *getNextSibling() const { return NextSibling; }
+ Node *getNextSibling() { return NextSibling; }
+ const Node *getPreviousSibling() const { return PreviousSibling; }
+ Node *getPreviousSibling() { return PreviousSibling; }
/// Dumps the structure of a subtree. For debugging and testing purposes.
- std::string dump(const Arena &A) const;
+ std::string dump(const SourceManager &SM) const;
/// Dumps the tokens forming this subtree.
- std::string dumpTokens(const Arena &A) const;
+ std::string dumpTokens(const SourceManager &SM) const;
/// Asserts invariants on this node of the tree and its immediate children.
/// Will not recurse into the subtree. No-op if NDEBUG is set.
@@ -130,6 +146,7 @@ private:
Tree *Parent;
Node *NextSibling;
+ Node *PreviousSibling;
unsigned Kind : 16;
unsigned Role : 8;
unsigned Original : 1;
@@ -139,56 +156,183 @@ private:
/// A leaf node points to a single token inside the expanded token stream.
class Leaf final : public Node {
public:
- Leaf(const syntax::Token *T);
+ Leaf(const Token *T);
static bool classof(const Node *N);
- const syntax::Token *token() const { return Tok; }
+ const Token *getToken() const { return Tok; }
private:
- const syntax::Token *Tok;
+ const Token *Tok;
};
/// A node that has children and represents a syntactic language construct.
class Tree : public Node {
+ /// Iterator over children (common base for const/non-const).
+ /// Not invalidated by tree mutations (holds a stable node pointer).
+ template <typename DerivedT, typename NodeT>
+ class ChildIteratorBase
+ : public llvm::iterator_facade_base<DerivedT, std::forward_iterator_tag,
+ NodeT> {
+ protected:
+ NodeT *N = nullptr;
+ using Base = ChildIteratorBase;
+
+ public:
+ ChildIteratorBase() = default;
+ explicit ChildIteratorBase(NodeT *N) : N(N) {}
+
+ bool operator==(const DerivedT &O) const { return O.N == N; }
+ NodeT &operator*() const { return *N; }
+ DerivedT &operator++() {
+ N = N->getNextSibling();
+ return *static_cast<DerivedT *>(this);
+ }
+
+ /// Truthy if valid (not past-the-end).
+ /// This allows: if (auto It = find_if(N.children(), ...) )
+ explicit operator bool() const { return N != nullptr; }
+ /// The element, or nullptr if past-the-end.
+ NodeT *asPointer() const { return N; }
+ };
+
public:
- using Node::Node;
static bool classof(const Node *N);
- Node *firstChild() { return FirstChild; }
- const Node *firstChild() const { return FirstChild; }
+ Node *getFirstChild() { return FirstChild; }
+ const Node *getFirstChild() const { return FirstChild; }
+ Node *getLastChild() { return LastChild; }
+ const Node *getLastChild() const { return LastChild; }
- Leaf *firstLeaf();
- const Leaf *firstLeaf() const {
- return const_cast<Tree *>(this)->firstLeaf();
+ const Leaf *findFirstLeaf() const;
+ Leaf *findFirstLeaf() {
+ return const_cast<Leaf *>(const_cast<const Tree *>(this)->findFirstLeaf());
}
- Leaf *lastLeaf();
- const Leaf *lastLeaf() const { return const_cast<Tree *>(this)->lastLeaf(); }
+ const Leaf *findLastLeaf() const;
+ Leaf *findLastLeaf() {
+ return const_cast<Leaf *>(const_cast<const Tree *>(this)->findLastLeaf());
+ }
+
+ /// child_iterator is not invalidated by mutations.
+ struct ChildIterator : ChildIteratorBase<ChildIterator, Node> {
+ using Base::ChildIteratorBase;
+ };
+ struct ConstChildIterator
+ : ChildIteratorBase<ConstChildIterator, const Node> {
+ using Base::ChildIteratorBase;
+ ConstChildIterator() = default;
+ ConstChildIterator(const ChildIterator &I) : Base(I.asPointer()) {}
+ };
+
+ llvm::iterator_range<ChildIterator> getChildren() {
+ return {ChildIterator(getFirstChild()), ChildIterator()};
+ }
+ llvm::iterator_range<ConstChildIterator> getChildren() const {
+ return {ConstChildIterator(getFirstChild()), ConstChildIterator()};
+ }
-protected:
/// Find the first node with a corresponding role.
- syntax::Node *findChild(NodeRole R);
+ const Node *findChild(NodeRole R) const;
+ Node *findChild(NodeRole R) {
+ return const_cast<Node *>(const_cast<const Tree *>(this)->findChild(R));
+ }
+
+protected:
+ using Node::Node;
private:
- /// Prepend \p Child to the list of children and and sets the parent pointer.
+ /// Append \p Child to the list of children and sets the parent pointer.
/// A very low-level operation that does not check any invariants, only used
/// by TreeBuilder and FactoryImpl.
/// EXPECTS: Role != Detached.
+ void appendChildLowLevel(Node *Child, NodeRole Role);
+ /// Similar but prepends.
void prependChildLowLevel(Node *Child, NodeRole Role);
- /// Like the previous overload, but does not set role for \p Child.
+
+ /// Like the previous overloads, but does not set role for \p Child.
/// EXPECTS: Child->Role != Detached
+ void appendChildLowLevel(Node *Child);
void prependChildLowLevel(Node *Child);
friend class TreeBuilder;
friend class FactoryImpl;
- /// Replace a range of children [BeforeBegin->NextSibling, End) with a list of
+ /// Replace a range of children [Begin, End) with a list of
/// new nodes starting at \p New.
/// Only used by MutationsImpl to implement higher-level mutation operations.
/// (!) \p New can be null to model removal of the child range.
- void replaceChildRangeLowLevel(Node *BeforeBegin, Node *End, Node *New);
+ /// (!) \p End can be null to model one past the end.
+ /// (!) \p Begin can be null to model an append.
+ void replaceChildRangeLowLevel(Node *Begin, Node *End, Node *New);
friend class MutationsImpl;
Node *FirstChild = nullptr;
+ Node *LastChild = nullptr;
+};
+
+// Provide missing non_const == const overload.
+// iterator_facade_base requires == to be a member, but implicit conversions
+// don't work on the LHS of a member operator.
+inline bool operator==(const Tree::ConstChildIterator &A,
+ const Tree::ConstChildIterator &B) {
+ return A.operator==(B);
+}
+
+/// A list of Elements separated or terminated by a fixed token.
+///
+/// This type models the following grammar construct:
+/// delimited-list(element, delimiter, termination, canBeEmpty)
+class List : public Tree {
+public:
+ template <typename Element> struct ElementAndDelimiter {
+ Element *element;
+ Leaf *delimiter;
+ };
+
+ enum class TerminationKind {
+ Terminated,
+ MaybeTerminated,
+ Separated,
+ };
+
+ using Tree::Tree;
+ static bool classof(const Node *N);
+ /// Returns the elements and corresponding delimiters. Missing elements
+ /// and delimiters are represented as null pointers.
+ ///
+ /// For example, in a separated list:
+ /// "a, b, c" <=> [("a" , ","), ("b" , "," ), ("c" , null)]
+ /// "a, , c" <=> [("a" , ","), (null, "," ), ("c" , null)]
+ /// "a, b c" <=> [("a" , ","), ("b" , null), ("c" , null)]
+ /// "a, b," <=> [("a" , ","), ("b" , "," ), (null, null)]
+ ///
+ /// In a terminated or maybe-terminated list:
+ /// "a; b; c;" <=> [("a" , ";"), ("b" , ";" ), ("c" , ";" )]
+ /// "a; ; c;" <=> [("a" , ";"), (null, ";" ), ("c" , ";" )]
+ /// "a; b c;" <=> [("a" , ";"), ("b" , null), ("c" , ";" )]
+ /// "a; b; c" <=> [("a" , ";"), ("b" , ";" ), ("c" , null)]
+ std::vector<ElementAndDelimiter<Node>> getElementsAsNodesAndDelimiters();
+
+ /// Returns the elements of the list. Missing elements are represented
+ /// as null pointers in the same way as in the return value of
+ /// `getElementsAsNodesAndDelimiters()`.
+ std::vector<Node *> getElementsAsNodes();
+
+ // These can't be implemented with the information we have!
+
+ /// Returns the appropriate delimiter for this list.
+ ///
+ /// Useful for discovering the correct delimiter to use when adding
+ /// elements to empty or one-element lists.
+ clang::tok::TokenKind getDelimiterTokenKind() const;
+
+ TerminationKind getTerminationKind() const;
+
+ /// Whether this list can be empty in syntactically and semantically correct
+ /// code.
+ ///
+ /// This list may be empty when the source code has errors even if
+ /// canBeEmpty() returns false.
+ bool canBeEmpty() const;
};
} // namespace syntax
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Tooling.h b/contrib/llvm-project/clang/include/clang/Tooling/Tooling.h
index 4fb0c18be95e..8b3b2e5ad002 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Tooling.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Tooling.h
@@ -265,21 +265,12 @@ public:
this->DiagConsumer = DiagConsumer;
}
- /// Map a virtual file to be used while running the tool.
- ///
- /// \param FilePath The path at which the content will be mapped.
- /// \param Content A null terminated buffer of the file's content.
- // FIXME: remove this when all users have migrated!
- void mapVirtualFile(StringRef FilePath, StringRef Content);
-
/// Run the clang invocation.
///
/// \returns True if there were no errors during execution.
bool run();
private:
- void addFileMappingsTo(SourceManager &SourceManager);
-
bool runInvocation(const char *BinaryName,
driver::Compilation *Compilation,
std::shared_ptr<CompilerInvocation> Invocation,
@@ -290,8 +281,6 @@ public:
bool OwnsAction;
FileManager *Files;
std::shared_ptr<PCHContainerOperations> PCHContainerOps;
- // Maps <file name> -> <file content>.
- llvm::StringMap<StringRef> MappedFileContents;
DiagnosticConsumer *DiagConsumer = nullptr;
};
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h
index f407ffce3d25..cb0a5f684b7d 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h
@@ -99,11 +99,5 @@ llvm::Expected<T> MatchComputation<T>::eval(
return Output;
}
} // namespace transformer
-
-namespace tooling {
-// DEPRECATED: Temporary alias supporting client migration to the `transformer`
-// namespace.
-using transformer::ifBound;
-} // namespace tooling
} // namespace clang
#endif // LLVM_CLANG_TOOLING_TRANSFORMER_MATCH_CONSUMER_H_
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h
index 2807037bc208..f17fb8c7b5c6 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h
@@ -56,8 +56,13 @@ RangeSelector before(RangeSelector Selector);
/// * the TokenRange [B,E'] where the token at E' spans the range [E',E).
RangeSelector after(RangeSelector Selector);
-/// Selects a node, including trailing semicolon (for non-expression
-/// statements). \p ID is the node's binding in the match result.
+/// Selects the range between `R1` and `R2.
+inline RangeSelector between(RangeSelector R1, RangeSelector R2) {
+ return enclose(after(std::move(R1)), before(std::move(R2)));
+}
+
+/// Selects a node, including trailing semicolon, if any (for declarations and
+/// non-expression statements). \p ID is the node's binding in the match result.
RangeSelector node(std::string ID);
/// Selects a node, including trailing semicolon (always). Useful for selecting
@@ -98,26 +103,6 @@ RangeSelector elseBranch(std::string ID);
/// `SourceManager::getExpansionRange`.
RangeSelector expansion(RangeSelector S);
} // namespace transformer
-
-namespace tooling {
-// DEPRECATED: These are temporary aliases supporting client migration to the
-// `transformer` namespace.
-using RangeSelector = transformer::RangeSelector;
-
-using transformer::after;
-using transformer::before;
-using transformer::callArgs;
-using transformer::charRange;
-using transformer::elseBranch;
-using transformer::expansion;
-using transformer::initListElements;
-using transformer::member;
-using transformer::name;
-using transformer::node;
-using transformer::range;
-using transformer::statement;
-using transformer::statements;
-} // namespace tooling
} // namespace clang
#endif // LLVM_CLANG_TOOLING_REFACTOR_RANGE_SELECTOR_H_
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h
index d9e68717d5c8..ac93db8446df 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h
@@ -31,14 +31,30 @@
namespace clang {
namespace transformer {
+// Specifies how to interpret an edit.
+enum class EditKind {
+ // Edits a source range in the file.
+ Range,
+ // Inserts an include in the file. The `Replacement` field is the name of the
+ // newly included file.
+ AddInclude,
+};
+
/// A concrete description of a source edit, represented by a character range in
/// the source to be replaced and a corresponding replacement string.
struct Edit {
+ EditKind Kind = EditKind::Range;
CharSourceRange Range;
std::string Replacement;
llvm::Any Metadata;
};
+/// Format of the path in an include directive -- angle brackets or quotes.
+enum class IncludeFormat {
+ Quoted,
+ Angled,
+};
+
/// Maps a match result to a list of concrete edits (with possible
/// failure). This type is a building block of rewrite rules, but users will
/// generally work in terms of `ASTEdit`s (below) rather than directly in terms
@@ -47,6 +63,8 @@ using EditGenerator = MatchConsumer<llvm::SmallVector<Edit, 1>>;
using TextGenerator = std::shared_ptr<MatchComputation<std::string>>;
+using AnyGenerator = MatchConsumer<llvm::Any>;
+
// Description of a source-code edit, expressed in terms of an AST node.
// Includes: an ID for the (bound) node, a selector for source related to the
// node, a replacement and, optionally, an explanation for the edit.
@@ -84,12 +102,21 @@ using TextGenerator = std::shared_ptr<MatchComputation<std::string>>;
// changeTo(cat("different_expr"))
// \endcode
struct ASTEdit {
+ EditKind Kind = EditKind::Range;
RangeSelector TargetRange;
TextGenerator Replacement;
TextGenerator Note;
- llvm::Any Metadata;
+ // Not all transformations will want or need to attach metadata and therefore
+ // should not be required to do so.
+ AnyGenerator Metadata = [](const ast_matchers::MatchFinder::MatchResult &)
+ -> llvm::Expected<llvm::Any> {
+ return llvm::Expected<llvm::Any>(llvm::Any());
+ };
};
+/// Generates a single (specified) edit.
+EditGenerator edit(ASTEdit E);
+
/// Lifts a list of `ASTEdit`s into an `EditGenerator`.
///
/// The `EditGenerator` will return an empty vector if any of the edits apply to
@@ -100,14 +127,130 @@ struct ASTEdit {
/// clients. We recommend use of the \c AtomicChange or \c Replacements classes
/// for assistance in detecting such conflicts.
EditGenerator editList(llvm::SmallVector<ASTEdit, 1> Edits);
-// Convenience form of `editList` for a single edit.
-EditGenerator edit(ASTEdit);
-/// Format of the path in an include directive -- angle brackets or quotes.
-enum class IncludeFormat {
- Quoted,
- Angled,
-};
+/// Generates no edits.
+inline EditGenerator noEdits() { return editList({}); }
+
+/// Generates a single, no-op edit anchored at the start location of the
+/// specified range. A `noopEdit` may be preferred over `noEdits` to associate a
+/// diagnostic `Explanation` with the rule.
+EditGenerator noopEdit(RangeSelector Anchor);
+
+/// Version of `ifBound` specialized to `ASTEdit`.
+inline EditGenerator ifBound(std::string ID, ASTEdit TrueEdit,
+ ASTEdit FalseEdit) {
+ return ifBound(std::move(ID), edit(std::move(TrueEdit)),
+ edit(std::move(FalseEdit)));
+}
+
+/// Version of `ifBound` that has no "False" branch. If the node is not bound,
+/// then no edits are produced.
+inline EditGenerator ifBound(std::string ID, ASTEdit TrueEdit) {
+ return ifBound(std::move(ID), edit(std::move(TrueEdit)), noEdits());
+}
+
+/// Flattens a list of generators into a single generator whose elements are the
+/// concatenation of the results of the argument generators.
+EditGenerator flattenVector(SmallVector<EditGenerator, 2> Generators);
+
+namespace detail {
+/// Helper function to construct an \c EditGenerator. Overloaded for common
+/// cases so that user doesn't need to specify which factory function to
+/// use. This pattern gives benefits similar to implicit constructors, while
+/// maintaing a higher degree of explicitness.
+inline EditGenerator injectEdits(ASTEdit E) { return edit(std::move(E)); }
+inline EditGenerator injectEdits(EditGenerator G) { return G; }
+} // namespace detail
+
+template <typename... Ts> EditGenerator flatten(Ts &&...Edits) {
+ return flattenVector({detail::injectEdits(std::forward<Ts>(Edits))...});
+}
+
+// Every rewrite rule is triggered by a match against some AST node.
+// Transformer guarantees that this ID is bound to the triggering node whenever
+// a rewrite rule is applied.
+extern const char RootID[];
+
+/// Replaces a portion of the source text with \p Replacement.
+ASTEdit changeTo(RangeSelector Target, TextGenerator Replacement);
+/// DEPRECATED: use \c changeTo.
+inline ASTEdit change(RangeSelector Target, TextGenerator Replacement) {
+ return changeTo(std::move(Target), std::move(Replacement));
+}
+
+/// Replaces the entirety of a RewriteRule's match with \p Replacement. For
+/// example, to replace a function call, one could write:
+/// \code
+/// makeRule(callExpr(callee(functionDecl(hasName("foo")))),
+/// changeTo(cat("bar()")))
+/// \endcode
+inline ASTEdit changeTo(TextGenerator Replacement) {
+ return changeTo(node(RootID), std::move(Replacement));
+}
+/// DEPRECATED: use \c changeTo.
+inline ASTEdit change(TextGenerator Replacement) {
+ return changeTo(std::move(Replacement));
+}
+
+/// Inserts \p Replacement before \p S, leaving the source selected by \S
+/// unchanged.
+inline ASTEdit insertBefore(RangeSelector S, TextGenerator Replacement) {
+ return changeTo(before(std::move(S)), std::move(Replacement));
+}
+
+/// Inserts \p Replacement after \p S, leaving the source selected by \S
+/// unchanged.
+inline ASTEdit insertAfter(RangeSelector S, TextGenerator Replacement) {
+ return changeTo(after(std::move(S)), std::move(Replacement));
+}
+
+/// Removes the source selected by \p S.
+ASTEdit remove(RangeSelector S);
+
+/// Adds an include directive for the given header to the file of `Target`. The
+/// particular location specified by `Target` is ignored.
+ASTEdit addInclude(RangeSelector Target, StringRef Header,
+ IncludeFormat Format = IncludeFormat::Quoted);
+
+/// Adds an include directive for the given header to the file associated with
+/// `RootID`. If `RootID` matches inside a macro expansion, will add the
+/// directive to the file in which the macro was expanded (as opposed to the
+/// file in which the macro is defined).
+inline ASTEdit addInclude(StringRef Header,
+ IncludeFormat Format = IncludeFormat::Quoted) {
+ return addInclude(expansion(node(RootID)), Header, Format);
+}
+
+// FIXME: If `Metadata` returns an `llvm::Expected<T>` the `AnyGenerator` will
+// construct an `llvm::Expected<llvm::Any>` where no error is present but the
+// `llvm::Any` holds the error. This is unlikely but potentially surprising.
+// Perhaps the `llvm::Expected` should be unwrapped, or perhaps this should be a
+// compile-time error. No solution here is perfect.
+//
+// Note: This function template accepts any type callable with a MatchResult
+// rather than a `std::function` because the return-type needs to be deduced. If
+// it accepted a `std::function<R(MatchResult)>`, lambdas or other callable
+// types would not be able to deduce `R`, and users would be forced to specify
+// explicitly the type they intended to return by wrapping the lambda at the
+// call-site.
+template <typename Callable>
+inline ASTEdit withMetadata(ASTEdit Edit, Callable Metadata) {
+ Edit.Metadata =
+ [Gen = std::move(Metadata)](
+ const ast_matchers::MatchFinder::MatchResult &R) -> llvm::Any {
+ return Gen(R);
+ };
+
+ return Edit;
+}
+
+/// Assuming that the inner range is enclosed by the outer range, creates
+/// precision edits to remove the parts of the outer range that are not included
+/// in the inner range.
+inline EditGenerator shrinkTo(RangeSelector outer, RangeSelector inner) {
+ return editList({remove(enclose(before(outer), before(inner))),
+ remove(enclose(after(inner), after(outer)))});
+}
/// Description of a source-code transformation.
//
@@ -137,25 +280,19 @@ struct RewriteRule {
ast_matchers::internal::DynTypedMatcher Matcher;
EditGenerator Edits;
TextGenerator Explanation;
- // Include paths to add to the file affected by this case. These are
- // bundled with the `Case`, rather than the `RewriteRule`, because each case
- // might have different associated changes to the includes.
- std::vector<std::pair<std::string, IncludeFormat>> AddedIncludes;
};
// We expect RewriteRules will most commonly include only one case.
SmallVector<Case, 1> Cases;
- // ID used as the default target of each match. The node described by the
- // matcher is should always be bound to this id.
- static constexpr llvm::StringLiteral RootID = "___root___";
+ /// DEPRECATED: use `::clang::transformer::RootID` instead.
+ static const llvm::StringRef RootID;
};
-/// Convenience function for constructing a simple \c RewriteRule.
+/// Constructs a simple \c RewriteRule.
RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
EditGenerator Edits, TextGenerator Explanation = nullptr);
-/// Convenience function for constructing a \c RewriteRule from multiple
-/// `ASTEdit`s.
+/// Constructs a \c RewriteRule from multiple `ASTEdit`s.
inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
llvm::SmallVector<ASTEdit, 1> Edits,
TextGenerator Explanation = nullptr) {
@@ -163,7 +300,7 @@ inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
std::move(Explanation));
}
-/// Convenience overload of \c makeRule for common case of only one edit.
+/// Overload of \c makeRule for common case of only one edit.
inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
ASTEdit Edit,
TextGenerator Explanation = nullptr) {
@@ -177,8 +314,8 @@ inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
/// \code
/// auto R = makeRule(callExpr(callee(functionDecl(hasName("foo")))),
/// changeTo(cat("bar()")));
-/// AddInclude(R, "path/to/bar_header.h");
-/// AddInclude(R, "vector", IncludeFormat::Angled);
+/// addInclude(R, "path/to/bar_header.h");
+/// addInclude(R, "vector", IncludeFormat::Angled);
/// \endcode
void addInclude(RewriteRule &Rule, llvm::StringRef Header,
IncludeFormat Format = IncludeFormat::Quoted);
@@ -224,47 +361,22 @@ void addInclude(RewriteRule &Rule, llvm::StringRef Header,
// ```
RewriteRule applyFirst(ArrayRef<RewriteRule> Rules);
-/// Replaces a portion of the source text with \p Replacement.
-ASTEdit changeTo(RangeSelector Target, TextGenerator Replacement);
-/// DEPRECATED: use \c changeTo.
-inline ASTEdit change(RangeSelector Target, TextGenerator Replacement) {
- return changeTo(std::move(Target), std::move(Replacement));
-}
-
-/// Replaces the entirety of a RewriteRule's match with \p Replacement. For
-/// example, to replace a function call, one could write:
-/// \code
-/// makeRule(callExpr(callee(functionDecl(hasName("foo")))),
-/// changeTo(cat("bar()")))
-/// \endcode
-inline ASTEdit changeTo(TextGenerator Replacement) {
- return changeTo(node(std::string(RewriteRule::RootID)),
- std::move(Replacement));
-}
-/// DEPRECATED: use \c changeTo.
-inline ASTEdit change(TextGenerator Replacement) {
- return changeTo(std::move(Replacement));
-}
-
-/// Inserts \p Replacement before \p S, leaving the source selected by \S
-/// unchanged.
-inline ASTEdit insertBefore(RangeSelector S, TextGenerator Replacement) {
- return changeTo(before(std::move(S)), std::move(Replacement));
-}
-
-/// Inserts \p Replacement after \p S, leaving the source selected by \S
-/// unchanged.
-inline ASTEdit insertAfter(RangeSelector S, TextGenerator Replacement) {
- return changeTo(after(std::move(S)), std::move(Replacement));
-}
-
-/// Removes the source selected by \p S.
-ASTEdit remove(RangeSelector S);
-
-inline ASTEdit withMetadata(ASTEdit edit, llvm::Any Metadata) {
- edit.Metadata = std::move(Metadata);
- return edit;
-}
+/// Applies `Rule` to all descendants of the node bound to `NodeId`. `Rule` can
+/// refer to nodes bound by the calling rule. `Rule` is not applied to the node
+/// itself.
+///
+/// For example,
+/// ```
+/// auto InlineX =
+/// makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3")));
+/// makeRule(functionDecl(hasName("f"), hasBody(stmt().bind("body"))).bind("f"),
+/// flatten(
+/// changeTo(name("f"), cat("newName")),
+/// rewriteDescendants("body", InlineX)));
+/// ```
+/// Here, we find the function `f`, change its name to `newName` and change all
+/// appearances of `x` in its body to `3`.
+EditGenerator rewriteDescendants(std::string NodeId, RewriteRule Rule);
/// The following three functions are a low-level part of the RewriteRule
/// API. We expose them for use in implementing the fixtures that interpret
@@ -275,6 +387,38 @@ inline ASTEdit withMetadata(ASTEdit edit, llvm::Any Metadata) {
// RewriteRule API. Recast them as such. Or, just declare these functions
// public and well-supported and move them out of `detail`.
namespace detail {
+/// The following overload set is a version of `rewriteDescendants` that
+/// operates directly on the AST, rather than generating a Transformer
+/// combinator. It applies `Rule` to all descendants of `Node`, although not
+/// `Node` itself. `Rule` can refer to nodes bound in `Result`.
+///
+/// For example, assuming that "body" is bound to a function body in MatchResult
+/// `Results`, this will produce edits to change all appearances of `x` in that
+/// body to `3`.
+/// ```
+/// auto InlineX =
+/// makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3")));
+/// const auto *Node = Results.Nodes.getNodeAs<Stmt>("body");
+/// auto Edits = rewriteDescendants(*Node, InlineX, Results);
+/// ```
+/// @{
+llvm::Expected<SmallVector<Edit, 1>>
+rewriteDescendants(const Decl &Node, RewriteRule Rule,
+ const ast_matchers::MatchFinder::MatchResult &Result);
+
+llvm::Expected<SmallVector<Edit, 1>>
+rewriteDescendants(const Stmt &Node, RewriteRule Rule,
+ const ast_matchers::MatchFinder::MatchResult &Result);
+
+llvm::Expected<SmallVector<Edit, 1>>
+rewriteDescendants(const TypeLoc &Node, RewriteRule Rule,
+ const ast_matchers::MatchFinder::MatchResult &Result);
+
+llvm::Expected<SmallVector<Edit, 1>>
+rewriteDescendants(const DynTypedNode &Node, RewriteRule Rule,
+ const ast_matchers::MatchFinder::MatchResult &Result);
+/// @}
+
/// Builds a single matcher for the rule, covering all of the rule's cases.
/// Only supports Rules whose cases' matchers share the same base "kind"
/// (`Stmt`, `Decl`, etc.) Deprecated: use `buildMatchers` instead, which
@@ -304,28 +448,6 @@ findSelectedCase(const ast_matchers::MatchFinder::MatchResult &Result,
const RewriteRule &Rule);
} // namespace detail
} // namespace transformer
-
-namespace tooling {
-// DEPRECATED: These are temporary aliases supporting client migration to the
-// `transformer` namespace.
-/// Wraps a string as a TextGenerator.
-using TextGenerator = transformer::TextGenerator;
-
-TextGenerator text(std::string M);
-
-using transformer::addInclude;
-using transformer::applyFirst;
-using transformer::change;
-using transformer::insertAfter;
-using transformer::insertBefore;
-using transformer::makeRule;
-using transformer::remove;
-using transformer::RewriteRule;
-using transformer::IncludeFormat;
-namespace detail {
-using namespace transformer::detail;
-} // namespace detail
-} // namespace tooling
} // namespace clang
#endif // LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
diff --git a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h
index 1b50a670f70b..1b7495eb0262 100644
--- a/contrib/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h
+++ b/contrib/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h
@@ -82,7 +82,6 @@ Stencil deref(llvm::StringRef ExprId);
/// If \p ExprId is of pointer type, constructs an idiomatic dereferencing of
/// the expression bound to \p ExprId, including wrapping it in parentheses, if
/// needed. Otherwise, generates the original expression source.
-/// FIXME: Identify smart-pointers as pointer types.
Stencil maybeDeref(llvm::StringRef ExprId);
/// Constructs an expression that idiomatically takes the address of the
@@ -94,7 +93,6 @@ Stencil addressOf(llvm::StringRef ExprId);
/// idiomatically takes the address of the expression bound to \p ExprId,
/// including wrapping \p ExprId in parentheses, if needed. Otherwise, generates
/// the original expression source.
-/// FIXME: Identify smart-pointers as pointer types.
Stencil maybeAddressOf(llvm::StringRef ExprId);
/// Constructs a `MemberExpr` that accesses the named member (\p Member) of the
@@ -123,6 +121,15 @@ inline Stencil ifBound(llvm::StringRef Id, llvm::StringRef TrueText,
/// Stencil. This supports user-defined extensions to the \c Stencil language.
Stencil run(MatchConsumer<std::string> C);
+/// Produces a human-readable rendering of the node bound to `Id`, suitable for
+/// diagnostics and debugging. This operator can be applied to any node, but is
+/// targeted at those whose source cannot be printed directly, including:
+///
+/// * Types. represented based on their structure. Note that namespace
+/// qualifiers are always printed, with the anonymous namespace represented
+/// explicitly. No desugaring or canonicalization is applied.
+Stencil describe(llvm::StringRef Id);
+
/// For debug use only; semantics are not guaranteed.
///
/// \returns the string resulting from calling the node's print() method.
diff --git a/contrib/llvm-project/clang/include/clang/module.modulemap b/contrib/llvm-project/clang/include/clang/module.modulemap
index 13d4dbf9dc2e..332e533f0347 100644
--- a/contrib/llvm-project/clang/include/clang/module.modulemap
+++ b/contrib/llvm-project/clang/include/clang/module.modulemap
@@ -62,6 +62,7 @@ module Clang_Basic {
textual header "Basic/OpenCLExtensionTypes.def"
textual header "Basic/OpenMPKinds.def"
textual header "Basic/OperatorKinds.def"
+ textual header "Basic/PPCTypes.def"
textual header "Basic/Sanitizers.def"
textual header "Basic/TokenKinds.def"
textual header "Basic/X86Target.def"