aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitry Andric <dim@FreeBSD.org>2015-06-21 14:00:56 +0000
committerDimitry Andric <dim@FreeBSD.org>2015-06-21 14:00:56 +0000
commit2e645aa5697838f16ec570eb07c2bee7e13d0e0b (patch)
treea764184c2fc9486979b074250b013a0937ee64e5
parent798321d8eb5630cd4a8f490a4f25e32ef195fb07 (diff)
downloadsrc-2e645aa5697838f16ec570eb07c2bee7e13d0e0b.tar.gz
src-2e645aa5697838f16ec570eb07c2bee7e13d0e0b.zip
Vendor import of clang trunk r240225:vendor/clang/clang-trunk-r240225
Notes
Notes: svn path=/vendor/clang/dist/; revision=284679 svn path=/vendor/clang/clang-trunk-r240225/; revision=284680; tag=vendor/clang/clang-trunk-r240225
-rw-r--r--.gitignore2
-rw-r--r--CMakeLists.txt13
-rw-r--r--docs/ClangFormatStyleOptions.rst38
-rw-r--r--docs/ControlFlowIntegrity.rst4
-rw-r--r--docs/LanguageExtensions.rst3
-rw-r--r--docs/Modules.rst11
-rw-r--r--docs/SafeStack.rst163
-rw-r--r--docs/UsersManual.rst60
-rw-r--r--docs/index.rst1
-rw-r--r--docs/tools/clang.pod14
-rw-r--r--include/clang-c/Index.h11
-rw-r--r--include/clang/ARCMigrate/ARCMT.h36
-rw-r--r--include/clang/AST/ASTContext.h30
-rw-r--r--include/clang/AST/CommentParser.h6
-rw-r--r--include/clang/AST/DataRecursiveASTVisitor.h10
-rw-r--r--include/clang/AST/DeclBase.h7
-rw-r--r--include/clang/AST/DeclCXX.h2
-rw-r--r--include/clang/AST/DeclObjC.h34
-rw-r--r--include/clang/AST/DeclTemplate.h193
-rw-r--r--include/clang/AST/EvaluatedExprVisitor.h71
-rw-r--r--include/clang/AST/Expr.h78
-rw-r--r--include/clang/AST/OpenMPClause.h4
-rw-r--r--include/clang/AST/RecursiveASTVisitor.h5
-rw-r--r--include/clang/AST/StmtOpenMP.h86
-rw-r--r--include/clang/AST/Type.h47
-rw-r--r--include/clang/ASTMatchers/ASTMatchersMacros.h183
-rw-r--r--include/clang/Basic/Attr.td33
-rw-r--r--include/clang/Basic/Builtins.def4
-rw-r--r--include/clang/Basic/BuiltinsAArch64.def8
-rw-r--r--include/clang/Basic/BuiltinsAMDGPU.def (renamed from include/clang/Basic/BuiltinsR600.def)2
-rw-r--r--include/clang/Basic/BuiltinsARM.def8
-rw-r--r--include/clang/Basic/BuiltinsPPC.def3
-rw-r--r--include/clang/Basic/BuiltinsX86.def3
-rw-r--r--include/clang/Basic/DiagnosticCommonKinds.td31
-rw-r--r--include/clang/Basic/DiagnosticGroups.td5
-rw-r--r--include/clang/Basic/DiagnosticLexKinds.td17
-rw-r--r--include/clang/Basic/DiagnosticOptions.def5
-rw-r--r--include/clang/Basic/DiagnosticOptions.h33
-rw-r--r--include/clang/Basic/DiagnosticParseKinds.td12
-rw-r--r--include/clang/Basic/DiagnosticSemaKinds.td78
-rw-r--r--include/clang/Basic/FileManager.h8
-rw-r--r--include/clang/Basic/LangOptions.def3
-rw-r--r--include/clang/Basic/OpenMPKinds.def1
-rw-r--r--include/clang/Basic/Sanitizers.def21
-rw-r--r--include/clang/Basic/Sanitizers.h3
-rw-r--r--include/clang/Basic/Specifiers.h19
-rw-r--r--include/clang/Basic/StmtNodes.td3
-rw-r--r--include/clang/Basic/TargetBuiltins.h6
-rw-r--r--include/clang/Basic/TargetInfo.h4
-rw-r--r--include/clang/Basic/TargetOptions.h2
-rw-r--r--include/clang/Basic/TokenKinds.def5
-rw-r--r--include/clang/Basic/arm_neon.td13
-rw-r--r--include/clang/Driver/CC1Options.td4
-rw-r--r--include/clang/Driver/CLCompatOptions.td4
-rw-r--r--include/clang/Driver/Driver.h4
-rw-r--r--include/clang/Driver/Options.td25
-rw-r--r--include/clang/Driver/SanitizerArgs.h6
-rw-r--r--include/clang/Driver/ToolChain.h9
-rw-r--r--include/clang/Format/Format.h9
-rw-r--r--include/clang/Frontend/ASTUnit.h52
-rw-r--r--include/clang/Frontend/CodeGenOptions.def2
-rw-r--r--include/clang/Frontend/CodeGenOptions.h3
-rw-r--r--include/clang/Frontend/CompilerInstance.h14
-rw-r--r--include/clang/Frontend/FrontendActions.h15
-rw-r--r--include/clang/Frontend/PCHContainerOperations.h76
-rw-r--r--include/clang/Frontend/Utils.h5
-rw-r--r--include/clang/Lex/HeaderSearchOptions.h7
-rw-r--r--include/clang/Lex/ModuleMap.h7
-rw-r--r--include/clang/Lex/Preprocessor.h23
-rw-r--r--include/clang/Lex/Token.h7
-rw-r--r--include/clang/Parse/Parser.h22
-rw-r--r--include/clang/Rewrite/Frontend/FixItRewriter.h6
-rw-r--r--include/clang/Sema/AttributeList.h12
-rw-r--r--include/clang/Sema/DeclSpec.h65
-rw-r--r--include/clang/Sema/Lookup.h8
-rw-r--r--include/clang/Sema/Sema.h148
-rw-r--r--include/clang/Serialization/ASTBitCodes.h5
-rw-r--r--include/clang/Serialization/ASTReader.h30
-rw-r--r--include/clang/Serialization/ASTWriter.h13
-rw-r--r--include/clang/Serialization/GlobalModuleIndex.h8
-rw-r--r--include/clang/Serialization/ModuleManager.h11
-rw-r--r--include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h8
-rw-r--r--include/clang/Tooling/Refactoring.h4
-rw-r--r--include/clang/Tooling/Tooling.h63
-rw-r--r--lib/ARCMigrate/ARCMT.cpp82
-rw-r--r--lib/ARCMigrate/ARCMTActions.cpp12
-rw-r--r--lib/AST/ASTConsumer.cpp1
-rw-r--r--lib/AST/ASTContext.cpp11
-rw-r--r--lib/AST/ASTImporter.cpp7
-rw-r--r--lib/AST/Decl.cpp3
-rw-r--r--lib/AST/DeclObjC.cpp8
-rw-r--r--lib/AST/DeclPrinter.cpp68
-rw-r--r--lib/AST/DeclTemplate.cpp34
-rw-r--r--lib/AST/Expr.cpp85
-rw-r--r--lib/AST/ExprClassification.cpp2
-rw-r--r--lib/AST/ExprConstant.cpp2
-rw-r--r--lib/AST/ItaniumMangle.cpp11
-rw-r--r--lib/AST/MicrosoftCXXABI.cpp5
-rw-r--r--lib/AST/MicrosoftMangle.cpp12
-rw-r--r--lib/AST/RecordLayoutBuilder.cpp2
-rw-r--r--lib/AST/Stmt.cpp33
-rw-r--r--lib/AST/StmtPrinter.cpp21
-rw-r--r--lib/AST/StmtProfile.cpp16
-rw-r--r--lib/AST/Type.cpp152
-rw-r--r--lib/AST/TypePrinter.cpp37
-rw-r--r--lib/Analysis/CFG.cpp2
-rw-r--r--lib/Analysis/CocoaConventions.cpp2
-rw-r--r--lib/Basic/CMakeLists.txt1
-rw-r--r--lib/Basic/Diagnostic.cpp12
-rw-r--r--lib/Basic/DiagnosticOptions.cpp24
-rw-r--r--lib/Basic/FileSystemStatCache.cpp11
-rw-r--r--lib/Basic/IdentifierTable.cpp15
-rw-r--r--lib/Basic/OpenMPKinds.cpp1
-rw-r--r--lib/Basic/Sanitizers.cpp4
-rw-r--r--lib/Basic/Targets.cpp103
-rw-r--r--lib/CodeGen/BackendUtil.cpp22
-rw-r--r--lib/CodeGen/CGBuiltin.cpp163
-rw-r--r--lib/CodeGen/CGCXXABI.h3
-rw-r--r--lib/CodeGen/CGCall.cpp73
-rw-r--r--lib/CodeGen/CGClass.cpp66
-rw-r--r--lib/CodeGen/CGDebugInfo.cpp19
-rw-r--r--lib/CodeGen/CGDecl.cpp15
-rw-r--r--lib/CodeGen/CGDeclCXX.cpp7
-rw-r--r--lib/CodeGen/CGException.cpp17
-rw-r--r--lib/CodeGen/CGExpr.cpp30
-rw-r--r--lib/CodeGen/CGExprAgg.cpp14
-rw-r--r--lib/CodeGen/CGExprCXX.cpp24
-rw-r--r--lib/CodeGen/CGExprConstant.cpp156
-rw-r--r--lib/CodeGen/CGExprScalar.cpp8
-rw-r--r--lib/CodeGen/CGLoopInfo.cpp31
-rw-r--r--lib/CodeGen/CGLoopInfo.h5
-rw-r--r--lib/CodeGen/CGObjC.cpp10
-rw-r--r--lib/CodeGen/CGOpenMPRuntime.cpp94
-rw-r--r--lib/CodeGen/CGOpenMPRuntime.h24
-rw-r--r--lib/CodeGen/CGStmt.cpp21
-rw-r--r--lib/CodeGen/CGStmtOpenMP.cpp408
-rw-r--r--lib/CodeGen/CGVTables.cpp22
-rw-r--r--lib/CodeGen/CodeGenAction.cpp4
-rw-r--r--lib/CodeGen/CodeGenFunction.cpp4
-rw-r--r--lib/CodeGen/CodeGenFunction.h34
-rw-r--r--lib/CodeGen/CodeGenModule.cpp76
-rw-r--r--lib/CodeGen/CodeGenModule.h5
-rw-r--r--lib/CodeGen/CoverageMappingGen.cpp3
-rw-r--r--lib/CodeGen/ItaniumCXXABI.cpp12
-rw-r--r--lib/CodeGen/MicrosoftCXXABI.cpp144
-rw-r--r--lib/CodeGen/SanitizerMetadata.cpp9
-rw-r--r--lib/Driver/Driver.cpp34
-rw-r--r--lib/Driver/MSVCToolChain.cpp9
-rw-r--r--lib/Driver/SanitizerArgs.cpp138
-rw-r--r--lib/Driver/ToolChain.cpp9
-rw-r--r--lib/Driver/ToolChains.cpp186
-rw-r--r--lib/Driver/ToolChains.h39
-rw-r--r--lib/Driver/Tools.cpp359
-rw-r--r--lib/Driver/Tools.h35
-rw-r--r--lib/Driver/Types.cpp2
-rw-r--r--lib/Format/BreakableToken.cpp14
-rw-r--r--lib/Format/ContinuationIndenter.cpp40
-rw-r--r--lib/Format/ContinuationIndenter.h81
-rw-r--r--lib/Format/Format.cpp17
-rw-r--r--lib/Format/FormatToken.cpp7
-rw-r--r--lib/Format/FormatToken.h18
-rw-r--r--lib/Format/TokenAnnotator.cpp100
-rw-r--r--lib/Format/TokenAnnotator.h20
-rw-r--r--lib/Format/UnwrappedLineFormatter.cpp25
-rw-r--r--lib/Format/UnwrappedLineFormatter.h3
-rw-r--r--lib/Format/UnwrappedLineParser.cpp54
-rw-r--r--lib/Format/WhitespaceManager.h6
-rw-r--r--lib/Frontend/ASTMerge.cpp6
-rw-r--r--lib/Frontend/ASTUnit.cpp109
-rw-r--r--lib/Frontend/CMakeLists.txt1
-rw-r--r--lib/Frontend/ChainedIncludesSource.cpp22
-rw-r--r--lib/Frontend/CompilerInstance.cpp56
-rw-r--r--lib/Frontend/CompilerInvocation.cpp44
-rw-r--r--lib/Frontend/FrontendAction.cpp16
-rw-r--r--lib/Frontend/FrontendActions.cpp59
-rw-r--r--lib/Frontend/InitPreprocessor.cpp15
-rw-r--r--lib/Frontend/MultiplexConsumer.cpp26
-rw-r--r--lib/Frontend/PCHContainerOperations.cpp70
-rw-r--r--lib/Frontend/PrintPreprocessedOutput.cpp52
-rw-r--r--lib/Frontend/Rewrite/FixItRewriter.cpp7
-rw-r--r--lib/Frontend/Rewrite/FrontendActions.cpp5
-rw-r--r--lib/Frontend/VerifyDiagnosticConsumer.cpp41
-rw-r--r--lib/Headers/CMakeLists.txt1
-rw-r--r--lib/Headers/Intrin.h177
-rw-r--r--lib/Headers/__wmmintrin_aes.h17
-rw-r--r--lib/Headers/__wmmintrin_pclmul.h4
-rw-r--r--lib/Headers/adxintrin.h19
-rw-r--r--lib/Headers/altivec.h23
-rw-r--r--lib/Headers/ammintrin.h17
-rw-r--r--lib/Headers/arm_acle.h8
-rw-r--r--lib/Headers/avx2intrin.h287
-rw-r--r--lib/Headers/avx512bwintrin.h135
-rw-r--r--lib/Headers/avx512dqintrin.h59
-rw-r--r--lib/Headers/avx512erintrin.h1
-rw-r--r--lib/Headers/avx512fintrin.h390
-rw-r--r--lib/Headers/avx512vlbwintrin.h237
-rw-r--r--lib/Headers/avx512vldqintrin.h80
-rw-r--r--lib/Headers/avx512vlintrin.h318
-rw-r--r--lib/Headers/avxintrin.h309
-rw-r--r--lib/Headers/bmi2intrin.h25
-rw-r--r--lib/Headers/bmiintrin.h39
-rw-r--r--lib/Headers/emmintrin.h439
-rw-r--r--lib/Headers/f16cintrin.h13
-rw-r--r--lib/Headers/fma4intrin.h73
-rw-r--r--lib/Headers/fmaintrin.h71
-rw-r--r--lib/Headers/immintrin.h83
-rw-r--r--lib/Headers/lzcntintrin.h19
-rw-r--r--lib/Headers/mm3dnow.h57
-rw-r--r--lib/Headers/mmintrin.h144
-rw-r--r--lib/Headers/nmmintrin.h5
-rw-r--r--lib/Headers/pmmintrin.h33
-rw-r--r--lib/Headers/popcntintrin.h13
-rw-r--r--lib/Headers/rdseedintrin.h14
-rw-r--r--lib/Headers/rtmintrin.h9
-rw-r--r--lib/Headers/shaintrin.h19
-rw-r--r--lib/Headers/smmintrin.h92
-rw-r--r--lib/Headers/tbmintrin.h54
-rw-r--r--lib/Headers/tmmintrin.h69
-rw-r--r--lib/Headers/wmmintrin.h9
-rw-r--r--lib/Headers/x86intrin.h24
-rw-r--r--lib/Headers/xmmintrin.h261
-rw-r--r--lib/Headers/xopintrin.h233
-rw-r--r--lib/Headers/xtestintrin.h41
-rw-r--r--lib/Lex/HeaderSearch.cpp14
-rw-r--r--lib/Lex/ModuleMap.cpp36
-rw-r--r--lib/Lex/PPDirectives.cpp22
-rw-r--r--lib/Lex/PPLexerChange.cpp11
-rw-r--r--lib/Lex/PPMacroExpansion.cpp17
-rw-r--r--lib/Lex/Pragma.cpp55
-rw-r--r--lib/Lex/TokenConcatenation.cpp20
-rw-r--r--lib/Lex/TokenLexer.cpp2
-rw-r--r--lib/Parse/ParseCXXInlineMethods.cpp9
-rw-r--r--lib/Parse/ParseDecl.cpp95
-rw-r--r--lib/Parse/ParseDeclCXX.cpp161
-rw-r--r--lib/Parse/ParseExpr.cpp47
-rw-r--r--lib/Parse/ParseExprCXX.cpp9
-rw-r--r--lib/Parse/ParseObjc.cpp169
-rw-r--r--lib/Parse/ParseOpenMP.cpp7
-rw-r--r--lib/Parse/ParsePragma.cpp9
-rw-r--r--lib/Parse/ParseStmt.cpp17
-rw-r--r--lib/Parse/ParseStmtAsm.cpp4
-rw-r--r--lib/Parse/ParseTemplate.cpp41
-rw-r--r--lib/Parse/ParseTentative.cpp71
-rw-r--r--lib/Parse/Parser.cpp4
-rw-r--r--lib/Sema/AnalysisBasedWarnings.cpp17
-rw-r--r--lib/Sema/Sema.cpp27
-rw-r--r--lib/Sema/SemaChecking.cpp300
-rw-r--r--lib/Sema/SemaCodeComplete.cpp71
-rw-r--r--lib/Sema/SemaDecl.cpp91
-rw-r--r--lib/Sema/SemaDeclAttr.cpp118
-rw-r--r--lib/Sema/SemaDeclCXX.cpp1
-rw-r--r--lib/Sema/SemaDeclObjC.cpp168
-rw-r--r--lib/Sema/SemaExceptionSpec.cpp2
-rw-r--r--lib/Sema/SemaExprCXX.cpp9
-rw-r--r--lib/Sema/SemaExprObjC.cpp137
-rw-r--r--lib/Sema/SemaInit.cpp232
-rw-r--r--lib/Sema/SemaLookup.cpp133
-rw-r--r--lib/Sema/SemaObjCProperty.cpp115
-rw-r--r--lib/Sema/SemaOpenMP.cpp64
-rw-r--r--lib/Sema/SemaOverload.cpp53
-rw-r--r--lib/Sema/SemaStmt.cpp2
-rw-r--r--lib/Sema/SemaStmtAttr.cpp4
-rw-r--r--lib/Sema/SemaTemplate.cpp89
-rw-r--r--lib/Sema/SemaTemplateInstantiateDecl.cpp14
-rw-r--r--lib/Sema/SemaType.cpp840
-rw-r--r--lib/Sema/TreeTransform.h41
-rw-r--r--lib/Serialization/ASTReader.cpp55
-rw-r--r--lib/Serialization/ASTReaderDecl.cpp277
-rw-r--r--lib/Serialization/ASTReaderStmt.cpp31
-rw-r--r--lib/Serialization/ASTWriter.cpp5
-rw-r--r--lib/Serialization/ASTWriterDecl.cpp29
-rw-r--r--lib/Serialization/ASTWriterStmt.cpp21
-rw-r--r--lib/Serialization/GeneratePCH.cpp33
-rw-r--r--lib/Serialization/GlobalModuleIndex.cpp17
-rw-r--r--lib/Serialization/ModuleManager.cpp14
-rw-r--r--lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp25
-rw-r--r--lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp74
-rw-r--r--lib/StaticAnalyzer/Core/BugReporterVisitors.cpp2
-rw-r--r--lib/StaticAnalyzer/Core/CallEvent.cpp2
-rw-r--r--lib/StaticAnalyzer/Core/ExprEngine.cpp3
-rw-r--r--lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp3
-rw-r--r--lib/StaticAnalyzer/Frontend/ModelInjector.cpp2
-rw-r--r--lib/Tooling/Core/Replacement.cpp7
-rw-r--r--lib/Tooling/Refactoring.cpp7
-rw-r--r--lib/Tooling/Tooling.cpp95
-rw-r--r--test/ARCMT/migrate-on-pch-and-module.m4
-rw-r--r--test/Analysis/CFContainers.mm22
-rw-r--r--test/Analysis/designated-initializer.c41
-rw-r--r--test/Analysis/retain-release.m34
-rw-r--r--test/CXX/except/except.spec/p9-dynamic.cpp2
-rw-r--r--test/CXX/except/except.spec/p9-noexcept.cpp2
-rw-r--r--test/CodeGen/2004-06-17-UnorderedCompares.c2
-rw-r--r--test/CodeGen/address-safety-attr-kasan.cpp38
-rw-r--r--test/CodeGen/arm-interrupt-attr.c16
-rw-r--r--test/CodeGen/arm_acle.c66
-rw-r--r--test/CodeGen/arm_neon_intrinsics.c24
-rw-r--r--test/CodeGen/attr-disable-tail-calls.c11
-rw-r--r--test/CodeGen/attr-mode-vector-types.c41
-rw-r--r--test/CodeGen/attr-target.c25
-rw-r--r--test/CodeGen/bounds-checking.c2
-rw-r--r--test/CodeGen/builtins-arm.c39
-rw-r--r--test/CodeGen/builtins-arm64.c36
-rw-r--r--test/CodeGen/builtins-ppc-p8vector.c23
-rw-r--r--test/CodeGen/catch-undef-behavior.c2
-rw-r--r--test/CodeGen/cleanup-destslot-simple.c6
-rw-r--r--test/CodeGen/exceptions-seh.c14
-rw-r--r--test/CodeGen/exceptions.c8
-rw-r--r--test/CodeGen/inline-asm-immediate-ubsan.c30
-rw-r--r--test/CodeGen/ms-inline-asm.c2
-rw-r--r--test/CodeGen/partial-reinitialization1.c74
-rw-r--r--test/CodeGen/partial-reinitialization2.c108
-rw-r--r--test/CodeGen/safestack-attr.cpp6
-rw-r--r--test/CodeGen/sanitize-trap.c25
-rw-r--r--test/CodeGen/stack-protector.c4
-rw-r--r--test/CodeGen/systemz-inline-asm.c20
-rw-r--r--test/CodeGen/target-data.c8
-rw-r--r--test/CodeGenCXX/arm.cpp8
-rw-r--r--test/CodeGenCXX/atomicinit.cpp6
-rw-r--r--test/CodeGenCXX/cfi-cast.cpp18
-rw-r--r--test/CodeGenCXX/cfi-vcall.cpp121
-rw-r--r--test/CodeGenCXX/ctor-globalopt.cpp2
-rw-r--r--test/CodeGenCXX/cxx11-exception-spec.cpp10
-rw-r--r--test/CodeGenCXX/destructors.cpp6
-rw-r--r--test/CodeGenCXX/dllexport.cpp16
-rw-r--r--test/CodeGenCXX/dynamic-cast.cpp3
-rw-r--r--test/CodeGenCXX/eh.cpp8
-rw-r--r--test/CodeGenCXX/exceptions-seh.cpp19
-rw-r--r--test/CodeGenCXX/init-invariant.cpp8
-rw-r--r--test/CodeGenCXX/mangle-long-double.cpp12
-rwxr-xr-xtest/CodeGenCXX/microsoft-abi-member-pointers.cpp17
-rw-r--r--test/CodeGenCXX/microsoft-abi-thread-safe-statics.cpp3
-rw-r--r--test/CodeGenCXX/microsoft-abi-virtual-member-pointers.cpp23
-rw-r--r--test/CodeGenCXX/microsoft-abi-vmemptr-fastcall.cpp14
-rw-r--r--test/CodeGenCXX/mingw-w64-seh-exceptions.cpp6
-rw-r--r--test/CodeGenCXX/nrvo.cpp11
-rw-r--r--test/CodeGenCXX/partial-destruction.cpp15
-rw-r--r--test/CodeGenCXX/pragma-loop-safety.cpp49
-rw-r--r--test/CodeGenCXX/redefine_extname.cpp18
-rw-r--r--test/CodeGenCXX/stack-reuse.cpp4
-rw-r--r--test/CodeGenCXX/threadsafe-statics-exceptions.cpp3
-rw-r--r--test/CodeGenCXX/typeid.cpp3
-rw-r--r--test/CodeGenCXX/windows-itanium-exceptions.cpp5
-rw-r--r--test/CodeGenObjC/autorelease.m2
-rw-r--r--test/CodeGenObjC/blocks-2.m2
-rw-r--r--test/CodeGenObjC/exceptions.m22
-rw-r--r--test/CodeGenObjC/gnu-exceptions.m5
-rw-r--r--test/CodeGenObjC/objc-asm-attribute-test.m16
-rw-r--r--test/CodeGenObjC/synchronized.m2
-rw-r--r--test/CodeGenObjC/terminate.m6
-rw-r--r--test/CodeGenObjCXX/catch-id-type.mm2
-rw-r--r--test/CodeGenObjCXX/debug-info-cyclic.mm3
-rw-r--r--test/CodeGenObjCXX/exceptions-legacy.mm14
-rw-r--r--test/CodeGenObjCXX/exceptions.mm3
-rw-r--r--test/CoverageMapping/control-flow-macro.c14
-rw-r--r--test/Driver/aarch64-cpus.c19
-rw-r--r--test/Driver/arm-cortex-cpus.c9
-rw-r--r--test/Driver/asan.c17
-rw-r--r--test/Driver/cl-options.c3
-rw-r--r--test/Driver/cl-outputs.c6
-rw-r--r--test/Driver/fsanitize.c65
-rw-r--r--test/Driver/mips-as.c76
-rw-r--r--test/Driver/mips-features.c72
-rw-r--r--test/Driver/mips-integrated-as.s84
-rw-r--r--test/Driver/modules.mm7
-rw-r--r--test/Driver/mrecip.c70
-rw-r--r--test/Driver/r600-mcpu.cl8
-rw-r--r--test/Driver/rtti-options.cpp18
-rw-r--r--test/Driver/shave-toolchain.c22
-rw-r--r--test/Driver/sparc-float.c18
-rw-r--r--test/FixIt/fixit-large-file.cpp318
-rw-r--r--test/FixIt/fixit-nullability-declspec.cpp9
-rw-r--r--test/Format/style-on-command-line.cpp4
-rw-r--r--test/Frontend/rewrite-includes-modules.c2
-rw-r--r--test/Frontend/verify-ignore-unexpected.c81
-rw-r--r--test/Headers/pmmintrin.c12
-rw-r--r--test/Headers/x86intrin-2.c137
-rw-r--r--test/Headers/x86intrin.c121
-rw-r--r--test/Headers/xmmintrin.c2
-rw-r--r--test/Index/comment-objc-decls.m8
-rw-r--r--test/Index/complete-method-decls.m13
-rw-r--r--test/Index/complete-objc-message.m11
-rw-r--r--test/Index/complete-property-flags.m12
-rw-r--r--test/Index/complete-stmt.c2
-rw-r--r--test/Index/pch-depending-on-deleted-module.c8
-rw-r--r--test/Lexer/has_feature_address_sanitizer.cpp1
-rw-r--r--test/Modules/Inputs/merge-class-definition-visibility/a.h1
-rw-r--r--test/Modules/Inputs/merge-class-definition-visibility/b.h2
-rw-r--r--test/Modules/Inputs/merge-class-definition-visibility/c.h1
-rw-r--r--test/Modules/Inputs/merge-class-definition-visibility/d.h1
-rw-r--r--test/Modules/Inputs/merge-class-definition-visibility/modmap7
-rw-r--r--test/Modules/Inputs/submodules-merge-defs/defs.h30
-rw-r--r--test/Modules/Inputs/submodules-merge-defs/indirect.h1
-rw-r--r--test/Modules/Inputs/submodules-merge-defs/module.modulemap6
-rw-r--r--test/Modules/Inputs/submodules-merge-defs/use-defs-2.h2
-rw-r--r--test/Modules/Inputs/submodules-merge-defs/use-defs.h1
-rw-r--r--test/Modules/Inputs/template-default-args/a.h3
-rw-r--r--test/Modules/Inputs/template-default-args/c.h2
-rw-r--r--test/Modules/Inputs/template-default-args/module.modulemap6
-rw-r--r--test/Modules/Rmodule-build.m10
-rw-r--r--test/Modules/Werror-Wsystem-headers.m6
-rw-r--r--test/Modules/Werror.m22
-rw-r--r--test/Modules/add-remove-private.m8
-rw-r--r--test/Modules/anon-namespace.cpp2
-rw-r--r--test/Modules/attr-unavailable.m2
-rw-r--r--test/Modules/auto-module-import.m4
-rw-r--r--test/Modules/autolink.m6
-rw-r--r--test/Modules/build-fail-notes.m6
-rw-r--r--test/Modules/builtins.m2
-rw-r--r--test/Modules/compiler_builtins.m4
-rw-r--r--test/Modules/compiler_builtins_arm.m2
-rw-r--r--test/Modules/config_macros.m4
-rw-r--r--test/Modules/conflicts.m2
-rw-r--r--test/Modules/crashes.m2
-rw-r--r--test/Modules/cstd.m2
-rw-r--r--test/Modules/cxx-decls.cpp4
-rw-r--r--test/Modules/cxx-dtor.cpp2
-rw-r--r--test/Modules/cxx-inline-namespace.cpp2
-rw-r--r--test/Modules/cxx-irgen.cpp4
-rw-r--r--test/Modules/cxx-linkage-cache.cpp2
-rw-r--r--test/Modules/cxx-lookup.cpp2
-rw-r--r--test/Modules/cxx-many-overloads.cpp2
-rw-r--r--test/Modules/cxx-templates.cpp10
-rw-r--r--test/Modules/cycles.c2
-rw-r--r--test/Modules/declare-use-compatible.cpp16
-rw-r--r--test/Modules/declare-use1.cpp2
-rw-r--r--test/Modules/declare-use2.cpp2
-rw-r--r--test/Modules/declare-use3.cpp2
-rw-r--r--test/Modules/declare-use4.cpp2
-rw-r--r--test/Modules/declare-use5.cpp2
-rw-r--r--test/Modules/decldef.m4
-rw-r--r--test/Modules/decldef.mm8
-rw-r--r--test/Modules/deferred-lookup.cpp2
-rw-r--r--test/Modules/dependency-dump-dependent-module.m2
-rw-r--r--test/Modules/dependency-dump.m2
-rw-r--r--test/Modules/dependency-gen-inferred-map.m2
-rw-r--r--test/Modules/dependency-gen-pch.m2
-rw-r--r--test/Modules/dependency-gen.m4
-rw-r--r--test/Modules/dependency-gen.modulemap4
-rw-r--r--test/Modules/diag-pragma.c4
-rw-r--r--test/Modules/diamond-pch.c12
-rw-r--r--test/Modules/diamond.c10
-rw-r--r--test/Modules/direct-module-import.m2
-rw-r--r--test/Modules/driver.c4
-rw-r--r--test/Modules/empty.modulemap4
-rw-r--r--test/Modules/epic-fail.m2
-rw-r--r--test/Modules/exclude-header.c2
-rw-r--r--test/Modules/explicit-build-relpath.cpp14
-rw-r--r--test/Modules/explicit-build.cpp50
-rw-r--r--test/Modules/exponential-paths.cpp86
-rw-r--r--test/Modules/extern_c.cpp24
-rw-r--r--test/Modules/extern_c_bad.cpp2
-rw-r--r--test/Modules/fatal-module-loader-error.m6
-rw-r--r--test/Modules/filename.cpp2
-rw-r--r--test/Modules/fmodules-validate-once-per-build-session.c14
-rw-r--r--test/Modules/global_index.m6
-rw-r--r--test/Modules/header-import.m2
-rw-r--r--test/Modules/ignored_macros.m20
-rw-r--r--test/Modules/implementation-of-module.m10
-rw-r--r--test/Modules/import-self.m4
-rw-r--r--test/Modules/include-relative.c2
-rw-r--r--test/Modules/include_next.c2
-rw-r--r--test/Modules/incomplete-module.m4
-rw-r--r--test/Modules/inferred-attributes.mm2
-rw-r--r--test/Modules/inferred-framework-case.m2
-rw-r--r--test/Modules/inferred-frameworks.m2
-rw-r--r--test/Modules/inferred-submodules.m2
-rw-r--r--test/Modules/invalidate-identifiers.c2
-rw-r--r--test/Modules/irgen.c4
-rw-r--r--test/Modules/linkage-merge.cpp2
-rw-r--r--test/Modules/linkage-merge.m4
-rw-r--r--test/Modules/load-after-failure.m4
-rw-r--r--test/Modules/load_failure.c6
-rw-r--r--test/Modules/lookup.cpp8
-rw-r--r--test/Modules/lookup.m8
-rw-r--r--test/Modules/macro-ambiguity.cpp12
-rw-r--r--test/Modules/macro-hiding.cpp128
-rw-r--r--test/Modules/macro-masking.cpp4
-rw-r--r--test/Modules/macro-reexport.cpp16
-rw-r--r--test/Modules/macro-undef-through-pch.m4
-rw-r--r--test/Modules/macros.c8
-rw-r--r--test/Modules/macros2.c4
-rw-r--r--test/Modules/malformed.cpp6
-rw-r--r--test/Modules/merge-anon-in-template.cpp2
-rw-r--r--test/Modules/merge-class-definition-visibility.cpp15
-rw-r--r--test/Modules/merge-decl-context.cpp8
-rw-r--r--test/Modules/merge-decl-order.cpp2
-rw-r--r--test/Modules/merge-dependent-friends.cpp2
-rw-r--r--test/Modules/merge-enumerators.cpp11
-rw-r--r--test/Modules/merge-friends.cpp2
-rw-r--r--test/Modules/merge-implicit-special-members.cpp2
-rw-r--r--test/Modules/merge-name-for-linkage.cpp2
-rw-r--r--test/Modules/merge-nested-templates.cpp2
-rw-r--r--test/Modules/merge-target-features.cpp10
-rw-r--r--test/Modules/merge-template-friend.cpp6
-rw-r--r--test/Modules/merge-template-members.cpp6
-rw-r--r--test/Modules/merge-typedefs.cpp2
-rw-r--r--test/Modules/merge-using-decls.cpp4
-rw-r--r--test/Modules/merge-vtable-codegen.cpp6
-rw-r--r--test/Modules/method_pool.m2
-rw-r--r--test/Modules/missing-header.m2
-rw-r--r--test/Modules/missing-submodule.m2
-rw-r--r--test/Modules/modify-module.m10
-rw-r--r--test/Modules/modular_maps.cpp12
-rw-r--r--test/Modules/module-private.cpp8
-rw-r--r--test/Modules/module_file_info.m2
-rw-r--r--test/Modules/modulemap-locations.m2
-rw-r--r--test/Modules/modules-with-same-name.m8
-rw-r--r--test/Modules/namespaces.cpp2
-rw-r--r--test/Modules/no-implicit-builds.cpp10
-rw-r--r--test/Modules/no-implicit-maps.cpp2
-rw-r--r--test/Modules/no-stale-modtime.m8
-rw-r--r--test/Modules/normal-module-map.cpp2
-rw-r--r--test/Modules/objc-categories.m12
-rw-r--r--test/Modules/objc_redef.m6
-rw-r--r--test/Modules/odr.cpp2
-rw-r--r--test/Modules/on-demand-build.m6
-rw-r--r--test/Modules/on-demand-macros.m4
-rw-r--r--test/Modules/pch-used.m4
-rw-r--r--test/Modules/pr19692.cpp2
-rw-r--r--test/Modules/pr20399.cpp2
-rw-r--r--test/Modules/pr20786.cpp2
-rw-r--r--test/Modules/pr21687.cpp2
-rw-r--r--test/Modules/preprocess.m12
-rw-r--r--test/Modules/private.cpp4
-rw-r--r--test/Modules/private1.cpp2
-rw-r--r--test/Modules/prune.m10
-rw-r--r--test/Modules/rebuild.m12
-rw-r--r--test/Modules/recursive.c4
-rw-r--r--test/Modules/recursive_visibility.mm2
-rw-r--r--test/Modules/redecl-add-after-load.cpp4
-rw-r--r--test/Modules/redecl-found-building-chains.cpp2
-rw-r--r--test/Modules/redecl-merge.m2
-rw-r--r--test/Modules/redecl-merge2.m2
-rw-r--r--test/Modules/redecl-namespaces.mm6
-rw-r--r--test/Modules/redecl-templates.cpp2
-rw-r--r--test/Modules/redeclarations.m6
-rw-r--r--test/Modules/redecls.m6
-rw-r--r--test/Modules/renamed.m2
-rw-r--r--test/Modules/require-modular-includes.m24
-rw-r--r--test/Modules/requires.m2
-rw-r--r--test/Modules/requires.mm2
-rw-r--r--test/Modules/resolution-change.m12
-rw-r--r--test/Modules/stddef.c2
-rw-r--r--test/Modules/stddef.m2
-rw-r--r--test/Modules/stress1.cpp20
-rw-r--r--test/Modules/strict-decluse.cpp2
-rw-r--r--test/Modules/string_names.cpp2
-rw-r--r--test/Modules/subframework-from-intermediate-path.m2
-rw-r--r--test/Modules/subframeworks.m4
-rw-r--r--test/Modules/submodule-visibility-cycles.cpp2
-rw-r--r--test/Modules/submodule-visibility.cpp8
-rw-r--r--test/Modules/submodules-merge-defs.cpp52
-rw-r--r--test/Modules/submodules-preprocess.cpp2
-rw-r--r--test/Modules/submodules.cpp2
-rw-r--r--test/Modules/submodules.m2
-rw-r--r--test/Modules/system_headers.m2
-rw-r--r--test/Modules/system_version.m6
-rw-r--r--test/Modules/template-default-args.cpp18
-rw-r--r--test/Modules/template-specialization-visibility.cpp2
-rw-r--r--test/Modules/templates-2.mm4
-rw-r--r--test/Modules/templates.mm4
-rw-r--r--test/Modules/textual-headers.cpp4
-rw-r--r--test/Modules/undefined-type-fixit1.cpp2
-rw-r--r--test/Modules/unnecessary-module-map-parsing.c2
-rw-r--r--test/Modules/update-after-load.cpp2
-rw-r--r--test/Modules/update-exception-spec.cpp2
-rw-r--r--test/Modules/using-decl.cpp2
-rw-r--r--test/Modules/va_list.m8
-rw-r--r--test/Modules/validate-system-headers.m12
-rw-r--r--test/Modules/warn-unused-local-typedef.cpp5
-rw-r--r--test/Modules/wildcard-submodule-exports.cpp2
-rw-r--r--test/OpenMP/for_simd_codegen.cpp686
-rw-r--r--test/OpenMP/parallel_for_codegen.cpp10
-rw-r--r--test/OpenMP/parallel_for_simd_codegen.cpp696
-rw-r--r--test/OpenMP/parallel_proc_bind_codegen.cpp52
-rw-r--r--test/OpenMP/simd_codegen.cpp67
-rw-r--r--test/OpenMP/taskgroup_ast_print.cpp29
-rw-r--r--test/OpenMP/taskgroup_codegen.cpp56
-rw-r--r--test/OpenMP/taskgroup_messages.cpp67
-rw-r--r--test/PCH/designated-init.c.h22
-rw-r--r--test/PCH/modified-module-dependency.m4
-rw-r--r--test/PCH/module-hash-difference.m4
-rw-r--r--test/Parser/MicrosoftExtensions.c5
-rw-r--r--test/Parser/nullability.c16
-rw-r--r--test/Parser/pragma-loop-safety.cpp34
-rw-r--r--test/Parser/pragma-loop.cpp8
-rw-r--r--test/Preprocessor/aarch64-target-features.c10
-rw-r--r--test/Preprocessor/openmp-macro-expansion.c31
-rw-r--r--test/Preprocessor/pp-modules.c2
-rw-r--r--test/Sema/aarch64-special-register.c77
-rw-r--r--test/Sema/arm-special-register.c89
-rw-r--r--test/Sema/attr-mode-vector-types.c26
-rw-r--r--test/Sema/attr-target.c8
-rw-r--r--test/Sema/designated-initializers.c24
-rw-r--r--test/Sema/non-null-warning.c42
-rw-r--r--test/Sema/nullability.c113
-rw-r--r--test/Sema/stmtexprs.c9
-rw-r--r--test/Sema/warn-unused-function.c2
-rw-r--r--test/SemaCXX/decltype.cpp25
-rw-r--r--test/SemaCXX/incomplete-call.cpp12
-rw-r--r--test/SemaCXX/nullability-declspec.cpp9
-rw-r--r--test/SemaCXX/nullability.cpp64
-rw-r--r--test/SemaObjC/arc-property-decl-attrs.m26
-rw-r--r--test/SemaObjC/arc-unavailable-for-weakref.m6
-rw-r--r--test/SemaObjC/attr-cf_returns.m49
-rw-r--r--test/SemaObjC/nullability-arc.m10
-rw-r--r--test/SemaObjC/nullability.m232
-rw-r--r--test/SemaObjC/nullable-weak-property.m18
-rw-r--r--test/SemaObjC/override-nullability.m15
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-1.h17
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-2.h16
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-3.h1
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-4.h1
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-5.h14
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-6.h8
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-7.h40
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-8.h27
-rw-r--r--test/SemaObjCXX/Inputs/nullability-consistency-system/nullability-consistency-system.h8
-rw-r--r--test/SemaObjCXX/Inputs/nullability-pragmas-1.h101
-rw-r--r--test/SemaObjCXX/Inputs/nullability-pragmas-2.h12
-rw-r--r--test/SemaObjCXX/Inputs/nullability-pragmas-3.h0
-rw-r--r--test/SemaObjCXX/nullability-consistency.mm16
-rw-r--r--test/SemaObjCXX/nullability-pragmas.mm41
-rw-r--r--test/SemaTemplate/ms-lookup-template-base-classes.cpp26
-rw-r--r--test/VFS/incomplete-umbrella.m2
-rw-r--r--test/VFS/module-import.m8
-rw-r--r--test/VFS/real-path-found-first.m20
-rw-r--r--test/VFS/umbrella-mismatch.m4
-rw-r--r--tools/arcmt-test/arcmt-test.cpp7
-rw-r--r--tools/c-index-test/c-index-test.c2
-rwxr-xr-xtools/clang-format/git-clang-format1
-rw-r--r--tools/driver/cc1_main.cpp4
-rw-r--r--tools/driver/cc1as_main.cpp4
-rw-r--r--tools/driver/driver.cpp18
-rw-r--r--tools/libclang/ARCMigrate.cpp4
-rw-r--r--tools/libclang/CIndex.cpp17
-rw-r--r--tools/libclang/CIndexCodeCompletion.cpp12
-rw-r--r--tools/libclang/CIndexer.h15
-rw-r--r--tools/libclang/CXCursor.cpp5
-rw-r--r--tools/libclang/Indexing.cpp21
-rwxr-xr-xtools/scan-build/ccc-analyzer4
-rwxr-xr-xtools/scan-build/scan-build2
-rw-r--r--unittests/ASTMatchers/ASTMatchersTest.h1
-rw-r--r--unittests/Format/CMakeLists.txt1
-rw-r--r--unittests/Format/FormatTest.cpp526
-rw-r--r--unittests/Format/FormatTestJS.cpp90
-rw-r--r--unittests/Format/FormatTestJava.cpp6
-rw-r--r--unittests/Format/FormatTestSelective.cpp441
-rw-r--r--unittests/Tooling/RewriterTest.cpp13
-rw-r--r--utils/TableGen/ClangAttrEmitter.cpp3
-rw-r--r--www/analyzer/scan-build.html3
651 files changed, 16261 insertions, 5782 deletions
diff --git a/.gitignore b/.gitignore
index 6c34e37f4cb6..3d07e81baf38 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,7 +16,7 @@
# Byte compiled python modules.
*.pyc
# vim swap files
-.*.swp
+.*.sw?
.sw?
#==============================================================================#
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 357286b0e6ae..ab70f1dab61f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -320,6 +320,17 @@ function(clang_tablegen)
endif()
endfunction(clang_tablegen)
+macro(set_clang_windows_version_resource_properties name)
+ if(DEFINED windows_resource_file)
+ set_windows_version_resource_properties(${name} ${windows_resource_file}
+ VERSION_MAJOR ${CLANG_VERSION_MAJOR}
+ VERSION_MINOR ${CLANG_VERSION_MINOR}
+ VERSION_PATCHLEVEL ${CLANG_VERSION_PATCHLEVEL}
+ VERSION_STRING "${CLANG_VERSION} (${BACKEND_PACKAGE_STRING})"
+ PRODUCT_NAME "clang")
+ endif()
+endmacro()
+
macro(add_clang_library name)
cmake_parse_arguments(ARG
""
@@ -377,11 +388,13 @@ macro(add_clang_library name)
endif()
set_target_properties(${name} PROPERTIES FOLDER "Clang libraries")
+ set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_library)
macro(add_clang_executable name)
add_llvm_executable( ${name} ${ARGN} )
set_target_properties(${name} PROPERTIES FOLDER "Clang executables")
+ set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_executable)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
diff --git a/docs/ClangFormatStyleOptions.rst b/docs/ClangFormatStyleOptions.rst
index c06a8c76ecd5..f4c4c8cc9a21 100644
--- a/docs/ClangFormatStyleOptions.rst
+++ b/docs/ClangFormatStyleOptions.rst
@@ -155,23 +155,21 @@ the configuration (without a prefix: ``Auto``).
This applies to round brackets (parentheses), angle brackets and square
brackets. This will result in formattings like
-
- .. code-block:: c++
-
- someLongFunction(argument1,
- argument2);
+ \code
+ someLongFunction(argument1,
+ argument2);
+ \endcode
**AlignConsecutiveAssignments** (``bool``)
If ``true``, aligns consecutive assignments.
This will align the assignment operators of consecutive lines. This
will result in formattings like
-
- .. code-block:: c++
-
- int aaaa = 12;
- int b = 23;
- int ccc = 23;
+ \code
+ int aaaa = 12;
+ int b = 23;
+ int ccc = 23;
+ \endcode
**AlignEscapedNewlinesLeft** (``bool``)
If ``true``, aligns escaped newlines as far left as possible.
@@ -204,10 +202,10 @@ the configuration (without a prefix: ``Auto``).
* ``SFS_None`` (in configuration: ``None``)
Never merge functions into a single line.
- * ``SFS_Inline`` (in configuration: ``Inline``)
- Only merge functions defined inside a class.
* ``SFS_Empty`` (in configuration: ``Empty``)
Only merge empty functions.
+ * ``SFS_Inline`` (in configuration: ``Inline``)
+ Only merge functions defined inside a class. Implies "empty".
* ``SFS_All`` (in configuration: ``All``)
Merge all functions fitting on a single line.
@@ -230,6 +228,11 @@ the configuration (without a prefix: ``Auto``).
**AlwaysBreakBeforeMultilineStrings** (``bool``)
If ``true``, always break before multiline string literals.
+ This flag is mean to make cases where there are multiple multiline strings
+ in a file look more consistent. Thus, it will only take effect if wrapping
+ the string at that point leads to it being indented
+ ``ContinuationIndentWidth`` spaces from the start of the line.
+
**AlwaysBreakTemplateDeclarations** (``bool``)
If ``true``, always break after the ``template<...>`` of a
template declaration.
@@ -343,11 +346,10 @@ the configuration (without a prefix: ``Auto``).
instead of as function calls.
These are expected to be macros of the form:
-
- .. code-block:: c++
-
- FOREACH(<variable-declaration>, ...)
- <loop-body>
+ \code
+ FOREACH(<variable-declaration>, ...)
+ <loop-body>
+ \endcode
For example: BOOST_FOREACH.
diff --git a/docs/ControlFlowIntegrity.rst b/docs/ControlFlowIntegrity.rst
index 915385b7b197..ce1c37bcd408 100644
--- a/docs/ControlFlowIntegrity.rst
+++ b/docs/ControlFlowIntegrity.rst
@@ -20,8 +20,8 @@ program's control flow. These schemes have been optimized for performance,
allowing developers to enable them in release builds.
To enable Clang's available CFI schemes, use the flag ``-fsanitize=cfi``.
-As currently implemented, CFI relies on link-time optimization (LTO); the CFI
-schemes imply ``-flto``, and the linker used must support LTO, for example
+As currently implemented, CFI relies on link-time optimization (LTO); so it is
+required to specify ``-flto``, and the linker used must support LTO, for example
via the `gold plugin`_. To allow the checks to be implemented efficiently,
the program must be structured such that certain object files are compiled
with CFI enabled, and are statically linked into the program. This may
diff --git a/docs/LanguageExtensions.rst b/docs/LanguageExtensions.rst
index bd5992e3d6e5..0b4775ba6ad4 100644
--- a/docs/LanguageExtensions.rst
+++ b/docs/LanguageExtensions.rst
@@ -1845,6 +1845,9 @@ with :doc:`ThreadSanitizer`.
Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
with :doc:`MemorySanitizer`.
+Use ``__has_feature(safe_stack)`` to check if the code is being built
+with :doc:`SafeStack`.
+
Extensions for selectively disabling optimization
=================================================
diff --git a/docs/Modules.rst b/docs/Modules.rst
index 9999106914f6..1f3d89897513 100644
--- a/docs/Modules.rst
+++ b/docs/Modules.rst
@@ -159,7 +159,7 @@ Module maps are specified as separate files (each named ``module.modulemap``) al
To actually see any benefits from modules, one first has to introduce module maps for the underlying C standard library and the libraries and headers on which it depends. The section `Modularizing a Platform`_ describes the steps one must take to write these module maps.
-One can use module maps without modules to check the integrity of the use of header files. To do this, use the ``-fmodule-maps`` option instead of the ``-fmodules`` option.
+One can use module maps without modules to check the integrity of the use of header files. To do this, use the ``-fimplicit-module-maps`` option instead of the ``-fmodules`` option, or use ``-fmodule-map-file=`` option to explicitly specify the module map files to load.
Compilation model
-----------------
@@ -174,8 +174,8 @@ Command-line parameters
``-fmodules``
Enable the modules feature.
-``-fmodule-maps``
- Enable interpretation of module maps. This option is implied by ``-fmodules``.
+``-fimplicit-module-maps``
+ Enable implicit search for module map files named ``module.modulemap`` and similar. This option is implied by ``-fmodules``. If this is disabled with ``-fno-implicit-module-maps``, module map files will only be loaded if they are explicitly specified via ``-fmodule-map-file`` or transitively used by another module map file.
``-fmodules-cache-path=<directory>``
Specify the path to the modules cache. If not provided, Clang will select a system-appropriate default.
@@ -207,9 +207,6 @@ Command-line parameters
``-fmodules-search-all``
If a symbol is not found, search modules referenced in the current module maps but not imported for symbols, so the error message can reference the module by name. Note that if the global module index has not been built before, this might take some time as it needs to build all the modules. Note that this option doesn't apply in module builds, to avoid the recursion.
-``-fno-modules-implicit-maps``
- Suppresses the implicit search for files called ``module.modulemap`` and similar. Instead, module files need to be explicitly specified via ``-fmodule-map-file`` or transitively used.
-
``-fno-implicit-modules``
All modules used by the build must be specified with ``-fmodule-file``.
@@ -682,7 +679,7 @@ A *link-declaration* with the ``framework`` specifies that the linker should lin
Configuration macros declaration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The *config-macros-declaration* specifies the set of configuration macros that have an effect on the the API of the enclosing module.
+The *config-macros-declaration* specifies the set of configuration macros that have an effect on the API of the enclosing module.
.. parsed-literal::
diff --git a/docs/SafeStack.rst b/docs/SafeStack.rst
new file mode 100644
index 000000000000..5115d959954e
--- /dev/null
+++ b/docs/SafeStack.rst
@@ -0,0 +1,163 @@
+=========
+SafeStack
+=========
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+SafeStack is an instrumentation pass that protects programs against attacks
+based on stack buffer overflows, without introducing any measurable performance
+overhead. It works by separating the program stack into two distinct regions:
+the safe stack and the unsafe stack. The safe stack stores return addresses,
+register spills, and local variables that are always accessed in a safe way,
+while the unsafe stack stores everything else. This separation ensures that
+buffer overflows on the unsafe stack cannot be used to overwrite anything
+on the safe stack, which includes return addresses.
+
+Performance
+-----------
+
+The performance overhead of the SafeStack instrumentation is less than 0.1% on
+average across a variety of benchmarks (see the `Code-Pointer Integrity
+<http://dslab.epfl.ch/pubs/cpi.pdf>`_ paper for details). This is mainly
+because most small functions do not have any variables that require the unsafe
+stack and, hence, do not need unsafe stack frames to be created. The cost of
+creating unsafe stack frames for large functions is amortized by the cost of
+executing the function.
+
+In some cases, SafeStack actually improves the performance. Objects that end up
+being moved to the unsafe stack are usually large arrays or variables that are
+used through multiple stack frames. Moving such objects away from the safe
+stack increases the locality of frequently accessed values on the stack, such
+as register spills, return addresses, and small local variables.
+
+Limitations
+-----------
+
+SafeStack has not been subjected to a comprehensive security review, and there
+exist known weaknesses, including but not limited to the following.
+
+In its current state, the separation of local variables provides protection
+against stack buffer overflows, but the safe stack itself is not protected
+from being corrupted through a pointer dereference. The Code-Pointer
+Integrity paper describes two ways in which we may protect the safe stack:
+hardware segmentation on the 32-bit x86 architecture or information hiding
+on other architectures.
+
+Even with information hiding, the safe stack would merely be hidden
+from attackers by being somewhere in the address space. Depending on the
+application, the address could be predictable even on 64-bit address spaces
+because not all the bits are addressable, multiple threads each have their
+stack, the application could leak the safe stack address to memory via
+``__builtin_frame_address``, bugs in the low-level runtime support etc.
+Safe stack leaks could be mitigated by writing and deploying a static binary
+analysis or a dynamic binary instrumentation based tool to find leaks.
+
+This approach doesn't prevent an attacker from "imbalancing" the safe
+stack by say having just one call, and doing two rets (thereby returning
+to an address that wasn't meant as a return address). This can be at least
+partially mitigated by deploying SafeStack alongside a forward control-flow
+integrity mechanism to ensure that calls are made using the correct calling
+convention. Clang does not currently implement a comprehensive forward
+control-flow integrity protection scheme; there exists one that protects
+:doc:`virtual calls <ControlFlowIntegrity>` but not non-virtual indirect calls.
+
+Compatibility
+-------------
+
+Most programs, static libraries, or individual files can be compiled
+with SafeStack as is. SafeStack requires basic runtime support, which, on most
+platforms, is implemented as a compiler-rt library that is automatically linked
+in when the program is compiled with SafeStack.
+
+Linking a DSO with SafeStack is not currently supported.
+
+Known compatibility limitations
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Certain code that relies on low-level stack manipulations requires adaption to
+work with SafeStack. One example is mark-and-sweep garbage collection
+implementations for C/C++ (e.g., Oilpan in chromium/blink), which must be
+changed to look for the live pointers on both safe and unsafe stacks.
+
+SafeStack supports linking together modules that are compiled with and without
+SafeStack, both statically and dynamically. One corner case that is not
+supported is using ``dlopen()`` to load a dynamic library that uses SafeStack into
+a program that is not compiled with SafeStack but uses threads.
+
+Signal handlers that use ``sigaltstack()`` must not use the unsafe stack (see
+``__attribute__((no_sanitize("safe-stack")))`` below).
+
+Programs that use APIs from ``ucontext.h`` are not supported yet.
+
+Usage
+=====
+
+To enable SafeStack, just pass ``-fsanitize=safe-stack`` flag to both compile and link
+command lines.
+
+Supported Platforms
+-------------------
+
+SafeStack was tested on Linux, FreeBSD and MacOSX.
+
+Low-level API
+-------------
+
+``__has_feature(safe_stack)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In some rare cases one may need to execute different code depending on
+whether SafeStack is enabled. The macro ``__has_feature(safe_stack)`` can
+be used for this purpose.
+
+.. code-block:: c
+
+ #if __has_feature(safe_stack)
+ // code that builds only under SafeStack
+ #endif
+
+``__attribute__((no_sanitize("safe-stack")))``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Use ``__attribute__((no_sanitize("safe-stack")))`` on a function declaration
+to specify that the safe stack instrumentation should not be applied to that
+function, even if enabled globally (see ``-fsanitize=safe-stack`` flag). This
+attribute may be required for functions that make assumptions about the
+exact layout of their stack frames.
+
+Care should be taken when using this attribute. The return address is not
+protected against stack buffer overflows, and it is easier to leak the
+address of the safe stack to memory by taking the address of a local variable.
+
+
+``__builtin___get_unsafe_stack_ptr()``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This builtin function returns current unsafe stack pointer of the current
+thread.
+
+``__builtin___get_unsafe_stack_start()``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This builtin function returns a pointer to the start of the unsafe stack of the
+current thread.
+
+Design
+======
+
+Please refer to
+`http://dslab.epfl.ch/proj/cpi/ <http://dslab.epfl.ch/proj/cpi/>`_ for more
+information about the design of the SafeStack and its related technologies.
+
+
+Publications
+------------
+
+`Code-Pointer Integrity <http://dslab.epfl.ch/pubs/cpi.pdf>`_.
+Volodymyr Kuznetsov, Laszlo Szekeres, Mathias Payer, George Candea, R. Sekar, Dawn Song.
+USENIX Symposium on Operating Systems Design and Implementation
+(`OSDI <https://www.usenix.org/conference/osdi14>`_), Broomfield, CO, October 2014
diff --git a/docs/UsersManual.rst b/docs/UsersManual.rst
index 2ddf0822dd6e..cd1b2b3c341d 100644
--- a/docs/UsersManual.rst
+++ b/docs/UsersManual.rst
@@ -970,16 +970,15 @@ are listed below.
includes all of the checks listed below other than
``unsigned-integer-overflow``.
- - ``-fsanitize=undefined-trap``: This includes all sanitizers
- included by ``-fsanitize=undefined``, except those that require
- runtime support. This group of sanitizers is intended to be
- used in conjunction with the ``-fsanitize-undefined-trap-on-error``
- flag. This includes all of the checks listed below other than
- ``unsigned-integer-overflow`` and ``vptr``.
+ - ``-fsanitize=undefined-trap``: This is a deprecated alias for
+ ``-fsanitize=undefined``.
+
- ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
flow analysis.
- ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
- checks. Implies ``-flto``.
+ checks. Requires ``-flto``.
+ - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
+ protection against stack-based memory corruption errors.
The following more fine-grained checks are also available:
@@ -992,13 +991,13 @@ are listed below.
- ``-fsanitize=cfi-cast-strict``: Enables :ref:`strict cast checks
<cfi-strictness>`.
- ``-fsanitize=cfi-derived-cast``: Base-to-derived cast to the wrong
- dynamic type. Implies ``-flto``.
+ dynamic type. Requires ``-flto``.
- ``-fsanitize=cfi-unrelated-cast``: Cast from ``void*`` or another
- unrelated type to the wrong dynamic type. Implies ``-flto``.
+ unrelated type to the wrong dynamic type. Requires ``-flto``.
- ``-fsanitize=cfi-nvcall``: Non-virtual call via an object whose vptr is of
- the wrong dynamic type. Implies ``-flto``.
+ the wrong dynamic type. Requires ``-flto``.
- ``-fsanitize=cfi-vcall``: Virtual call via an object whose vptr is of the
- wrong dynamic type. Implies ``-flto``.
+ wrong dynamic type. Requires ``-flto``.
- ``-fsanitize=enum``: Load of a value of an enumerated type which
is not in the range of representable values for that enumerated
type.
@@ -1067,15 +1066,6 @@ are listed below.
through. This mode may use extra memory in programs that copy
uninitialized memory a lot.
- Extra features of UndefinedBehaviorSanitizer:
-
- - ``-fsanitize-undefined-trap-on-error``: Causes traps to be emitted
- rather than calls to runtime libraries when a problem is detected.
- This option is intended for use in cases where the sanitizer runtime
- cannot be used (for instance, when building libc or a kernel module).
- This is only compatible with the sanitizers in the ``undefined-trap``
- group.
-
The ``-fsanitize=`` argument must also be provided when linking, in
order to link to the appropriate runtime library. When using
``-fsanitize=vptr`` (or a group that includes it, such as
@@ -1099,11 +1089,41 @@ are listed below.
sanitizers (e.g. :doc:`AddressSanitizer`) may not support recovery,
and always crash the program after the issue is detected.
+ Note that the ``-fsanitize-trap`` flag has precedence over this flag.
+ This means that if a check has been configured to trap elsewhere on the
+ command line, or if the check traps by default, this flag will not have
+ any effect unless that sanitizer's trapping behavior is disabled with
+ ``-fno-sanitize-trap``.
+
+ For example, if a command line contains the flags ``-fsanitize=undefined
+ -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
+ will have no effect on its own; it will need to be accompanied by
+ ``-fno-sanitize-trap=alignment``.
+
+**-f[no-]sanitize-trap=check1,check2,...**
+
+ Controls which checks enabled by the ``-fsanitize=`` flag trap. This
+ option is intended for use in cases where the sanitizer runtime cannot
+ be used (for instance, when building libc or a kernel module), or where
+ the binary size increase caused by the sanitizer runtime is a concern.
+
+ This flag is only compatible with ``local-bounds``,
+ ``unsigned-integer-overflow``, sanitizers in the ``cfi`` group and
+ sanitizers in the ``undefined`` group other than ``vptr``. If this flag
+ is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
+ will be implicitly disabled.
+
+ This flag is enabled by default for sanitizers in the ``cfi`` group.
+
**-f[no-]sanitize-coverage=[type,features,...]**
Enable simple code coverage in addition to certain sanitizers.
See :doc:`SanitizerCoverage` for more details.
+.. option:: -fsanitize-undefined-trap-on-error
+
+ Deprecated alias for ``-fsanitize-trap=undefined``.
+
.. option:: -fno-assume-sane-operator-new
Don't assume that the C++'s new operator is sane.
diff --git a/docs/index.rst b/docs/index.rst
index a3c8ffb8dc69..dec2bc828c1c 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -29,6 +29,7 @@ Using Clang as a Compiler
SanitizerCoverage
SanitizerSpecialCaseList
ControlFlowIntegrity
+ SafeStack
Modules
MSVCCompatibility
FAQ
diff --git a/docs/tools/clang.pod b/docs/tools/clang.pod
index f7d2eaf683cb..153f97b2caa0 100644
--- a/docs/tools/clang.pod
+++ b/docs/tools/clang.pod
@@ -39,12 +39,12 @@ the other tools.
This stage handles tokenization of the input source file, macro expansion,
#include expansion and handling of other preprocessor directives. The output of
this stage is typically called a ".i" (for C), ".ii" (for C++), ".mi" (for
-Objective-C) , or ".mii" (for Objective-C++) file.
+Objective-C), or ".mii" (for Objective-C++) file.
=item B<Parsing and Semantic Analysis>
This stage parses the input file, translating preprocessor tokens into a parse
-tree. Once in the form of a parser tree, it applies semantic analysis to compute
+tree. Once in the form of a parse tree, it applies semantic analysis to compute
types for expressions as well and determine whether the code is well formed. This
stage is responsible for generating most of the compiler warnings as well as
parse errors. The output of this stage is an "Abstract Syntax Tree" (AST).
@@ -330,13 +330,13 @@ all by the program.
=item B<-fexceptions>
-Enable generation of unwind information, this allows exceptions to be thrown
+Enable generation of unwind information. This allows exceptions to be thrown
through Clang compiled stack frames. This is on by default in x86-64.
=item B<-ftrapv>
Generate code to catch integer overflow errors. Signed integer overflow is
-undefined in C, with this flag, extra code is generated to detect this and abort
+undefined in C. With this flag, extra code is generated to detect this and abort
when it happens.
@@ -389,7 +389,7 @@ Display available options.
=item B<-Qunused-arguments>
-Don't emit warning for unused driver arguments.
+Do not emit any warnings for unused driver arguments.
=item B<-Wa,>I<args>
@@ -578,7 +578,7 @@ write temporary files used during the compilation process.
If this environment variable is present, it is treated as a delimited
list of paths to be added to the default system include path list. The
-delimiter is the platform dependent delimitor, as used in the I<PATH>
+delimiter is the platform dependent delimiter, as used in the I<PATH>
environment variable.
Empty components in the environment variable are ignored.
@@ -592,7 +592,7 @@ which are only used when processing the appropriate language.
=item B<MACOSX_DEPLOYMENT_TARGET>
If -mmacosx-version-min is unspecified, the default deployment target
-is read from this environment variable. This option only affects darwin
+is read from this environment variable. This option only affects Darwin
targets.
=back
diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h
index 3276afc4b960..a2241802078e 100644
--- a/include/clang-c/Index.h
+++ b/include/clang-c/Index.h
@@ -2225,7 +2225,12 @@ enum CXCursorKind {
*/
CXCursor_OMPTeamsDirective = 253,
- CXCursor_LastStmt = CXCursor_OMPTeamsDirective,
+ /** \brief OpenMP taskwait directive.
+ */
+ CXCursor_OMPTaskgroupDirective = 254,
+
+
+ CXCursor_LastStmt = CXCursor_OMPTaskgroupDirective,
/**
* \brief Cursor that represents the translation unit itself.
@@ -5628,7 +5633,7 @@ typedef enum {
* reused after indexing is finished. Set to \c NULL if you do not require it.
*
* \returns 0 on success or if there were errors from which the compiler could
- * recover. If there is a failure from which the there is no recovery, returns
+ * recover. If there is a failure from which there is no recovery, returns
* a non-zero \c CXErrorCode.
*
* The rest of the parameters are the same as #clang_parseTranslationUnit.
@@ -5659,7 +5664,7 @@ CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction,
*
* The parameters are the same as #clang_indexSourceFile.
*
- * \returns If there is a failure from which the there is no recovery, returns
+ * \returns If there is a failure from which there is no recovery, returns
* non-zero, otherwise returns 0.
*/
CINDEX_LINKAGE int clang_indexTranslationUnit(CXIndexAction,
diff --git a/include/clang/ARCMigrate/ARCMT.h b/include/clang/ARCMigrate/ARCMT.h
index ad4f23c604b3..74081867eebc 100644
--- a/include/clang/ARCMigrate/ARCMT.h
+++ b/include/clang/ARCMigrate/ARCMT.h
@@ -17,6 +17,7 @@
namespace clang {
class ASTContext;
class DiagnosticConsumer;
+ class PCHContainerOperations;
namespace arcmt {
class MigrationPass;
@@ -37,19 +38,22 @@ namespace arcmt {
/// the pre-migration ARC diagnostics.
///
/// \returns false if no error is produced, true otherwise.
-bool checkForManualIssues(CompilerInvocation &CI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient,
- bool emitPremigrationARCErrors = false,
- StringRef plistOut = StringRef());
+bool
+checkForManualIssues(CompilerInvocation &CI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient,
+ bool emitPremigrationARCErrors = false,
+ StringRef plistOut = StringRef());
/// \brief Works similar to checkForManualIssues but instead of checking, it
/// applies automatic modifications to source files to conform to ARC.
///
/// \returns false if no error is produced, true otherwise.
-bool applyTransformations(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient);
+bool
+applyTransformations(CompilerInvocation &origCI,
+ const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient);
/// \brief Applies automatic modifications and produces temporary files
/// and metadata into the \p outputDir path.
@@ -62,12 +66,11 @@ bool applyTransformations(CompilerInvocation &origCI,
/// the pre-migration ARC diagnostics.
///
/// \returns false if no error is produced, true otherwise.
-bool migrateWithTemporaryFiles(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient,
- StringRef outputDir,
- bool emitPremigrationARCErrors,
- StringRef plistOut);
+bool migrateWithTemporaryFiles(
+ CompilerInvocation &origCI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient, StringRef outputDir,
+ bool emitPremigrationARCErrors, StringRef plistOut);
/// \brief Get the set of file remappings from the \p outputDir path that
/// migrateWithTemporaryFiles produced.
@@ -93,13 +96,16 @@ std::vector<TransformFn> getAllTransformations(LangOptions::GCMode OrigGCMode,
class MigrationProcess {
CompilerInvocation OrigCI;
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps;
DiagnosticConsumer *DiagClient;
FileRemapper Remapper;
public:
bool HadARCErrors;
- MigrationProcess(const CompilerInvocation &CI, DiagnosticConsumer *diagClient,
+ MigrationProcess(const CompilerInvocation &CI,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *diagClient,
StringRef outputDir = StringRef());
class RewriteListener {
diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h
index 049221ad9144..da288c4fe5ed 100644
--- a/include/clang/AST/ASTContext.h
+++ b/include/clang/AST/ASTContext.h
@@ -1854,6 +1854,36 @@ public:
getCanonicalType(T2).getTypePtr();
}
+ bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
+ bool IsParam) const {
+ auto SubTnullability = SubT->getNullability(*this);
+ auto SuperTnullability = SuperT->getNullability(*this);
+ if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
+ // Neither has nullability; return true
+ if (!SubTnullability)
+ return true;
+ // Both have nullability qualifier.
+ if (*SubTnullability == *SuperTnullability ||
+ *SubTnullability == NullabilityKind::Unspecified ||
+ *SuperTnullability == NullabilityKind::Unspecified)
+ return true;
+
+ if (IsParam) {
+ // Ok for the superclass method parameter to be "nonnull" and the subclass
+ // method parameter to be "nullable"
+ 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);
+ }
+ }
+ return true;
+ }
+
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
const ObjCMethodDecl *MethodImp);
diff --git a/include/clang/AST/CommentParser.h b/include/clang/AST/CommentParser.h
index 42bf4c989a23..fa8862899c14 100644
--- a/include/clang/AST/CommentParser.h
+++ b/include/clang/AST/CommentParser.h
@@ -75,11 +75,7 @@ class Parser {
return;
MoreLATokens.push_back(Tok);
- for (const Token *I = &Toks.back(),
- *B = &Toks.front();
- I != B; --I) {
- MoreLATokens.push_back(*I);
- }
+ MoreLATokens.append(Toks.rbegin(), std::prev(Toks.rend()));
Tok = Toks[0];
}
diff --git a/include/clang/AST/DataRecursiveASTVisitor.h b/include/clang/AST/DataRecursiveASTVisitor.h
index 971841e8fb5d..ef8817659338 100644
--- a/include/clang/AST/DataRecursiveASTVisitor.h
+++ b/include/clang/AST/DataRecursiveASTVisitor.h
@@ -531,10 +531,7 @@ bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S) {
}
}
- for (SmallVectorImpl<Stmt *>::reverse_iterator RI = StmtsToEnqueue.rbegin(),
- RE = StmtsToEnqueue.rend();
- RI != RE; ++RI)
- Queue.push_back(*RI);
+ Queue.append(StmtsToEnqueue.rbegin(), StmtsToEnqueue.rend());
}
return true;
@@ -2204,9 +2201,11 @@ DEF_TRAVERSE_STMT(CXXThisExpr, {})
DEF_TRAVERSE_STMT(CXXThrowExpr, {})
DEF_TRAVERSE_STMT(UserDefinedLiteral, {})
DEF_TRAVERSE_STMT(DesignatedInitExpr, {})
+DEF_TRAVERSE_STMT(DesignatedInitUpdateExpr, {})
DEF_TRAVERSE_STMT(ExtVectorElementExpr, {})
DEF_TRAVERSE_STMT(GNUNullExpr, {})
DEF_TRAVERSE_STMT(ImplicitValueInitExpr, {})
+DEF_TRAVERSE_STMT(NoInitExpr, {})
DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, {})
DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
if (TypeSourceInfo *TInfo = S->getEncodedTypeSourceInfo())
@@ -2356,6 +2355,9 @@ DEF_TRAVERSE_STMT(OMPBarrierDirective,
DEF_TRAVERSE_STMT(OMPTaskwaitDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
+DEF_TRAVERSE_STMT(OMPTaskgroupDirective,
+ { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
DEF_TRAVERSE_STMT(OMPFlushDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
diff --git a/include/clang/AST/DeclBase.h b/include/clang/AST/DeclBase.h
index f176e5479e1e..6b6ac3f7d5a5 100644
--- a/include/clang/AST/DeclBase.h
+++ b/include/clang/AST/DeclBase.h
@@ -178,7 +178,12 @@ public:
OBJC_TQ_Out = 0x4,
OBJC_TQ_Bycopy = 0x8,
OBJC_TQ_Byref = 0x10,
- OBJC_TQ_Oneway = 0x20
+ OBJC_TQ_Oneway = 0x20,
+
+ /// The nullability qualifier is set when the nullability of the
+ /// result or parameter was expressed via a context-sensitive
+ /// keyword.
+ OBJC_TQ_CSNullability = 0x40
};
protected:
diff --git a/include/clang/AST/DeclCXX.h b/include/clang/AST/DeclCXX.h
index 537ad4640c24..08451c051b57 100644
--- a/include/clang/AST/DeclCXX.h
+++ b/include/clang/AST/DeclCXX.h
@@ -1440,7 +1440,7 @@ public:
///
/// \returns true if this class is derived from \p Base, false otherwise.
///
- /// \todo add a separate paramaeter to configure IsDerivedFrom, rather than
+ /// \todo add a separate parameter to configure IsDerivedFrom, rather than
/// tangling input and output in \p Paths
bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
diff --git a/include/clang/AST/DeclObjC.h b/include/clang/AST/DeclObjC.h
index 4a5b4f3d0756..c3fb57770245 100644
--- a/include/clang/AST/DeclObjC.h
+++ b/include/clang/AST/DeclObjC.h
@@ -141,7 +141,7 @@ private:
// NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
/// in, inout, etc.
- unsigned objcDeclQualifier : 6;
+ unsigned objcDeclQualifier : 7;
/// \brief Indicates whether this method has a related result type.
unsigned RelatedResultType : 1;
@@ -2203,13 +2203,17 @@ public:
OBJC_PR_atomic = 0x100,
OBJC_PR_weak = 0x200,
OBJC_PR_strong = 0x400,
- OBJC_PR_unsafe_unretained = 0x800
+ OBJC_PR_unsafe_unretained = 0x800,
+ /// Indicates that the nullability of the type was spelled with a
+ /// property attribute rather than a type qualifier.
+ OBJC_PR_nullability = 0x1000,
+ OBJC_PR_null_resettable = 0x2000
// Adding a property should change NumPropertyAttrsBits
};
enum {
/// \brief Number of bits fitting all the property attributes.
- NumPropertyAttrsBits = 12
+ NumPropertyAttrsBits = 14
};
enum SetterKind { Assign, Retain, Copy, Weak };
@@ -2217,7 +2221,8 @@ public:
private:
SourceLocation AtLoc; // location of \@property
SourceLocation LParenLoc; // location of '(' starting attribute list or null.
- TypeSourceInfo *DeclType;
+ QualType DeclType;
+ TypeSourceInfo *DeclTypeSourceInfo;
unsigned PropertyAttributes : NumPropertyAttrsBits;
unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
// \@required/\@optional
@@ -2232,12 +2237,13 @@ private:
ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
SourceLocation AtLocation, SourceLocation LParenLocation,
- TypeSourceInfo *T)
+ QualType T, TypeSourceInfo *TSI,
+ PropertyControl propControl)
: NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
- LParenLoc(LParenLocation), DeclType(T),
+ LParenLoc(LParenLocation), DeclType(T), DeclTypeSourceInfo(TSI),
PropertyAttributes(OBJC_PR_noattr),
PropertyAttributesAsWritten(OBJC_PR_noattr),
- PropertyImplementation(None),
+ PropertyImplementation(propControl),
GetterName(Selector()),
SetterName(Selector()),
GetterMethodDecl(nullptr), SetterMethodDecl(nullptr),
@@ -2248,7 +2254,8 @@ public:
SourceLocation L,
IdentifierInfo *Id, SourceLocation AtLocation,
SourceLocation LParenLocation,
- TypeSourceInfo *T,
+ QualType T,
+ TypeSourceInfo *TSI,
PropertyControl propControl = None);
static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
@@ -2259,9 +2266,14 @@ public:
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
- TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
- QualType getType() const { return DeclType->getType(); }
- void setType(TypeSourceInfo *T) { DeclType = T; }
+ TypeSourceInfo *getTypeSourceInfo() const { return DeclTypeSourceInfo; }
+
+ QualType getType() const { return DeclType; }
+
+ void setType(QualType T, TypeSourceInfo *TSI) {
+ DeclType = T;
+ DeclTypeSourceInfo = TSI;
+ }
PropertyAttributeKind getPropertyAttributes() const {
return PropertyAttributeKind(PropertyAttributes);
diff --git a/include/clang/AST/DeclTemplate.h b/include/clang/AST/DeclTemplate.h
index 90cfb2049173..0fc9b4947d49 100644
--- a/include/clang/AST/DeclTemplate.h
+++ b/include/clang/AST/DeclTemplate.h
@@ -217,6 +217,88 @@ public:
}
};
+void *allocateDefaultArgStorageChain(const ASTContext &C);
+
+/// Storage for a default argument. This is conceptually either empty, or an
+/// argument value, or a pointer to a previous declaration that had a default
+/// argument.
+///
+/// However, this is complicated by modules: while we require all the default
+/// arguments for a template to be equivalent, there may be more than one, and
+/// we need to track all the originating parameters to determine if the default
+/// argument is visible.
+template<typename ParmDecl, typename ArgType>
+class DefaultArgStorage {
+ /// Storage for both the value *and* another parameter from which we inherit
+ /// the default argument. This is used when multiple default arguments for a
+ /// parameter are merged together from different modules.
+ struct Chain {
+ ParmDecl *PrevDeclWithDefaultArg;
+ ArgType Value;
+ };
+ static_assert(sizeof(Chain) == sizeof(void *) * 2,
+ "non-pointer argument type?");
+
+ llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
+
+ static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
+ const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
+ if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
+ Parm = Prev;
+ assert(!Parm->getDefaultArgStorage()
+ .ValueOrInherited.template is<ParmDecl *>() &&
+ "should only be one level of indirection");
+ return Parm;
+ }
+
+public:
+ DefaultArgStorage() : ValueOrInherited(ArgType()) {}
+
+ /// Determine whether there is a default argument for this parameter.
+ bool isSet() const { return !ValueOrInherited.isNull(); }
+ /// Determine whether the default argument for this parameter was inherited
+ /// from a previous declaration of the same entity.
+ bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
+ /// Get the default argument's value. This does not consider whether the
+ /// default argument is visible.
+ ArgType get() const {
+ const DefaultArgStorage *Storage = this;
+ if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
+ Storage = &Prev->getDefaultArgStorage();
+ if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
+ return C->Value;
+ return Storage->ValueOrInherited.template get<ArgType>();
+ }
+ /// Get the parameter from which we inherit the default argument, if any.
+ /// This is the parameter on which the default argument was actually written.
+ const ParmDecl *getInheritedFrom() const {
+ if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
+ return D;
+ if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
+ return C->PrevDeclWithDefaultArg;
+ return nullptr;
+ }
+ /// Set the default argument.
+ void set(ArgType Arg) {
+ assert(!isSet() && "default argument already set");
+ ValueOrInherited = Arg;
+ }
+ /// Set that the default argument was inherited from another parameter.
+ void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
+ assert(!isInherited() && "default argument already inherited");
+ InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
+ if (!isSet())
+ ValueOrInherited = InheritedFrom;
+ else
+ ValueOrInherited = new (allocateDefaultArgStorageChain(C))
+ Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
+ }
+ /// Remove the default argument, even if it was inherited.
+ void clear() {
+ ValueOrInherited = ArgType();
+ }
+};
+
//===----------------------------------------------------------------------===//
// Kinds of Templates
//===----------------------------------------------------------------------===//
@@ -942,18 +1024,16 @@ class TemplateTypeParmDecl : public TypeDecl {
/// If false, it was declared with the 'class' keyword.
bool Typename : 1;
- /// \brief Whether this template type parameter inherited its
- /// default argument.
- bool InheritedDefault : 1;
-
/// \brief The default template argument, if any.
- TypeSourceInfo *DefaultArgument;
+ typedef DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>
+ DefArgStorage;
+ DefArgStorage DefaultArgument;
TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Typename)
: TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
- InheritedDefault(false), DefaultArgument() { }
+ DefaultArgument() { }
/// Sema creates these on the stack during auto type deduction.
friend class Sema;
@@ -974,35 +1054,45 @@ public:
/// If not, it was declared with the 'class' keyword.
bool wasDeclaredWithTypename() const { return Typename; }
+ const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
+
/// \brief Determine whether this template parameter has a default
/// argument.
- bool hasDefaultArgument() const { return DefaultArgument != nullptr; }
+ bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
/// \brief Retrieve the default argument, if any.
- QualType getDefaultArgument() const { return DefaultArgument->getType(); }
+ QualType getDefaultArgument() const {
+ return DefaultArgument.get()->getType();
+ }
/// \brief Retrieves the default argument's source information, if any.
- TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
+ TypeSourceInfo *getDefaultArgumentInfo() const {
+ return DefaultArgument.get();
+ }
/// \brief Retrieves the location of the default argument declaration.
SourceLocation getDefaultArgumentLoc() const;
/// \brief Determines whether the default argument was inherited
/// from a previous declaration of this template.
- bool defaultArgumentWasInherited() const { return InheritedDefault; }
+ bool defaultArgumentWasInherited() const {
+ return DefaultArgument.isInherited();
+ }
- /// \brief Set the default argument for this template parameter, and
- /// whether that default argument was inherited from another
- /// declaration.
- void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
- DefaultArgument = DefArg;
- InheritedDefault = Inherited;
+ /// \brief Set the default argument for this template parameter.
+ void setDefaultArgument(TypeSourceInfo *DefArg) {
+ DefaultArgument.set(DefArg);
+ }
+ /// \brief Set that this default argument was inherited from another
+ /// parameter.
+ void setInheritedDefaultArgument(const ASTContext &C,
+ TemplateTypeParmDecl *Prev) {
+ DefaultArgument.setInherited(C, Prev);
}
/// \brief Removes the default argument of this template parameter.
void removeDefaultArgument() {
- DefaultArgument = nullptr;
- InheritedDefault = false;
+ DefaultArgument.clear();
}
/// \brief Set whether this template type parameter was declared with
@@ -1034,7 +1124,8 @@ class NonTypeTemplateParmDecl
: public DeclaratorDecl, protected TemplateParmPosition {
/// \brief The default template argument, if any, and whether or not
/// it was inherited.
- llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
+ typedef DefaultArgStorage<NonTypeTemplateParmDecl, Expr*> DefArgStorage;
+ DefArgStorage DefaultArgument;
// FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
// down here to save memory.
@@ -1055,9 +1146,8 @@ class NonTypeTemplateParmDecl
IdentifierInfo *Id, QualType T,
bool ParameterPack, TypeSourceInfo *TInfo)
: DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
- TemplateParmPosition(D, P), DefaultArgumentAndInherited(nullptr, false),
- ParameterPack(ParameterPack), ExpandedParameterPack(false),
- NumExpandedTypes(0)
+ TemplateParmPosition(D, P), ParameterPack(ParameterPack),
+ ExpandedParameterPack(false), NumExpandedTypes(0)
{ }
NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
@@ -1097,16 +1187,14 @@ public:
SourceRange getSourceRange() const override LLVM_READONLY;
+ const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
+
/// \brief Determine whether this template parameter has a default
/// argument.
- bool hasDefaultArgument() const {
- return DefaultArgumentAndInherited.getPointer() != nullptr;
- }
+ bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
/// \brief Retrieve the default argument, if any.
- Expr *getDefaultArgument() const {
- return DefaultArgumentAndInherited.getPointer();
- }
+ Expr *getDefaultArgument() const { return DefaultArgument.get(); }
/// \brief Retrieve the location of the default argument, if any.
SourceLocation getDefaultArgumentLoc() const;
@@ -1114,22 +1202,20 @@ public:
/// \brief Determines whether the default argument was inherited
/// from a previous declaration of this template.
bool defaultArgumentWasInherited() const {
- return DefaultArgumentAndInherited.getInt();
+ return DefaultArgument.isInherited();
}
/// \brief Set the default argument for this template parameter, and
/// whether that default argument was inherited from another
/// declaration.
- void setDefaultArgument(Expr *DefArg, bool Inherited) {
- DefaultArgumentAndInherited.setPointer(DefArg);
- DefaultArgumentAndInherited.setInt(Inherited);
+ void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
+ void setInheritedDefaultArgument(const ASTContext &C,
+ NonTypeTemplateParmDecl *Parm) {
+ DefaultArgument.setInherited(C, Parm);
}
/// \brief Removes the default argument of this template parameter.
- void removeDefaultArgument() {
- DefaultArgumentAndInherited.setPointer(nullptr);
- DefaultArgumentAndInherited.setInt(false);
- }
+ void removeDefaultArgument() { DefaultArgument.clear(); }
/// \brief Whether this parameter is a non-type template parameter pack.
///
@@ -1217,10 +1303,10 @@ class TemplateTemplateParmDecl : public TemplateDecl,
{
void anchor() override;
- /// DefaultArgument - The default template argument, if any.
- TemplateArgumentLoc DefaultArgument;
- /// Whether or not the default argument was inherited.
- bool DefaultArgumentWasInherited;
+ /// \brief The default template argument, if any.
+ typedef DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>
+ DefArgStorage;
+ DefArgStorage DefaultArgument;
/// \brief Whether this parameter is a parameter pack.
bool ParameterPack;
@@ -1237,8 +1323,7 @@ class TemplateTemplateParmDecl : public TemplateDecl,
unsigned D, unsigned P, bool ParameterPack,
IdentifierInfo *Id, TemplateParameterList *Params)
: TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
- TemplateParmPosition(D, P), DefaultArgument(),
- DefaultArgumentWasInherited(false), ParameterPack(ParameterPack),
+ TemplateParmPosition(D, P), ParameterPack(ParameterPack),
ExpandedParameterPack(false), NumExpandedParams(0)
{ }
@@ -1322,15 +1407,16 @@ public:
return reinterpret_cast<TemplateParameterList *const *>(this + 1)[I];
}
+ const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
+
/// \brief Determine whether this template parameter has a default
/// argument.
- bool hasDefaultArgument() const {
- return !DefaultArgument.getArgument().isNull();
- }
+ bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
/// \brief Retrieve the default argument, if any.
const TemplateArgumentLoc &getDefaultArgument() const {
- return DefaultArgument;
+ static const TemplateArgumentLoc None;
+ return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
}
/// \brief Retrieve the location of the default argument, if any.
@@ -1339,22 +1425,21 @@ public:
/// \brief Determines whether the default argument was inherited
/// from a previous declaration of this template.
bool defaultArgumentWasInherited() const {
- return DefaultArgumentWasInherited;
+ return DefaultArgument.isInherited();
}
/// \brief Set the default argument for this template parameter, and
/// whether that default argument was inherited from another
/// declaration.
- void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
- DefaultArgument = DefArg;
- DefaultArgumentWasInherited = Inherited;
+ void setDefaultArgument(const ASTContext &C,
+ const TemplateArgumentLoc &DefArg);
+ void setInheritedDefaultArgument(const ASTContext &C,
+ TemplateTemplateParmDecl *Prev) {
+ DefaultArgument.setInherited(C, Prev);
}
/// \brief Removes the default argument of this template parameter.
- void removeDefaultArgument() {
- DefaultArgument = TemplateArgumentLoc();
- DefaultArgumentWasInherited = false;
- }
+ void removeDefaultArgument() { DefaultArgument.clear(); }
SourceRange getSourceRange() const override LLVM_READONLY {
SourceLocation End = getLocation();
diff --git a/include/clang/AST/EvaluatedExprVisitor.h b/include/clang/AST/EvaluatedExprVisitor.h
index 59de104b83f9..5cae5d9eca3f 100644
--- a/include/clang/AST/EvaluatedExprVisitor.h
+++ b/include/clang/AST/EvaluatedExprVisitor.h
@@ -26,29 +26,32 @@ class ASTContext;
/// \brief Given a potentially-evaluated expression, this visitor visits all
/// of its potentially-evaluated subexpressions, recursively.
-template<typename ImplClass>
-class EvaluatedExprVisitor : public StmtVisitor<ImplClass> {
- ASTContext &Context;
-
+template<template <typename> class Ptr, typename ImplClass>
+class EvaluatedExprVisitorBase : public StmtVisitorBase<Ptr, ImplClass, void> {
+protected:
+ const ASTContext &Context;
+
public:
- explicit EvaluatedExprVisitor(ASTContext &Context) : Context(Context) { }
-
+#define PTR(CLASS) typename Ptr<CLASS>::type
+
+ explicit EvaluatedExprVisitorBase(const ASTContext &Context) : Context(Context) { }
+
// Expressions that have no potentially-evaluated subexpressions (but may have
// other sub-expressions).
- void VisitDeclRefExpr(DeclRefExpr *E) { }
- void VisitOffsetOfExpr(OffsetOfExpr *E) { }
- void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { }
- void VisitExpressionTraitExpr(ExpressionTraitExpr *E) { }
- void VisitBlockExpr(BlockExpr *E) { }
- void VisitCXXUuidofExpr(CXXUuidofExpr *E) { }
- void VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { }
-
- void VisitMemberExpr(MemberExpr *E) {
+ void VisitDeclRefExpr(PTR(DeclRefExpr) E) { }
+ void VisitOffsetOfExpr(PTR(OffsetOfExpr) E) { }
+ void VisitUnaryExprOrTypeTraitExpr(PTR(UnaryExprOrTypeTraitExpr) E) { }
+ void VisitExpressionTraitExpr(PTR(ExpressionTraitExpr) E) { }
+ void VisitBlockExpr(PTR(BlockExpr) E) { }
+ void VisitCXXUuidofExpr(PTR(CXXUuidofExpr) E) { }
+ void VisitCXXNoexceptExpr(PTR(CXXNoexceptExpr) E) { }
+
+ void VisitMemberExpr(PTR(MemberExpr) E) {
// Only the base matters.
return this->Visit(E->getBase());
}
-
- void VisitChooseExpr(ChooseExpr *E) {
+
+ void VisitChooseExpr(PTR(ChooseExpr) E) {
// Don't visit either child expression if the condition is dependent.
if (E->getCond()->isValueDependent())
return;
@@ -56,7 +59,7 @@ public:
return this->Visit(E->getChosenSubExpr());
}
- void VisitGenericSelectionExpr(GenericSelectionExpr *E) {
+ void VisitGenericSelectionExpr(PTR(GenericSelectionExpr) E) {
// The controlling expression of a generic selection is not evaluated.
// Don't visit either child expression if the condition is type-dependent.
@@ -67,23 +70,23 @@ public:
return this->Visit(E->getResultExpr());
}
- void VisitDesignatedInitExpr(DesignatedInitExpr *E) {
+ void VisitDesignatedInitExpr(PTR(DesignatedInitExpr) E) {
// Only the actual initializer matters; the designators are all constant
// expressions.
return this->Visit(E->getInit());
}
- void VisitCXXTypeidExpr(CXXTypeidExpr *E) {
+ void VisitCXXTypeidExpr(PTR(CXXTypeidExpr) E) {
if (E->isPotentiallyEvaluated())
return this->Visit(E->getExprOperand());
}
- void VisitCallExpr(CallExpr *CE) {
+ void VisitCallExpr(PTR(CallExpr) CE) {
if (!CE->isUnevaluatedBuiltinCall(Context))
return static_cast<ImplClass*>(this)->VisitExpr(CE);
}
- void VisitLambdaExpr(LambdaExpr *LE) {
+ void VisitLambdaExpr(PTR(LambdaExpr) LE) {
// Only visit the capture initializers, and not the body.
for (LambdaExpr::capture_init_iterator I = LE->capture_init_begin(),
E = LE->capture_init_end();
@@ -94,11 +97,31 @@ public:
/// \brief The basis case walks all of the children of the statement or
/// expression, assuming they are all potentially evaluated.
- void VisitStmt(Stmt *S) {
- for (Stmt::child_range C = S->children(); C; ++C)
+ void VisitStmt(PTR(Stmt) S) {
+ for (auto C = S->children(); C; ++C)
if (*C)
this->Visit(*C);
}
+
+#undef PTR
+};
+
+/// EvaluatedExprVisitor - This class visits 'Expr *'s
+template<typename ImplClass>
+class EvaluatedExprVisitor
+ : public EvaluatedExprVisitorBase<make_ptr, ImplClass> {
+public:
+ explicit EvaluatedExprVisitor(const ASTContext &Context) :
+ EvaluatedExprVisitorBase<make_ptr, ImplClass>(Context) { }
+};
+
+/// ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
+template<typename ImplClass>
+class ConstEvaluatedExprVisitor
+ : public EvaluatedExprVisitorBase<make_const_ptr, ImplClass> {
+public:
+ explicit ConstEvaluatedExprVisitor(const ASTContext &Context) :
+ EvaluatedExprVisitorBase<make_const_ptr, ImplClass>(Context) { }
};
}
diff --git a/include/clang/AST/Expr.h b/include/clang/AST/Expr.h
index a3be7d06c4b1..2a5b4c0f5ed0 100644
--- a/include/clang/AST/Expr.h
+++ b/include/clang/AST/Expr.h
@@ -598,7 +598,7 @@ public:
/// \brief Determine whether this expression involves a call to any function
/// that is not trivial.
- bool hasNonTrivialCall(ASTContext &Ctx);
+ bool hasNonTrivialCall(const ASTContext &Ctx) const;
/// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
/// integer. This must be called on an expression that constant folds to an
@@ -2273,7 +2273,7 @@ public:
/// \brief Returns \c true if this is a call to a builtin which does not
/// evaluate side-effects within its arguments.
- bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
+ bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
/// getCallReturnType - Get the return type of the call expr. This is not
/// always the type of the expr itself, if the return type is a reference
@@ -4267,6 +4267,80 @@ public:
}
};
+/// \brief Represents a place-holder for an object not to be initialized by
+/// anything.
+///
+/// This only makes sense when it appears as part of an updater of a
+/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
+/// initializes a big object, and the NoInitExpr's mark the spots within the
+/// big object not to be overwritten by the updater.
+///
+/// \see DesignatedInitUpdateExpr
+class NoInitExpr : public Expr {
+public:
+ explicit NoInitExpr(QualType ty)
+ : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
+ false, false, ty->isInstantiationDependentType(), false) { }
+
+ explicit NoInitExpr(EmptyShell Empty)
+ : Expr(NoInitExprClass, Empty) { }
+
+ static bool classof(const Stmt *T) {
+ return T->getStmtClass() == NoInitExprClass;
+ }
+
+ SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
+ SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
+
+ // Iterators
+ child_range children() { return child_range(); }
+};
+
+// In cases like:
+// struct Q { int a, b, c; };
+// Q *getQ();
+// void foo() {
+// struct A { Q q; } a = { *getQ(), .q.b = 3 };
+// }
+//
+// We will have an InitListExpr for a, with type A, and then a
+// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
+// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
+//
+class DesignatedInitUpdateExpr : public Expr {
+ // BaseAndUpdaterExprs[0] is the base expression;
+ // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
+ Stmt *BaseAndUpdaterExprs[2];
+
+public:
+ DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
+ Expr *baseExprs, SourceLocation rBraceLoc);
+
+ explicit DesignatedInitUpdateExpr(EmptyShell Empty)
+ : Expr(DesignatedInitUpdateExprClass, Empty) { }
+
+ SourceLocation getLocStart() const LLVM_READONLY;
+ SourceLocation getLocEnd() const LLVM_READONLY;
+
+ static bool classof(const Stmt *T) {
+ return T->getStmtClass() == DesignatedInitUpdateExprClass;
+ }
+
+ Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
+ void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
+
+ InitListExpr *getUpdater() const {
+ return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
+ }
+ void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
+
+ // Iterators
+ // children = the base and the updater
+ child_range children() {
+ return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
+ }
+};
+
/// \brief Represents an implicitly-generated value initialization of
/// an object of a given type.
///
diff --git a/include/clang/AST/OpenMPClause.h b/include/clang/AST/OpenMPClause.h
index c8ecef8ce50c..386c8dd3ee94 100644
--- a/include/clang/AST/OpenMPClause.h
+++ b/include/clang/AST/OpenMPClause.h
@@ -1752,7 +1752,7 @@ public:
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
- reinterpret_cast<Stmt **>(getFinals().end() + 2));
+ reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
@@ -1837,7 +1837,7 @@ public:
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
- reinterpret_cast<Stmt **>(varlist_end() + 1));
+ reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
diff --git a/include/clang/AST/RecursiveASTVisitor.h b/include/clang/AST/RecursiveASTVisitor.h
index 95e0df3066b0..95d773073184 100644
--- a/include/clang/AST/RecursiveASTVisitor.h
+++ b/include/clang/AST/RecursiveASTVisitor.h
@@ -2234,9 +2234,11 @@ DEF_TRAVERSE_STMT(CXXThisExpr, {})
DEF_TRAVERSE_STMT(CXXThrowExpr, {})
DEF_TRAVERSE_STMT(UserDefinedLiteral, {})
DEF_TRAVERSE_STMT(DesignatedInitExpr, {})
+DEF_TRAVERSE_STMT(DesignatedInitUpdateExpr, {})
DEF_TRAVERSE_STMT(ExtVectorElementExpr, {})
DEF_TRAVERSE_STMT(GNUNullExpr, {})
DEF_TRAVERSE_STMT(ImplicitValueInitExpr, {})
+DEF_TRAVERSE_STMT(NoInitExpr, {})
DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, {})
DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
if (TypeSourceInfo *TInfo = S->getEncodedTypeSourceInfo())
@@ -2386,6 +2388,9 @@ DEF_TRAVERSE_STMT(OMPBarrierDirective,
DEF_TRAVERSE_STMT(OMPTaskwaitDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
+DEF_TRAVERSE_STMT(OMPTaskgroupDirective,
+ { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
DEF_TRAVERSE_STMT(OMPFlushDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
diff --git a/include/clang/AST/StmtOpenMP.h b/include/clang/AST/StmtOpenMP.h
index 5161eff0993b..63f295ddfec0 100644
--- a/include/clang/AST/StmtOpenMP.h
+++ b/include/clang/AST/StmtOpenMP.h
@@ -285,24 +285,23 @@ class OMPLoopDirective : public OMPExecutableDirective {
CalcLastIterationOffset = 3,
PreConditionOffset = 4,
CondOffset = 5,
- SeparatedCondOffset = 6,
- InitOffset = 7,
- IncOffset = 8,
+ InitOffset = 6,
+ IncOffset = 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 arrays).
- DefaultEnd = 9,
+ DefaultEnd = 8,
// The following 7 exprs are used by worksharing loops only.
- IsLastIterVariableOffset = 9,
- LowerBoundVariableOffset = 10,
- UpperBoundVariableOffset = 11,
- StrideVariableOffset = 12,
- EnsureUpperBoundOffset = 13,
- NextLowerBoundOffset = 14,
- NextUpperBoundOffset = 15,
+ IsLastIterVariableOffset = 8,
+ LowerBoundVariableOffset = 9,
+ UpperBoundVariableOffset = 10,
+ StrideVariableOffset = 11,
+ EnsureUpperBoundOffset = 12,
+ NextLowerBoundOffset = 13,
+ NextUpperBoundOffset = 14,
// Offset to the end (and start of the following counters/updates/finals
// arrays) for worksharing loop directives.
- WorksharingEnd = 16,
+ WorksharingEnd = 15,
};
/// \brief Get the counters storage.
@@ -374,9 +373,8 @@ protected:
void setPreCond(Expr *PC) {
*std::next(child_begin(), PreConditionOffset) = PC;
}
- void setCond(Expr *Cond, Expr *SeparatedCond) {
+ void setCond(Expr *Cond) {
*std::next(child_begin(), CondOffset) = Cond;
- *std::next(child_begin(), SeparatedCondOffset) = SeparatedCond;
}
void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
@@ -435,8 +433,6 @@ public:
Expr *PreCond;
/// \brief Loop condition.
Expr *Cond;
- /// \brief A condition with 1 iteration separated.
- Expr *SeparatedCond;
/// \brief Loop iteration variable init.
Expr *Init;
/// \brief Loop increment.
@@ -467,8 +463,7 @@ public:
bool builtAll() {
return IterationVarRef != nullptr && LastIteration != nullptr &&
NumIterations != nullptr && PreCond != nullptr &&
- Cond != nullptr && SeparatedCond != nullptr && Init != nullptr &&
- Inc != nullptr;
+ Cond != nullptr && Init != nullptr && Inc != nullptr;
}
/// \brief Initialize all the fields to null.
@@ -479,7 +474,6 @@ public:
CalcLastIteration = nullptr;
PreCond = nullptr;
Cond = nullptr;
- SeparatedCond = nullptr;
Init = nullptr;
Inc = nullptr;
IL = nullptr;
@@ -519,10 +513,9 @@ public:
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PreConditionOffset)));
}
- Expr *getCond(bool SeparateIter) const {
- return const_cast<Expr *>(reinterpret_cast<const Expr *>(
- *std::next(child_begin(),
- (SeparateIter ? SeparatedCondOffset : CondOffset))));
+ Expr *getCond() const {
+ return const_cast<Expr *>(
+ reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset)));
}
Expr *getInit() const {
return const_cast<Expr *>(
@@ -1462,6 +1455,53 @@ public:
}
};
+/// \brief This represents '#pragma omp taskgroup' directive.
+///
+/// \code
+/// #pragma omp taskgroup
+/// \endcode
+///
+class OMPTaskgroupDirective : public OMPExecutableDirective {
+ friend class ASTStmtReader;
+ /// \brief Build directive with the given start and end location.
+ ///
+ /// \param StartLoc Starting location of the directive kind.
+ /// \param EndLoc Ending location of the directive.
+ ///
+ OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+ : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
+ StartLoc, EndLoc, 0, 1) {}
+
+ /// \brief Build an empty directive.
+ ///
+ explicit OMPTaskgroupDirective()
+ : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
+ SourceLocation(), SourceLocation(), 0, 1) {}
+
+public:
+ /// \brief Creates directive.
+ ///
+ /// \param C AST context.
+ /// \param StartLoc Starting location of the directive kind.
+ /// \param EndLoc Ending Location of the directive.
+ /// \param AssociatedStmt Statement, associated with the directive.
+ ///
+ static OMPTaskgroupDirective *Create(const ASTContext &C,
+ SourceLocation StartLoc,
+ SourceLocation EndLoc,
+ Stmt *AssociatedStmt);
+
+ /// \brief Creates an empty directive.
+ ///
+ /// \param C AST context.
+ ///
+ static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C, EmptyShell);
+
+ static bool classof(const Stmt *T) {
+ return T->getStmtClass() == OMPTaskgroupDirectiveClass;
+ }
+};
+
/// \brief This represents '#pragma omp flush' directive.
///
/// \code
diff --git a/include/clang/AST/Type.h b/include/clang/AST/Type.h
index 8cd29b7b917e..d903b9d8cbcf 100644
--- a/include/clang/AST/Type.h
+++ b/include/clang/AST/Type.h
@@ -1818,6 +1818,19 @@ public:
/// checking. Should always return true.
bool isLinkageValid() const;
+ /// Determine the nullability of the given type.
+ ///
+ /// Note that nullability is only captured as sugar within the type
+ /// system, not as part of the canonical type, so nullability will
+ /// be lost by canonicalization and desugaring.
+ Optional<NullabilityKind> getNullability(const ASTContext &context) const;
+
+ /// Determine whether the given type can have a nullability
+ /// specifier applied to it, i.e., if it is any kind of pointer type
+ /// or a dependent type that could instantiate to any kind of
+ /// pointer type.
+ bool canHaveNullability() const;
+
const char *getTypeClassName() const;
QualType getCanonicalTypeInternal() const {
@@ -3479,7 +3492,10 @@ public:
attr_ptr32,
attr_ptr64,
attr_sptr,
- attr_uptr
+ attr_uptr,
+ attr_nonnull,
+ attr_nullable,
+ attr_null_unspecified,
};
private:
@@ -3513,6 +3529,35 @@ public:
bool isCallingConv() const;
+ llvm::Optional<NullabilityKind> getImmediateNullability() const;
+
+ /// Retrieve the attribute kind corresponding to the given
+ /// nullability kind.
+ static Kind getNullabilityAttrKind(NullabilityKind kind) {
+ switch (kind) {
+ case NullabilityKind::NonNull:
+ return attr_nonnull;
+
+ case NullabilityKind::Nullable:
+ return attr_nullable;
+
+ case NullabilityKind::Unspecified:
+ return attr_null_unspecified;
+ }
+ llvm_unreachable("Unknown nullability kind.");
+ }
+
+ /// Strip off the top-level nullability annotation on the given
+ /// type, if it's there.
+ ///
+ /// \param T The type to strip. If the type is exactly an
+ /// AttributedType specifying nullability (without looking through
+ /// type sugar), the nullability is returned and this type changed
+ /// to the underlying modified type.
+ ///
+ /// \returns the top-level nullability, if present.
+ static Optional<NullabilityKind> stripOuterNullability(QualType &T);
+
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
}
diff --git a/include/clang/ASTMatchers/ASTMatchersMacros.h b/include/clang/ASTMatchers/ASTMatchersMacros.h
index e8eab864b298..8ad0c16ef83a 100644
--- a/include/clang/ASTMatchers/ASTMatchersMacros.h
+++ b/include/clang/ASTMatchers/ASTMatchersMacros.h
@@ -20,17 +20,30 @@
// to only have the functions (which is all the user cares about) in the
// 'ast_matchers' namespace and hide the boilerplate.
//
-// To define a matcher in user code, always put it into the clang::ast_matchers
-// namespace and refer to the internal types via the 'internal::':
+// To define a matcher in user code, put it into your own namespace. This would
+// help to prevent ODR violations in case a matcher with the same name is
+// defined in multiple translation units:
+//
+// namespace my_matchers {
+// AST_MATCHER_P(clang::MemberExpr, Member,
+// clang::ast_matchers::internal::Matcher<clang::ValueDecl>,
+// InnerMatcher) {
+// return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
+// }
+// } // namespace my_matchers
+//
+// Alternatively, an unnamed namespace may be used:
//
// namespace clang {
// namespace ast_matchers {
+// namespace {
// AST_MATCHER_P(MemberExpr, Member,
// internal::Matcher<ValueDecl>, InnerMatcher) {
// return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
// }
-// } // end namespace ast_matchers
-// } // end namespace clang
+// } // namespace
+// } // namespace ast_matchers
+// } // namespace clang
//
//===----------------------------------------------------------------------===//
@@ -43,12 +56,13 @@
#define AST_MATCHER_FUNCTION(ReturnType, DefineMatcher) \
inline ReturnType DefineMatcher##_getInstance(); \
inline ReturnType DefineMatcher() { \
- return internal::MemoizedMatcher< \
+ return ::clang::ast_matchers::internal::MemoizedMatcher< \
ReturnType, DefineMatcher##_getInstance>::getInstance(); \
} \
inline ReturnType DefineMatcher##_getInstance()
-/// \brief AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) { ... }
+/// \brief AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) {
+/// ... }
/// defines a single-parameter function named DefineMatcher() that returns a
/// ReturnType object.
///
@@ -80,20 +94,24 @@
/// The code should return true if 'Node' matches.
#define AST_MATCHER(Type, DefineMatcher) \
namespace internal { \
- class matcher_##DefineMatcher##Matcher : public MatcherInterface<Type> { \
+ class matcher_##DefineMatcher##Matcher \
+ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \
public: \
explicit matcher_##DefineMatcher##Matcher() {} \
- bool matches(const Type &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
}; \
} \
- inline internal::Matcher<Type> DefineMatcher() { \
- return internal::makeMatcher( \
+ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher() { \
+ return ::clang::ast_matchers::internal::makeMatcher( \
new internal::matcher_##DefineMatcher##Matcher()); \
} \
inline bool internal::matcher_##DefineMatcher##Matcher::matches( \
- const Type &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const
/// \brief AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) { ... }
/// defines a single-parameter function named DefineMatcher() that returns a
@@ -115,27 +133,31 @@
OverloadId) \
namespace internal { \
class matcher_##DefineMatcher##OverloadId##Matcher \
- : public MatcherInterface<Type> { \
+ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \
public: \
explicit matcher_##DefineMatcher##OverloadId##Matcher( \
ParamType const &A##Param) \
: Param(A##Param) {} \
- bool matches(const Type &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
\
private: \
ParamType const Param; \
}; \
} \
- inline internal::Matcher<Type> DefineMatcher(ParamType const &Param) { \
- return internal::makeMatcher( \
+ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \
+ ParamType const &Param) { \
+ return ::clang::ast_matchers::internal::makeMatcher( \
new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param)); \
} \
- typedef internal::Matcher<Type>(&DefineMatcher##_Type##OverloadId)( \
- ParamType const &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, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const
/// \brief AST_MATCHER_P2(
/// Type, DefineMatcher, ParamType1, Param1, ParamType2, Param2) { ... }
@@ -160,30 +182,34 @@
ParamType2, Param2, OverloadId) \
namespace internal { \
class matcher_##DefineMatcher##OverloadId##Matcher \
- : public MatcherInterface<Type> { \
+ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \
public: \
matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \
ParamType2 const &A##Param2) \
: Param1(A##Param1), Param2(A##Param2) {} \
- bool matches(const Type &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
\
private: \
ParamType1 const Param1; \
ParamType2 const Param2; \
}; \
} \
- inline internal::Matcher<Type> DefineMatcher(ParamType1 const &Param1, \
- ParamType2 const &Param2) { \
- return internal::makeMatcher( \
+ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \
+ ParamType1 const &Param1, ParamType2 const &Param2) { \
+ return ::clang::ast_matchers::internal::makeMatcher( \
new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param1, \
Param2)); \
} \
- typedef internal::Matcher<Type>(&DefineMatcher##_Type##OverloadId)( \
- ParamType1 const &Param1, ParamType2 const &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, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ const Type &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const
/// \brief Construct a type-list to be passed to the AST_POLYMORPHIC_MATCHER*
/// macros.
@@ -194,7 +220,7 @@
/// The \c PolymorphicMatcherWithParam* classes will unpack the function type to
/// extract the TypeList object.
#define AST_POLYMORPHIC_SUPPORTED_TYPES(...) \
- void(internal::TypeList<__VA_ARGS__>)
+ void(::clang::ast_matchers::internal::TypeList<__VA_ARGS__>)
/// \brief AST_POLYMORPHIC_MATCHER(DefineMatcher) { ... }
/// defines a single-parameter function named DefineMatcher() that is
@@ -205,22 +231,26 @@
#define AST_POLYMORPHIC_MATCHER(DefineMatcher, ReturnTypesF) \
namespace internal { \
template <typename NodeType> \
- class matcher_##DefineMatcher##Matcher : public MatcherInterface<NodeType> { \
+ class matcher_##DefineMatcher##Matcher \
+ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \
public: \
- bool matches(const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
}; \
} \
- inline internal::PolymorphicMatcherWithParam0< \
+ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam0< \
internal::matcher_##DefineMatcher##Matcher, ReturnTypesF> \
DefineMatcher() { \
- return internal::PolymorphicMatcherWithParam0< \
+ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam0< \
internal::matcher_##DefineMatcher##Matcher, ReturnTypesF>(); \
} \
template <typename NodeType> \
bool internal::matcher_##DefineMatcher##Matcher<NodeType>::matches( \
- const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const
/// \brief AST_POLYMORPHIC_MATCHER_P(DefineMatcher, ParamType, Param) { ... }
/// defines a single-parameter function named DefineMatcher() that is
@@ -241,33 +271,39 @@
namespace internal { \
template <typename NodeType, typename ParamT> \
class matcher_##DefineMatcher##OverloadId##Matcher \
- : public MatcherInterface<NodeType> { \
+ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \
public: \
explicit matcher_##DefineMatcher##OverloadId##Matcher( \
ParamType const &A##Param) \
: Param(A##Param) {} \
- bool matches(const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
\
private: \
ParamType const Param; \
}; \
} \
- inline internal::PolymorphicMatcherWithParam1< \
+ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
- ReturnTypesF> DefineMatcher(ParamType const &Param) { \
- return internal::PolymorphicMatcherWithParam1< \
+ ReturnTypesF> \
+ DefineMatcher(ParamType const &Param) { \
+ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
ReturnTypesF>(Param); \
} \
- typedef internal::PolymorphicMatcherWithParam1< \
+ typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \
ReturnTypesF>(&DefineMatcher##_Type##OverloadId)( \
ParamType const &Param); \
template <typename NodeType, typename ParamT> \
- bool internal::matcher_##DefineMatcher##OverloadId##Matcher< \
- NodeType, ParamT>::matches(const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ bool internal:: \
+ matcher_##DefineMatcher##OverloadId##Matcher<NodeType, ParamT>::matches( \
+ const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) \
+ const
/// \brief AST_POLYMORPHIC_MATCHER_P2(
/// DefineMatcher, ParamType1, Param1, ParamType2, Param2) { ... }
@@ -288,41 +324,46 @@
namespace internal { \
template <typename NodeType, typename ParamT1, typename ParamT2> \
class matcher_##DefineMatcher##OverloadId##Matcher \
- : public MatcherInterface<NodeType> { \
+ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \
public: \
matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \
ParamType2 const &A##Param2) \
: Param1(A##Param1), Param2(A##Param2) {} \
- bool matches(const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const override; \
+ bool matches(const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \
+ *Builder) const override; \
\
private: \
ParamType1 const Param1; \
ParamType2 const Param2; \
}; \
} \
- inline internal::PolymorphicMatcherWithParam2< \
+ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
- ParamType2, ReturnTypesF> DefineMatcher(ParamType1 const &Param1, \
- ParamType2 const &Param2) { \
- return internal::PolymorphicMatcherWithParam2< \
+ ParamType2, ReturnTypesF> \
+ DefineMatcher(ParamType1 const &Param1, ParamType2 const &Param2) { \
+ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
ParamType2, ReturnTypesF>(Param1, Param2); \
} \
- typedef internal::PolymorphicMatcherWithParam2< \
+ typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \
internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \
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>::matches( \
- const NodeType &Node, ASTMatchFinder *Finder, \
- BoundNodesTreeBuilder *Builder) const
+ NodeType, ParamT1, ParamT2>:: \
+ matches(const NodeType &Node, \
+ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \
+ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) \
+ const
/// \brief Creates a variadic matcher for both a specific \c Type as well as
/// the corresponding \c TypeLoc.
#define AST_TYPE_MATCHER(NodeType, MatcherName) \
- const internal::VariadicDynCastAllOfMatcher<Type, NodeType> MatcherName
+ const ::clang::ast_matchers::internal::VariadicDynCastAllOfMatcher< \
+ Type, NodeType> MatcherName
// FIXME: add a matcher for TypeLoc derived classes using its custom casting
// API (no longer dyn_cast) if/when we need such matching
@@ -330,7 +371,7 @@
/// the matcher \c MatcherName that can be used to traverse from one \c Type
/// to another.
///
-/// For a specific \c SpecificType, the traversal is done using
+/// For a specific \c SpecificType, the traversal is done using
/// \c SpecificType::FunctionName. The existence of such a function determines
/// whether a corresponding matcher can be used on \c SpecificType.
#define AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName, ReturnTypesF) \
@@ -339,9 +380,11 @@
static QualType (T::*value())() const { return &T::FunctionName; } \
}; \
} \
- const internal::TypeTraversePolymorphicMatcher< \
- QualType, internal::TypeMatcher##MatcherName##Getter, \
- internal::TypeTraverseMatcher, ReturnTypesF>::Func MatcherName
+ const ::clang::ast_matchers::internal::TypeTraversePolymorphicMatcher< \
+ QualType, \
+ ::clang::ast_matchers::internal::TypeMatcher##MatcherName##Getter, \
+ ::clang::ast_matchers::internal::TypeTraverseMatcher, \
+ ReturnTypesF>::Func MatcherName
/// \brief AST_TYPELOC_TRAVERSE_MATCHER(MatcherName, FunctionName) works
/// identical to \c AST_TYPE_TRAVERSE_MATCHER but operates on \c TypeLocs.
@@ -351,9 +394,11 @@
static TypeLoc (T::*value())() const { return &T::FunctionName##Loc; } \
}; \
} \
- const internal::TypeTraversePolymorphicMatcher< \
- TypeLoc, internal::TypeLocMatcher##MatcherName##Getter, \
- internal::TypeLocTraverseMatcher, ReturnTypesF>::Func MatcherName##Loc; \
+ const ::clang::ast_matchers::internal::TypeTraversePolymorphicMatcher< \
+ TypeLoc, \
+ ::clang::ast_matchers::internal::TypeLocMatcher##MatcherName##Getter, \
+ ::clang::ast_matchers::internal::TypeLocTraverseMatcher, \
+ ReturnTypesF>::Func MatcherName##Loc; \
AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName##Type, ReturnTypesF)
#endif
diff --git a/include/clang/Basic/Attr.td b/include/clang/Basic/Attr.td
index c310d25a5518..f36f654ff630 100644
--- a/include/clang/Basic/Attr.td
+++ b/include/clang/Basic/Attr.td
@@ -195,7 +195,8 @@ class CXX11<string namespace, string name, int version = 1>
: Spelling<name, "CXX11"> {
string Namespace = namespace;
int Version = version;
-} class Keyword<string name> : Spelling<name, "Keyword">;
+}
+class Keyword<string name> : Spelling<name, "Keyword">;
class Pragma<string namespace, string name> : Spelling<name, "Pragma"> {
string Namespace = namespace;
}
@@ -959,6 +960,22 @@ def ReturnsNonNull : InheritableAttr {
let Documentation = [Undocumented];
}
+// Nullability type attributes.
+def TypeNonNull : TypeAttr {
+ let Spellings = [Keyword<"__nonnull">];
+ let Documentation = [Undocumented];
+}
+
+def TypeNullable : TypeAttr {
+ let Spellings = [Keyword<"__nullable">];
+ let Documentation = [Undocumented];
+}
+
+def TypeNullUnspecified : TypeAttr {
+ let Spellings = [Keyword<"__null_unspecified">];
+ let Documentation = [Undocumented];
+}
+
def AssumeAligned : InheritableAttr {
let Spellings = [GCC<"assume_aligned">];
let Subjects = SubjectList<[ObjCMethod, Function]>;
@@ -1250,6 +1267,14 @@ def Pascal : InheritableAttr {
let Documentation = [Undocumented];
}
+def Target : InheritableAttr {
+ let Spellings = [GCC<"target">];
+ let Args = [StringArgument<"features">];
+ let Subjects =
+ SubjectList<[Function], ErrorDiag, "ExpectedFunctionMethodOrClass">;
+ let Documentation = [Undocumented];
+}
+
def TransparentUnion : InheritableAttr {
let Spellings = [GCC<"transparent_union">];
// let Subjects = SubjectList<[Record, TypedefName]>;
@@ -1935,8 +1960,8 @@ def LoopHint : Attr {
["Vectorize", "VectorizeWidth", "Interleave", "InterleaveCount",
"Unroll", "UnrollCount"]>,
EnumArgument<"State", "LoopHintState",
- ["default", "enable", "disable"],
- ["Default", "Enable", "Disable"]>,
+ ["default", "enable", "disable", "assume_safety"],
+ ["Default", "Enable", "Disable", "AssumeSafety"]>,
ExprArgument<"Value">];
let AdditionalMembers = [{
@@ -1982,6 +2007,8 @@ def LoopHint : Attr {
return "";
else if (state == Enable)
OS << (option == Unroll ? "full" : "enable");
+ else if (state == AssumeSafety)
+ OS << "assume_safety";
else
OS << "disable";
OS << ")";
diff --git a/include/clang/Basic/Builtins.def b/include/clang/Basic/Builtins.def
index 192790749be8..bf65b5fa2ea8 100644
--- a/include/clang/Basic/Builtins.def
+++ b/include/clang/Basic/Builtins.def
@@ -1240,6 +1240,10 @@ BUILTIN(__builtin_addressof, "v*v&", "nct")
BUILTIN(__builtin_operator_new, "v*z", "c")
BUILTIN(__builtin_operator_delete, "vv*", "n")
+// Safestack builtins
+BUILTIN(__builtin___get_unsafe_stack_start, "v*", "Fn")
+BUILTIN(__builtin___get_unsafe_stack_ptr, "v*", "Fn")
+
#undef BUILTIN
#undef LIBBUILTIN
#undef LANGBUILTIN
diff --git a/include/clang/Basic/BuiltinsAArch64.def b/include/clang/Basic/BuiltinsAArch64.def
index 9d223c3e8516..1db4c1471029 100644
--- a/include/clang/Basic/BuiltinsAArch64.def
+++ b/include/clang/Basic/BuiltinsAArch64.def
@@ -53,4 +53,12 @@ BUILTIN(__builtin_arm_isb, "vUi", "nc")
// Prefetch
BUILTIN(__builtin_arm_prefetch, "vvC*UiUiUiUi", "nc")
+// System Registers
+BUILTIN(__builtin_arm_rsr, "UicC*", "nc")
+BUILTIN(__builtin_arm_rsr64, "LUicC*", "nc")
+BUILTIN(__builtin_arm_rsrp, "v*cC*", "nc")
+BUILTIN(__builtin_arm_wsr, "vcC*Ui", "nc")
+BUILTIN(__builtin_arm_wsr64, "vcC*LUi", "nc")
+BUILTIN(__builtin_arm_wsrp, "vcC*vC*", "nc")
+
#undef BUILTIN
diff --git a/include/clang/Basic/BuiltinsR600.def b/include/clang/Basic/BuiltinsAMDGPU.def
index 84fc4fae4eab..bb9931f7a206 100644
--- a/include/clang/Basic/BuiltinsR600.def
+++ b/include/clang/Basic/BuiltinsAMDGPU.def
@@ -1,4 +1,4 @@
-//==- BuiltinsR600.def - R600 Builtin function database ----------*- C++ -*-==//
+//==- BuiltinsAMDGPU.def - AMDGPU Builtin function database ------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
diff --git a/include/clang/Basic/BuiltinsARM.def b/include/clang/Basic/BuiltinsARM.def
index 98d5ab73aa38..0610d47f8ba1 100644
--- a/include/clang/Basic/BuiltinsARM.def
+++ b/include/clang/Basic/BuiltinsARM.def
@@ -84,6 +84,14 @@ BUILTIN(__builtin_arm_isb, "vUi", "nc")
// Prefetch
BUILTIN(__builtin_arm_prefetch, "vvC*UiUi", "nc")
+// System registers (ACLE)
+BUILTIN(__builtin_arm_rsr, "UicC*", "nc")
+BUILTIN(__builtin_arm_rsr64, "LLUicC*", "nc")
+BUILTIN(__builtin_arm_rsrp, "v*cC*", "nc")
+BUILTIN(__builtin_arm_wsr, "vcC*Ui", "nc")
+BUILTIN(__builtin_arm_wsr64, "vcC*LLUi", "nc")
+BUILTIN(__builtin_arm_wsrp, "vcC*vC*", "nc")
+
// MSVC
LANGBUILTIN(__emit, "vIUiC", "", ALL_MS_LANGUAGES)
diff --git a/include/clang/Basic/BuiltinsPPC.def b/include/clang/Basic/BuiltinsPPC.def
index 57ae63e634f4..6f3bea887f59 100644
--- a/include/clang/Basic/BuiltinsPPC.def
+++ b/include/clang/Basic/BuiltinsPPC.def
@@ -231,6 +231,9 @@ BUILTIN(__builtin_altivec_vcmpgtsd_p, "iiV2LLiV2LLi", "")
BUILTIN(__builtin_altivec_vcmpgtud_p, "iiV2ULLiV2ULLi", "")
BUILTIN(__builtin_altivec_vcmpgtfp_p, "iiV4fV4f", "")
+BUILTIN(__builtin_altivec_vgbbd, "V16UcV16Uc", "")
+BUILTIN(__builtin_altivec_vbpermq, "V2ULLiV16UcV16Uc", "")
+
// P8 Crypto built-ins.
BUILTIN(__builtin_altivec_crypto_vsbox, "V2ULLiV2ULLi", "")
BUILTIN(__builtin_altivec_crypto_vpermxor, "V16UcV16UcV16UcV16Uc", "")
diff --git a/include/clang/Basic/BuiltinsX86.def b/include/clang/Basic/BuiltinsX86.def
index 1a597b5c27d4..00c1340ac37f 100644
--- a/include/clang/Basic/BuiltinsX86.def
+++ b/include/clang/Basic/BuiltinsX86.def
@@ -59,6 +59,9 @@ BUILTIN(__builtin_ia32_pswapdsi, "V2iV2i", "nc")
// All MMX instructions will be generated via builtins. Any MMX vector
// types (<1 x i64>, <2 x i32>, etc.) that aren't used by these builtins will be
// expanded by the back-end.
+// FIXME: _mm_prefetch must be a built-in because it takes a compile-time constant
+// argument and our prior approach of using a #define to the current built-in
+// doesn't work in the presence of re-declaration of _mm_prefetch for windows.
BUILTIN(_mm_prefetch, "vcC*i", "nc")
BUILTIN(__builtin_ia32_emms, "v", "")
BUILTIN(__builtin_ia32_paddb, "V8cV8cV8c", "")
diff --git a/include/clang/Basic/DiagnosticCommonKinds.td b/include/clang/Basic/DiagnosticCommonKinds.td
index deb23f3149cb..82718d9255f3 100644
--- a/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/include/clang/Basic/DiagnosticCommonKinds.td
@@ -99,6 +99,37 @@ def err_enum_template : Error<"enumeration cannot be a template">;
}
+let CategoryName = "Nullability Issue" in {
+
+def warn_nullability_duplicate : Warning<
+ "duplicate nullability specifier "
+ "'%select{__|}1%select{nonnull|nullable|null_unspecified}0'">,
+ InGroup<Nullability>;
+
+def warn_conflicting_nullability_attr_overriding_ret_types : Warning<
+ "conflicting nullability specifier on return types, "
+ "'%select{%select{__|}1nonnull|"
+ "%select{__|}1nullable|%select{__|}1null_unspecified}0' "
+ "conflicts with existing specifier '%select{%select{__|}3nonnull|"
+ "%select{__|}3nullable|%select{__|}3null_unspecified}2'">,
+ InGroup<Nullability>;
+
+def warn_conflicting_nullability_attr_overriding_param_types : Warning<
+ "conflicting nullability specifier on parameter types, "
+ "'%select{%select{__|}1nonnull|"
+ "%select{__|}1nullable|%select{__|}1null_unspecified}0' "
+ "conflicts with existing specifier '%select{%select{__|}3nonnull|"
+ "%select{__|}3nullable|%select{__|}3null_unspecified}2'">,
+ InGroup<Nullability>;
+
+def err_nullability_conflicting : Error<
+ "nullability specifier "
+ "'%select{__|}1%select{nonnull|nullable|null_unspecified}0' conflicts with "
+ "existing specifier '%select{__|}3%select{nonnull|nullable|"
+ "null_unspecified}2'">;
+
+}
+
// Sema && Lex
def ext_c99_longlong : Extension<
"'long long' is an extension when C99 mode is not enabled">,
diff --git a/include/clang/Basic/DiagnosticGroups.td b/include/clang/Basic/DiagnosticGroups.td
index 016c2e198e3a..85796cc0d325 100644
--- a/include/clang/Basic/DiagnosticGroups.td
+++ b/include/clang/Basic/DiagnosticGroups.td
@@ -248,6 +248,10 @@ def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
def ModuleBuild : DiagGroup<"module-build">;
def ModuleConflict : DiagGroup<"module-conflict">;
def NewlineEOF : DiagGroup<"newline-eof">;
+def Nullability : DiagGroup<"nullability">;
+def NullabilityDeclSpec : DiagGroup<"nullability-declspec">;
+def NullableToNonNullConversion : DiagGroup<"nullable-to-nonnull-conversion">;
+def NullabilityCompleteness : DiagGroup<"nullability-completeness">;
def NullArithmetic : DiagGroup<"null-arithmetic">;
def NullCharacter : DiagGroup<"null-character">;
def NullDereference : DiagGroup<"null-dereference">;
@@ -598,6 +602,7 @@ def Most : DiagGroup<"most", [
DeleteNonVirtualDtor,
Format,
Implicit,
+ InfiniteRecursion,
MismatchedTags,
MissingBraces,
Move,
diff --git a/include/clang/Basic/DiagnosticLexKinds.td b/include/clang/Basic/DiagnosticLexKinds.td
index 3d568e84a9a6..5dd4ae0ac7fd 100644
--- a/include/clang/Basic/DiagnosticLexKinds.td
+++ b/include/clang/Basic/DiagnosticLexKinds.td
@@ -646,5 +646,20 @@ def warn_header_guard : Warning<
"%0 is used as a header guard here, followed by #define of a different macro">,
InGroup<DiagGroup<"header-guard">>;
def note_header_guard : Note<
- "%0 is defined here; did you mean %1?">;
+ "%0 is defined here; did you mean %1?">;
+
+let CategoryName = "Nullability Issue" in {
+
+def err_pp_assume_nonnull_syntax : Error<"expected 'begin' or 'end'">;
+def err_pp_double_begin_of_assume_nonnull : Error<
+ "already inside '#pragma clang assume_nonnull'">;
+def err_pp_unmatched_end_of_assume_nonnull : Error<
+ "not currently inside '#pragma clang assume_nonnull'">;
+def err_pp_include_in_assume_nonnull : Error<
+ "cannot #include files inside '#pragma clang assume_nonnull'">;
+def err_pp_eof_in_assume_nonnull : Error<
+ "'#pragma clang assume_nonnull' was not ended within this file">;
+
+}
+
}
diff --git a/include/clang/Basic/DiagnosticOptions.def b/include/clang/Basic/DiagnosticOptions.def
index fdd325446e27..f4ba6da81fe0 100644
--- a/include/clang/Basic/DiagnosticOptions.def
+++ b/include/clang/Basic/DiagnosticOptions.def
@@ -69,7 +69,10 @@ ENUM_DIAGOPT(ShowOverloads, OverloadsShown, 1,
DIAGOPT(VerifyDiagnostics, 1, 0) /// Check that diagnostics match the expected
/// diagnostics, indicated by markers in the
/// input source file.
-
+ENUM_DIAGOPT(VerifyIgnoreUnexpected, DiagnosticLevelMask, 4,
+ DiagnosticLevelMask::None) /// Ignore unexpected diagnostics of
+ /// the specified levels when using
+ /// -verify.
DIAGOPT(ElideType, 1, 0) /// Elide identical types in template diffing
DIAGOPT(ShowTemplateTree, 1, 0) /// Print a template tree when diffing
DIAGOPT(CLFallbackMode, 1, 0) /// Format for clang-cl fallback mode
diff --git a/include/clang/Basic/DiagnosticOptions.h b/include/clang/Basic/DiagnosticOptions.h
index a16c7747cec3..c9b0c5def992 100644
--- a/include/clang/Basic/DiagnosticOptions.h
+++ b/include/clang/Basic/DiagnosticOptions.h
@@ -13,6 +13,7 @@
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include <string>
+#include <type_traits>
#include <vector>
namespace clang {
@@ -24,6 +25,38 @@ enum OverloadsShown : unsigned {
Ovl_Best ///< Show just the "best" overload candidates.
};
+/// \brief A bitmask representing the diagnostic levels used by
+/// VerifyDiagnosticConsumer.
+enum class DiagnosticLevelMask : unsigned {
+ None = 0,
+ Note = 1 << 0,
+ Remark = 1 << 1,
+ Warning = 1 << 2,
+ Error = 1 << 3,
+ All = Note | Remark | Warning | Error
+};
+
+inline DiagnosticLevelMask operator~(DiagnosticLevelMask M) {
+ using UT = std::underlying_type<DiagnosticLevelMask>::type;
+ return static_cast<DiagnosticLevelMask>(~static_cast<UT>(M));
+}
+
+inline DiagnosticLevelMask operator|(DiagnosticLevelMask LHS,
+ DiagnosticLevelMask RHS) {
+ using UT = std::underlying_type<DiagnosticLevelMask>::type;
+ return static_cast<DiagnosticLevelMask>(
+ static_cast<UT>(LHS) | static_cast<UT>(RHS));
+}
+
+inline DiagnosticLevelMask operator&(DiagnosticLevelMask LHS,
+ DiagnosticLevelMask RHS) {
+ using UT = std::underlying_type<DiagnosticLevelMask>::type;
+ return static_cast<DiagnosticLevelMask>(
+ static_cast<UT>(LHS) & static_cast<UT>(RHS));
+}
+
+raw_ostream& operator<<(raw_ostream& Out, DiagnosticLevelMask M);
+
/// \brief Options for controlling the compiler diagnostics engine.
class DiagnosticOptions : public RefCountedBase<DiagnosticOptions>{
public:
diff --git a/include/clang/Basic/DiagnosticParseKinds.td b/include/clang/Basic/DiagnosticParseKinds.td
index f00a3b39d23b..6a11d240c63c 100644
--- a/include/clang/Basic/DiagnosticParseKinds.td
+++ b/include/clang/Basic/DiagnosticParseKinds.td
@@ -65,6 +65,10 @@ def ext_keyword_as_ident : ExtWarn<
"%select{here|for the remainder of the translation unit}1">,
InGroup<KeywordCompat>;
+def ext_nullability : Extension<
+ "type nullability specifier %0 is a Clang extension">,
+ InGroup<DiagGroup<"nullability-extension">>;
+
def error_empty_enum : Error<"use of empty enum">;
def err_invalid_sign_spec : Error<"'%0' cannot be signed or unsigned">;
def err_invalid_short_spec : Error<"'short %0' is invalid">;
@@ -989,17 +993,21 @@ def err_omp_expected_identifier_for_critical : Error<
// Pragma loop support.
def err_pragma_loop_missing_argument : Error<
"missing argument; expected %select{an integer value|"
- "'%select{enable|full}1' or 'disable'}0">;
+ "%select{'enable', 'assume_safety'|'full'}1 or 'disable'}0">;
def err_pragma_loop_invalid_option : Error<
"%select{invalid|missing}0 option%select{ %1|}0; expected vectorize, "
"vectorize_width, interleave, interleave_count, unroll, or unroll_count">;
def err_pragma_invalid_keyword : Error<
- "invalid argument; expected '%select{enable|full}0' or 'disable'">;
+ "invalid argument; expected %select{'enable', 'assume_safety'|'full'}0 or 'disable'">;
// Pragma unroll support.
def warn_pragma_unroll_cuda_value_in_parens : Warning<
"argument to '#pragma unroll' should not be in parentheses in CUDA C/C++">,
InGroup<CudaCompat>;
+
+def err_empty_attribute_block : Error<
+ "Microsoft attribute block cannot be empty">;
+
} // end of Parse Issue category.
let CategoryName = "Modules Issue" in {
diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td
index be1911e7d506..803203cc50be 100644
--- a/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/include/clang/Basic/DiagnosticSemaKinds.td
@@ -108,6 +108,7 @@ def err_ice_ambiguous_conversion : Error<
def err_ice_too_large : Error<
"integer constant expression evaluates to value %0 that cannot be "
"represented in a %1-bit %select{signed|unsigned}2 integer type">;
+def err_expr_not_string_literal : Error<"expression is not a string literal">;
// Semantic analysis of constant literals.
def ext_predef_outside_function : Warning<
@@ -424,6 +425,7 @@ def warn_redecl_library_builtin : Warning<
"incompatible redeclaration of library function %0">,
InGroup<DiagGroup<"incompatible-library-redeclaration">>;
def err_builtin_definition : Error<"definition of builtin function %0">;
+def err_arm_invalid_specialreg : Error<"invalid special register for builtin">;
def warn_builtin_unknown : Warning<"use of unknown builtin %0">,
InGroup<ImplicitFunctionDeclare>, DefaultError;
def warn_dyn_class_memaccess : Warning<
@@ -1974,8 +1976,11 @@ def err_attribute_too_few_arguments : Error<
def err_attribute_invalid_vector_type : Error<"invalid vector element type %0">;
def err_attribute_bad_neon_vector_size : Error<
"Neon vector size must be 64 or 128 bits">;
-def err_attribute_unsupported : Error<
- "%0 attribute is not supported for this target">;
+def warn_unsupported_target_attribute
+ : Warning<"Ignoring unsupported '%0' in the target attribute string">,
+ InGroup<IgnoredAttributes>;
+def err_attribute_unsupported
+ : Error<"%0 attribute is not supported for this target">;
// The err_*_attribute_argument_not_int are seperate because they're used by
// VerifyIntegerConstantExpression.
def err_aligned_attribute_argument_not_int : Error<
@@ -2249,7 +2254,7 @@ def warn_attribute_dllimport_static_field_definition : Warning<
InGroup<DiagGroup<"dllimport-static-field-def">>;
def warn_attribute_dllexport_explicit_instantiation_decl : Warning<
"explicit instantiation declaration should not be 'dllexport'">,
- InGroup<DiagGroup<"dllexport-explicit-instantation-decl">>;
+ InGroup<DiagGroup<"dllexport-explicit-instantiation-decl">>;
def warn_invalid_initializer_from_system_header : Warning<
"invalid constructor form class in system header, should not be explicit">,
InGroup<DiagGroup<"invalid-initializer-from-system-header">>;
@@ -2680,6 +2685,8 @@ def err_mode_not_primitive : Error<
"mode attribute only supported for integer and floating-point types">;
def err_mode_wrong_type : Error<
"type of machine mode does not match type of base type">;
+def err_complex_mode_vector_type : Error<
+ "type of machine mode does not support base vector types">;
def err_attr_wrong_decl : Error<
"%0 attribute invalid on this declaration, requires typedef or value">;
def warn_attribute_nonnull_no_pointers : Warning<
@@ -2744,8 +2751,8 @@ def warn_ns_attribute_wrong_return_type : Warning<
"return %select{an Objective-C object|a pointer|a non-retainable pointer}2">,
InGroup<IgnoredAttributes>;
def warn_ns_attribute_wrong_parameter_type : Warning<
- "%0 attribute only applies to %select{Objective-C object|pointer}1 "
- "parameters">,
+ "%0 attribute only applies to "
+ "%select{Objective-C object|pointer|pointer-to-CF-pointer}1 parameters">,
InGroup<IgnoredAttributes>;
def warn_objc_requires_super_protocol : Warning<
"%0 attribute cannot be applied to %select{methods in protocols|dealloc}1">,
@@ -7631,10 +7638,12 @@ def err_module_private_local : Error<
def err_module_private_local_class : Error<
"local %select{struct|interface|union|class|enum}0 cannot be declared "
"__module_private__">;
-def err_module_private_declaration : Error<
- "declaration of %0 must be imported from module '%1' before it is required">;
-def err_module_private_definition : Error<
- "definition of %0 must be imported from module '%1' before it is required">;
+def err_module_unimported_use : Error<
+ "%select{declaration|definition|default argument}0 of %1 must be imported "
+ "from module '%2' before it is required">;
+def err_module_unimported_use_multiple : Error<
+ "%select{declaration|definition|default argument}0 of %1 must be imported "
+ "from one of the following modules before it is required:%2">;
def err_module_import_in_extern_c : Error<
"import of C++ module '%0' appears within extern \"C\" language linkage "
"specification">;
@@ -7665,4 +7674,55 @@ def warn_profile_data_unprofiled : Warning<
} // end of instrumentation issue category
+let CategoryName = "Nullability Issue" in {
+
+def warn_mismatched_nullability_attr : Warning<
+ "nullability specifier "
+ "'%select{__|}1%select{nonnull|nullable|null_unspecified}0' "
+ "conflicts with existing specifier "
+ "'%select{__|}3%select{nonnull|nullable|null_unspecified}2'">,
+ InGroup<Nullability>;
+
+def warn_nullability_declspec : Warning<
+ "nullability specifier "
+ "'%select{__nonnull|__nullable|__null_unspecified}0' cannot be applied "
+ "to non-pointer type %1; did you mean to apply the specifier to the "
+ "%select{pointer|block pointer|member pointer|function pointer|"
+ "member function pointer}2?">,
+ InGroup<NullabilityDeclSpec>,
+ DefaultError;
+
+def note_nullability_here : Note<
+ "'%select{__nonnull|__nullable|__null_unspecified}0' specified here">;
+
+def err_nullability_nonpointer : Error<
+ "nullability specifier "
+ "'%select{__|}1%select{nonnull|nullable|null_unspecified}0' cannot be applied "
+ "to non-pointer type %2">;
+
+def warn_nullability_lost : Warning<
+ "implicit conversion from nullable pointer %0 to non-nullable pointer "
+ "type %1">,
+ InGroup<NullableToNonNullConversion>, DefaultIgnore;
+
+def err_nullability_cs_multilevel : Error<
+ "nullability keyword "
+ "'%select{nonnull|nullable|null_unspecified}0' cannot be applied to "
+ "multi-level pointer type %1">;
+def note_nullability_type_specifier : Note<
+ "use nullability type specifier "
+ "'%select{__nonnull|__nullable|__null_unspecified}0' to affect the innermost "
+ "pointer type of %1">;
+
+def warn_null_resettable_setter : Warning<
+ "synthesized setter %0 for null_resettable property %1 does not handle nil">,
+ InGroup<Nullability>;
+
+def warn_nullability_missing : Warning<
+ "%select{pointer|block pointer|member pointer}0 is missing a nullability "
+ "type specifier (__nonnull, __nullable, or __null_unspecified)">,
+ InGroup<NullabilityCompleteness>;
+
+}
+
} // end of sema component.
diff --git a/include/clang/Basic/FileManager.h b/include/clang/Basic/FileManager.h
index 37e19e1e279d..ac0d7a15e568 100644
--- a/include/clang/Basic/FileManager.h
+++ b/include/clang/Basic/FileManager.h
@@ -25,16 +25,8 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include <memory>
-// FIXME: Enhance libsystem to support inode and other fields in stat.
-#include <sys/types.h>
#include <map>
-#ifdef _MSC_VER
-typedef unsigned short mode_t;
-#endif
-
-struct stat;
-
namespace llvm {
class MemoryBuffer;
}
diff --git a/include/clang/Basic/LangOptions.def b/include/clang/Basic/LangOptions.def
index 95d3f0682abd..bef122f093c4 100644
--- a/include/clang/Basic/LangOptions.def
+++ b/include/clang/Basic/LangOptions.def
@@ -127,8 +127,7 @@ LANGOPT(Modules , 1, 0, "modules extension to C")
COMPATIBLE_LANGOPT(ModulesDeclUse , 1, 0, "require declaration of module uses")
LANGOPT(ModulesSearchAll , 1, 1, "search even non-imported modules to find unresolved references")
COMPATIBLE_LANGOPT(ModulesStrictDeclUse, 1, 0, "require declaration of module uses and all headers to be in modules")
-LANGOPT(ModulesErrorRecovery, 1, 1, "automatically import modules as needed when performing error recovery")
-BENIGN_LANGOPT(ModulesImplicitMaps, 1, 1, "use files called module.modulemap implicitly as module maps")
+BENIGN_LANGOPT(ModulesErrorRecovery, 1, 1, "automatically import modules as needed when performing error recovery")
BENIGN_LANGOPT(ImplicitModules, 1, 1, "build modules that are not specified via -fmodule-file")
COMPATIBLE_LANGOPT(ModulesLocalVisibility, 1, 0, "local submodule visibility")
COMPATIBLE_LANGOPT(Optimize , 1, 0, "__OPTIMIZE__ predefined macro")
diff --git a/include/clang/Basic/OpenMPKinds.def b/include/clang/Basic/OpenMPKinds.def
index 0145db059329..b09f012c4317 100644
--- a/include/clang/Basic/OpenMPKinds.def
+++ b/include/clang/Basic/OpenMPKinds.def
@@ -84,6 +84,7 @@ OPENMP_DIRECTIVE(critical)
OPENMP_DIRECTIVE(taskyield)
OPENMP_DIRECTIVE(barrier)
OPENMP_DIRECTIVE(taskwait)
+OPENMP_DIRECTIVE(taskgroup)
OPENMP_DIRECTIVE(flush)
OPENMP_DIRECTIVE(ordered)
OPENMP_DIRECTIVE(atomic)
diff --git a/include/clang/Basic/Sanitizers.def b/include/clang/Basic/Sanitizers.def
index 65ababd5ac86..1b528c8d6f69 100644
--- a/include/clang/Basic/Sanitizers.def
+++ b/include/clang/Basic/Sanitizers.def
@@ -41,6 +41,9 @@
// AddressSanitizer
SANITIZER("address", Address)
+// Kernel AddressSanitizer (KASan)
+SANITIZER("kernel-address", KernelAddress)
+
// MemorySanitizer
SANITIZER("memory", Memory)
@@ -87,18 +90,20 @@ SANITIZER("cfi-vcall", CFIVCall)
SANITIZER_GROUP("cfi", CFI,
CFIDerivedCast | CFIUnrelatedCast | CFINVCall | CFIVCall)
-// -fsanitize=undefined-trap includes sanitizers from -fsanitize=undefined
-// that can be used without runtime support, generally by providing extra
-// -fsanitize-undefined-trap-on-error flag.
-SANITIZER_GROUP("undefined-trap", UndefinedTrap,
+// Safe Stack
+SANITIZER("safe-stack", SafeStack)
+
+// -fsanitize=undefined includes all the sanitizers which have low overhead, no
+// ABI or address space layout implications, and only catch undefined behavior.
+SANITIZER_GROUP("undefined", Undefined,
Alignment | Bool | ArrayBounds | Enum | FloatCastOverflow |
FloatDivideByZero | IntegerDivideByZero | NonnullAttribute |
Null | ObjectSize | Return | ReturnsNonnullAttribute |
- Shift | SignedIntegerOverflow | Unreachable | VLABound)
+ Shift | SignedIntegerOverflow | Unreachable | VLABound |
+ Function | Vptr)
-// -fsanitize=undefined includes all the sanitizers which have low overhead, no
-// ABI or address space layout implications, and only catch undefined behavior.
-SANITIZER_GROUP("undefined", Undefined, UndefinedTrap | Function | Vptr)
+// -fsanitize=undefined-trap is an alias for -fsanitize=undefined.
+SANITIZER_GROUP("undefined-trap", UndefinedTrap, Undefined)
SANITIZER_GROUP("integer", Integer,
SignedIntegerOverflow | UnsignedIntegerOverflow | Shift |
diff --git a/include/clang/Basic/Sanitizers.h b/include/clang/Basic/Sanitizers.h
index 3b1797e9f539..78c1ddb56f9b 100644
--- a/include/clang/Basic/Sanitizers.h
+++ b/include/clang/Basic/Sanitizers.h
@@ -52,6 +52,9 @@ struct SanitizerSet {
/// \brief Check if a certain (single) sanitizer is enabled.
bool has(SanitizerMask K) const;
+ /// \brief Check if one or more sanitizers are enabled.
+ bool hasOneOf(SanitizerMask K) const;
+
/// \brief Enable or disable a certain (single) sanitizer.
void set(SanitizerMask K, bool Value);
diff --git a/include/clang/Basic/Specifiers.h b/include/clang/Basic/Specifiers.h
index 7569c16412b2..5ce56c0ee1f8 100644
--- a/include/clang/Basic/Specifiers.h
+++ b/include/clang/Basic/Specifiers.h
@@ -16,6 +16,9 @@
#ifndef LLVM_CLANG_BASIC_SPECIFIERS_H
#define LLVM_CLANG_BASIC_SPECIFIERS_H
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+
namespace clang {
/// \brief Specifies the width of a type, e.g., short, long, or long long.
enum TypeSpecifierWidth {
@@ -239,6 +242,22 @@ namespace clang {
SD_Static, ///< Static storage duration.
SD_Dynamic ///< Dynamic storage duration.
};
+
+ /// Describes the nullability of a particular type.
+ enum class NullabilityKind : uint8_t {
+ /// Values of this type can never be null.
+ NonNull = 0,
+ /// Values of this type can be null.
+ Nullable,
+ /// Whether values of this type can be null is (explicitly)
+ /// 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
+ };
+
+ /// Retrieve the spelling of the given nullability kind.
+ llvm::StringRef getNullabilitySpelling(NullabilityKind kind);
} // end namespace clang
#endif // LLVM_CLANG_BASIC_SPECIFIERS_H
diff --git a/include/clang/Basic/StmtNodes.td b/include/clang/Basic/StmtNodes.td
index 750108f39f9a..675e91d866d0 100644
--- a/include/clang/Basic/StmtNodes.td
+++ b/include/clang/Basic/StmtNodes.td
@@ -77,7 +77,9 @@ def CompoundLiteralExpr : DStmt<Expr>;
def ExtVectorElementExpr : DStmt<Expr>;
def InitListExpr : DStmt<Expr>;
def DesignatedInitExpr : DStmt<Expr>;
+def DesignatedInitUpdateExpr : DStmt<Expr>;
def ImplicitValueInitExpr : DStmt<Expr>;
+def NoInitExpr : DStmt<Expr>;
def ParenListExpr : DStmt<Expr>;
def VAArgExpr : DStmt<Expr>;
def GenericSelectionExpr : DStmt<Expr>;
@@ -197,6 +199,7 @@ def OMPTaskDirective : DStmt<OMPExecutableDirective>;
def OMPTaskyieldDirective : DStmt<OMPExecutableDirective>;
def OMPBarrierDirective : DStmt<OMPExecutableDirective>;
def OMPTaskwaitDirective : DStmt<OMPExecutableDirective>;
+def OMPTaskgroupDirective : DStmt<OMPExecutableDirective>;
def OMPFlushDirective : DStmt<OMPExecutableDirective>;
def OMPOrderedDirective : DStmt<OMPExecutableDirective>;
def OMPAtomicDirective : DStmt<OMPExecutableDirective>;
diff --git a/include/clang/Basic/TargetBuiltins.h b/include/clang/Basic/TargetBuiltins.h
index eece4e8de13c..b4740c595226 100644
--- a/include/clang/Basic/TargetBuiltins.h
+++ b/include/clang/Basic/TargetBuiltins.h
@@ -73,12 +73,12 @@ namespace clang {
};
}
- /// \brief R600 builtins
- namespace R600 {
+ /// \brief AMDGPU builtins
+ namespace AMDGPU {
enum {
LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1,
#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
- #include "clang/Basic/BuiltinsR600.def"
+ #include "clang/Basic/BuiltinsAMDGPU.def"
LastTSBuiltin
};
}
diff --git a/include/clang/Basic/TargetInfo.h b/include/clang/Basic/TargetInfo.h
index 8406205c7fd9..e415733189ab 100644
--- a/include/clang/Basic/TargetInfo.h
+++ b/include/clang/Basic/TargetInfo.h
@@ -363,6 +363,10 @@ public:
return *LongDoubleFormat;
}
+ /// \brief Return true if the 'long double' type should be mangled like
+ /// __float128.
+ virtual bool useFloat128ManglingForLongDouble() const { return false; }
+
/// \brief Return the value for the C99 FLT_EVAL_METHOD macro.
virtual unsigned getFloatEvalMethod() const { return 0; }
diff --git a/include/clang/Basic/TargetOptions.h b/include/clang/Basic/TargetOptions.h
index 97825394202f..ca0cca78bfc8 100644
--- a/include/clang/Basic/TargetOptions.h
+++ b/include/clang/Basic/TargetOptions.h
@@ -45,6 +45,8 @@ public:
/// The list of target specific features to enable or disable -- this should
/// be a list of strings starting with by '+' or '-'.
std::vector<std::string> Features;
+
+ std::vector<std::string> Reciprocals;
};
} // end namespace clang
diff --git a/include/clang/Basic/TokenKinds.def b/include/clang/Basic/TokenKinds.def
index b6d983b55245..67b9933562eb 100644
--- a/include/clang/Basic/TokenKinds.def
+++ b/include/clang/Basic/TokenKinds.def
@@ -548,6 +548,11 @@ ALIAS("__typeof__" , typeof , KEYALL)
ALIAS("__volatile" , volatile , KEYALL)
ALIAS("__volatile__" , volatile , KEYALL)
+// Type nullability.
+KEYWORD(__nonnull , KEYALL)
+KEYWORD(__nullable , KEYALL)
+KEYWORD(__null_unspecified , KEYALL)
+
// Microsoft extensions which should be disabled in strict conformance mode
KEYWORD(__ptr64 , KEYMS)
KEYWORD(__ptr32 , KEYMS)
diff --git a/include/clang/Basic/arm_neon.td b/include/clang/Basic/arm_neon.td
index 933f204bfb52..c6f879513eac 100644
--- a/include/clang/Basic/arm_neon.td
+++ b/include/clang/Basic/arm_neon.td
@@ -803,6 +803,13 @@ def VREINTERPRET
def VFMA : SInst<"vfma", "dddd", "fQf">;
////////////////////////////////////////////////////////////////////////////////
+// fp16 vector operations
+def SCALAR_HALF_GET_LANE : IOpInst<"vget_lane", "sdi", "h", OP_SCALAR_HALF_GET_LN>;
+def SCALAR_HALF_SET_LANE : IOpInst<"vset_lane", "dsdi", "h", OP_SCALAR_HALF_SET_LN>;
+def SCALAR_HALF_GET_LANEQ : IOpInst<"vget_lane", "sdi", "Qh", OP_SCALAR_HALF_GET_LNQ>;
+def SCALAR_HALF_SET_LANEQ : IOpInst<"vset_lane", "dsdi", "Qh", OP_SCALAR_HALF_SET_LNQ>;
+
+////////////////////////////////////////////////////////////////////////////////
// AArch64 Intrinsics
let ArchGuard = "defined(__aarch64__)" in {
@@ -1594,10 +1601,4 @@ def SCALAR_SQRDMULH_LANEQ : SOpInst<"vqrdmulh_laneq", "ssji", "SsSi", OP_SCALAR_
def SCALAR_VDUP_LANE : IInst<"vdup_lane", "sdi", "ScSsSiSlSfSdSUcSUsSUiSUlSPcSPs">;
def SCALAR_VDUP_LANEQ : IInst<"vdup_laneq", "sji", "ScSsSiSlSfSdSUcSUsSUiSUlSPcSPs">;
-
-// FIXME: Rename so it is obvious this only applies to halfs.
-def SCALAR_HALF_GET_LANE : IOpInst<"vget_lane", "sdi", "h", OP_SCALAR_HALF_GET_LN>;
-def SCALAR_HALF_SET_LANE : IOpInst<"vset_lane", "dsdi", "h", OP_SCALAR_HALF_SET_LN>;
-def SCALAR_HALF_GET_LANEQ : IOpInst<"vget_lane", "sdi", "Qh", OP_SCALAR_HALF_GET_LNQ>;
-def SCALAR_HALF_SET_LANEQ : IOpInst<"vset_lane", "dsdi", "Qh", OP_SCALAR_HALF_SET_LNQ>;
}
diff --git a/include/clang/Driver/CC1Options.td b/include/clang/Driver/CC1Options.td
index 1622c41fe13a..f2ef71e2f919 100644
--- a/include/clang/Driver/CC1Options.td
+++ b/include/clang/Driver/CC1Options.td
@@ -301,6 +301,10 @@ def fmessage_length : Separate<["-"], "fmessage-length">, MetaVarName<"<N>">,
HelpText<"Format message diagnostics so that they fit within N columns or fewer, when possible.">;
def verify : Flag<["-"], "verify">,
HelpText<"Verify diagnostic output using comment directives">;
+def verify_ignore_unexpected : Flag<["-"], "verify-ignore-unexpected">,
+ HelpText<"Ignore unexpected diagnostic messages">;
+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">;
diff --git a/include/clang/Driver/CLCompatOptions.td b/include/clang/Driver/CLCompatOptions.td
index e217cb755f6e..01913be93d56 100644
--- a/include/clang/Driver/CLCompatOptions.td
+++ b/include/clang/Driver/CLCompatOptions.td
@@ -139,6 +139,8 @@ def _SLASH_wd4005 : CLFlag<"wd4005">, Alias<W_Joined>,
AliasArgs<["no-macro-redefined"]>;
def _SLASH_wd4996 : CLFlag<"wd4996">, Alias<W_Joined>,
AliasArgs<["no-deprecated-declarations"]>;
+def _SLASH_wd4910 : CLFlag<"wd4910">, Alias<W_Joined>,
+ AliasArgs<["no-dllexport-explicit-instantiation-decl"]>;
def _SLASH_vd : CLJoined<"vd">, HelpText<"Control vtordisp placement">,
Alias<vtordisp_mode_EQ>;
def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
@@ -202,7 +204,6 @@ def _SLASH_Fi : CLCompileJoined<"Fi">,
def _SLASH_Fo : CLCompileJoined<"Fo">,
HelpText<"Set output object file, or directory (ends in / or \\)">,
MetaVarName<"<file or directory>">;
-def _SLASH_GL : CLFlag<"GL">, Alias<flto>;
def _SLASH_LD : CLFlag<"LD">, HelpText<"Create DLL">;
def _SLASH_LDd : CLFlag<"LDd">, HelpText<"Create debug DLL">;
def _SLASH_link : CLRemainingArgs<"link">,
@@ -287,6 +288,7 @@ def _SLASH_G2 : CLFlag<"G2">;
def _SLASH_Ge : CLFlag<"Ge">;
def _SLASH_Gh : CLFlag<"Gh">;
def _SLASH_GH : CLFlag<"GH">;
+def _SLASH_GL : CLFlag<"GL">;
def _SLASH_GL_ : CLFlag<"GL-">;
def _SLASH_Gm : CLFlag<"Gm">;
def _SLASH_Gm_ : CLFlag<"Gm-">;
diff --git a/include/clang/Driver/Driver.h b/include/clang/Driver/Driver.h
index 09521c2bae3f..d7bb1d2283fb 100644
--- a/include/clang/Driver/Driver.h
+++ b/include/clang/Driver/Driver.h
@@ -91,7 +91,7 @@ public:
/// The path to the compiler resource directory.
std::string ResourceDir;
- /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
+ /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
/// functionality.
/// FIXME: This type of customization should be removed in favor of the
/// universal driver when it is ready.
@@ -402,7 +402,7 @@ public:
/// handle this action.
bool ShouldUseClangCompiler(const JobAction &JA) const;
- bool IsUsingLTO(const ToolChain &TC, const llvm::opt::ArgList &Args) const;
+ bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
private:
/// \brief Retrieves a ToolChain for a particular target triple.
diff --git a/include/clang/Driver/Options.td b/include/clang/Driver/Options.td
index 7e39a9ae5b22..aae377693551 100644
--- a/include/clang/Driver/Options.td
+++ b/include/clang/Driver/Options.td
@@ -561,8 +561,13 @@ def fno_sanitize_recover_EQ
: CommaJoined<["-"], "fno-sanitize-recover=">,
Group<f_clang_Group>,
HelpText<"Disable recovery for specified sanitizers">;
+def fsanitize_trap_EQ : CommaJoined<["-"], "fsanitize-trap=">, Group<f_clang_Group>,
+ Flags<[CC1Option, CoreOption]>,
+ HelpText<"Enable trapping for specified sanitizers">;
+def fno_sanitize_trap_EQ : CommaJoined<["-"], "fno-sanitize-trap=">, Group<f_clang_Group>,
+ HelpText<"Disable trapping for specified sanitizers">;
def fsanitize_undefined_trap_on_error : Flag<["-"], "fsanitize-undefined-trap-on-error">,
- Group<f_clang_Group>, Flags<[CC1Option]>;
+ Group<f_clang_Group>;
def fno_sanitize_undefined_trap_on_error : Flag<["-"], "fno-sanitize-undefined-trap-on-error">,
Group<f_clang_Group>;
def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
@@ -691,9 +696,10 @@ def fmodules_validate_system_headers : Flag<["-"], "fmodules-validate-system-hea
def fmodules : Flag <["-"], "fmodules">, Group<f_Group>,
Flags<[DriverOption, CC1Option]>,
HelpText<"Enable the 'modules' language feature">;
-def fmodule_maps : Flag <["-"], "fmodule-maps">, Group<f_Group>,
- Flags<[DriverOption,CC1Option]>,
- HelpText<"Read module maps to understand the structure of library headers">;
+def fimplicit_module_maps : Flag <["-"], "fimplicit-module-maps">, Group<f_Group>,
+ Flags<[DriverOption, CC1Option]>,
+ HelpText<"Implicitly search the file system for module map files.">;
+def fmodule_maps : Flag <["-"], "fmodule-maps">, Alias<fimplicit_module_maps>;
def fmodule_name : JoinedOrSeparate<["-"], "fmodule-name=">, Group<f_Group>,
Flags<[DriverOption,CC1Option]>, MetaVarName<"<name>">,
HelpText<"Specify the name of the module to build">;
@@ -713,12 +719,6 @@ def fmodules_strict_decluse : Flag <["-"], "fmodules-strict-decluse">, Group<f_G
HelpText<"Like -fmodules-decluse but requires all headers to be in modules">;
def fno_modules_search_all : Flag <["-"], "fno-modules-search-all">, Group<f_Group>,
Flags<[DriverOption, CC1Option]>;
-def fmodules_implicit_maps :
- Flag <["-"], "fmodules-implicit-maps">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>;
-def fno_modules_implicit_maps :
- Flag <["-"], "fno-modules-implicit-maps">,
- Group<f_Group>, Flags<[DriverOption, CC1Option]>;
def fno_implicit_modules :
Flag <["-"], "fno-implicit-modules">,
Group<f_Group>, Flags<[DriverOption, CC1Option]>;
@@ -780,8 +780,9 @@ def fno_merge_all_constants : Flag<["-"], "fno-merge-all-constants">, Group<f_Gr
Flags<[CC1Option]>, HelpText<"Disallow merging of constants">;
def fno_modules : Flag <["-"], "fno-modules">, Group<f_Group>,
Flags<[DriverOption]>;
-def fno_module_maps : Flag <["-"], "fno-module-maps">, Group<f_Group>,
+def fno_implicit_module_maps : Flag <["-"], "fno-implicit-module-maps">, Group<f_Group>,
Flags<[DriverOption]>;
+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]>;
def fno_modules_strict_decluse : Flag <["-"], "fno-strict-modules-decluse">, Group<f_Group>,
@@ -1338,6 +1339,8 @@ def msoft_float : Flag<["-"], "msoft-float">, Group<m_Group>, Flags<[CC1Option]>
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 msse2 : Flag<["-"], "msse2">, Group<m_x86_Features_Group>;
def msse3 : Flag<["-"], "msse3">, Group<m_x86_Features_Group>;
def msse4a : Flag<["-"], "msse4a">, Group<m_x86_Features_Group>;
diff --git a/include/clang/Driver/SanitizerArgs.h b/include/clang/Driver/SanitizerArgs.h
index bfa63e7734fb..ceba912dad13 100644
--- a/include/clang/Driver/SanitizerArgs.h
+++ b/include/clang/Driver/SanitizerArgs.h
@@ -23,13 +23,13 @@ class ToolChain;
class SanitizerArgs {
SanitizerSet Sanitizers;
SanitizerSet RecoverableSanitizers;
+ SanitizerSet TrapSanitizers;
std::vector<std::string> BlacklistFiles;
int CoverageFeatures;
int MsanTrackOrigins;
int AsanFieldPadding;
bool AsanZeroBaseShadow;
- bool UbsanTrapOnError;
bool AsanSharedRuntime;
bool LinkCXXRuntimes;
@@ -47,10 +47,12 @@ class SanitizerArgs {
}
bool needsUbsanRt() const;
bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
+ bool needsSafeStackRt() const {
+ return Sanitizers.has(SanitizerKind::SafeStack);
+ }
bool requiresPIE() const;
bool needsUnwindTables() const;
- bool needsLTO() const;
bool linkCXXRuntimes() const { return LinkCXXRuntimes; }
void addArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
diff --git a/include/clang/Driver/ToolChain.h b/include/clang/Driver/ToolChain.h
index 560df19e25ce..aba18c9916c3 100644
--- a/include/clang/Driver/ToolChain.h
+++ b/include/clang/Driver/ToolChain.h
@@ -10,6 +10,7 @@
#ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
#define LLVM_CLANG_DRIVER_TOOLCHAIN_H
+#include "clang/Basic/Sanitizers.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Multilib.h"
#include "clang/Driver/Types.h"
@@ -164,7 +165,10 @@ public:
}
/// Choose a tool to use to handle the action \p JA.
- Tool *SelectTool(const JobAction &JA) const;
+ ///
+ /// This can be overridden when a particular ToolChain needs to use
+ /// a C compiler other than Clang.
+ virtual Tool *SelectTool(const JobAction &JA) const;
// Helper methods
@@ -345,6 +349,9 @@ public:
virtual bool
AddFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
+
+ /// \brief Return sanitizers which are available in this toolchain.
+ virtual SanitizerMask getSupportedSanitizers() const;
};
} // end namespace driver
diff --git a/include/clang/Format/Format.h b/include/clang/Format/Format.h
index 3fdee99f3e55..ad87a057a6a7 100644
--- a/include/clang/Format/Format.h
+++ b/include/clang/Format/Format.h
@@ -210,10 +210,10 @@ struct FormatStyle {
enum ShortFunctionStyle {
/// \brief Never merge functions into a single line.
SFS_None,
- /// \brief Only merge functions defined inside a class.
- SFS_Inline,
/// \brief Only merge empty functions.
SFS_Empty,
+ /// \brief Only merge functions defined inside a class. Implies "empty".
+ SFS_Inline,
/// \brief Merge all functions fitting on a single line.
SFS_All,
};
@@ -287,6 +287,11 @@ struct FormatStyle {
bool AlwaysBreakTemplateDeclarations;
/// \brief If \c true, always break before multiline string literals.
+ ///
+ /// This flag is mean to make cases where there are multiple multiline strings
+ /// in a file look more consistent. Thus, it will only take effect if wrapping
+ /// the string at that point leads to it being indented
+ /// \c ContinuationIndentWidth spaces from the start of the line.
bool AlwaysBreakBeforeMultilineStrings;
/// \brief Different ways to use tab in formatting.
diff --git a/include/clang/Frontend/ASTUnit.h b/include/clang/Frontend/ASTUnit.h
index 405774b811c8..2d38352d22a8 100644
--- a/include/clang/Frontend/ASTUnit.h
+++ b/include/clang/Frontend/ASTUnit.h
@@ -56,6 +56,7 @@ class FileEntry;
class FileManager;
class HeaderSearch;
class Preprocessor;
+class PCHContainerOperations;
class SourceManager;
class TargetInfo;
class ASTFrontendAction;
@@ -422,7 +423,8 @@ private:
explicit ASTUnit(bool MainFileIsAST);
void CleanTemporaryFiles();
- bool Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
+ bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
struct ComputedPreamble {
llvm::MemoryBuffer *Buffer;
@@ -442,6 +444,7 @@ private:
unsigned MaxLines);
std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
unsigned MaxLines = 0);
void RealizeTopLevelDeclsFromPreamble();
@@ -715,12 +718,16 @@ public:
///
/// \param Filename - The AST file to load.
///
+ /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
+ /// creating modules.
/// \param Diags - The diagnostics engine to use for reporting errors; its
/// 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, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+ const std::string &Filename,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls = false,
ArrayRef<RemappedFile> RemappedFiles = None,
bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
@@ -735,8 +742,10 @@ private:
///
/// \returns \c true if a catastrophic failure occurred (which means that the
/// \c ASTUnit itself is invalid), or \c false otherwise.
- bool LoadFromCompilerInvocation(bool PrecompilePreamble);
-
+ bool LoadFromCompilerInvocation(
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ bool PrecompilePreamble);
+
public:
/// \brief Create an ASTUnit from a source file, via a CompilerInvocation
@@ -745,6 +754,9 @@ public:
/// \param CI - The compiler invocation to use; it must have exactly one input
/// source file. The ASTUnit takes ownership of the CompilerInvocation object.
///
+ /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
+ /// creating modules.
+ ///
/// \param Diags - The diagnostics engine to use for reporting errors; its
/// lifetime is expected to extend past that of the returned ASTUnit.
///
@@ -765,7 +777,9 @@ public:
/// created ASTUnit was passed in \p Unit then the caller can check that.
///
static ASTUnit *LoadFromCompilerInvocationAction(
- CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+ CompilerInvocation *CI,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
ASTFrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
@@ -780,15 +794,20 @@ public:
/// \param CI - The compiler invocation to use; it must have exactly one input
/// source file. The ASTUnit takes ownership of the CompilerInvocation object.
///
+ /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
+ /// creating modules.
+ ///
/// \param Diags - The diagnostics engine to use for reporting errors; its
/// lifetime is expected to extend past that of the returned ASTUnit.
//
// FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
// shouldn't need to specify them at construction time.
static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
- CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
- bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
- bool PrecompilePreamble = false, TranslationUnitKind TUKind = TU_Complete,
+ CompilerInvocation *CI,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool OnlyLocalDecls = false,
+ bool CaptureDiagnostics = false, bool PrecompilePreamble = false,
+ TranslationUnitKind TUKind = TU_Complete,
bool CacheCodeCompletionResults = false,
bool IncludeBriefCommentsInCodeCompletion = false,
bool UserFilesAreVolatile = false);
@@ -800,6 +819,9 @@ public:
///
/// \param ArgEnd - The end of the argument vector.
///
+ /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
+ /// creating modules.
+ ///
/// \param Diags - The diagnostics engine to use for reporting errors; its
/// lifetime is expected to extend past that of the returned ASTUnit.
///
@@ -813,6 +835,7 @@ public:
// shouldn't need to specify them at construction time.
static ASTUnit *LoadFromCommandLine(
const char **ArgBegin, const char **ArgEnd,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
ArrayRef<RemappedFile> RemappedFiles = None,
@@ -828,8 +851,9 @@ public:
/// were originally used to produce this translation unit.
///
/// \returns True if a failure occurred that causes the ASTUnit not to
- /// contain any translation-unit information, false otherwise.
- bool Reparse(ArrayRef<RemappedFile> RemappedFiles = None);
+ /// contain any translation-unit information, false otherwise.
+ bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ ArrayRef<RemappedFile> RemappedFiles = None);
/// \brief Perform code completion at the given file, line, and
/// column within this translation unit.
@@ -852,14 +876,14 @@ public:
/// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
/// OwnedBuffers parameters are all disgusting hacks. They will go away.
void CodeComplete(StringRef File, unsigned Line, unsigned Column,
- ArrayRef<RemappedFile> RemappedFiles,
- bool IncludeMacros, bool IncludeCodePatterns,
- bool IncludeBriefComments,
+ ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
+ bool IncludeCodePatterns, bool IncludeBriefComments,
CodeCompleteConsumer &Consumer,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticsEngine &Diag, LangOptions &LangOpts,
SourceManager &SourceMgr, FileManager &FileMgr,
SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
- SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
+ SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
/// \brief Save this translation unit to a file with the given name.
///
diff --git a/include/clang/Frontend/CodeGenOptions.def b/include/clang/Frontend/CodeGenOptions.def
index adf1c879d40e..d34cf0cad1c9 100644
--- a/include/clang/Frontend/CodeGenOptions.def
+++ b/include/clang/Frontend/CodeGenOptions.def
@@ -120,8 +120,6 @@ CODEGENOPT(SanitizeCoverageTraceCmp, 1, 0) ///< Enable cmp instruction tracing
///< in sanitizer coverage.
CODEGENOPT(SanitizeCoverage8bitCounters, 1, 0) ///< Use 8-bit frequency counters
///< in sanitizer coverage.
-CODEGENOPT(SanitizeUndefinedTrapOnError, 1, 0) ///< Set on
- /// -fsanitize-undefined-trap-on-error
CODEGENOPT(SimplifyLibCalls , 1, 1) ///< Set when -fbuiltin is enabled.
CODEGENOPT(SoftFloat , 1, 0) ///< -soft-float.
CODEGENOPT(StrictEnums , 1, 0) ///< Optimize based on strict enum definition.
diff --git a/include/clang/Frontend/CodeGenOptions.h b/include/clang/Frontend/CodeGenOptions.h
index 0c5ce5813769..66597bd0af8e 100644
--- a/include/clang/Frontend/CodeGenOptions.h
+++ b/include/clang/Frontend/CodeGenOptions.h
@@ -197,6 +197,9 @@ public:
/// continued when possible).
SanitizerSet SanitizeRecover;
+ /// Set of sanitizer checks that trap rather than diagnose.
+ SanitizerSet SanitizeTrap;
+
public:
// Define accessors/mutators for code generation options of enumeration type.
#define CODEGENOPT(Name, Bits, Default)
diff --git a/include/clang/Frontend/CompilerInstance.h b/include/clang/Frontend/CompilerInstance.h
index 8d0d939d7811..9cd806c99b85 100644
--- a/include/clang/Frontend/CompilerInstance.h
+++ b/include/clang/Frontend/CompilerInstance.h
@@ -11,6 +11,7 @@
#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
#include "clang/AST/ASTConsumer.h"
+#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInvocation.h"
@@ -109,6 +110,9 @@ class CompilerInstance : public ModuleLoader {
/// \brief The module dependency collector for crashdumps
std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
+ /// \brief The module provider.
+ std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
+
/// \brief The dependency file generator.
std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
@@ -172,7 +176,10 @@ class CompilerInstance : public ModuleLoader {
CompilerInstance(const CompilerInstance &) = delete;
void operator=(const CompilerInstance &) = delete;
public:
- explicit CompilerInstance(bool BuildingModule = false);
+ explicit CompilerInstance(
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>(),
+ bool BuildingModule = false);
~CompilerInstance() override;
/// @name High-Level Operations
@@ -492,6 +499,10 @@ public:
void setModuleDepCollector(
std::shared_ptr<ModuleDependencyCollector> Collector);
+ std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
+ return ThePCHContainerOperations;
+ }
+
/// }
/// @name Code Completion
/// {
@@ -605,6 +616,7 @@ public:
static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
+ const PCHContainerOperations &PCHContainerOps,
void *DeserializationListener, bool OwnDeserializationListener,
bool Preamble, bool UseGlobalModuleIndex);
diff --git a/include/clang/Frontend/FrontendActions.h b/include/clang/Frontend/FrontendActions.h
index b1508287c85f..f61775f014f8 100644
--- a/include/clang/Frontend/FrontendActions.h
+++ b/include/clang/Frontend/FrontendActions.h
@@ -85,10 +85,9 @@ public:
/// create the PCHGenerator instance returned by CreateASTConsumer.
///
/// \returns true if an error occurred, false otherwise.
- static raw_ostream *ComputeASTConsumerArguments(CompilerInstance &CI,
- StringRef InFile,
- std::string &Sysroot,
- std::string &OutputFile);
+ static raw_pwrite_stream *
+ ComputeASTConsumerArguments(CompilerInstance &CI, StringRef InFile,
+ std::string &Sysroot, std::string &OutputFile);
};
class GenerateModuleAction : public ASTFrontendAction {
@@ -118,10 +117,10 @@ public:
/// create the PCHGenerator instance returned by CreateASTConsumer.
///
/// \returns true if an error occurred, false otherwise.
- raw_ostream *ComputeASTConsumerArguments(CompilerInstance &CI,
- StringRef InFile,
- std::string &Sysroot,
- std::string &OutputFile);
+ raw_pwrite_stream *ComputeASTConsumerArguments(CompilerInstance &CI,
+ StringRef InFile,
+ std::string &Sysroot,
+ std::string &OutputFile);
};
class SyntaxOnlyAction : public ASTFrontendAction {
diff --git a/include/clang/Frontend/PCHContainerOperations.h b/include/clang/Frontend/PCHContainerOperations.h
new file mode 100644
index 000000000000..949ee63c615d
--- /dev/null
+++ b/include/clang/Frontend/PCHContainerOperations.h
@@ -0,0 +1,76 @@
+//===--- Frontend/PCHContainerOperations.h - PCH Containers -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_PCH_CONTAINER_OPERATIONS_H
+#define LLVM_CLANG_PCH_CONTAINER_OPERATIONS_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include <memory>
+
+namespace llvm {
+class raw_pwrite_stream;
+class BitstreamReader;
+}
+
+namespace clang {
+
+class ASTConsumer;
+class CodeGenOptions;
+class DiagnosticsEngine;
+class HeaderSearchOptions;
+class LangOptions;
+class PreprocessorOptions;
+class TargetOptions;
+
+struct PCHBuffer {
+ bool IsComplete;
+ llvm::SmallVector<char, 0> Data;
+};
+
+/// \brief This abstract interface provides operations for creating
+/// and unwrapping containers for serialized ASTs (precompiled headers
+/// and clang modules).
+class PCHContainerOperations {
+public:
+ virtual ~PCHContainerOperations();
+ /// \brief Return an ASTConsumer that can be chained with a
+ /// PCHGenerator that produces a wrapper file format containing a
+ /// serialized AST bitstream.
+ virtual std::unique_ptr<ASTConsumer> CreatePCHContainerGenerator(
+ DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
+ const PreprocessorOptions &PPO, const TargetOptions &TO,
+ const LangOptions &LO, const std::string &MainFileName,
+ const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
+ std::shared_ptr<PCHBuffer> Buffer) const = 0;
+
+ /// \brief Initialize an llvm::BitstreamReader with the serialized AST inside
+ /// the PCH container Buffer.
+ virtual void ExtractPCH(llvm::MemoryBufferRef Buffer,
+ llvm::BitstreamReader &StreamFile) const = 0;
+};
+
+/// \brief Implements a raw pass-through PCH container.
+class RawPCHContainerOperations : public PCHContainerOperations {
+ /// \brief Return an ASTConsumer that can be chained with a
+ /// PCHGenerator that writes the module to a flat file.
+ std::unique_ptr<ASTConsumer> CreatePCHContainerGenerator(
+ DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
+ const PreprocessorOptions &PPO, const TargetOptions &TO,
+ const LangOptions &LO, const std::string &MainFileName,
+ const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
+ std::shared_ptr<PCHBuffer> Buffer) const override;
+
+ /// \brief Initialize an llvm::BitstreamReader with Buffer.
+ void ExtractPCH(llvm::MemoryBufferRef Buffer,
+ llvm::BitstreamReader &StreamFile) const override;
+};
+}
+
+#endif
diff --git a/include/clang/Frontend/Utils.h b/include/clang/Frontend/Utils.h
index cd0ebf611201..639965343c45 100644
--- a/include/clang/Frontend/Utils.h
+++ b/include/clang/Frontend/Utils.h
@@ -45,6 +45,7 @@ class HeaderSearch;
class HeaderSearchOptions;
class IdentifierTable;
class LangOptions;
+class PCHContainerOperations;
class Preprocessor;
class PreprocessorOptions;
class PreprocessorOutputOptions;
@@ -61,8 +62,8 @@ void ApplyHeaderSearchOptions(HeaderSearch &HS,
/// InitializePreprocessor - Initialize the preprocessor getting it and the
/// environment ready to process a single file.
-void InitializePreprocessor(Preprocessor &PP,
- const PreprocessorOptions &PPOpts,
+void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
+ const PCHContainerOperations &PCHContainerOps,
const FrontendOptions &FEOpts);
/// DoPrintPreprocessedInput - Implement -E mode.
diff --git a/include/clang/Lex/HeaderSearchOptions.h b/include/clang/Lex/HeaderSearchOptions.h
index 316134c405b3..c9c32609f19b 100644
--- a/include/clang/Lex/HeaderSearchOptions.h
+++ b/include/clang/Lex/HeaderSearchOptions.h
@@ -98,8 +98,9 @@ public:
/// Note: Only used for testing!
unsigned DisableModuleHash : 1;
- /// \brief Interpret module maps. This option is implied by full modules.
- unsigned ModuleMaps : 1;
+ /// \brief Implicit module maps. This option is enabld by default when
+ /// modules is enabled.
+ unsigned ImplicitModuleMaps : 1;
/// \brief Set the 'home directory' of a module map file to the current
/// working directory (or the home directory of the module map file that
@@ -166,7 +167,7 @@ public:
public:
HeaderSearchOptions(StringRef _Sysroot = "/")
- : Sysroot(_Sysroot), DisableModuleHash(0), ModuleMaps(0),
+ : Sysroot(_Sysroot), DisableModuleHash(0), ImplicitModuleMaps(0),
ModuleMapFileHomeIsCwd(0),
ModuleCachePruneInterval(7*24*60*60),
ModuleCachePruneAfter(31*24*60*60),
diff --git a/include/clang/Lex/ModuleMap.h b/include/clang/Lex/ModuleMap.h
index e41efc5d419d..0bbcfac3b81b 100644
--- a/include/clang/Lex/ModuleMap.h
+++ b/include/clang/Lex/ModuleMap.h
@@ -268,15 +268,10 @@ public:
///
/// \param File The header file that is likely to be included.
///
- /// \param RequestingModule Specifies the module the header is intended to be
- /// used from. Used to disambiguate if a header is present in multiple
- /// modules.
- ///
/// \returns The module KnownHeader, which provides the module that owns the
/// given header file. The KnownHeader is default constructed to indicate
/// that no module owns this header file.
- KnownHeader findModuleForHeader(const FileEntry *File,
- Module *RequestingModule = nullptr);
+ KnownHeader findModuleForHeader(const FileEntry *File);
/// \brief Reports errors if a module must not include a specific file.
///
diff --git a/include/clang/Lex/Preprocessor.h b/include/clang/Lex/Preprocessor.h
index f6e61c0e7ad6..439a28041e2d 100644
--- a/include/clang/Lex/Preprocessor.h
+++ b/include/clang/Lex/Preprocessor.h
@@ -256,6 +256,10 @@ class Preprocessor : public RefCountedBase<Preprocessor> {
/// \#pragma clang arc_cf_code_audited begin.
SourceLocation PragmaARCCFCodeAuditedLoc;
+ /// \brief The source location of the currently-active
+ /// \#pragma clang assume_nonnull begin.
+ SourceLocation PragmaAssumeNonNullLoc;
+
/// \brief True if we hit the code-completion point.
bool CodeCompletionReached;
@@ -455,8 +459,9 @@ class Preprocessor : public RefCountedBase<Preprocessor> {
void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
if (auto *Info = getModuleInfo(PP, II)) {
- for (auto *Active : Info->ActiveModuleMacros)
- Info->OverriddenMacros.push_back(Active);
+ Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
+ Info->ActiveModuleMacros.begin(),
+ Info->ActiveModuleMacros.end());
Info->ActiveModuleMacros.clear();
Info->IsAmbiguous = false;
}
@@ -1249,6 +1254,20 @@ public:
PragmaARCCFCodeAuditedLoc = Loc;
}
+ /// \brief The location of the currently-active \#pragma clang
+ /// assume_nonnull begin.
+ ///
+ /// Returns an invalid location if there is no such pragma active.
+ SourceLocation getPragmaAssumeNonNullLoc() const {
+ return PragmaAssumeNonNullLoc;
+ }
+
+ /// \brief Set the location of the currently-active \#pragma clang
+ /// assume_nonnull begin. An invalid location ends the pragma.
+ void setPragmaAssumeNonNullLoc(SourceLocation Loc) {
+ PragmaAssumeNonNullLoc = Loc;
+ }
+
/// \brief Set the directory in which the main file should be considered
/// to have been found, if it is not a real file.
void setMainFileDir(const DirectoryEntry *Dir) {
diff --git a/include/clang/Lex/Token.h b/include/clang/Lex/Token.h
index e0878093402a..7ba22b2f626c 100644
--- a/include/clang/Lex/Token.h
+++ b/include/clang/Lex/Token.h
@@ -94,6 +94,13 @@ public:
/// "if (Tok.is(tok::l_brace)) {...}".
bool is(tok::TokenKind K) const { return Kind == K; }
bool isNot(tok::TokenKind K) const { return Kind != K; }
+ bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
+ return is(K1) || is(K2);
+ }
+ template <typename... Ts>
+ bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const {
+ return is(K1) || isOneOf(K2, Ks...);
+ }
/// \brief Return true if this is a raw identifier (when lexing
/// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
diff --git a/include/clang/Parse/Parser.h b/include/clang/Parse/Parser.h
index caba77b74c67..7042a1ef6e29 100644
--- a/include/clang/Parse/Parser.h
+++ b/include/clang/Parse/Parser.h
@@ -303,6 +303,12 @@ public:
return true;
}
+ /// Retrieve the underscored keyword (__nonnull, __nullable) that corresponds
+ /// to the given nullability kind.
+ IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
+ return Actions.getNullabilityKeyword(nullability);
+ }
+
private:
//===--------------------------------------------------------------------===//
// Low-Level token peeking and consumption methods.
@@ -620,6 +626,16 @@ private:
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
+ /// Returns true if the current token is the identifier 'instancetype'.
+ ///
+ /// Should only be used in Objective-C language modes.
+ bool isObjCInstancetype() {
+ assert(getLangOpts().ObjC1);
+ if (!Ident_instancetype)
+ Ident_instancetype = PP.getIdentifierInfo("instancetype");
+ return Tok.getIdentifierInfo() == Ident_instancetype;
+ }
+
/// TryKeywordIdentFallback - For compatibility with system headers using
/// keywords as identifiers, attempt to convert the current token to an
/// identifier and optionally disable the keyword for the remainder of the
@@ -1282,6 +1298,7 @@ private:
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
+ objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
@@ -1685,7 +1702,8 @@ private:
DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
DSC_top_level, // top-level/namespace declaration context
- DSC_template_type_arg // template type argument context
+ DSC_template_type_arg, // template type argument context
+ DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
};
/// Is this a context in which we are parsing just a type-specifier (or
@@ -1695,6 +1713,7 @@ private:
case DSC_normal:
case DSC_class:
case DSC_top_level:
+ case DSC_objc_method_result:
return false;
case DSC_template_type_arg:
@@ -2106,6 +2125,7 @@ private:
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
+ void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
diff --git a/include/clang/Rewrite/Frontend/FixItRewriter.h b/include/clang/Rewrite/Frontend/FixItRewriter.h
index ad828e55ae88..3b1b31e0cdee 100644
--- a/include/clang/Rewrite/Frontend/FixItRewriter.h
+++ b/include/clang/Rewrite/Frontend/FixItRewriter.h
@@ -27,7 +27,7 @@ class FileEntry;
class FixItOptions {
public:
- FixItOptions() : FixWhatYouCan(false),
+ FixItOptions() : InPlace(false), FixWhatYouCan(false),
FixOnlyWarnings(false), Silent(false) { }
virtual ~FixItOptions();
@@ -41,6 +41,10 @@ public:
///
virtual std::string RewriteFilename(const std::string &Filename, int &fd) = 0;
+ /// True if files should be updated in place. RewriteFilename is only called
+ /// if this is false.
+ bool InPlace;
+
/// \brief Whether to abort fixing a file when not all errors could be fixed.
bool FixWhatYouCan;
diff --git a/include/clang/Sema/AttributeList.h b/include/clang/Sema/AttributeList.h
index 58b1b9ee2436..4d18633cd338 100644
--- a/include/clang/Sema/AttributeList.h
+++ b/include/clang/Sema/AttributeList.h
@@ -81,6 +81,8 @@ public:
AS_Declspec,
/// __ptr16, alignas(...), etc.
AS_Keyword,
+ /// Context-sensitive version of a keyword attribute.
+ AS_ContextSensitiveKeyword,
/// #pragma ...
AS_Pragma
};
@@ -343,14 +345,20 @@ public:
bool isAlignasAttribute() const {
// FIXME: Use a better mechanism to determine this.
- return getKind() == AT_Aligned && SyntaxUsed == AS_Keyword;
+ return getKind() == AT_Aligned && isKeywordAttribute();
}
bool isDeclspecAttribute() const { return SyntaxUsed == AS_Declspec; }
bool isCXX11Attribute() const {
return SyntaxUsed == AS_CXX11 || isAlignasAttribute();
}
- bool isKeywordAttribute() const { return SyntaxUsed == AS_Keyword; }
+ bool isKeywordAttribute() const {
+ return SyntaxUsed == AS_Keyword || SyntaxUsed == AS_ContextSensitiveKeyword;
+ }
+
+ bool isContextSensitiveKeywordAttribute() const {
+ return SyntaxUsed == AS_ContextSensitiveKeyword;
+ }
bool isInvalid() const { return Invalid; }
void setInvalid(bool b = true) const { Invalid = b; }
diff --git a/include/clang/Sema/DeclSpec.h b/include/clang/Sema/DeclSpec.h
index de39d83bded4..2ec3286ad799 100644
--- a/include/clang/Sema/DeclSpec.h
+++ b/include/clang/Sema/DeclSpec.h
@@ -31,6 +31,7 @@
#include "clang/Lex/Token.h"
#include "clang/Sema/AttributeList.h"
#include "clang/Sema/Ownership.h"
+#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
@@ -785,7 +786,8 @@ public:
DQ_Out = 0x4,
DQ_Bycopy = 0x8,
DQ_Byref = 0x10,
- DQ_Oneway = 0x20
+ DQ_Oneway = 0x20,
+ DQ_CSNullability = 0x40
};
/// PropertyAttributeKind - list of property attributes.
@@ -802,17 +804,22 @@ public:
DQ_PR_atomic = 0x100,
DQ_PR_weak = 0x200,
DQ_PR_strong = 0x400,
- DQ_PR_unsafe_unretained = 0x800
+ DQ_PR_unsafe_unretained = 0x800,
+ DQ_PR_nullability = 0x1000,
+ DQ_PR_null_resettable = 0x2000
};
-
ObjCDeclSpec()
: objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
- GetterName(nullptr), SetterName(nullptr) { }
+ Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
+
ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
}
+ void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
+ objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
+ }
ObjCPropertyAttributeKind getPropertyAttributes() const {
return ObjCPropertyAttributeKind(PropertyAttributes);
@@ -822,6 +829,28 @@ public:
(ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
}
+ NullabilityKind getNullability() const {
+ assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
+ (getPropertyAttributes() & DQ_PR_nullability)) &&
+ "Objective-C declspec doesn't have nullability");
+ return static_cast<NullabilityKind>(Nullability);
+ }
+
+ SourceLocation getNullabilityLoc() const {
+ assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
+ (getPropertyAttributes() & DQ_PR_nullability)) &&
+ "Objective-C declspec doesn't have nullability");
+ return NullabilityLoc;
+ }
+
+ void setNullability(SourceLocation loc, NullabilityKind kind) {
+ assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
+ (getPropertyAttributes() & DQ_PR_nullability)) &&
+ "Set the nullability declspec or property attribute first");
+ Nullability = static_cast<unsigned>(kind);
+ NullabilityLoc = loc;
+ }
+
const IdentifierInfo *getGetterName() const { return GetterName; }
IdentifierInfo *getGetterName() { return GetterName; }
void setGetterName(IdentifierInfo *name) { GetterName = name; }
@@ -834,10 +863,15 @@ private:
// FIXME: These two are unrelated and mutually exclusive. So perhaps
// we can put them in a union to reflect their mutual exclusivity
// (space saving is negligible).
- ObjCDeclQualifier objcDeclQualifier : 6;
+ ObjCDeclQualifier objcDeclQualifier : 7;
// NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
- unsigned PropertyAttributes : 12;
+ unsigned PropertyAttributes : 14;
+
+ unsigned Nullability : 2;
+
+ SourceLocation NullabilityLoc;
+
IdentifierInfo *GetterName; // getter name or NULL if no getter
IdentifierInfo *SetterName; // setter name or NULL if no setter
};
@@ -1616,7 +1650,13 @@ private:
bool InlineParamsUsed;
/// \brief true if the declaration is preceded by \c __extension__.
- bool Extension : 1;
+ unsigned Extension : 1;
+
+ /// Indicates whether this is an Objective-C instance variable.
+ unsigned ObjCIvar : 1;
+
+ /// Indicates whether this is an Objective-C 'weak' property.
+ unsigned ObjCWeakProperty : 1;
/// \brief If this is the second or subsequent declarator in this declaration,
/// the location of the comma before this declarator.
@@ -1635,7 +1675,8 @@ public:
GroupingParens(false), FunctionDefinition(FDK_Declaration),
Redeclaration(false),
Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr),
- InlineParamsUsed(false), Extension(false) {
+ InlineParamsUsed(false), Extension(false), ObjCIvar(false),
+ ObjCWeakProperty(false) {
}
~Declarator() {
@@ -1713,6 +1754,8 @@ public:
Attrs.clear();
AsmLabel = nullptr;
InlineParamsUsed = false;
+ ObjCIvar = false;
+ ObjCWeakProperty = false;
CommaLoc = SourceLocation();
EllipsisLoc = SourceLocation();
}
@@ -2121,6 +2164,12 @@ public:
void setExtension(bool Val = true) { Extension = Val; }
bool getExtension() const { return Extension; }
+ void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
+ bool isObjCIvar() const { return ObjCIvar; }
+
+ void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
+ bool isObjCWeakProperty() const { return ObjCWeakProperty; }
+
void setInvalidType(bool Val = true) { InvalidType = Val; }
bool isInvalidType() const {
return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
diff --git a/include/clang/Sema/Lookup.h b/include/clang/Sema/Lookup.h
index 97192b53fa44..5bfee8b0d037 100644
--- a/include/clang/Sema/Lookup.h
+++ b/include/clang/Sema/Lookup.h
@@ -302,14 +302,10 @@ public:
if (!D->isInIdentifierNamespace(IDNS))
return nullptr;
- if (isVisible(getSema(), D))
+ if (isHiddenDeclarationVisible() || isVisible(getSema(), D))
return D;
- if (auto *Visible = getAcceptableDeclSlow(D))
- return Visible;
-
- // Even if hidden declarations are visible, prefer a visible declaration.
- return isHiddenDeclarationVisible() ? D : nullptr;
+ return getAcceptableDeclSlow(D);
}
private:
diff --git a/include/clang/Sema/Sema.h b/include/clang/Sema/Sema.h
index 60664c5fdc99..cb75b969f116 100644
--- a/include/clang/Sema/Sema.h
+++ b/include/clang/Sema/Sema.h
@@ -210,6 +210,50 @@ namespace threadSafety {
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
+/// Describes whether we've seen any nullability information for the given
+/// file.
+struct FileNullability {
+ /// The first pointer declarator (of any pointer kind) in the file that does
+ /// not have a corresponding nullability annotation.
+ SourceLocation PointerLoc;
+
+ /// Which kind of pointer declarator we saw.
+ uint8_t PointerKind;
+
+ /// Whether we saw any type nullability annotations in the given file.
+ bool SawTypeNullability = false;
+};
+
+/// A mapping from file IDs to a record of whether we've seen nullability
+/// information in that file.
+class FileNullabilityMap {
+ /// A mapping from file IDs to the nullability information for each file ID.
+ llvm::DenseMap<FileID, FileNullability> Map;
+
+ /// A single-element cache based on the file ID.
+ struct {
+ FileID File;
+ FileNullability Nullability;
+ } Cache;
+
+public:
+ FileNullability &operator[](FileID file) {
+ // Check the single-element cache.
+ if (file == Cache.File)
+ return Cache.Nullability;
+
+ // It's not in the single-element cache; flush the cache if we have one.
+ if (!Cache.File.isInvalid()) {
+ Map[Cache.File] = Cache.Nullability;
+ }
+
+ // Pull this entry into the cache.
+ Cache.File = file;
+ Cache.Nullability = Map[file];
+ return Cache.Nullability;
+ }
+};
+
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
@@ -341,6 +385,9 @@ public:
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
+ /// A mapping that describes the nullability we've seen in each header file.
+ FileNullabilityMap NullabilityMap;
+
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
@@ -1157,6 +1204,16 @@ public:
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
+ unsigned deduceWeakPropertyFromType(QualType T) {
+ if ((getLangOpts().getGC() != LangOptions::NonGC &&
+ T.isObjCGCWeak()) ||
+ (getLangOpts().ObjCAutoRefCount &&
+ T.getObjCLifetime() == Qualifiers::OCL_Weak))
+ return ObjCDeclSpec::DQ_PR_weak;
+ return 0;
+ }
+
+
/// \brief Build a function type.
///
/// This routine checks the function type according to C++ rules and
@@ -1325,6 +1382,11 @@ public:
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
+ /// Determine if the template parameter \p D has a visible default argument.
+ bool
+ hasVisibleDefaultArgument(const NamedDecl *D,
+ llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
@@ -1727,6 +1789,22 @@ public:
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
+ /// Kinds of missing import. Note, the values of these enumerators correspond
+ /// to %select values in diagnostics.
+ enum class MissingImportKind {
+ Declaration,
+ Definition,
+ DefaultArgument
+ };
+
+ /// \brief Diagnose that the specified declaration needs to be visible but
+ /// isn't, and suggest a module import that would resolve the problem.
+ void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
+ bool NeedDefinition, bool Recover = true);
+ void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
+ SourceLocation DeclLoc, ArrayRef<Module *> Modules,
+ MissingImportKind MIK, bool Recover);
+
/// \brief Retrieve a suitable printing policy.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
@@ -1847,10 +1925,10 @@ public:
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
+ typedef void *SkippedDefinitionContext;
+
/// \brief Invoked when we enter a tag definition that we're skipping.
- void ActOnTagStartSkippedDefinition(Scope *S, Decl *TD) {
- PushDeclContext(S, cast<DeclContext>(TD));
- }
+ SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
@@ -1867,9 +1945,7 @@ public:
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceLocation RBraceLoc);
- void ActOnTagFinishSkippedDefinition() {
- PopDeclContext();
- }
+ void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
@@ -2819,6 +2895,7 @@ public:
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
+ void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
@@ -2839,6 +2916,26 @@ public:
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
+ /// Check whether a nullability type specifier can be added to the given
+ /// type.
+ ///
+ /// \param type The type to which the nullability specifier will be
+ /// added. On success, this type will be updated appropriately.
+ ///
+ /// \param nullability The nullability specifier to add.
+ ///
+ /// \param nullabilityLoc The location of the nullability specifier.
+ ///
+ /// \param isContextSensitive Whether this nullability specifier was
+ /// written as a context-sensitive keyword (in an Objective-C
+ /// method) or an Objective-C property attribute, rather than as an
+ /// underscored type specifier.
+ ///
+ /// \returns true if nullability cannot be applied, false otherwise.
+ bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
+ SourceLocation nullabilityLoc,
+ bool isContextSensitive);
+
/// \brief Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
SourceRange Range);
@@ -2878,6 +2975,9 @@ public:
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
+ /// Diagnose any null-resettable synthesized setters.
+ void diagnoseNullResettableSynthesizedSetters(ObjCImplDecl *impDecl);
+
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
@@ -2914,7 +3014,8 @@ public:
const unsigned Attributes,
const unsigned AttributesAsWritten,
bool *isOverridingProperty,
- TypeSourceInfo *T,
+ QualType T,
+ TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
@@ -2930,7 +3031,8 @@ public:
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
- TypeSourceInfo *T,
+ QualType T,
+ TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
@@ -7629,6 +7731,9 @@ public:
/// \brief Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
+ /// \brief Called on well-formed '\#pragma omp taskgroup'.
+ StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
+ SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
@@ -8557,9 +8662,10 @@ private:
const FunctionProtoType *Proto,
SourceLocation Loc);
- void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
- unsigned NumParams, bool IsMemberFunction, SourceLocation Loc,
- SourceRange Range, VariadicCallType CallType);
+ void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
+ ArrayRef<const Expr *> Args, bool IsMemberFunction,
+ SourceLocation Loc, SourceRange Range,
+ VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
@@ -8602,7 +8708,9 @@ private:
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High);
-
+ bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
+ int ArgNum, unsigned ExpectedFieldNum,
+ bool AllowName);
public:
enum FormatStringType {
FST_Scanf,
@@ -8731,6 +8839,13 @@ private:
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
+ /// Nullability type specifiers.
+ IdentifierInfo *Ident___nonnull = nullptr;
+ IdentifierInfo *Ident___nullable = nullptr;
+ IdentifierInfo *Ident___null_unspecified = nullptr;
+
+ IdentifierInfo *Ident_NSError = nullptr;
+
protected:
friend class Parser;
friend class InitializationSequence;
@@ -8739,6 +8854,15 @@ protected:
friend class ASTWriter;
public:
+ /// Retrieve the keyword associated
+ IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
+
+ /// The struct behind the CFErrorRef pointer.
+ RecordDecl *CFError = nullptr;
+
+ /// Retrieve the identifier "NSError".
+ IdentifierInfo *getNSErrorIdent();
+
/// \brief Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
diff --git a/include/clang/Serialization/ASTBitCodes.h b/include/clang/Serialization/ASTBitCodes.h
index e0f01c8a3545..83185a870ab1 100644
--- a/include/clang/Serialization/ASTBitCodes.h
+++ b/include/clang/Serialization/ASTBitCodes.h
@@ -1211,8 +1211,12 @@ namespace clang {
EXPR_INIT_LIST,
/// \brief A DesignatedInitExpr record.
EXPR_DESIGNATED_INIT,
+ /// \brief A DesignatedInitUpdateExpr record.
+ EXPR_DESIGNATED_INIT_UPDATE,
/// \brief An ImplicitValueInitExpr record.
EXPR_IMPLICIT_VALUE_INIT,
+ /// \brief An NoInitExpr record.
+ EXPR_NO_INIT,
/// \brief A VAArgExpr record.
EXPR_VA_ARG,
/// \brief An AddrLabelExpr record.
@@ -1392,6 +1396,7 @@ namespace clang {
STMT_OMP_ATOMIC_DIRECTIVE,
STMT_OMP_TARGET_DIRECTIVE,
STMT_OMP_TEAMS_DIRECTIVE,
+ STMT_OMP_TASKGROUP_DIRECTIVE,
// ARC
EXPR_OBJC_BRIDGED_CAST, // ObjCBridgedCastExpr
diff --git a/include/clang/Serialization/ASTReader.h b/include/clang/Serialization/ASTReader.h
index c7cc1be6e62c..429f00f852bb 100644
--- a/include/clang/Serialization/ASTReader.h
+++ b/include/clang/Serialization/ASTReader.h
@@ -362,6 +362,7 @@ private:
SourceManager &SourceMgr;
FileManager &FileMgr;
+ const PCHContainerOperations &PCHContainerOps;
DiagnosticsEngine &Diags;
/// \brief The semantic analysis object that will be processing the
@@ -1237,6 +1238,9 @@ public:
/// \param Context the AST context that this precompiled header will be
/// loaded into.
///
+ /// \param PCHContainerOps the PCHContainerOperations to use for loading and
+ /// creating modules.
+ ///
/// \param isysroot If non-NULL, the system include path specified by the
/// user. This is only used with relocatable PCH files. If non-NULL,
/// a relocatable PCH file will use the default path "/".
@@ -1258,12 +1262,12 @@ public:
///
/// \param UseGlobalIndex If true, the AST reader will try to load and use
/// the global module index.
- ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
- bool DisableValidation = false,
+ ASTReader(Preprocessor &PP, ASTContext &Context,
+ const PCHContainerOperations &PCHContainerOps,
+ StringRef isysroot = "", bool DisableValidation = false,
bool AllowASTWithCompilerErrors = false,
bool AllowConfigurationMismatch = false,
- bool ValidateSystemInputs = false,
- bool UseGlobalIndex = true);
+ bool ValidateSystemInputs = false, bool UseGlobalIndex = true);
~ASTReader() override;
@@ -1425,21 +1429,23 @@ public:
/// \brief Retrieve the name of the original source file name directly from
/// the AST file, without actually loading the AST file.
- static std::string getOriginalSourceFile(const std::string &ASTFileName,
- FileManager &FileMgr,
- DiagnosticsEngine &Diags);
+ static std::string
+ getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
+ const PCHContainerOperations &PCHContainerOps,
+ DiagnosticsEngine &Diags);
/// \brief Read the control block for the named AST file.
///
/// \returns true if an error occurred, false otherwise.
- static bool readASTFileControlBlock(StringRef Filename,
- FileManager &FileMgr,
- ASTReaderListener &Listener);
+ static bool
+ readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
+ const PCHContainerOperations &PCHContainerOps,
+ ASTReaderListener &Listener);
/// \brief Determine whether the given AST file is acceptable to load into a
/// translation unit with the given language and target options.
- static bool isAcceptableASTFile(StringRef Filename,
- FileManager &FileMgr,
+ static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
+ const PCHContainerOperations &PCHContainerOps,
const LangOptions &LangOpts,
const TargetOptions &TargetOpts,
const PreprocessorOptions &PPOpts,
diff --git a/include/clang/Serialization/ASTWriter.h b/include/clang/Serialization/ASTWriter.h
index 297ee22dfa68..decd07a00ed5 100644
--- a/include/clang/Serialization/ASTWriter.h
+++ b/include/clang/Serialization/ASTWriter.h
@@ -17,6 +17,7 @@
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclarationName.h"
+#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/AST/TemplateBase.h"
#include "clang/Sema/SemaConsumer.h"
#include "clang/Serialization/ASTBitCodes.h"
@@ -868,30 +869,28 @@ class PCHGenerator : public SemaConsumer {
std::string OutputFile;
clang::Module *Module;
std::string isysroot;
- raw_ostream *Out;
Sema *SemaPtr;
- SmallVector<char, 128> Buffer;
+ std::shared_ptr<PCHBuffer> Buffer;
llvm::BitstreamWriter Stream;
ASTWriter Writer;
bool AllowASTWithErrors;
- bool HasEmittedPCH;
protected:
ASTWriter &getWriter() { return Writer; }
const ASTWriter &getWriter() const { return Writer; }
+ SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
public:
PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
- clang::Module *Module,
- StringRef isysroot, raw_ostream *Out,
+ clang::Module *Module, StringRef isysroot,
+ std::shared_ptr<PCHBuffer> Buffer,
bool AllowASTWithErrors = false);
~PCHGenerator() override;
void InitializeSema(Sema &S) override { SemaPtr = &S; }
void HandleTranslationUnit(ASTContext &Ctx) override;
ASTMutationListener *GetASTMutationListener() override;
ASTDeserializationListener *GetASTDeserializationListener() override;
-
- bool hasEmittedPCH() const { return HasEmittedPCH; }
+ bool hasEmittedPCH() const { return Buffer->IsComplete; }
};
} // end namespace clang
diff --git a/include/clang/Serialization/GlobalModuleIndex.h b/include/clang/Serialization/GlobalModuleIndex.h
index 640c7bb34454..7e205106c4ee 100644
--- a/include/clang/Serialization/GlobalModuleIndex.h
+++ b/include/clang/Serialization/GlobalModuleIndex.h
@@ -35,6 +35,7 @@ class DirectoryEntry;
class FileEntry;
class FileManager;
class IdentifierIterator;
+class PCHContainerOperations;
namespace serialization {
class ModuleFile;
@@ -192,10 +193,13 @@ public:
/// \brief Write a global index into the given
///
/// \param FileMgr The file manager to use to load module files.
- ///
+ /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
+ /// creating modules.
/// \param Path The path to the directory containing module files, into
/// which the global index will be written.
- static ErrorCode writeIndex(FileManager &FileMgr, StringRef Path);
+ static ErrorCode writeIndex(FileManager &FileMgr,
+ const PCHContainerOperations &PCHContainerOps,
+ StringRef Path);
};
}
diff --git a/include/clang/Serialization/ModuleManager.h b/include/clang/Serialization/ModuleManager.h
index 3de86feb66b9..ea4b57fa3ace 100644
--- a/include/clang/Serialization/ModuleManager.h
+++ b/include/clang/Serialization/ModuleManager.h
@@ -24,6 +24,7 @@ namespace clang {
class GlobalModuleIndex;
class ModuleMap;
+class PCHContainerOperations;
namespace serialization {
@@ -49,7 +50,10 @@ class ModuleManager {
/// \brief FileManager that handles translating between filenames and
/// FileEntry *.
FileManager &FileMgr;
-
+
+ /// \brief Knows how to unwrap module containers.
+ const PCHContainerOperations &PCHContainerOps;
+
/// \brief A lookup of in-memory (virtual file) buffers
llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>>
InMemoryBuffers;
@@ -112,8 +116,9 @@ public:
typedef SmallVectorImpl<ModuleFile*>::const_iterator ModuleConstIterator;
typedef SmallVectorImpl<ModuleFile*>::reverse_iterator ModuleReverseIterator;
typedef std::pair<uint32_t, StringRef> ModuleOffset;
-
- explicit ModuleManager(FileManager &FileMgr);
+
+ explicit ModuleManager(FileManager &FileMgr,
+ const PCHContainerOperations &PCHContainerOps);
~ModuleManager();
/// \brief Forward iterator to traverse all loaded modules. This is reverse
diff --git a/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h b/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
index ab92a2465c53..5850656916e3 100644
--- a/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
+++ b/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
@@ -69,6 +69,14 @@ enum ArgEffect {
/// transfers the object to the Garbage Collector under GC.
MakeCollectable,
+ /// The argument is a pointer to a retain-counted object; on exit, the new
+ /// value of the pointer is a +0 value or NULL.
+ UnretainedOutParameter,
+
+ /// The argument is a pointer to a retain-counted object; on exit, the new
+ /// value of the pointer is a +1 value or NULL.
+ RetainedOutParameter,
+
/// The argument is treated as potentially escaping, meaning that
/// even when its reference count hits 0 it should be treated as still
/// possibly being alive as someone else *may* be holding onto the object.
diff --git a/include/clang/Tooling/Refactoring.h b/include/clang/Tooling/Refactoring.h
index e3e7f83c38c8..944fd41f85c1 100644
--- a/include/clang/Tooling/Refactoring.h
+++ b/include/clang/Tooling/Refactoring.h
@@ -38,7 +38,9 @@ class RefactoringTool : public ClangTool {
public:
/// \see ClangTool::ClangTool.
RefactoringTool(const CompilationDatabase &Compilations,
- ArrayRef<std::string> SourcePaths);
+ ArrayRef<std::string> SourcePaths,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
/// \brief Returns the set of replacements to which replacements should
/// be added during the run of the tool.
diff --git a/include/clang/Tooling/Tooling.h b/include/clang/Tooling/Tooling.h
index ca187b168448..fb887e1df9e8 100644
--- a/include/clang/Tooling/Tooling.h
+++ b/include/clang/Tooling/Tooling.h
@@ -31,11 +31,13 @@
#define LLVM_CLANG_TOOLING_TOOLING_H
#include "clang/AST/ASTConsumer.h"
+#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LLVM.h"
#include "clang/Driver/Util.h"
#include "clang/Frontend/FrontendAction.h"
+#include "clang/Lex/ModuleLoader.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "llvm/ADT/StringMap.h"
@@ -66,9 +68,10 @@ public:
virtual ~ToolAction();
/// \brief Perform an action for an invocation.
- virtual bool runInvocation(clang::CompilerInvocation *Invocation,
- FileManager *Files,
- DiagnosticConsumer *DiagConsumer) = 0;
+ virtual bool
+ runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagConsumer) = 0;
};
/// \brief Interface to generate clang::FrontendActions.
@@ -83,6 +86,7 @@ public:
/// \brief Invokes the compiler with a FrontendAction created by create().
bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *DiagConsumer) override;
/// \brief Returns a new clang::FrontendAction.
@@ -139,10 +143,14 @@ inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
/// \param ToolAction The action to run over the code.
/// \param Code C++ code.
/// \param FileName The file name which 'Code' will be mapped as.
+/// \param PCHContainerOps The PCHContainerOperations for loading and creating
+/// clang modules.
///
/// \return - True if 'ToolAction' was successfully executed.
bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
- const Twine &FileName = "input.cc");
+ const Twine &FileName = "input.cc",
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
/// The first part of the pair is the filename, the second part the
/// file-content.
@@ -155,37 +163,48 @@ typedef std::vector<std::pair<std::string, std::string>> FileContentMappings;
/// \param Code C++ code.
/// \param Args Additional flags to pass on.
/// \param FileName The file name which 'Code' will be mapped as.
+/// \param PCHContainerOps The PCHContainerOperations for loading and creating
+/// clang modules.
///
/// \return - True if 'ToolAction' was successfully executed.
bool runToolOnCodeWithArgs(
clang::FrontendAction *ToolAction, const Twine &Code,
const std::vector<std::string> &Args, const Twine &FileName = "input.cc",
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>(),
const FileContentMappings &VirtualMappedFiles = FileContentMappings());
/// \brief Builds an AST for 'Code'.
///
/// \param Code C++ code.
/// \param FileName The file name which 'Code' will be mapped as.
+/// \param PCHContainerOps The PCHContainerOperations for loading and creating
+/// clang modules.
///
/// \return The resulting AST or null if an error occurred.
-std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code,
- const Twine &FileName = "input.cc");
+std::unique_ptr<ASTUnit>
+buildASTFromCode(const Twine &Code, const Twine &FileName = "input.cc",
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
/// \brief Builds an AST for 'Code' with additional flags.
///
/// \param Code C++ code.
/// \param Args Additional flags to pass on.
/// \param FileName The file name which 'Code' will be mapped as.
+/// \param PCHContainerOps The PCHContainerOperations for loading and creating
+/// clang modules.
///
/// \return The resulting AST or null if an error occurred.
-std::unique_ptr<ASTUnit>
-buildASTFromCodeWithArgs(const Twine &Code,
- const std::vector<std::string> &Args,
- const Twine &FileName = "input.cc");
+std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
+ const Twine &Code, const std::vector<std::string> &Args,
+ const Twine &FileName = "input.cc",
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
/// \brief Utility to run a FrontendAction in a single clang invocation.
class ToolInvocation {
- public:
+public:
/// \brief Create a tool invocation.
///
/// \param CommandLine The command line arguments to clang. Note that clang
@@ -195,16 +214,23 @@ class ToolInvocation {
/// \param FAction The action to be executed. Class takes ownership.
/// \param Files The FileManager used for the execution. Class does not take
/// ownership.
+ /// \param PCHContainerOps The PCHContainerOperations for loading and creating
+ /// clang modules.
ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction,
- FileManager *Files);
+ FileManager *Files,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
/// \brief Create a tool invocation.
///
/// \param CommandLine The command line arguments to clang.
/// \param Action The action to be executed.
/// \param Files The FileManager used for the execution.
+ /// \param PCHContainerOps The PCHContainerOperations for loading and creating
+ /// clang modules.
ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action,
- FileManager *Files);
+ FileManager *Files,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps);
~ToolInvocation();
@@ -229,12 +255,14 @@ class ToolInvocation {
bool runInvocation(const char *BinaryName,
clang::driver::Compilation *Compilation,
- clang::CompilerInvocation *Invocation);
+ clang::CompilerInvocation *Invocation,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps);
std::vector<std::string> CommandLine;
ToolAction *Action;
bool OwnsAction;
FileManager *Files;
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps;
// Maps <file name> -> <file content>.
llvm::StringMap<StringRef> MappedFileContents;
DiagnosticConsumer *DiagConsumer;
@@ -255,8 +283,12 @@ class ClangTool {
/// command lines for the given source paths.
/// \param SourcePaths The source files to run over. If a source files is
/// not found in Compilations, it is skipped.
+ /// \param PCHContainerOps The PCHContainerOperations for loading and creating
+ /// clang modules.
ClangTool(const CompilationDatabase &Compilations,
- ArrayRef<std::string> SourcePaths);
+ ArrayRef<std::string> SourcePaths,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps =
+ std::make_shared<RawPCHContainerOperations>());
~ClangTool();
@@ -297,6 +329,7 @@ class ClangTool {
private:
const CompilationDatabase &Compilations;
std::vector<std::string> SourcePaths;
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps;
llvm::IntrusiveRefCntPtr<FileManager> Files;
// Contains a list of pairs (<file name>, <file content>).
diff --git a/lib/ARCMigrate/ARCMT.cpp b/lib/ARCMigrate/ARCMT.cpp
index f266eaf83968..f33ad21cf029 100644
--- a/lib/ARCMigrate/ARCMT.cpp
+++ b/lib/ARCMigrate/ARCMT.cpp
@@ -166,7 +166,8 @@ static bool HasARCRuntime(CompilerInvocation &origCI) {
}
static CompilerInvocation *
-createInvocationForMigration(CompilerInvocation &origCI) {
+createInvocationForMigration(CompilerInvocation &origCI,
+ const PCHContainerOperations &PCHContainerOps) {
std::unique_ptr<CompilerInvocation> CInvok;
CInvok.reset(new CompilerInvocation(origCI));
PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
@@ -178,9 +179,8 @@ createInvocationForMigration(CompilerInvocation &origCI) {
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
new IgnoringDiagConsumer()));
- std::string OriginalFile =
- ASTReader::getOriginalSourceFile(PPOpts.ImplicitPCHInclude,
- FileMgr, *Diags);
+ std::string OriginalFile = ASTReader::getOriginalSourceFile(
+ PPOpts.ImplicitPCHInclude, FileMgr, PCHContainerOps, *Diags);
if (!OriginalFile.empty())
PPOpts.Includes.insert(PPOpts.Includes.begin(), OriginalFile);
PPOpts.ImplicitPCHInclude.clear();
@@ -230,11 +230,11 @@ static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
// checkForManualIssues.
//===----------------------------------------------------------------------===//
-bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient,
- bool emitPremigrationARCErrors,
- StringRef plistOut) {
+bool arcmt::checkForManualIssues(
+ CompilerInvocation &origCI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient, bool emitPremigrationARCErrors,
+ StringRef plistOut) {
if (!origCI.getLangOpts()->ObjC1)
return false;
@@ -247,7 +247,7 @@ bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
assert(!transforms.empty());
std::unique_ptr<CompilerInvocation> CInvok;
- CInvok.reset(createInvocationForMigration(origCI));
+ CInvok.reset(createInvocationForMigration(origCI, *PCHContainerOps));
CInvok->getFrontendOpts().Inputs.clear();
CInvok->getFrontendOpts().Inputs.push_back(Input);
@@ -263,8 +263,8 @@ bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
- std::unique_ptr<ASTUnit> Unit(
- ASTUnit::LoadFromCompilerInvocationAction(CInvok.release(), Diags));
+ std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
+ CInvok.release(), PCHContainerOps, Diags));
if (!Unit) {
errRec.FinishCapture();
return true;
@@ -330,12 +330,11 @@ bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
// applyTransformations.
//===----------------------------------------------------------------------===//
-static bool applyTransforms(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient,
- StringRef outputDir,
- bool emitPremigrationARCErrors,
- StringRef plistOut) {
+static bool
+applyTransforms(CompilerInvocation &origCI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient, StringRef outputDir,
+ bool emitPremigrationARCErrors, StringRef plistOut) {
if (!origCI.getLangOpts()->ObjC1)
return false;
@@ -343,15 +342,16 @@ static bool applyTransforms(CompilerInvocation &origCI,
// Make sure checking is successful first.
CompilerInvocation CInvokForCheck(origCI);
- if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
- emitPremigrationARCErrors, plistOut))
+ if (arcmt::checkForManualIssues(CInvokForCheck, Input, PCHContainerOps,
+ DiagClient, emitPremigrationARCErrors,
+ plistOut))
return true;
CompilerInvocation CInvok(origCI);
CInvok.getFrontendOpts().Inputs.clear();
CInvok.getFrontendOpts().Inputs.push_back(Input);
-
- MigrationProcess migration(CInvok, DiagClient, outputDir);
+
+ MigrationProcess migration(CInvok, PCHContainerOps, DiagClient, outputDir);
bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
@@ -376,22 +376,22 @@ static bool applyTransforms(CompilerInvocation &origCI,
}
}
-bool arcmt::applyTransformations(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient) {
- return applyTransforms(origCI, Input, DiagClient,
+bool arcmt::applyTransformations(
+ CompilerInvocation &origCI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient) {
+ return applyTransforms(origCI, Input, PCHContainerOps, DiagClient,
StringRef(), false, StringRef());
}
-bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
- const FrontendInputFile &Input,
- DiagnosticConsumer *DiagClient,
- StringRef outputDir,
- bool emitPremigrationARCErrors,
- StringRef plistOut) {
+bool arcmt::migrateWithTemporaryFiles(
+ CompilerInvocation &origCI, const FrontendInputFile &Input,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *DiagClient, StringRef outputDir,
+ bool emitPremigrationARCErrors, StringRef plistOut) {
assert(!outputDir.empty() && "Expected output directory path");
- return applyTransforms(origCI, Input, DiagClient,
- outputDir, emitPremigrationARCErrors, plistOut);
+ return applyTransforms(origCI, Input, PCHContainerOps, DiagClient, outputDir,
+ emitPremigrationARCErrors, plistOut);
}
bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
@@ -499,10 +499,12 @@ public:
/// \brief Anchor for VTable.
MigrationProcess::RewriteListener::~RewriteListener() { }
-MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
- DiagnosticConsumer *diagClient,
- StringRef outputDir)
- : OrigCI(CI), DiagClient(diagClient), HadARCErrors(false) {
+MigrationProcess::MigrationProcess(
+ const CompilerInvocation &CI,
+ std::shared_ptr<PCHContainerOperations> PCHContainerOps,
+ DiagnosticConsumer *diagClient, StringRef outputDir)
+ : OrigCI(CI), PCHContainerOps(PCHContainerOps), DiagClient(diagClient),
+ HadARCErrors(false) {
if (!outputDir.empty()) {
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
@@ -515,7 +517,7 @@ MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
bool MigrationProcess::applyTransform(TransformFn trans,
RewriteListener *listener) {
std::unique_ptr<CompilerInvocation> CInvok;
- CInvok.reset(createInvocationForMigration(OrigCI));
+ CInvok.reset(createInvocationForMigration(OrigCI, *PCHContainerOps));
CInvok->getDiagnosticOpts().IgnoreWarnings = true;
Remapper.applyMappings(CInvok->getPreprocessorOpts());
@@ -537,7 +539,7 @@ bool MigrationProcess::applyTransform(TransformFn trans,
ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
- CInvok.release(), Diags, ASTAction.get()));
+ CInvok.release(), PCHContainerOps, Diags, ASTAction.get()));
if (!Unit) {
errRec.FinishCapture();
return true;
diff --git a/lib/ARCMigrate/ARCMTActions.cpp b/lib/ARCMigrate/ARCMTActions.cpp
index 0ed36ddf68c8..39a922f426c3 100644
--- a/lib/ARCMigrate/ARCMTActions.cpp
+++ b/lib/ARCMigrate/ARCMTActions.cpp
@@ -16,6 +16,7 @@ using namespace arcmt;
bool CheckAction::BeginInvocation(CompilerInstance &CI) {
if (arcmt::checkForManualIssues(CI.getInvocation(), getCurrentInput(),
+ CI.getPCHContainerOperations(),
CI.getDiagnostics().getClient()))
return false; // errors, stop the action.
@@ -29,6 +30,7 @@ CheckAction::CheckAction(FrontendAction *WrappedAction)
bool ModifyAction::BeginInvocation(CompilerInstance &CI) {
return !arcmt::applyTransformations(CI.getInvocation(), getCurrentInput(),
+ CI.getPCHContainerOperations(),
CI.getDiagnostics().getClient());
}
@@ -36,12 +38,10 @@ ModifyAction::ModifyAction(FrontendAction *WrappedAction)
: WrapperFrontendAction(WrappedAction) {}
bool MigrateAction::BeginInvocation(CompilerInstance &CI) {
- if (arcmt::migrateWithTemporaryFiles(CI.getInvocation(),
- getCurrentInput(),
- CI.getDiagnostics().getClient(),
- MigrateDir,
- EmitPremigrationARCErros,
- PlistOut))
+ if (arcmt::migrateWithTemporaryFiles(
+ CI.getInvocation(), getCurrentInput(), CI.getPCHContainerOperations(),
+ CI.getDiagnostics().getClient(), MigrateDir, EmitPremigrationARCErros,
+ PlistOut))
return false; // errors, stop the action.
// We only want to see diagnostics emitted by migrateWithTemporaryFiles.
diff --git a/lib/AST/ASTConsumer.cpp b/lib/AST/ASTConsumer.cpp
index 55033b238c66..cff82e9b1003 100644
--- a/lib/AST/ASTConsumer.cpp
+++ b/lib/AST/ASTConsumer.cpp
@@ -12,6 +12,7 @@
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
+#include "llvm/Bitcode/BitstreamReader.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
using namespace clang;
diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp
index 4a831d90e645..049eebd82b66 100644
--- a/lib/AST/ASTContext.cpp
+++ b/lib/AST/ASTContext.cpp
@@ -5610,8 +5610,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
// @encode(class_name)
ObjCInterfaceDecl *OI = OIT->getDecl();
S += '{';
- const IdentifierInfo *II = OI->getIdentifier();
- S += II->getName();
+ S += OI->getObjCRuntimeNameAsString();
S += '=';
SmallVector<const ObjCIvarDecl*, 32> Ivars;
DeepCollectObjCIvars(OI, true, Ivars);
@@ -5654,7 +5653,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
S += '"';
for (const auto *I : OPT->quals()) {
S += '<';
- S += I->getNameAsString();
+ S += I->getObjCRuntimeNameAsString();
S += '>';
}
S += '"';
@@ -5678,7 +5677,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
if (cast<FieldDecl>(Ivars[i]) == FD) {
S += '{';
- S += OI->getIdentifier()->getName();
+ S += OI->getObjCRuntimeNameAsString();
S += '}';
return;
}
@@ -5696,10 +5695,10 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
if (OPT->getInterfaceDecl() &&
(FD || EncodingProperty || EncodeClassNames)) {
S += '"';
- S += OPT->getInterfaceDecl()->getIdentifier()->getName();
+ S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
for (const auto *I : OPT->quals()) {
S += '<';
- S += I->getNameAsString();
+ S += I->getObjCRuntimeNameAsString();
S += '>';
}
S += '"';
diff --git a/lib/AST/ASTImporter.cpp b/lib/AST/ASTImporter.cpp
index 911f1681ce61..76e4e1191501 100644
--- a/lib/AST/ASTImporter.cpp
+++ b/lib/AST/ASTImporter.cpp
@@ -3922,8 +3922,8 @@ Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
}
// Import the type.
- TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
- if (!T)
+ TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
+ if (!TSI)
return nullptr;
// Create the new property.
@@ -3932,7 +3932,8 @@ Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
Name.getAsIdentifierInfo(),
Importer.Import(D->getAtLoc()),
Importer.Import(D->getLParenLoc()),
- T,
+ Importer.Import(D->getType()),
+ TSI,
D->getPropertyImplementation());
Importer.Imported(D, ToProperty);
ToProperty->setLexicalDeclContext(LexicalDC);
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index 8eff4c4427b3..d9a3389c58f3 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -3681,7 +3681,8 @@ void RecordDecl::LoadFieldsFromExternalStorage() const {
bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
ASTContext &Context = getASTContext();
- if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
+ if (!Context.getLangOpts().Sanitize.hasOneOf(
+ SanitizerKind::Address | SanitizerKind::KernelAddress) ||
!Context.getLangOpts().SanitizeAddressFieldPadding)
return false;
const auto &Blacklist = Context.getSanitizerBlacklist();
diff --git a/lib/AST/DeclObjC.cpp b/lib/AST/DeclObjC.cpp
index a63ba7e698a8..a1600cb11014 100644
--- a/lib/AST/DeclObjC.cpp
+++ b/lib/AST/DeclObjC.cpp
@@ -1862,16 +1862,18 @@ ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
IdentifierInfo *Id,
SourceLocation AtLoc,
SourceLocation LParenLoc,
- TypeSourceInfo *T,
+ QualType T,
+ TypeSourceInfo *TSI,
PropertyControl propControl) {
- return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T);
+ return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
+ propControl);
}
ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
unsigned ID) {
return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
SourceLocation(), SourceLocation(),
- nullptr);
+ QualType(), nullptr, None);
}
//===----------------------------------------------------------------------===//
diff --git a/lib/AST/DeclPrinter.cpp b/lib/AST/DeclPrinter.cpp
index d8cd40ec9c60..c3ce47600972 100644
--- a/lib/AST/DeclPrinter.cpp
+++ b/lib/AST/DeclPrinter.cpp
@@ -37,6 +37,13 @@ namespace {
void Print(AccessSpecifier AS);
+ /// Print an Objective-C method type in parentheses.
+ ///
+ /// \param Quals The Objective-C declaration qualifiers.
+ /// \param T The type to print.
+ void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,
+ QualType T);
+
public:
DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
unsigned Indentation = 0, bool PrintInstantiation = false)
@@ -930,24 +937,52 @@ void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
// Objective-C declarations
//----------------------------------------------------------------------------
+void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
+ Decl::ObjCDeclQualifier Quals,
+ QualType T) {
+ Out << '(';
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
+ Out << "in ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
+ Out << "inout ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
+ Out << "out ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
+ Out << "bycopy ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
+ Out << "byref ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
+ Out << "oneway ";
+ if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
+ if (auto nullability = AttributedType::stripOuterNullability(T)) {
+ Out << getNullabilitySpelling(*nullability).substr(2) << ' ';
+ }
+ }
+
+ Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
+ Out << ')';
+}
+
void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
if (OMD->isInstanceMethod())
Out << "- ";
else
Out << "+ ";
- if (!OMD->getReturnType().isNull())
- Out << '(' << OMD->getASTContext()
- .getUnqualifiedObjCPointerType(OMD->getReturnType())
- .getAsString(Policy) << ")";
+ if (!OMD->getReturnType().isNull()) {
+ PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
+ OMD->getReturnType());
+ }
std::string name = OMD->getSelector().getAsString();
std::string::size_type pos, lastPos = 0;
for (const auto *PI : OMD->params()) {
// FIXME: selector is missing here!
pos = name.find_first_of(':', lastPos);
- Out << " " << name.substr(lastPos, pos - lastPos);
- Out << ":(" << PI->getASTContext().getUnqualifiedObjCPointerType(PI->getType()).
- getAsString(Policy) << ')' << *PI;
+ Out << " " << name.substr(lastPos, pos - lastPos) << ':';
+ PrintObjCMethodType(OMD->getASTContext(),
+ PI->getObjCDeclQualifier(),
+ PI->getType());
+ Out << *PI;
lastPos = pos + 1;
}
@@ -1103,6 +1138,8 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
Out << "@optional\n";
+ QualType T = PDecl->getType();
+
Out << "@property";
if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
bool first = true;
@@ -1161,10 +1198,25 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
first = false;
}
+ if (PDecl->getPropertyAttributes() &
+ ObjCPropertyDecl::OBJC_PR_nullability) {
+ if (auto nullability = AttributedType::stripOuterNullability(T)) {
+ if (*nullability == NullabilityKind::Unspecified &&
+ (PDecl->getPropertyAttributes() &
+ ObjCPropertyDecl::OBJC_PR_null_resettable)) {
+ Out << (first ? ' ' : ',') << "null_resettable";
+ } else {
+ Out << (first ? ' ' : ',')
+ << getNullabilitySpelling(*nullability).substr(2);
+ }
+ first = false;
+ }
+ }
+
(void) first; // Silence dead store warning due to idiomatic code.
Out << " )";
}
- Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()).
+ Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
getAsString(Policy) << ' ' << *PDecl;
if (Policy.PolishForDeclaration)
Out << ';';
diff --git a/lib/AST/DeclTemplate.cpp b/lib/AST/DeclTemplate.cpp
index 6374a92621a4..cde497b012e2 100644
--- a/lib/AST/DeclTemplate.cpp
+++ b/lib/AST/DeclTemplate.cpp
@@ -124,6 +124,12 @@ static void AdoptTemplateParameterList(TemplateParameterList *Params,
}
}
+namespace clang {
+void *allocateDefaultArgStorageChain(const ASTContext &C) {
+ return new (C) char[sizeof(void*) * 2];
+}
+}
+
//===----------------------------------------------------------------------===//
// RedeclarableTemplateDecl Implementation
//===----------------------------------------------------------------------===//
@@ -504,14 +510,14 @@ TemplateTypeParmDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
SourceLocation TemplateTypeParmDecl::getDefaultArgumentLoc() const {
return hasDefaultArgument()
- ? DefaultArgument->getTypeLoc().getBeginLoc()
- : SourceLocation();
+ ? getDefaultArgumentInfo()->getTypeLoc().getBeginLoc()
+ : SourceLocation();
}
SourceRange TemplateTypeParmDecl::getSourceRange() const {
if (hasDefaultArgument() && !defaultArgumentWasInherited())
return SourceRange(getLocStart(),
- DefaultArgument->getTypeLoc().getEndLoc());
+ getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
else
return TypeDecl::getSourceRange();
}
@@ -543,10 +549,8 @@ NonTypeTemplateParmDecl::NonTypeTemplateParmDecl(DeclContext *DC,
unsigned NumExpandedTypes,
TypeSourceInfo **ExpandedTInfos)
: DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
- TemplateParmPosition(D, P), DefaultArgumentAndInherited(nullptr, false),
- ParameterPack(true), ExpandedParameterPack(true),
- NumExpandedTypes(NumExpandedTypes)
-{
+ TemplateParmPosition(D, P), ParameterPack(true),
+ ExpandedParameterPack(true), NumExpandedTypes(NumExpandedTypes) {
if (ExpandedTypes && ExpandedTInfos) {
void **TypesAndInfos = reinterpret_cast<void **>(this + 1);
for (unsigned I = 0; I != NumExpandedTypes; ++I) {
@@ -621,8 +625,7 @@ TemplateTemplateParmDecl::TemplateTemplateParmDecl(
IdentifierInfo *Id, TemplateParameterList *Params,
unsigned NumExpansions, TemplateParameterList * const *Expansions)
: TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
- TemplateParmPosition(D, P), DefaultArgument(),
- DefaultArgumentWasInherited(false), ParameterPack(true),
+ TemplateParmPosition(D, P), ParameterPack(true),
ExpandedParameterPack(true), NumExpandedParams(NumExpansions) {
if (Expansions)
std::memcpy(reinterpret_cast<void*>(this + 1), Expansions,
@@ -663,6 +666,19 @@ TemplateTemplateParmDecl::CreateDeserialized(ASTContext &C, unsigned ID,
nullptr, NumExpansions, nullptr);
}
+SourceLocation TemplateTemplateParmDecl::getDefaultArgumentLoc() const {
+ return hasDefaultArgument() ? getDefaultArgument().getLocation()
+ : SourceLocation();
+}
+
+void TemplateTemplateParmDecl::setDefaultArgument(
+ const ASTContext &C, const TemplateArgumentLoc &DefArg) {
+ if (DefArg.getArgument().isNull())
+ DefaultArgument.set(nullptr);
+ else
+ DefaultArgument.set(new (C) TemplateArgumentLoc(DefArg));
+}
+
//===----------------------------------------------------------------------===//
// TemplateArgumentList Implementation
//===----------------------------------------------------------------------===//
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index 76a4da2371b5..36f4139f8352 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -1238,7 +1238,7 @@ unsigned CallExpr::getBuiltinCallee() const {
return FDecl->getBuiltinID();
}
-bool CallExpr::isUnevaluatedBuiltinCall(ASTContext &Ctx) const {
+bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
if (unsigned BI = getBuiltinCallee())
return Ctx.BuiltinInfo.isUnevaluated(BI);
return false;
@@ -2772,6 +2772,11 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
return Exp->isConstantInitializer(Ctx, false, Culprit);
}
+ case DesignatedInitUpdateExprClass: {
+ const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
+ return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
+ DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
+ }
case InitListExprClass: {
const InitListExpr *ILE = cast<InitListExpr>(this);
if (ILE->getType()->isArrayType()) {
@@ -2818,6 +2823,7 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
break;
}
case ImplicitValueInitExprClass:
+ case NoInitExprClass:
return true;
case ParenExprClass:
return cast<ParenExpr>(this)->getSubExpr()
@@ -2881,6 +2887,28 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
return false;
}
+namespace {
+ /// \brief Look for any side effects within a Stmt.
+ class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
+ typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
+ const bool IncludePossibleEffects;
+ bool HasSideEffects;
+
+ public:
+ explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
+ : Inherited(Context),
+ IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
+
+ bool hasSideEffects() const { return HasSideEffects; }
+
+ void VisitExpr(const Expr *E) {
+ if (!HasSideEffects &&
+ E->HasSideEffects(Context, IncludePossibleEffects))
+ HasSideEffects = true;
+ }
+ };
+}
+
bool Expr::HasSideEffects(const ASTContext &Ctx,
bool IncludePossibleEffects) const {
// In circumstances where we care about definite side effects instead of
@@ -2925,6 +2953,7 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
case UnaryExprOrTypeTraitExprClass:
case AddrLabelExprClass:
case GNUNullExprClass:
+ case NoInitExprClass:
case CXXBoolLiteralExprClass:
case CXXNullPtrLiteralExprClass:
case CXXThisExprClass:
@@ -2967,7 +2996,6 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
case CompoundAssignOperatorClass:
case VAArgExprClass:
case AtomicExprClass:
- case StmtExprClass:
case CXXThrowExprClass:
case CXXNewExprClass:
case CXXDeleteExprClass:
@@ -2975,6 +3003,13 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
// These always have a side-effect.
return true;
+ case StmtExprClass: {
+ // StmtExprs have a side-effect if any substatement does.
+ SideEffectFinder Finder(Ctx, IncludePossibleEffects);
+ Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
+ return Finder.hasSideEffects();
+ }
+
case ParenExprClass:
case ArraySubscriptExprClass:
case MemberExprClass:
@@ -2983,6 +3018,7 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
case CompoundLiteralExprClass:
case ExtVectorElementExprClass:
case DesignatedInitExprClass:
+ case DesignatedInitUpdateExprClass:
case ParenListExprClass:
case CXXPseudoDestructorExprClass:
case CXXStdInitializerListExprClass:
@@ -3128,21 +3164,21 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
namespace {
/// \brief Look for a call to a non-trivial function within an expression.
- class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
+ class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
{
- typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
-
+ typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
+
bool NonTrivial;
public:
- explicit NonTrivialCallFinder(ASTContext &Context)
+ explicit NonTrivialCallFinder(const ASTContext &Context)
: Inherited(Context), NonTrivial(false) { }
bool hasNonTrivialCall() const { return NonTrivial; }
-
- void VisitCallExpr(CallExpr *E) {
- if (CXXMethodDecl *Method
- = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
+
+ void VisitCallExpr(const CallExpr *E) {
+ if (const CXXMethodDecl *Method
+ = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
if (Method->isTrivial()) {
// Recurse to children of the call.
Inherited::VisitStmt(E);
@@ -3152,8 +3188,8 @@ namespace {
NonTrivial = true;
}
-
- void VisitCXXConstructExpr(CXXConstructExpr *E) {
+
+ void VisitCXXConstructExpr(const CXXConstructExpr *E) {
if (E->getConstructor()->isTrivial()) {
// Recurse to children of the call.
Inherited::VisitStmt(E);
@@ -3162,8 +3198,8 @@ namespace {
NonTrivial = true;
}
-
- void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
+
+ void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
if (E->getTemporary()->getDestructor()->isTrivial()) {
Inherited::VisitStmt(E);
return;
@@ -3174,7 +3210,7 @@ namespace {
};
}
-bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
+bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
NonTrivialCallFinder Finder(Ctx);
Finder.Visit(this);
return Finder.hasNonTrivialCall();
@@ -3989,6 +4025,25 @@ void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
NumDesignators = NumDesignators - 1 + NumNewDesignators;
}
+DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
+ SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
+ : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
+ OK_Ordinary, false, false, false, false) {
+ BaseAndUpdaterExprs[0] = baseExpr;
+
+ InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
+ ILE->setType(baseExpr->getType());
+ BaseAndUpdaterExprs[1] = ILE;
+}
+
+SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
+ return getBase()->getLocStart();
+}
+
+SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
+ return getBase()->getLocEnd();
+}
+
ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
ArrayRef<Expr*> exprs,
SourceLocation rparenloc)
diff --git a/lib/AST/ExprClassification.cpp b/lib/AST/ExprClassification.cpp
index 5b320c2694ab..9cc612eae9b7 100644
--- a/lib/AST/ExprClassification.cpp
+++ b/lib/AST/ExprClassification.cpp
@@ -183,6 +183,8 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
case Expr::ObjCIndirectCopyRestoreExprClass:
case Expr::AtomicExprClass:
case Expr::CXXFoldExprClass:
+ case Expr::NoInitExprClass:
+ case Expr::DesignatedInitUpdateExprClass:
return Cl::CL_PRValue;
// Next come the complicated cases.
diff --git a/lib/AST/ExprConstant.cpp b/lib/AST/ExprConstant.cpp
index be24a2ae2c8c..8e472f174140 100644
--- a/lib/AST/ExprConstant.cpp
+++ b/lib/AST/ExprConstant.cpp
@@ -8675,6 +8675,8 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
case Expr::CompoundLiteralExprClass:
case Expr::ExtVectorElementExprClass:
case Expr::DesignatedInitExprClass:
+ case Expr::NoInitExprClass:
+ case Expr::DesignatedInitUpdateExprClass:
case Expr::ImplicitValueInitExprClass:
case Expr::ParenListExprClass:
case Expr::VAArgExprClass:
diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp
index d07efaee7bba..e5a31f879b76 100644
--- a/lib/AST/ItaniumMangle.cpp
+++ b/lib/AST/ItaniumMangle.cpp
@@ -2010,7 +2010,11 @@ void CXXNameMangler::mangleType(const BuiltinType *T) {
case BuiltinType::Half: Out << "Dh"; break;
case BuiltinType::Float: Out << 'f'; break;
case BuiltinType::Double: Out << 'd'; break;
- case BuiltinType::LongDouble: Out << 'e'; break;
+ case BuiltinType::LongDouble:
+ Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
+ ? 'g'
+ : 'e');
+ break;
case BuiltinType::NullPtr: Out << "Dn"; break;
#define BUILTIN_TYPE(Id, SingletonId)
@@ -2676,7 +2680,9 @@ recurse:
// These all can only appear in local or variable-initialization
// contexts and so should never appear in a mangling.
case Expr::AddrLabelExprClass:
+ case Expr::DesignatedInitUpdateExprClass:
case Expr::ImplicitValueInitExprClass:
+ case Expr::NoInitExprClass:
case Expr::ParenListExprClass:
case Expr::LambdaExprClass:
case Expr::MSPropertyRefExprClass:
@@ -4060,8 +4066,7 @@ void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
raw_ostream &Out) {
- Linkage L = RD->getLinkageInternal();
- if (L == InternalLinkage || L == UniqueExternalLinkage) {
+ if (!RD->isExternallyVisible()) {
// This part of the identifier needs to be unique across all translation
// units in the linked program. The scheme fails if multiple translation
// units are compiled using the same relative source file path, or if
diff --git a/lib/AST/MicrosoftCXXABI.cpp b/lib/AST/MicrosoftCXXABI.cpp
index 93ff77a2e964..aba6796256a7 100644
--- a/lib/AST/MicrosoftCXXABI.cpp
+++ b/lib/AST/MicrosoftCXXABI.cpp
@@ -179,8 +179,9 @@ MSVtorDispAttr::Mode CXXRecordDecl::getMSVtorDispMode() const {
// // slot.
// void *FunctionPointerOrVirtualThunk;
//
-// // An offset to add to the address of the vbtable pointer after (possibly)
-// // selecting the virtual base but before resolving and calling the function.
+// // An offset to add to the address of the vbtable pointer after
+// // (possibly) selecting the virtual base but before resolving and calling
+// // the function.
// // Only needed if the class has any virtual bases or bases at a non-zero
// // offset.
// int NonVirtualBaseAdjustment;
diff --git a/lib/AST/MicrosoftMangle.cpp b/lib/AST/MicrosoftMangle.cpp
index db5b48e5672d..29a95a5103ce 100644
--- a/lib/AST/MicrosoftMangle.cpp
+++ b/lib/AST/MicrosoftMangle.cpp
@@ -2761,7 +2761,17 @@ void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
raw_ostream &Out) {
- llvm::report_fatal_error("Cannot mangle bitsets yet");
+ if (!RD->isExternallyVisible()) {
+ // This part of the identifier needs to be unique across all translation
+ // units in the linked program. The scheme fails if multiple translation
+ // units are compiled using the same relative source file path, or if
+ // multiple translation units are built from the same source file.
+ SourceManager &SM = getASTContext().getSourceManager();
+ Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
+ }
+
+ MicrosoftCXXNameMangler mangler(*this, Out);
+ mangler.mangleName(RD);
}
MicrosoftMangleContext *
diff --git a/lib/AST/RecordLayoutBuilder.cpp b/lib/AST/RecordLayoutBuilder.cpp
index 2101a5534a6b..388c91c9cbc0 100644
--- a/lib/AST/RecordLayoutBuilder.cpp
+++ b/lib/AST/RecordLayoutBuilder.cpp
@@ -1467,7 +1467,7 @@ void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
// ms_struct basically requests a complete replacement of the
// platform ABI's struct-layout algorithm, with the high-level goal
// of duplicating MSVC's layout. For non-bitfields, this follows
- // the the standard algorithm. The basic bitfield layout rule is to
+ // the standard algorithm. The basic bitfield layout rule is to
// allocate an entire unit of the bitfield's declared type
// (e.g. 'unsigned long'), then parcel it up among successive
// bitfields whose declared types have the same size, making a new
diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp
index 09bb17b0e701..6f4a89fee39c 100644
--- a/lib/AST/Stmt.cpp
+++ b/lib/AST/Stmt.cpp
@@ -1636,7 +1636,7 @@ OMPSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc,
Dir->setLastIteration(Exprs.LastIteration);
Dir->setCalcLastIteration(Exprs.CalcLastIteration);
Dir->setPreCond(Exprs.PreCond);
- Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+ Dir->setCond(Exprs.Cond);
Dir->setInit(Exprs.Init);
Dir->setInc(Exprs.Inc);
Dir->setCounters(Exprs.Counters);
@@ -1675,7 +1675,7 @@ OMPForDirective::Create(const ASTContext &C, SourceLocation StartLoc,
Dir->setLastIteration(Exprs.LastIteration);
Dir->setCalcLastIteration(Exprs.CalcLastIteration);
Dir->setPreCond(Exprs.PreCond);
- Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+ Dir->setCond(Exprs.Cond);
Dir->setInit(Exprs.Init);
Dir->setInc(Exprs.Inc);
Dir->setIsLastIterVariable(Exprs.IL);
@@ -1721,7 +1721,7 @@ OMPForSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc,
Dir->setLastIteration(Exprs.LastIteration);
Dir->setCalcLastIteration(Exprs.CalcLastIteration);
Dir->setPreCond(Exprs.PreCond);
- Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+ Dir->setCond(Exprs.Cond);
Dir->setInit(Exprs.Init);
Dir->setInc(Exprs.Inc);
Dir->setIsLastIterVariable(Exprs.IL);
@@ -1777,7 +1777,7 @@ OMPSectionDirective *OMPSectionDirective::Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AssociatedStmt) {
- unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPSectionsDirective),
+ unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPSectionDirective),
llvm::alignOf<Stmt *>());
void *Mem = C.Allocate(Size + sizeof(Stmt *));
OMPSectionDirective *Dir = new (Mem) OMPSectionDirective(StartLoc, EndLoc);
@@ -1876,7 +1876,7 @@ OMPParallelForDirective *OMPParallelForDirective::Create(
Dir->setLastIteration(Exprs.LastIteration);
Dir->setCalcLastIteration(Exprs.CalcLastIteration);
Dir->setPreCond(Exprs.PreCond);
- Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+ Dir->setCond(Exprs.Cond);
Dir->setInit(Exprs.Init);
Dir->setInc(Exprs.Inc);
Dir->setIsLastIterVariable(Exprs.IL);
@@ -1920,7 +1920,7 @@ OMPParallelForSimdDirective *OMPParallelForSimdDirective::Create(
Dir->setLastIteration(Exprs.LastIteration);
Dir->setCalcLastIteration(Exprs.CalcLastIteration);
Dir->setPreCond(Exprs.PreCond);
- Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+ Dir->setCond(Exprs.Cond);
Dir->setInit(Exprs.Init);
Dir->setInc(Exprs.Inc);
Dir->setIsLastIterVariable(Exprs.IL);
@@ -2041,6 +2041,27 @@ OMPTaskwaitDirective *OMPTaskwaitDirective::CreateEmpty(const ASTContext &C,
return new (Mem) OMPTaskwaitDirective();
}
+OMPTaskgroupDirective *OMPTaskgroupDirective::Create(const ASTContext &C,
+ SourceLocation StartLoc,
+ SourceLocation EndLoc,
+ Stmt *AssociatedStmt) {
+ unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPTaskgroupDirective),
+ llvm::alignOf<Stmt *>());
+ void *Mem = C.Allocate(Size + sizeof(Stmt *));
+ OMPTaskgroupDirective *Dir =
+ new (Mem) OMPTaskgroupDirective(StartLoc, EndLoc);
+ Dir->setAssociatedStmt(AssociatedStmt);
+ return Dir;
+}
+
+OMPTaskgroupDirective *OMPTaskgroupDirective::CreateEmpty(const ASTContext &C,
+ EmptyShell) {
+ unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPTaskgroupDirective),
+ llvm::alignOf<Stmt *>());
+ void *Mem = C.Allocate(Size + sizeof(Stmt *));
+ return new (Mem) OMPTaskgroupDirective();
+}
+
OMPFlushDirective *OMPFlushDirective::Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
diff --git a/lib/AST/StmtPrinter.cpp b/lib/AST/StmtPrinter.cpp
index db6d8c231ef2..658e3dfdeed4 100644
--- a/lib/AST/StmtPrinter.cpp
+++ b/lib/AST/StmtPrinter.cpp
@@ -910,6 +910,11 @@ void StmtPrinter::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *Node) {
PrintOMPExecutableDirective(Node);
}
+void StmtPrinter::VisitOMPTaskgroupDirective(OMPTaskgroupDirective *Node) {
+ Indent() << "#pragma omp taskgroup";
+ PrintOMPExecutableDirective(Node);
+}
+
void StmtPrinter::VisitOMPFlushDirective(OMPFlushDirective *Node) {
Indent() << "#pragma omp flush ";
PrintOMPExecutableDirective(Node);
@@ -1430,6 +1435,22 @@ void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
PrintExpr(Node->getInit());
}
+void StmtPrinter::VisitDesignatedInitUpdateExpr(
+ DesignatedInitUpdateExpr *Node) {
+ OS << "{";
+ OS << "/*base*/";
+ PrintExpr(Node->getBase());
+ OS << ", ";
+
+ OS << "/*updater*/";
+ PrintExpr(Node->getUpdater());
+ OS << "}";
+}
+
+void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) {
+ OS << "/*no init*/";
+}
+
void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
if (Policy.LangOpts.CPlusPlus) {
OS << "/*implicit*/";
diff --git a/lib/AST/StmtProfile.cpp b/lib/AST/StmtProfile.cpp
index c66b153eadbb..23f8d0c8be7a 100644
--- a/lib/AST/StmtProfile.cpp
+++ b/lib/AST/StmtProfile.cpp
@@ -510,6 +510,10 @@ void StmtProfiler::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *S) {
VisitOMPExecutableDirective(S);
}
+void StmtProfiler::VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *S) {
+ VisitOMPExecutableDirective(S);
+}
+
void StmtProfiler::VisitOMPFlushDirective(const OMPFlushDirective *S) {
VisitOMPExecutableDirective(S);
}
@@ -744,6 +748,18 @@ void StmtProfiler::VisitDesignatedInitExpr(const DesignatedInitExpr *S) {
}
}
+// Seems that if VisitInitListExpr() only works on the syntactic form of an
+// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
+void StmtProfiler::VisitDesignatedInitUpdateExpr(
+ const DesignatedInitUpdateExpr *S) {
+ llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
+ "initializer");
+}
+
+void StmtProfiler::VisitNoInitExpr(const NoInitExpr *S) {
+ llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
+}
+
void StmtProfiler::VisitImplicitValueInitExpr(const ImplicitValueInitExpr *S) {
VisitExpr(S);
}
diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp
index 09bb7692596c..3ac117194099 100644
--- a/lib/AST/Type.cpp
+++ b/lib/AST/Type.cpp
@@ -1919,7 +1919,10 @@ bool AttributedType::isCallingConv() const {
case attr_objc_gc:
case attr_objc_ownership:
case attr_noreturn:
- return false;
+ case attr_nonnull:
+ case attr_nullable:
+ case attr_null_unspecified:
+ return false;
case attr_pcs:
case attr_pcs_vfp:
case attr_cdecl:
@@ -2340,6 +2343,153 @@ LinkageInfo Type::getLinkageAndVisibility() const {
return LV;
}
+Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
+ QualType type(this, 0);
+ do {
+ // Check whether this is an attributed type with nullability
+ // information.
+ if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
+ if (auto nullability = attributed->getImmediateNullability())
+ return nullability;
+ }
+
+ // Desugar the type. If desugaring does nothing, we're done.
+ QualType desugared = type.getSingleStepDesugaredType(context);
+ if (desugared.getTypePtr() == type.getTypePtr())
+ return None;
+
+ type = desugared;
+ } while (true);
+}
+
+bool Type::canHaveNullability() const {
+ QualType type = getCanonicalTypeInternal();
+
+ switch (type->getTypeClass()) {
+ // We'll only see canonical types here.
+#define NON_CANONICAL_TYPE(Class, Parent) \
+ case Type::Class: \
+ llvm_unreachable("non-canonical type");
+#define TYPE(Class, Parent)
+#include "clang/AST/TypeNodes.def"
+
+ // Pointer types.
+ case Type::Pointer:
+ case Type::BlockPointer:
+ case Type::MemberPointer:
+ case Type::ObjCObjectPointer:
+ return true;
+
+ // Dependent types that could instantiate to pointer types.
+ case Type::UnresolvedUsing:
+ case Type::TypeOfExpr:
+ case Type::TypeOf:
+ case Type::Decltype:
+ case Type::UnaryTransform:
+ case Type::TemplateTypeParm:
+ case Type::SubstTemplateTypeParmPack:
+ case Type::DependentName:
+ case Type::DependentTemplateSpecialization:
+ return true;
+
+ // Dependent template specializations can instantiate to pointer
+ // types unless they're known to be specializations of a class
+ // template.
+ case Type::TemplateSpecialization:
+ if (TemplateDecl *templateDecl
+ = cast<TemplateSpecializationType>(type.getTypePtr())
+ ->getTemplateName().getAsTemplateDecl()) {
+ if (isa<ClassTemplateDecl>(templateDecl))
+ return false;
+ }
+ return true;
+
+ // auto is considered dependent when it isn't deduced.
+ case Type::Auto:
+ return !cast<AutoType>(type.getTypePtr())->isDeduced();
+
+ case Type::Builtin:
+ switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
+ // Signed, unsigned, and floating-point types cannot have nullability.
+#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
+#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
+#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
+#define BUILTIN_TYPE(Id, SingletonId)
+#include "clang/AST/BuiltinTypes.def"
+ return false;
+
+ // Dependent types that could instantiate to a pointer type.
+ case BuiltinType::Dependent:
+ case BuiltinType::Overload:
+ case BuiltinType::BoundMember:
+ case BuiltinType::PseudoObject:
+ case BuiltinType::UnknownAny:
+ case BuiltinType::ARCUnbridgedCast:
+ return true;
+
+ case BuiltinType::Void:
+ case BuiltinType::ObjCId:
+ case BuiltinType::ObjCClass:
+ case BuiltinType::ObjCSel:
+ case BuiltinType::OCLImage1d:
+ case BuiltinType::OCLImage1dArray:
+ case BuiltinType::OCLImage1dBuffer:
+ case BuiltinType::OCLImage2d:
+ case BuiltinType::OCLImage2dArray:
+ case BuiltinType::OCLImage3d:
+ case BuiltinType::OCLSampler:
+ case BuiltinType::OCLEvent:
+ case BuiltinType::BuiltinFn:
+ case BuiltinType::NullPtr:
+ return false;
+ }
+
+ // Non-pointer types.
+ case Type::Complex:
+ case Type::LValueReference:
+ case Type::RValueReference:
+ case Type::ConstantArray:
+ case Type::IncompleteArray:
+ case Type::VariableArray:
+ case Type::DependentSizedArray:
+ case Type::DependentSizedExtVector:
+ case Type::Vector:
+ case Type::ExtVector:
+ case Type::FunctionProto:
+ case Type::FunctionNoProto:
+ case Type::Record:
+ case Type::Enum:
+ case Type::InjectedClassName:
+ case Type::PackExpansion:
+ case Type::ObjCObject:
+ case Type::ObjCInterface:
+ case Type::Atomic:
+ return false;
+ }
+ llvm_unreachable("bad type kind!");
+}
+
+llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
+ if (getAttrKind() == AttributedType::attr_nonnull)
+ return NullabilityKind::NonNull;
+ if (getAttrKind() == AttributedType::attr_nullable)
+ return NullabilityKind::Nullable;
+ if (getAttrKind() == AttributedType::attr_null_unspecified)
+ return NullabilityKind::Unspecified;
+ return None;
+}
+
+Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
+ if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
+ if (auto nullability = attributed->getImmediateNullability()) {
+ T = attributed->getModifiedType();
+ return nullability;
+ }
+ }
+
+ return None;
+}
+
Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
if (isObjCARCImplicitlyUnretainedType())
return Qualifiers::OCL_ExplicitNone;
diff --git a/lib/AST/TypePrinter.cpp b/lib/AST/TypePrinter.cpp
index 3928fe8f8942..ebe09d85495e 100644
--- a/lib/AST/TypePrinter.cpp
+++ b/lib/AST/TypePrinter.cpp
@@ -1141,6 +1141,21 @@ void TypePrinter::printAttributedBefore(const AttributedType *T,
}
spaceBeforePlaceHolder(OS);
}
+
+ // Print nullability type specifiers.
+ if (T->getAttrKind() == AttributedType::attr_nonnull ||
+ T->getAttrKind() == AttributedType::attr_nullable ||
+ T->getAttrKind() == AttributedType::attr_null_unspecified) {
+ if (T->getAttrKind() == AttributedType::attr_nonnull)
+ OS << " __nonnull";
+ else if (T->getAttrKind() == AttributedType::attr_nullable)
+ OS << " __nullable";
+ else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
+ OS << " __null_unspecified";
+ else
+ llvm_unreachable("unhandled nullability");
+ spaceBeforePlaceHolder(OS);
+ }
}
void TypePrinter::printAttributedAfter(const AttributedType *T,
@@ -1154,12 +1169,34 @@ void TypePrinter::printAttributedAfter(const AttributedType *T,
if (T->isMSTypeSpec())
return;
+ // Nothing to print after.
+ if (T->getAttrKind() == AttributedType::attr_nonnull ||
+ T->getAttrKind() == AttributedType::attr_nullable ||
+ T->getAttrKind() == AttributedType::attr_null_unspecified)
+ return printAfter(T->getModifiedType(), OS);
+
// If this is a calling convention attribute, don't print the implicit CC from
// the modified type.
SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
printAfter(T->getModifiedType(), OS);
+ // Print nullability type specifiers that occur after
+ if (T->getAttrKind() == AttributedType::attr_nonnull ||
+ T->getAttrKind() == AttributedType::attr_nullable ||
+ T->getAttrKind() == AttributedType::attr_null_unspecified) {
+ if (T->getAttrKind() == AttributedType::attr_nonnull)
+ OS << " __nonnull";
+ else if (T->getAttrKind() == AttributedType::attr_nullable)
+ OS << " __nullable";
+ else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
+ OS << " __null_unspecified";
+ else
+ llvm_unreachable("unhandled nullability");
+
+ return;
+ }
+
OS << " __attribute__((";
switch (T->getAttrKind()) {
default: llvm_unreachable("This attribute should have been handled already");
diff --git a/lib/Analysis/CFG.cpp b/lib/Analysis/CFG.cpp
index b2fdd2787985..19b3f5a47654 100644
--- a/lib/Analysis/CFG.cpp
+++ b/lib/Analysis/CFG.cpp
@@ -454,7 +454,7 @@ private:
TerminatorExpr(nullptr) {}
/// Returns whether we need to start a new branch for a temporary destructor
- /// call. This is the case when the the temporary destructor is
+ /// call. This is the case when the temporary destructor is
/// conditionally executed, and it is the first one we encounter while
/// visiting a subexpression - other temporary destructors at the same level
/// will be added to the same block and are executed under the same
diff --git a/lib/Analysis/CocoaConventions.cpp b/lib/Analysis/CocoaConventions.cpp
index 0db3cac58b56..be1262dc9910 100644
--- a/lib/Analysis/CocoaConventions.cpp
+++ b/lib/Analysis/CocoaConventions.cpp
@@ -25,7 +25,7 @@ using namespace ento;
bool cocoa::isRefType(QualType RetTy, StringRef Prefix,
StringRef Name) {
// Recursively walk the typedef stack, allowing typedefs of reference types.
- while (const TypedefType *TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
+ while (const TypedefType *TD = RetTy->getAs<TypedefType>()) {
StringRef TDName = TD->getDecl()->getIdentifier()->getName();
if (TDName.startswith(Prefix) && TDName.endswith("Ref"))
return true;
diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt
index 50a06d9e7a42..cfad8c3649ed 100644
--- a/lib/Basic/CMakeLists.txt
+++ b/lib/Basic/CMakeLists.txt
@@ -61,6 +61,7 @@ add_clang_library(clangBasic
CharInfo.cpp
Diagnostic.cpp
DiagnosticIDs.cpp
+ DiagnosticOptions.cpp
FileManager.cpp
FileSystemStatCache.cpp
IdentifierTable.cpp
diff --git a/lib/Basic/Diagnostic.cpp b/lib/Basic/Diagnostic.cpp
index 19928042fdac..7f5a15dab6b2 100644
--- a/lib/Basic/Diagnostic.cpp
+++ b/lib/Basic/Diagnostic.cpp
@@ -321,18 +321,10 @@ void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
NumDiagArgs = 0;
DiagRanges.clear();
- DiagRanges.reserve(storedDiag.range_size());
- for (StoredDiagnostic::range_iterator
- RI = storedDiag.range_begin(),
- RE = storedDiag.range_end(); RI != RE; ++RI)
- DiagRanges.push_back(*RI);
+ DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
DiagFixItHints.clear();
- DiagFixItHints.reserve(storedDiag.fixit_size());
- for (StoredDiagnostic::fixit_iterator
- FI = storedDiag.fixit_begin(),
- FE = storedDiag.fixit_end(); FI != FE; ++FI)
- DiagFixItHints.push_back(*FI);
+ DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
assert(Client && "DiagnosticConsumer not set!");
Level DiagLevel = storedDiag.getLevel();
diff --git a/lib/Basic/DiagnosticOptions.cpp b/lib/Basic/DiagnosticOptions.cpp
new file mode 100644
index 000000000000..f54a0ef4edb2
--- /dev/null
+++ b/lib/Basic/DiagnosticOptions.cpp
@@ -0,0 +1,24 @@
+//===--- DiagnosticOptions.cpp - C Language Family Diagnostic Handling ----===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the DiagnosticOptions related interfaces.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Basic/DiagnosticOptions.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace clang {
+
+raw_ostream& operator<<(raw_ostream& Out, DiagnosticLevelMask M) {
+ using UT = std::underlying_type<DiagnosticLevelMask>::type;
+ return Out << static_cast<UT>(M);
+}
+
+} // end namespace clang
diff --git a/lib/Basic/FileSystemStatCache.cpp b/lib/Basic/FileSystemStatCache.cpp
index 83e42bdb8483..187ea37e0c28 100644
--- a/lib/Basic/FileSystemStatCache.cpp
+++ b/lib/Basic/FileSystemStatCache.cpp
@@ -15,19 +15,8 @@
#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/Support/Path.h"
-// FIXME: This is terrible, we need this for ::close.
-#if !defined(_MSC_VER) && !defined(__MINGW32__)
-#include <unistd.h>
-#include <sys/uio.h>
-#else
-#include <io.h>
-#endif
using namespace clang;
-#if defined(_MSC_VER)
-#define S_ISDIR(s) ((_S_IFDIR & s) !=0)
-#endif
-
void FileSystemStatCache::anchor() { }
static void copyStatusToFileData(const vfs::Status &Status,
diff --git a/lib/Basic/IdentifierTable.cpp b/lib/Basic/IdentifierTable.cpp
index 4e06352d31d8..b29500810003 100644
--- a/lib/Basic/IdentifierTable.cpp
+++ b/lib/Basic/IdentifierTable.cpp
@@ -16,6 +16,7 @@
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
+#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
@@ -645,3 +646,17 @@ const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
llvm_unreachable("Invalid OverloadedOperatorKind!");
}
+
+StringRef clang::getNullabilitySpelling(NullabilityKind kind) {
+ switch (kind) {
+ case NullabilityKind::NonNull:
+ return "__nonnull";
+
+ case NullabilityKind::Nullable:
+ return "__nullable";
+
+ case NullabilityKind::Unspecified:
+ return "__null_unspecified";
+ }
+ llvm_unreachable("Unknown nullability kind.");
+}
diff --git a/lib/Basic/OpenMPKinds.cpp b/lib/Basic/OpenMPKinds.cpp
index b83a0692c132..b2798b7f0fd3 100644
--- a/lib/Basic/OpenMPKinds.cpp
+++ b/lib/Basic/OpenMPKinds.cpp
@@ -332,6 +332,7 @@ bool clang::isAllowedClauseForDirective(OpenMPDirectiveKind DKind,
case OMPD_taskyield:
case OMPD_barrier:
case OMPD_taskwait:
+ case OMPD_taskgroup:
case OMPD_ordered:
break;
}
diff --git a/lib/Basic/Sanitizers.cpp b/lib/Basic/Sanitizers.cpp
index 8c4884b8ec36..d3676b6b465c 100644
--- a/lib/Basic/Sanitizers.cpp
+++ b/lib/Basic/Sanitizers.cpp
@@ -25,6 +25,10 @@ bool SanitizerSet::has(SanitizerMask K) const {
return Mask & K;
}
+bool SanitizerSet::hasOneOf(SanitizerMask K) const {
+ return Mask & K;
+}
+
void SanitizerSet::set(SanitizerMask K, bool Value) {
assert(llvm::countPopulation(K) == 1);
Mask = Value ? (Mask | K) : (Mask & ~K);
diff --git a/lib/Basic/Targets.cpp b/lib/Basic/Targets.cpp
index c0c692484588..076b04bf342c 100644
--- a/lib/Basic/Targets.cpp
+++ b/lib/Basic/Targets.cpp
@@ -992,6 +992,12 @@ public:
bool hasSjLjLowering() const override {
return true;
}
+
+ bool useFloat128ManglingForLongDouble() const override {
+ return LongDoubleWidth == 128 &&
+ LongDoubleFormat == &llvm::APFloat::PPCDoubleDouble &&
+ getTriple().isOSBinFormatELF();
+ }
};
const Builtin::Info PPCTargetInfo::BuiltinInfo[] = {
@@ -1661,7 +1667,7 @@ public:
}
};
-static const unsigned R600AddrSpaceMap[] = {
+static const unsigned AMDGPUAddrSpaceMap[] = {
1, // opencl_global
3, // opencl_local
2, // opencl_constant
@@ -1687,11 +1693,11 @@ static const char *DescriptionStringSI =
"-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
"-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
-class R600TargetInfo : public TargetInfo {
+class AMDGPUTargetInfo : public TargetInfo {
static const Builtin::Info BuiltinInfo[];
static const char * const GCCRegNames[];
- /// \brief The GPU profiles supported by the R600 target.
+ /// \brief The GPU profiles supported by the AMDGPU target.
enum GPUKind {
GK_NONE,
GK_R600,
@@ -1703,7 +1709,8 @@ class R600TargetInfo : public TargetInfo {
GK_NORTHERN_ISLANDS,
GK_CAYMAN,
GK_SOUTHERN_ISLANDS,
- GK_SEA_ISLANDS
+ GK_SEA_ISLANDS,
+ GK_VOLCANIC_ISLANDS
} GPU;
bool hasFP64:1;
@@ -1711,8 +1718,8 @@ class R600TargetInfo : public TargetInfo {
bool hasLDEXPF:1;
public:
- R600TargetInfo(const llvm::Triple &Triple)
- : TargetInfo(Triple) {
+ AMDGPUTargetInfo(const llvm::Triple &Triple)
+ : TargetInfo(Triple) {
if (Triple.getArch() == llvm::Triple::amdgcn) {
DescriptionString = DescriptionStringSI;
@@ -1727,7 +1734,7 @@ public:
hasFMAF = false;
hasLDEXPF = false;
}
- AddrSpaceMap = &R600AddrSpaceMap;
+ AddrSpaceMap = &AMDGPUAddrSpaceMap;
UseAddrSpaceMapMangling = true;
}
@@ -1766,7 +1773,7 @@ public:
void getTargetBuiltins(const Builtin::Info *&Records,
unsigned &NumRecords) const override {
Records = BuiltinInfo;
- NumRecords = clang::R600::LastTSBuiltin - Builtin::FirstTSBuiltin;
+ NumRecords = clang::AMDGPU::LastTSBuiltin - Builtin::FirstTSBuiltin;
}
void getTargetDefines(const LangOptions &Opts,
@@ -1822,6 +1829,9 @@ public:
.Case("kaveri", GK_SEA_ISLANDS)
.Case("hawaii", GK_SEA_ISLANDS)
.Case("mullins", GK_SEA_ISLANDS)
+ .Case("tonga", GK_VOLCANIC_ISLANDS)
+ .Case("iceland", GK_VOLCANIC_ISLANDS)
+ .Case("carrizo", GK_VOLCANIC_ISLANDS)
.Default(GK_NONE);
if (GPU == GK_NONE) {
@@ -1851,6 +1861,7 @@ public:
break;
case GK_SOUTHERN_ISLANDS:
case GK_SEA_ISLANDS:
+ case GK_VOLCANIC_ISLANDS:
DescriptionString = DescriptionStringSI;
hasFP64 = true;
hasFMAF = true;
@@ -1862,12 +1873,12 @@ public:
}
};
-const Builtin::Info R600TargetInfo::BuiltinInfo[] = {
+const Builtin::Info AMDGPUTargetInfo::BuiltinInfo[] = {
#define BUILTIN(ID, TYPE, ATTRS) \
{ #ID, TYPE, ATTRS, 0, ALL_LANGUAGES },
-#include "clang/Basic/BuiltinsR600.def"
+#include "clang/Basic/BuiltinsAMDGPU.def"
};
-const char * const R600TargetInfo::GCCRegNames[] = {
+const char * const AMDGPUTargetInfo::GCCRegNames[] = {
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
@@ -1920,8 +1931,8 @@ const char * const R600TargetInfo::GCCRegNames[] = {
"vcc_lo", "vcc_hi", "flat_scr_lo", "flat_scr_hi"
};
-void R600TargetInfo::getGCCRegNames(const char * const *&Names,
- unsigned &NumNames) const {
+void AMDGPUTargetInfo::getGCCRegNames(const char * const *&Names,
+ unsigned &NumNames) const {
Names = GCCRegNames;
NumNames = llvm::array_lengthof(GCCRegNames);
}
@@ -5688,6 +5699,10 @@ public:
return "vector";
return "";
}
+
+ bool useFloat128ManglingForLongDouble() const override {
+ return true;
+ }
};
const Builtin::Info SystemZTargetInfo::BuiltinInfo[] = {
@@ -5890,6 +5905,60 @@ validateAsmConstraint(const char *&Name,
unsigned &NumAliases) const override {}
};
+class BPFTargetInfo : public TargetInfo {
+public:
+ BPFTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
+ LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
+ SizeType = UnsignedLong;
+ PtrDiffType = SignedLong;
+ IntPtrType = SignedLong;
+ IntMaxType = SignedLong;
+ Int64Type = SignedLong;
+ RegParmMax = 5;
+ if (Triple.getArch() == llvm::Triple::bpfeb) {
+ BigEndian = true;
+ DescriptionString = "E-m:e-p:64:64-i64:64-n32:64-S128";
+ } else {
+ BigEndian = false;
+ DescriptionString = "e-m:e-p:64:64-i64:64-n32:64-S128";
+ }
+ MaxAtomicPromoteWidth = 64;
+ MaxAtomicInlineWidth = 64;
+ TLSSupported = false;
+ }
+ void getTargetDefines(const LangOptions &Opts,
+ MacroBuilder &Builder) const override {
+ DefineStd(Builder, "bpf", Opts);
+ Builder.defineMacro("__BPF__");
+ }
+ bool hasFeature(StringRef Feature) const override {
+ return Feature == "bpf";
+ }
+
+ void getTargetBuiltins(const Builtin::Info *&Records,
+ unsigned &NumRecords) const override {}
+ const char *getClobbers() const override {
+ return "";
+ }
+ BuiltinVaListKind getBuiltinVaListKind() const override {
+ return TargetInfo::VoidPtrBuiltinVaList;
+ }
+ void getGCCRegNames(const char * const *&Names,
+ unsigned &NumNames) const override {
+ Names = nullptr;
+ NumNames = 0;
+ }
+ bool validateAsmConstraint(const char *&Name,
+ TargetInfo::ConstraintInfo &info) const override {
+ return true;
+ }
+ void getGCCRegAliases(const GCCRegAlias *&Aliases,
+ unsigned &NumAliases) const override {
+ Aliases = nullptr;
+ NumAliases = 0;
+ }
+};
+
class MipsTargetInfoBase : public TargetInfo {
virtual void setDescriptionString() = 0;
@@ -6888,6 +6957,10 @@ static TargetInfo *AllocateTarget(const llvm::Triple &Triple) {
return new ARMbeTargetInfo(Triple);
}
+ case llvm::Triple::bpfeb:
+ case llvm::Triple::bpfel:
+ return new BPFTargetInfo(Triple);
+
case llvm::Triple::msp430:
return new MSP430TargetInfo(Triple);
@@ -7015,7 +7088,7 @@ static TargetInfo *AllocateTarget(const llvm::Triple &Triple) {
case llvm::Triple::amdgcn:
case llvm::Triple::r600:
- return new R600TargetInfo(Triple);
+ return new AMDGPUTargetInfo(Triple);
case llvm::Triple::sparc:
switch (os) {
@@ -7080,6 +7153,8 @@ static TargetInfo *AllocateTarget(const llvm::Triple &Triple) {
return new DarwinI386TargetInfo(Triple);
switch (os) {
+ case llvm::Triple::CloudABI:
+ return new CloudABITargetInfo<X86_32TargetInfo>(Triple);
case llvm::Triple::Linux: {
switch (Triple.getEnvironment()) {
default:
diff --git a/lib/CodeGen/BackendUtil.cpp b/lib/CodeGen/BackendUtil.cpp
index 8cece0d126f5..f5edea7810ab 100644
--- a/lib/CodeGen/BackendUtil.cpp
+++ b/lib/CodeGen/BackendUtil.cpp
@@ -201,8 +201,14 @@ static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
legacy::PassManagerBase &PM) {
- PM.add(createAddressSanitizerFunctionPass());
- PM.add(createAddressSanitizerModulePass());
+ PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false));
+ PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false));
+}
+
+static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
+ legacy::PassManagerBase &PM) {
+ PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true));
+ PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true));
}
static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
@@ -283,7 +289,6 @@ void EmitAssemblyHelper::CreatePasses() {
PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
- PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
@@ -329,6 +334,13 @@ void EmitAssemblyHelper::CreatePasses() {
addAddressSanitizerPasses);
}
+ if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
+ PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
+ addKernelAddressSanitizerPasses);
+ PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
+ addKernelAddressSanitizerPasses);
+ }
+
if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
addMemorySanitizerPass);
@@ -478,6 +490,9 @@ TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
llvm::TargetOptions Options;
+ if (!TargetOpts.Reciprocals.empty())
+ Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
+
Options.ThreadModel =
llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
.Case("posix", llvm::ThreadModel::POSIX)
@@ -521,7 +536,6 @@ TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
- Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Options.FunctionSections = CodeGenOpts.FunctionSections;
diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp
index d86534d5f8d4..a14daac596f5 100644
--- a/lib/CodeGen/CGBuiltin.cpp
+++ b/lib/CodeGen/CGBuiltin.cpp
@@ -1877,7 +1877,7 @@ Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID,
return EmitPPCBuiltinExpr(BuiltinID, E);
case llvm::Triple::r600:
case llvm::Triple::amdgcn:
- return EmitR600BuiltinExpr(BuiltinID, E);
+ return EmitAMDGPUBuiltinExpr(BuiltinID, E);
case llvm::Triple::systemz:
return EmitSystemZBuiltinExpr(BuiltinID, E);
default:
@@ -3279,6 +3279,66 @@ Value *CodeGenFunction::GetValueForARMHint(unsigned BuiltinID) {
}
}
+// Generates the IR for the read/write special register builtin,
+// ValueType is the type of the value that is to be written or read,
+// RegisterType is the type of the register being written to or read from.
+static Value *EmitSpecialRegisterBuiltin(CodeGenFunction &CGF,
+ const CallExpr *E,
+ llvm::Type *RegisterType,
+ llvm::Type *ValueType, bool IsRead) {
+ // write and register intrinsics only support 32 and 64 bit operations.
+ assert((RegisterType->isIntegerTy(32) || RegisterType->isIntegerTy(64))
+ && "Unsupported size for register.");
+
+ CodeGen::CGBuilderTy &Builder = CGF.Builder;
+ CodeGen::CodeGenModule &CGM = CGF.CGM;
+ LLVMContext &Context = CGM.getLLVMContext();
+
+ const Expr *SysRegStrExpr = E->getArg(0)->IgnoreParenCasts();
+ StringRef SysReg = cast<StringLiteral>(SysRegStrExpr)->getString();
+
+ llvm::Metadata *Ops[] = { llvm::MDString::get(Context, SysReg) };
+ llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);
+ llvm::Value *Metadata = llvm::MetadataAsValue::get(Context, RegName);
+
+ llvm::Type *Types[] = { RegisterType };
+
+ bool MixedTypes = RegisterType->isIntegerTy(64) && ValueType->isIntegerTy(32);
+ assert(!(RegisterType->isIntegerTy(32) && ValueType->isIntegerTy(64))
+ && "Can't fit 64-bit value in 32-bit register");
+
+ if (IsRead) {
+ llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
+ llvm::Value *Call = Builder.CreateCall(F, Metadata);
+
+ if (MixedTypes)
+ // Read into 64 bit register and then truncate result to 32 bit.
+ return Builder.CreateTrunc(Call, ValueType);
+
+ if (ValueType->isPointerTy())
+ // Have i32/i64 result (Call) but want to return a VoidPtrTy (i8*).
+ return Builder.CreateIntToPtr(Call, ValueType);
+
+ return Call;
+ }
+
+ llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
+ llvm::Value *ArgValue = CGF.EmitScalarExpr(E->getArg(1));
+ if (MixedTypes) {
+ // Extend 32 bit write value to 64 bit to pass to write.
+ ArgValue = Builder.CreateZExt(ArgValue, RegisterType);
+ return Builder.CreateCall(F, { Metadata, ArgValue });
+ }
+
+ if (ValueType->isPointerTy()) {
+ // Have VoidPtrTy ArgValue but want to return an i32/i64.
+ ArgValue = Builder.CreatePtrToInt(ArgValue, RegisterType);
+ return Builder.CreateCall(F, { Metadata, ArgValue });
+ }
+
+ return Builder.CreateCall(F, { Metadata, ArgValue });
+}
+
Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
const CallExpr *E) {
if (auto Hint = GetValueForARMHint(BuiltinID))
@@ -3491,6 +3551,37 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
}
}
+ if (BuiltinID == ARM::BI__builtin_arm_rsr ||
+ BuiltinID == ARM::BI__builtin_arm_rsr64 ||
+ BuiltinID == ARM::BI__builtin_arm_rsrp ||
+ BuiltinID == ARM::BI__builtin_arm_wsr ||
+ BuiltinID == ARM::BI__builtin_arm_wsr64 ||
+ BuiltinID == ARM::BI__builtin_arm_wsrp) {
+
+ bool IsRead = BuiltinID == ARM::BI__builtin_arm_rsr ||
+ BuiltinID == ARM::BI__builtin_arm_rsr64 ||
+ BuiltinID == ARM::BI__builtin_arm_rsrp;
+
+ bool IsPointerBuiltin = BuiltinID == ARM::BI__builtin_arm_rsrp ||
+ BuiltinID == ARM::BI__builtin_arm_wsrp;
+
+ bool Is64Bit = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
+ BuiltinID == ARM::BI__builtin_arm_wsr64;
+
+ llvm::Type *ValueType;
+ llvm::Type *RegisterType;
+ if (IsPointerBuiltin) {
+ ValueType = VoidPtrTy;
+ RegisterType = Int32Ty;
+ } else if (Is64Bit) {
+ ValueType = RegisterType = Int64Ty;
+ } else {
+ ValueType = RegisterType = Int32Ty;
+ }
+
+ return EmitSpecialRegisterBuiltin(*this, E, RegisterType, ValueType, IsRead);
+ }
+
// Find out if any arguments are required to be integer constant
// expressions.
unsigned ICEArguments = 0;
@@ -4239,6 +4330,36 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID,
return Builder.CreateCall(F, {Arg0, Arg1});
}
+ if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
+ BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
+ BuiltinID == AArch64::BI__builtin_arm_rsrp ||
+ BuiltinID == AArch64::BI__builtin_arm_wsr ||
+ BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
+ BuiltinID == AArch64::BI__builtin_arm_wsrp) {
+
+ bool IsRead = BuiltinID == AArch64::BI__builtin_arm_rsr ||
+ BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
+ BuiltinID == AArch64::BI__builtin_arm_rsrp;
+
+ bool IsPointerBuiltin = BuiltinID == AArch64::BI__builtin_arm_rsrp ||
+ BuiltinID == AArch64::BI__builtin_arm_wsrp;
+
+ bool Is64Bit = BuiltinID != AArch64::BI__builtin_arm_rsr &&
+ BuiltinID != AArch64::BI__builtin_arm_wsr;
+
+ llvm::Type *ValueType;
+ llvm::Type *RegisterType = Int64Ty;
+ if (IsPointerBuiltin) {
+ ValueType = VoidPtrTy;
+ } else if (Is64Bit) {
+ ValueType = Int64Ty;
+ } else {
+ ValueType = Int32Ty;
+ }
+
+ return EmitSpecialRegisterBuiltin(*this, E, RegisterType, ValueType, IsRead);
+ }
+
// Find out if any arguments are required to be integer constant
// expressions.
unsigned ICEArguments = 0;
@@ -6427,11 +6548,11 @@ static Value *emitFPIntBuiltin(CodeGenFunction &CGF,
return CGF.Builder.CreateCall(F, {Src0, Src1});
}
-Value *CodeGenFunction::EmitR600BuiltinExpr(unsigned BuiltinID,
- const CallExpr *E) {
+Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned BuiltinID,
+ const CallExpr *E) {
switch (BuiltinID) {
- case R600::BI__builtin_amdgpu_div_scale:
- case R600::BI__builtin_amdgpu_div_scalef: {
+ case AMDGPU::BI__builtin_amdgpu_div_scale:
+ case AMDGPU::BI__builtin_amdgpu_div_scalef: {
// Translate from the intrinsics's struct return to the builtin's out
// argument.
@@ -6458,8 +6579,8 @@ Value *CodeGenFunction::EmitR600BuiltinExpr(unsigned BuiltinID,
FlagStore->setAlignment(FlagOutPtr.second);
return Result;
}
- case R600::BI__builtin_amdgpu_div_fmas:
- case R600::BI__builtin_amdgpu_div_fmasf: {
+ case AMDGPU::BI__builtin_amdgpu_div_fmas:
+ case AMDGPU::BI__builtin_amdgpu_div_fmasf: {
llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
@@ -6470,26 +6591,26 @@ Value *CodeGenFunction::EmitR600BuiltinExpr(unsigned BuiltinID,
llvm::Value *Src3ToBool = Builder.CreateIsNotNull(Src3);
return Builder.CreateCall(F, {Src0, Src1, Src2, Src3ToBool});
}
- case R600::BI__builtin_amdgpu_div_fixup:
- case R600::BI__builtin_amdgpu_div_fixupf:
+ case AMDGPU::BI__builtin_amdgpu_div_fixup:
+ case AMDGPU::BI__builtin_amdgpu_div_fixupf:
return emitTernaryFPBuiltin(*this, E, Intrinsic::AMDGPU_div_fixup);
- case R600::BI__builtin_amdgpu_trig_preop:
- case R600::BI__builtin_amdgpu_trig_preopf:
+ case AMDGPU::BI__builtin_amdgpu_trig_preop:
+ case AMDGPU::BI__builtin_amdgpu_trig_preopf:
return emitFPIntBuiltin(*this, E, Intrinsic::AMDGPU_trig_preop);
- case R600::BI__builtin_amdgpu_rcp:
- case R600::BI__builtin_amdgpu_rcpf:
+ case AMDGPU::BI__builtin_amdgpu_rcp:
+ case AMDGPU::BI__builtin_amdgpu_rcpf:
return emitUnaryFPBuiltin(*this, E, Intrinsic::AMDGPU_rcp);
- case R600::BI__builtin_amdgpu_rsq:
- case R600::BI__builtin_amdgpu_rsqf:
+ case AMDGPU::BI__builtin_amdgpu_rsq:
+ case AMDGPU::BI__builtin_amdgpu_rsqf:
return emitUnaryFPBuiltin(*this, E, Intrinsic::AMDGPU_rsq);
- case R600::BI__builtin_amdgpu_rsq_clamped:
- case R600::BI__builtin_amdgpu_rsq_clampedf:
+ case AMDGPU::BI__builtin_amdgpu_rsq_clamped:
+ case AMDGPU::BI__builtin_amdgpu_rsq_clampedf:
return emitUnaryFPBuiltin(*this, E, Intrinsic::AMDGPU_rsq_clamped);
- case R600::BI__builtin_amdgpu_ldexp:
- case R600::BI__builtin_amdgpu_ldexpf:
+ case AMDGPU::BI__builtin_amdgpu_ldexp:
+ case AMDGPU::BI__builtin_amdgpu_ldexpf:
return emitFPIntBuiltin(*this, E, Intrinsic::AMDGPU_ldexp);
- case R600::BI__builtin_amdgpu_class:
- case R600::BI__builtin_amdgpu_classf:
+ case AMDGPU::BI__builtin_amdgpu_class:
+ case AMDGPU::BI__builtin_amdgpu_classf:
return emitFPIntBuiltin(*this, E, Intrinsic::AMDGPU_class);
default:
return nullptr;
diff --git a/lib/CodeGen/CGCXXABI.h b/lib/CodeGen/CGCXXABI.h
index 2c7392188f78..b6b4ee6850ac 100644
--- a/lib/CodeGen/CGCXXABI.h
+++ b/lib/CodeGen/CGCXXABI.h
@@ -366,7 +366,8 @@ public:
virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Value *This,
- llvm::Type *Ty) = 0;
+ llvm::Type *Ty,
+ SourceLocation Loc) = 0;
/// Emit the ABI-specific virtual destructor call.
virtual llvm::Value *
diff --git a/lib/CodeGen/CGCall.cpp b/lib/CodeGen/CGCall.cpp
index e77539c63236..58ef171df0d7 100644
--- a/lib/CodeGen/CGCall.cpp
+++ b/lib/CodeGen/CGCall.cpp
@@ -1465,6 +1465,8 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
}
+ FuncAttrs.addAttribute("disable-tail-calls",
+ llvm::toStringRef(CodeGenOpts.DisableTailCalls));
FuncAttrs.addAttribute("less-precise-fpmad",
llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
FuncAttrs.addAttribute("no-infs-fp-math",
@@ -1481,24 +1483,62 @@ void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
if (!CodeGenOpts.StackRealignment)
FuncAttrs.addAttribute("no-realign-stack");
- // Add target-cpu and target-features work if they differ from the defaults.
- std::string &CPU = getTarget().getTargetOpts().CPU;
- if (CPU != "")
- FuncAttrs.addAttribute("target-cpu", CPU);
+ // Add target-cpu and target-features attributes to functions. If
+ // we have a decl for the function and it has a target attribute then
+ // parse that and add it to the feature set.
+ StringRef TargetCPU = getTarget().getTargetOpts().CPU;
// TODO: Features gets us the features on the command line including
// feature dependencies. For canonicalization purposes we might want to
- // avoid putting features in the target-features set if we know it'll be one
- // of the default features in the backend, e.g. corei7-avx and +avx or figure
- // out non-explicit dependencies.
- std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
+ // avoid putting features in the target-features set if we know it'll be
+ // one of the default features in the backend, e.g. corei7-avx and +avx or
+ // figure out non-explicit dependencies.
+ std::vector<std::string> Features(getTarget().getTargetOpts().Features);
+
+ // TODO: The target attribute complicates this further by allowing multiple
+ // additional features to be tacked on to the feature string for a
+ // particular function. For now we simply append to the set of features and
+ // let backend resolution fix them up.
+ const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
+ if (FD) {
+ if (const TargetAttr *TD = FD->getAttr<TargetAttr>()) {
+ StringRef FeaturesStr = TD->getFeatures();
+ SmallVector<StringRef, 1> AttrFeatures;
+ FeaturesStr.split(AttrFeatures, ",");
+
+ // Grab the various features and prepend a "+" to turn on the feature to
+ // the backend and add them to our existing set of Features.
+ for (auto &Feature : AttrFeatures) {
+ // While we're here iterating check for a different target cpu.
+ if (Feature.startswith("arch="))
+ TargetCPU = Feature.split("=").second;
+ else if (Feature.startswith("tune="))
+ // We don't support cpu tuning this way currently.
+ ;
+ else if (Feature.startswith("fpmath="))
+ // TODO: Support the fpmath option this way. It will require checking
+ // overall feature validity for the function with the rest of the
+ // attributes on the function.
+ ;
+ else if (Feature.startswith("mno-"))
+ Features.push_back("-" + Feature.split("-").second.str());
+ else
+ Features.push_back("+" + Feature.str());
+ }
+ }
+ }
+
+ // Now add the target-cpu and target-features to the function.
+ if (TargetCPU != "")
+ FuncAttrs.addAttribute("target-cpu", TargetCPU);
if (!Features.empty()) {
- std::stringstream S;
+ std::stringstream TargetFeatures;
std::copy(Features.begin(), Features.end(),
- std::ostream_iterator<std::string>(S, ","));
+ std::ostream_iterator<std::string>(TargetFeatures, ","));
+
// The drop_back gets rid of the trailing space.
FuncAttrs.addAttribute("target-features",
- StringRef(S.str()).drop_back(1));
+ StringRef(TargetFeatures.str()).drop_back(1));
}
}
@@ -2231,11 +2271,10 @@ static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
++II;
- if (isa<llvm::BitCastInst>(&*II)) {
- if (CastAddr == &*II) {
- continue;
- }
- }
+ if (II == IE)
+ break;
+ if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
+ continue;
}
}
I = &*II;
@@ -2571,7 +2610,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
LValue srcLV;
// Make an optimistic effort to emit the address as an l-value.
- // This can fail if the the argument expression is more complicated.
+ // This can fail if the argument expression is more complicated.
if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
srcLV = CGF.EmitLValue(lvExpr);
diff --git a/lib/CodeGen/CGClass.cpp b/lib/CodeGen/CGClass.cpp
index cd75da276287..1d2b7875d8f7 100644
--- a/lib/CodeGen/CGClass.cpp
+++ b/lib/CodeGen/CGClass.cpp
@@ -370,25 +370,25 @@ namespace {
/// A visitor which checks whether an initializer uses 'this' in a
/// way which requires the vtable to be properly set.
- struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
- typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
+ struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
+ typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
bool UsesThis;
- DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
+ DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
// Black-list all explicit and implicit references to 'this'.
//
// Do we need to worry about external references to 'this' derived
// from arbitrary code? If so, then anything which runs arbitrary
// external code might potentially access the vtable.
- void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
+ void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
};
}
static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
DynamicThisUseChecker Checker(C);
- Checker.Visit(const_cast<Expr*>(Init));
+ Checker.Visit(Init);
return Checker.UsesThis;
}
@@ -2134,17 +2134,21 @@ LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
}
void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
- llvm::Value *VTable) {
+ llvm::Value *VTable,
+ CFITypeCheckKind TCK,
+ SourceLocation Loc) {
const CXXRecordDecl *ClassDecl = MD->getParent();
if (!SanOpts.has(SanitizerKind::CFICastStrict))
ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
- EmitVTablePtrCheck(ClassDecl, VTable);
+ EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
}
void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
llvm::Value *Derived,
- bool MayBeNull) {
+ bool MayBeNull,
+ CFITypeCheckKind TCK,
+ SourceLocation Loc) {
if (!getLangOpts().CPlusPlus)
return;
@@ -2184,7 +2188,7 @@ void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
}
llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
- EmitVTablePtrCheck(ClassDecl, VTable);
+ EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
if (MayBeNull) {
Builder.CreateBr(ContBlock);
@@ -2193,11 +2197,15 @@ void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
}
void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
- llvm::Value *VTable) {
+ llvm::Value *VTable,
+ CFITypeCheckKind TCK,
+ SourceLocation Loc) {
// FIXME: Add blacklisting scheme.
if (RD->isInStdNamespace())
return;
+ SanitizerScope SanScope(this);
+
std::string OutName;
llvm::raw_string_ostream Out(OutName);
CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
@@ -2205,20 +2213,34 @@ void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
llvm::Value *BitSetName = llvm::MetadataAsValue::get(
getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
- llvm::Value *BitSetTest = Builder.CreateCall(
- CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
- {Builder.CreateBitCast(VTable, CGM.Int8PtrTy), BitSetName});
+ llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
+ llvm::Value *BitSetTest =
+ Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
+ {CastedVTable, BitSetName});
- llvm::BasicBlock *ContBlock = createBasicBlock("vtable.check.cont");
- llvm::BasicBlock *TrapBlock = createBasicBlock("vtable.check.trap");
-
- Builder.CreateCondBr(BitSetTest, ContBlock, TrapBlock);
-
- EmitBlock(TrapBlock);
- Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap), {});
- Builder.CreateUnreachable();
+ SanitizerMask M;
+ switch (TCK) {
+ case CFITCK_VCall:
+ M = SanitizerKind::CFIVCall;
+ break;
+ case CFITCK_NVCall:
+ M = SanitizerKind::CFINVCall;
+ break;
+ case CFITCK_DerivedCast:
+ M = SanitizerKind::CFIDerivedCast;
+ break;
+ case CFITCK_UnrelatedCast:
+ M = SanitizerKind::CFIUnrelatedCast;
+ break;
+ }
- EmitBlock(ContBlock);
+ llvm::Constant *StaticData[] = {
+ EmitCheckSourceLocation(Loc),
+ EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
+ llvm::ConstantInt::get(Int8Ty, TCK),
+ };
+ EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
+ CastedVTable);
}
// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
diff --git a/lib/CodeGen/CGDebugInfo.cpp b/lib/CodeGen/CGDebugInfo.cpp
index 48458dbd6003..a20e39f3fc00 100644
--- a/lib/CodeGen/CGDebugInfo.cpp
+++ b/lib/CodeGen/CGDebugInfo.cpp
@@ -590,18 +590,29 @@ llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
Ty->getPointeeType(), Unit);
}
+/// \return whether a C++ mangling exists for the type defined by TD.
+static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
+ switch (TheCU->getSourceLanguage()) {
+ case llvm::dwarf::DW_LANG_C_plus_plus:
+ return true;
+ case llvm::dwarf::DW_LANG_ObjC_plus_plus:
+ return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
+ default:
+ return false;
+ }
+}
+
/// In C++ mode, types have linkage, so we can rely on the ODR and
/// on their mangled names, if they're external.
static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
CodeGenModule &CGM,
llvm::DICompileUnit *TheCU) {
SmallString<256> FullName;
- // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
- // For now, only apply ODR with C++.
const TagDecl *TD = Ty->getDecl();
- if (TheCU->getSourceLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
- !TD->isExternallyVisible())
+
+ if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
return FullName;
+
// Microsoft Mangler does not have support for mangleCXXRTTIName yet.
if (CGM.getTarget().getCXXABI().isMicrosoft())
return FullName;
diff --git a/lib/CodeGen/CGDecl.cpp b/lib/CodeGen/CGDecl.cpp
index 579a04145567..07dbce4252fe 100644
--- a/lib/CodeGen/CGDecl.cpp
+++ b/lib/CodeGen/CGDecl.cpp
@@ -864,20 +864,17 @@ llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
return nullptr;
llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
- llvm::Value *Args[] = {
- SizeV,
- new llvm::BitCastInst(Addr, Int8PtrTy, "", Builder.GetInsertBlock())};
- llvm::CallInst *C = llvm::CallInst::Create(CGM.getLLVMLifetimeStartFn(), Args,
- "", Builder.GetInsertBlock());
+ Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
+ llvm::CallInst *C =
+ Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
C->setDoesNotThrow();
return SizeV;
}
void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
- llvm::Value *Args[] = {Size, new llvm::BitCastInst(Addr, Int8PtrTy, "",
- Builder.GetInsertBlock())};
- llvm::CallInst *C = llvm::CallInst::Create(CGM.getLLVMLifetimeEndFn(), Args,
- "", Builder.GetInsertBlock());
+ Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
+ llvm::CallInst *C =
+ Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
C->setDoesNotThrow();
}
diff --git a/lib/CodeGen/CGDeclCXX.cpp b/lib/CodeGen/CGDeclCXX.cpp
index 06d157bd82e7..00d6d5cee749 100644
--- a/lib/CodeGen/CGDeclCXX.cpp
+++ b/lib/CodeGen/CGDeclCXX.cpp
@@ -267,12 +267,15 @@ llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
Fn->setDoesNotThrow();
if (!isInSanitizerBlacklist(Fn, Loc)) {
- if (getLangOpts().Sanitize.has(SanitizerKind::Address))
+ if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
+ SanitizerKind::KernelAddress))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
Fn->addFnAttr(llvm::Attribute::SanitizeThread);
if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
+ if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack))
+ Fn->addFnAttr(llvm::Attribute::SafeStack);
}
return Fn;
@@ -421,6 +424,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
AddGlobalCtor(Fn, Priority);
}
+ PrioritizedCXXGlobalInits.clear();
}
SmallString<128> FileName;
@@ -448,7 +452,6 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
AddGlobalCtor(Fn);
CXXGlobalInits.clear();
- PrioritizedCXXGlobalInits.clear();
}
void CodeGenModule::EmitCXXGlobalDtorFunc() {
diff --git a/lib/CodeGen/CGException.cpp b/lib/CodeGen/CGException.cpp
index d9a3f0b252a5..4c8501724bd8 100644
--- a/lib/CodeGen/CGException.cpp
+++ b/lib/CodeGen/CGException.cpp
@@ -698,13 +698,15 @@ llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
const EHPersonality &personality = EHPersonality::get(*this);
+ if (!CurFn->hasPersonalityFn())
+ CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, personality));
+
// Create and configure the landing pad.
llvm::BasicBlock *lpad = createBasicBlock("lpad");
EmitBlock(lpad);
- llvm::LandingPadInst *LPadInst =
- Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
- getOpaquePersonalityFn(CGM, personality), 0);
+ llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
+ llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
Builder.CreateStore(LPadExn, getExceptionSlot());
@@ -1193,9 +1195,12 @@ llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
// Tell the backend that this is a landing pad.
const EHPersonality &Personality = EHPersonality::get(*this);
- llvm::LandingPadInst *LPadInst =
- Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
- getOpaquePersonalityFn(CGM, Personality), 0);
+
+ if (!CurFn->hasPersonalityFn())
+ CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
+
+ llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
+ llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
LPadInst->addClause(getCatchAllValue(*this));
llvm::Value *Exn = 0;
diff --git a/lib/CodeGen/CGExpr.cpp b/lib/CodeGen/CGExpr.cpp
index 1ed45a33d0fd..1a76afaf1158 100644
--- a/lib/CodeGen/CGExpr.cpp
+++ b/lib/CodeGen/CGExpr.cpp
@@ -2300,15 +2300,24 @@ void CodeGenFunction::EmitCheck(
llvm::Value *FatalCond = nullptr;
llvm::Value *RecoverableCond = nullptr;
+ llvm::Value *TrapCond = nullptr;
for (int i = 0, n = Checked.size(); i < n; ++i) {
llvm::Value *Check = Checked[i].first;
+ // -fsanitize-trap= overrides -fsanitize-recover=.
llvm::Value *&Cond =
- CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
- ? RecoverableCond
- : FatalCond;
+ CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
+ ? TrapCond
+ : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
+ ? RecoverableCond
+ : FatalCond;
Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
}
+ if (TrapCond)
+ EmitTrapCheck(TrapCond);
+ if (!FatalCond && !RecoverableCond)
+ return;
+
llvm::Value *JointCond;
if (FatalCond && RecoverableCond)
JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
@@ -2326,15 +2335,6 @@ void CodeGenFunction::EmitCheck(
}
#endif
- if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
- assert(RecoverKind != CheckRecoverableKind::AlwaysRecoverable &&
- "Runtime call required for AlwaysRecoverable kind!");
- // Assume that -fsanitize-undefined-trap-on-error overrides
- // -fsanitize-recover= options, as we can only print meaningful error
- // message and recover if we have a runtime support.
- return EmitTrapCheck(JointCond);
- }
-
llvm::BasicBlock *Cont = createBasicBlock("cont");
llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
@@ -3035,7 +3035,8 @@ LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Derived, E->getType());
if (SanOpts.has(SanitizerKind::CFIDerivedCast))
- EmitVTablePtrCheckForCast(E->getType(), Derived, /*MayBeNull=*/false);
+ EmitVTablePtrCheckForCast(E->getType(), Derived, /*MayBeNull=*/false,
+ CFITCK_DerivedCast, E->getLocStart());
return MakeAddrLValue(Derived, E->getType());
}
@@ -3048,7 +3049,8 @@ LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
ConvertType(CE->getTypeAsWritten()));
if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
- EmitVTablePtrCheckForCast(E->getType(), V, /*MayBeNull=*/false);
+ EmitVTablePtrCheckForCast(E->getType(), V, /*MayBeNull=*/false,
+ CFITCK_UnrelatedCast, E->getLocStart());
return MakeAddrLValue(V, E->getType());
}
diff --git a/lib/CodeGen/CGExprAgg.cpp b/lib/CodeGen/CGExprAgg.cpp
index 8b1bc69352b3..883b76bcfab0 100644
--- a/lib/CodeGen/CGExprAgg.cpp
+++ b/lib/CodeGen/CGExprAgg.cpp
@@ -160,10 +160,12 @@ public:
EmitAggLoadOfLValue(E);
}
+ void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
void VisitChooseExpr(const ChooseExpr *CE);
void VisitInitListExpr(InitListExpr *E);
void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
+ void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
Visit(DAE->getExpr());
}
@@ -1056,6 +1058,9 @@ AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
return;
} else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
return EmitNullInitializationToLValue(LV);
+ } else if (isa<NoInitExpr>(E)) {
+ // Do nothing.
+ return;
} else if (type->isReferenceType()) {
RValue RV = CGF.EmitReferenceBindingToExpr(E);
return CGF.EmitStoreThroughLValue(RV, LV);
@@ -1276,6 +1281,15 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
cleanupDominator->eraseFromParent();
}
+void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
+ AggValueSlot Dest = EnsureSlot(E->getType());
+
+ LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
+ Dest.getAlignment());
+ EmitInitializationToLValue(E->getBase(), DestLV);
+ VisitInitListExpr(E->getUpdater());
+}
+
//===----------------------------------------------------------------------===//
// Entry Points into this File
//===----------------------------------------------------------------------===//
diff --git a/lib/CodeGen/CGExprCXX.cpp b/lib/CodeGen/CGExprCXX.cpp
index 13dfbb38816f..f0f706d7b957 100644
--- a/lib/CodeGen/CGExprCXX.cpp
+++ b/lib/CodeGen/CGExprCXX.cpp
@@ -254,12 +254,13 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
} else if (UseVirtualCall) {
- Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
+ Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
+ CE->getLocStart());
} else {
if (SanOpts.has(SanitizerKind::CFINVCall) &&
MD->getParent()->isDynamicClass()) {
llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy);
- EmitVTablePtrCheckForCall(MD, VTable);
+ EmitVTablePtrCheckForCall(MD, VTable, CFITCK_NVCall, CE->getLocStart());
}
if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
@@ -958,6 +959,25 @@ void CodeGenFunction::EmitNewArrayInitializer(
if (ILE->getNumInits() == 0 && TryMemsetInitialization())
return;
+ // If we have a struct whose every field is value-initialized, we can
+ // usually use memset.
+ if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
+ if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
+ if (RType->getDecl()->isStruct()) {
+ unsigned NumFields = 0;
+ for (auto *Field : RType->getDecl()->fields())
+ if (!Field->isUnnamedBitfield())
+ ++NumFields;
+ if (ILE->getNumInits() == NumFields)
+ for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
+ if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
+ --NumFields;
+ if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
+ return;
+ }
+ }
+ }
+
// Create the loop blocks.
llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
diff --git a/lib/CodeGen/CGExprConstant.cpp b/lib/CodeGen/CGExprConstant.cpp
index b90b3ab61d8e..acfb9b6dbb25 100644
--- a/lib/CodeGen/CGExprConstant.cpp
+++ b/lib/CodeGen/CGExprConstant.cpp
@@ -33,6 +33,7 @@ using namespace CodeGen;
//===----------------------------------------------------------------------===//
namespace {
+class ConstExprEmitter;
class ConstStructBuilder {
CodeGenModule &CGM;
CodeGenFunction *CGF;
@@ -42,6 +43,10 @@ class ConstStructBuilder {
CharUnits LLVMStructAlignment;
SmallVector<llvm::Constant *, 32> Elements;
public:
+ static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CFG,
+ ConstExprEmitter *Emitter,
+ llvm::ConstantStruct *Base,
+ InitListExpr *Updater);
static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
InitListExpr *ILE);
static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
@@ -68,6 +73,8 @@ private:
void ConvertStructToPacked();
bool Build(InitListExpr *ILE);
+ bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base,
+ InitListExpr *Updater);
void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
llvm::Constant *Finalize(QualType Ty);
@@ -547,6 +554,17 @@ llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
CodeGenFunction *CGF,
+ ConstExprEmitter *Emitter,
+ llvm::ConstantStruct *Base,
+ InitListExpr *Updater) {
+ ConstStructBuilder Builder(CGM, CGF);
+ if (!Builder.Build(Emitter, Base, Updater))
+ return nullptr;
+ return Builder.Finalize(Updater->getType());
+}
+
+llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
+ CodeGenFunction *CGF,
InitListExpr *ILE) {
ConstStructBuilder Builder(CGM, CGF);
@@ -818,6 +836,82 @@ public:
return nullptr;
}
+ llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
+ InitListExpr *Updater) {
+ QualType ExprType = Updater->getType();
+
+ if (ExprType->isArrayType()) {
+ llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType));
+ llvm::Type *ElemType = AType->getElementType();
+
+ unsigned NumInitElements = Updater->getNumInits();
+ unsigned NumElements = AType->getNumElements();
+
+ std::vector<llvm::Constant *> Elts;
+ Elts.reserve(NumElements);
+
+ if (llvm::ConstantDataArray *DataArray =
+ dyn_cast<llvm::ConstantDataArray>(Base))
+ for (unsigned i = 0; i != NumElements; ++i)
+ Elts.push_back(DataArray->getElementAsConstant(i));
+ else if (llvm::ConstantArray *Array =
+ dyn_cast<llvm::ConstantArray>(Base))
+ for (unsigned i = 0; i != NumElements; ++i)
+ Elts.push_back(Array->getOperand(i));
+ else
+ return nullptr; // FIXME: other array types not implemented
+
+ llvm::Constant *fillC = nullptr;
+ if (Expr *filler = Updater->getArrayFiller())
+ if (!isa<NoInitExpr>(filler))
+ fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
+ bool RewriteType = (fillC && fillC->getType() != ElemType);
+
+ for (unsigned i = 0; i != NumElements; ++i) {
+ Expr *Init = nullptr;
+ if (i < NumInitElements)
+ Init = Updater->getInit(i);
+
+ if (!Init && fillC)
+ Elts[i] = fillC;
+ else if (!Init || isa<NoInitExpr>(Init))
+ ; // Do nothing.
+ else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
+ Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE);
+ else
+ Elts[i] = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
+
+ if (!Elts[i])
+ return nullptr;
+ RewriteType |= (Elts[i]->getType() != ElemType);
+ }
+
+ if (RewriteType) {
+ std::vector<llvm::Type *> Types;
+ Types.reserve(NumElements);
+ for (unsigned i = 0; i != NumElements; ++i)
+ Types.push_back(Elts[i]->getType());
+ llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
+ Types, true);
+ return llvm::ConstantStruct::get(SType, Elts);
+ }
+
+ return llvm::ConstantArray::get(AType, Elts);
+ }
+
+ if (ExprType->isRecordType())
+ return ConstStructBuilder::BuildStruct(CGM, CGF, this,
+ dyn_cast<llvm::ConstantStruct>(Base), Updater);
+
+ return nullptr;
+ }
+
+ llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
+ return EmitDesignatedInitUpdater(
+ CGM.EmitConstantExpr(E->getBase(), E->getType(), CGF),
+ E->getUpdater());
+ }
+
llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
if (!E->getConstructor()->isTrivial())
return nullptr;
@@ -1003,6 +1097,68 @@ public:
} // end anonymous namespace.
+bool ConstStructBuilder::Build(ConstExprEmitter *Emitter,
+ llvm::ConstantStruct *Base,
+ InitListExpr *Updater) {
+ assert(Base && "base expression should not be empty");
+
+ QualType ExprType = Updater->getType();
+ RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
+ const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
+ const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
+ Base->getType());
+ unsigned FieldNo = -1;
+ unsigned ElementNo = 0;
+
+ for (FieldDecl *Field : RD->fields()) {
+ ++FieldNo;
+
+ if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
+ continue;
+
+ // Skip anonymous bitfields.
+ if (Field->isUnnamedBitfield())
+ continue;
+
+ llvm::Constant *EltInit = Base->getOperand(ElementNo);
+
+ // Bail out if the type of the ConstantStruct does not have the same layout
+ // as the type of the InitListExpr.
+ if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
+ Layout.getFieldOffset(ElementNo) !=
+ BaseLayout->getElementOffsetInBits(ElementNo))
+ return false;
+
+ // Get the initializer. If we encounter an empty field or a NoInitExpr,
+ // we use values from the base expression.
+ Expr *Init = nullptr;
+ if (ElementNo < Updater->getNumInits())
+ Init = Updater->getInit(ElementNo);
+
+ if (!Init || isa<NoInitExpr>(Init))
+ ; // Do nothing.
+ else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
+ EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE);
+ else
+ EltInit = CGM.EmitConstantExpr(Init, Field->getType(), CGF);
+
+ ++ElementNo;
+
+ if (!EltInit)
+ return false;
+
+ if (!Field->isBitField())
+ AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
+ else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
+ AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
+ else
+ // Initializing a bitfield with a non-trivial constant?
+ return false;
+ }
+
+ return true;
+}
+
llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
CodeGenFunction *CGF) {
// Make a quick check if variable can be default NULL initialized
diff --git a/lib/CodeGen/CGExprScalar.cpp b/lib/CodeGen/CGExprScalar.cpp
index 08c81c012c76..330a0dffb244 100644
--- a/lib/CodeGen/CGExprScalar.cpp
+++ b/lib/CodeGen/CGExprScalar.cpp
@@ -1386,7 +1386,9 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
if (auto PT = DestTy->getAs<PointerType>())
CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
- /*MayBeNull=*/true);
+ /*MayBeNull=*/true,
+ CodeGenFunction::CFITCK_UnrelatedCast,
+ CE->getLocStart());
}
return Builder.CreateBitCast(Src, DstTy);
@@ -1420,7 +1422,9 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), Derived,
- /*MayBeNull=*/true);
+ /*MayBeNull=*/true,
+ CodeGenFunction::CFITCK_DerivedCast,
+ CE->getLocStart());
return Derived;
}
diff --git a/lib/CodeGen/CGLoopInfo.cpp b/lib/CodeGen/CGLoopInfo.cpp
index 0675544bedf0..1163d63b4a20 100644
--- a/lib/CodeGen/CGLoopInfo.cpp
+++ b/lib/CodeGen/CGLoopInfo.cpp
@@ -8,6 +8,8 @@
//===----------------------------------------------------------------------===//
#include "CGLoopInfo.h"
+#include "clang/AST/Attr.h"
+#include "clang/Sema/LoopHint.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InstrTypes.h"
@@ -76,7 +78,34 @@ LoopInfo::LoopInfo(BasicBlock *Header, const LoopAttributes &Attrs)
LoopID = createMetadata(Header->getContext(), Attrs);
}
-void LoopInfoStack::push(BasicBlock *Header) {
+void LoopInfoStack::push(BasicBlock *Header,
+ ArrayRef<const clang::Attr *> Attrs) {
+ for (const auto *Attr : Attrs) {
+ const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
+
+ // Skip non loop hint attributes
+ if (!LH)
+ continue;
+
+ LoopHintAttr::OptionType Option = LH->getOption();
+ LoopHintAttr::LoopHintState State = LH->getState();
+ switch (Option) {
+ case LoopHintAttr::Vectorize:
+ case LoopHintAttr::Interleave:
+ if (State == LoopHintAttr::AssumeSafety) {
+ // Apply "llvm.mem.parallel_loop_access" metadata to load/stores.
+ setParallel(true);
+ }
+ break;
+ case LoopHintAttr::VectorizeWidth:
+ case LoopHintAttr::InterleaveCount:
+ case LoopHintAttr::Unroll:
+ case LoopHintAttr::UnrollCount:
+ // Nothing to do here for these loop hints.
+ break;
+ }
+ }
+
Active.push_back(LoopInfo(Header, StagedAttrs));
// Clear the attributes so nested loops do not inherit them.
StagedAttrs.clear();
diff --git a/lib/CodeGen/CGLoopInfo.h b/lib/CodeGen/CGLoopInfo.h
index aee162118a2f..2249937cd0d0 100644
--- a/lib/CodeGen/CGLoopInfo.h
+++ b/lib/CodeGen/CGLoopInfo.h
@@ -15,6 +15,7 @@
#ifndef LLVM_CLANG_LIB_CODEGEN_CGLOOPINFO_H
#define LLVM_CLANG_LIB_CODEGEN_CGLOOPINFO_H
+#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Value.h"
@@ -27,6 +28,7 @@ class MDNode;
} // end namespace llvm
namespace clang {
+class Attr;
namespace CodeGen {
/// \brief Attributes that may be specified on loops.
@@ -86,7 +88,8 @@ public:
/// \brief Begin a new structured loop. The set of staged attributes will be
/// applied to the loop and then cleared.
- void push(llvm::BasicBlock *Header);
+ void push(llvm::BasicBlock *Header,
+ llvm::ArrayRef<const Attr *> Attrs = llvm::None);
/// \brief End the current loop.
void pop();
diff --git a/lib/CodeGen/CGObjC.cpp b/lib/CodeGen/CGObjC.cpp
index ef9a92dfc35b..9981fccb3e9d 100644
--- a/lib/CodeGen/CGObjC.cpp
+++ b/lib/CodeGen/CGObjC.cpp
@@ -2996,13 +2996,9 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
SmallVector<Expr*, 4> ConstructorArgs;
ConstructorArgs.push_back(&SRC);
- CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
- ++A;
-
- for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
- A != AEnd; ++A)
- ConstructorArgs.push_back(*A);
-
+ ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
+ CXXConstExpr->arg_end());
+
CXXConstructExpr *TheCXXConstructExpr =
CXXConstructExpr::Create(C, Ty, SourceLocation(),
CXXConstExpr->getConstructor(),
diff --git a/lib/CodeGen/CGOpenMPRuntime.cpp b/lib/CodeGen/CGOpenMPRuntime.cpp
index 1238accf42d7..3161af36c23e 100644
--- a/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -741,7 +741,7 @@ CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
break;
}
case OMPRTL__kmpc_end_ordered: {
- // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
+ // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
llvm::FunctionType *FnTy =
llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
@@ -756,6 +756,31 @@ CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
break;
}
+ case OMPRTL__kmpc_taskgroup: {
+ // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
+ llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+ llvm::FunctionType *FnTy =
+ llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
+ RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
+ break;
+ }
+ case OMPRTL__kmpc_end_taskgroup: {
+ // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
+ llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+ llvm::FunctionType *FnTy =
+ llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
+ RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
+ break;
+ }
+ case OMPRTL__kmpc_push_proc_bind: {
+ // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
+ // int proc_bind)
+ llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
+ llvm::FunctionType *FnTy =
+ llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
+ RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
+ break;
+ }
}
return RTLFn;
}
@@ -1240,6 +1265,25 @@ void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
}
+void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
+ const RegionCodeGenTy &TaskgroupOpGen,
+ SourceLocation Loc) {
+ // __kmpc_taskgroup(ident_t *, gtid);
+ // TaskgroupOpGen();
+ // __kmpc_end_taskgroup(ident_t *, gtid);
+ // Prepare arguments and build a call to __kmpc_taskgroup
+ {
+ CodeGenFunction::RunCleanupsScope Scope(CGF);
+ llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
+ CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
+ // Build a call to __kmpc_end_taskgroup
+ CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
+ NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
+ llvm::makeArrayRef(Args));
+ emitInlinedDirective(CGF, TaskgroupOpGen);
+ }
+}
+
static llvm::Value *emitCopyprivateCopyFunction(
CodeGenModule &CGM, llvm::Type *ArgsType,
ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
@@ -1600,6 +1644,39 @@ void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
Args);
}
+void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
+ OpenMPProcBindClauseKind ProcBind,
+ SourceLocation Loc) {
+ // Constants for proc bind value accepted by the runtime.
+ enum ProcBindTy {
+ ProcBindFalse = 0,
+ ProcBindTrue,
+ ProcBindMaster,
+ ProcBindClose,
+ ProcBindSpread,
+ ProcBindIntel,
+ ProcBindDefault
+ } RuntimeProcBind;
+ switch (ProcBind) {
+ case OMPC_PROC_BIND_master:
+ RuntimeProcBind = ProcBindMaster;
+ break;
+ case OMPC_PROC_BIND_close:
+ RuntimeProcBind = ProcBindClose;
+ break;
+ case OMPC_PROC_BIND_spread:
+ RuntimeProcBind = ProcBindSpread;
+ break;
+ case OMPC_PROC_BIND_unknown:
+ llvm_unreachable("Unsupported proc_bind value.");
+ }
+ // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
+ llvm::Value *Args[] = {
+ emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
+ llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
+ CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
+}
+
void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
SourceLocation Loc) {
// Build call void __kmpc_flush(ident_t *loc)
@@ -2242,7 +2319,7 @@ void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
ArrayRef<const Expr *> ReductionOps,
- bool WithNowait) {
+ bool WithNowait, bool SimpleReduction) {
// Next code should be emitted for reduction:
//
// static kmp_critical_name lock = { 0 };
@@ -2272,9 +2349,22 @@ void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
// break;
// default:;
// }
+ //
+ // if SimpleReduction is true, only the next code is generated:
+ // ...
+ // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
+ // ...
auto &C = CGM.getContext();
+ if (SimpleReduction) {
+ CodeGenFunction::RunCleanupsScope Scope(CGF);
+ for (auto *E : ReductionOps) {
+ CGF.EmitIgnoredExpr(E);
+ }
+ return;
+ }
+
// 1. Build a list of reduction variables.
// void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
diff --git a/lib/CodeGen/CGOpenMPRuntime.h b/lib/CodeGen/CGOpenMPRuntime.h
index f5aa4a51df93..d1efde25d096 100644
--- a/lib/CodeGen/CGOpenMPRuntime.h
+++ b/lib/CodeGen/CGOpenMPRuntime.h
@@ -131,6 +131,13 @@ private:
// Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
// global_tid);
OMPRTL__kmpc_omp_taskwait,
+ // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
+ OMPRTL__kmpc_taskgroup,
+ // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
+ OMPRTL__kmpc_end_taskgroup,
+ // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
+ // int proc_bind);
+ OMPRTL__kmpc_push_proc_bind,
};
/// \brief Values for bit flags used in the ident_t to describe the fields.
@@ -388,6 +395,13 @@ public:
/// \brief Emits code for a taskyield directive.
virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
+ /// \brief Emit a taskgroup region.
+ /// \param TaskgroupOpGen Generator for the statement associated with the
+ /// given taskgroup region.
+ virtual void emitTaskgroupRegion(CodeGenFunction &CGF,
+ const RegionCodeGenTy &TaskgroupOpGen,
+ SourceLocation Loc);
+
/// \brief Emits a single region.
/// \param SingleOpGen Generator for the statement associated with the given
/// single region.
@@ -401,7 +415,7 @@ public:
/// \brief Emit an ordered region.
/// \param OrderedOpGen Generator for the statement associated with the given
- /// critical region.
+ /// ordered region.
virtual void emitOrderedRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &OrderedOpGen,
SourceLocation Loc);
@@ -504,6 +518,12 @@ public:
llvm::Value *NumThreads,
SourceLocation Loc);
+ /// \brief Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
+ /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
+ virtual void emitProcBindClause(CodeGenFunction &CGF,
+ OpenMPProcBindClauseKind ProcBind,
+ SourceLocation Loc);
+
/// \brief Returns address of the threadprivate variable for the current
/// thread.
/// \param VD Threadprivate variable.
@@ -632,7 +652,7 @@ public:
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
ArrayRef<const Expr *> ReductionOps,
- bool WithNowait);
+ bool WithNowait, bool SimpleReduction);
/// \brief Emit code for 'taskwait' directive.
virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc);
diff --git a/lib/CodeGen/CGStmt.cpp b/lib/CodeGen/CGStmt.cpp
index c879750015bf..9286f0358926 100644
--- a/lib/CodeGen/CGStmt.cpp
+++ b/lib/CodeGen/CGStmt.cpp
@@ -222,6 +222,9 @@ void CodeGenFunction::EmitStmt(const Stmt *S) {
case Stmt::OMPTaskwaitDirectiveClass:
EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
break;
+ case Stmt::OMPTaskgroupDirectiveClass:
+ EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
+ break;
case Stmt::OMPFlushDirectiveClass:
EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
break;
@@ -682,7 +685,7 @@ void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
EmitBlock(LoopHeader.getBlock());
- LoopStack.push(LoopHeader.getBlock());
+ LoopStack.push(LoopHeader.getBlock(), WhileAttrs);
// Create an exit block for when the condition fails, which will
// also become the break target.
@@ -776,7 +779,7 @@ void CodeGenFunction::EmitDoStmt(const DoStmt &S,
// Emit the body of the loop.
llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
- LoopStack.push(LoopBody);
+ LoopStack.push(LoopBody, DoAttrs);
EmitBlockWithFallThrough(LoopBody, &S);
{
@@ -842,7 +845,7 @@ void CodeGenFunction::EmitForStmt(const ForStmt &S,
llvm::BasicBlock *CondBlock = Continue.getBlock();
EmitBlock(CondBlock);
- LoopStack.push(CondBlock);
+ LoopStack.push(CondBlock, ForAttrs);
// If the for loop doesn't have an increment we can just use the
// condition as the continue block. Otherwise we'll need to create
@@ -940,7 +943,7 @@ CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
EmitBlock(CondBlock);
- LoopStack.push(CondBlock);
+ LoopStack.push(CondBlock, ForAttrs);
// If there are any cleanups between here and the loop-exit scope,
// create a block to stage a loop exit along.
@@ -1750,6 +1753,16 @@ llvm::Value* CodeGenFunction::EmitAsmInput(
const TargetInfo::ConstraintInfo &Info,
const Expr *InputExpr,
std::string &ConstraintStr) {
+ // If this can't be a register or memory, i.e., has to be a constant
+ // (immediate or symbolic), try to emit it as such.
+ if (!Info.allowsRegister() && !Info.allowsMemory()) {
+ llvm::APSInt Result;
+ if (InputExpr->EvaluateAsInt(Result, getContext()))
+ return llvm::ConstantInt::get(getLLVMContext(), Result);
+ assert(!Info.requiresImmediateConstant() &&
+ "Required-immediate inlineasm arg isn't constant?");
+ }
+
if (Info.allowsRegister() || !Info.allowsMemory())
if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
return EmitScalarExpr(InputExpr);
diff --git a/lib/CodeGen/CGStmtOpenMP.cpp b/lib/CodeGen/CGStmtOpenMP.cpp
index 07fc6e966af6..5e94d56feb5f 100644
--- a/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/lib/CodeGen/CGStmtOpenMP.cpp
@@ -316,26 +316,32 @@ void CodeGenFunction::EmitOMPLastprivateClauseFinal(
// ...
// orig_varn = private_orig_varn;
// }
- auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
- auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
- Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
- EmitBlock(ThenBB);
+ llvm::BasicBlock *ThenBB = nullptr;
+ llvm::BasicBlock *DoneBB = nullptr;
+ if (IsLastIterCond) {
+ ThenBB = createBasicBlock(".omp.lastprivate.then");
+ DoneBB = createBasicBlock(".omp.lastprivate.done");
+ Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
+ EmitBlock(ThenBB);
+ }
llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
const Expr *LastIterVal = nullptr;
const Expr *IVExpr = nullptr;
const Expr *IncExpr = nullptr;
if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
- LastIterVal =
- cast<VarDecl>(cast<DeclRefExpr>(LoopDirective->getUpperBoundVariable())
- ->getDecl())
- ->getAnyInitializer();
- IVExpr = LoopDirective->getIterationVariable();
- IncExpr = LoopDirective->getInc();
- auto IUpdate = LoopDirective->updates().begin();
- for (auto *E : LoopDirective->counters()) {
- auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
- LoopCountersAndUpdates[D] = *IUpdate;
- ++IUpdate;
+ if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
+ LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
+ LoopDirective->getUpperBoundVariable())
+ ->getDecl())
+ ->getAnyInitializer();
+ IVExpr = LoopDirective->getIterationVariable();
+ IncExpr = LoopDirective->getInc();
+ auto IUpdate = LoopDirective->updates().begin();
+ for (auto *E : LoopDirective->counters()) {
+ auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
+ LoopCountersAndUpdates[D] = *IUpdate;
+ ++IUpdate;
+ }
}
}
{
@@ -355,7 +361,7 @@ void CodeGenFunction::EmitOMPLastprivateClauseFinal(
// directive, update its value before copyin back to original
// variable.
if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
- if (FirstLCV) {
+ if (FirstLCV && LastIterVal) {
EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
IVExpr->getType().getQualifiers(),
/*IsInitializer=*/false);
@@ -379,7 +385,9 @@ void CodeGenFunction::EmitOMPLastprivateClauseFinal(
}
}
}
- EmitBlock(DoneBB, /*IsFinished=*/true);
+ if (IsLastIterCond) {
+ EmitBlock(DoneBB, /*IsFinished=*/true);
+ }
}
void CodeGenFunction::EmitOMPReductionClauseInit(
@@ -435,7 +443,9 @@ void CodeGenFunction::EmitOMPReductionClauseFinal(
CGM.getOpenMPRuntime().emitReduction(
*this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
D.getSingleClause(OMPC_nowait) ||
- isOpenMPParallelDirective(D.getDirectiveKind()));
+ isOpenMPParallelDirective(D.getDirectiveKind()) ||
+ D.getDirectiveKind() == OMPD_simd,
+ D.getDirectiveKind() == OMPD_simd);
}
}
@@ -454,6 +464,12 @@ static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
CGF, NumThreads, NumThreadsClause->getLocStart());
}
+ if (auto *C = S.getSingleClause(OMPC_proc_bind)) {
+ CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
+ auto *ProcBindClause = cast<OMPProcBindClause>(C);
+ CGF.CGM.getOpenMPRuntime().emitProcBindClause(
+ CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
+ }
const Expr *IfCond = nullptr;
if (auto C = S.getSingleClause(OMPC_if)) {
IfCond = cast<OMPIfClause>(C)->getCondition();
@@ -489,15 +505,14 @@ void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
emitCommonOMPParallelDirective(*this, S, CodeGen);
}
-void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
- bool SeparateIter) {
+void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D) {
RunCleanupsScope BodyScope(*this);
// Update counters values on current iteration.
- for (auto I : S.updates()) {
+ for (auto I : D.updates()) {
EmitIgnoredExpr(I);
}
// Update the linear variables.
- for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
+ for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
auto *C = cast<OMPLinearClause>(*I);
for (auto U : C->updates()) {
EmitIgnoredExpr(U);
@@ -508,16 +523,14 @@ void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
auto Continue = getJumpDestInCurrentScope("omp.body.continue");
BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
// Emit loop body.
- EmitStmt(S.getBody());
+ EmitStmt(D.getBody());
// The end (updates/cleanups).
EmitBlock(Continue.getBlock());
BreakContinueStack.pop_back();
- if (SeparateIter) {
// TODO: Update lastprivates if the SeparateIter flag is true.
// This will be implemented in a follow-up OMPLastprivateClause patch, but
// result should be still correct without it, as we do not make these
// variables private yet.
- }
}
void CodeGenFunction::EmitOMPInnerLoop(
@@ -567,70 +580,89 @@ void CodeGenFunction::EmitOMPInnerLoop(
EmitBlock(LoopExit.getBlock());
}
-void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
- auto IC = S.counters().begin();
- for (auto F : S.finals()) {
- auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
- if (LocalDeclMap.lookup(OrigVD)) {
+void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
+ // Emit inits for the linear variables.
+ for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
+ auto *C = cast<OMPLinearClause>(*I);
+ for (auto Init : C->inits()) {
+ auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
+ auto *OrigVD = cast<VarDecl>(
+ cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
CapturedStmtInfo->lookup(OrigVD) != nullptr,
- (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
- auto *OrigAddr = EmitLValue(&DRE).getAddress();
- OMPPrivateScope VarScope(*this);
- VarScope.addPrivate(OrigVD,
- [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
- (void)VarScope.Privatize();
- EmitIgnoredExpr(F);
+ VD->getInit()->getType(), VK_LValue,
+ VD->getInit()->getExprLoc());
+ AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
+ EmitExprAsInit(&DRE, VD,
+ MakeAddrLValue(Emission.getAllocatedAddress(),
+ VD->getType(), Emission.Alignment),
+ /*capturedByInit=*/false);
+ EmitAutoVarCleanups(Emission);
}
- ++IC;
+ // Emit the linear steps for the linear clauses.
+ // If a step is not constant, it is pre-calculated before the loop.
+ if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
+ if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
+ EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
+ // Emit calculation of the linear step.
+ EmitIgnoredExpr(CS);
+ }
}
+}
+
+static void emitLinearClauseFinal(CodeGenFunction &CGF,
+ const OMPLoopDirective &D) {
// Emit the final values of the linear variables.
- for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
+ for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
auto *C = cast<OMPLinearClause>(*I);
auto IC = C->varlist_begin();
for (auto F : C->finals()) {
auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
- CapturedStmtInfo->lookup(OrigVD) != nullptr,
+ CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
(*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
- auto *OrigAddr = EmitLValue(&DRE).getAddress();
- OMPPrivateScope VarScope(*this);
+ auto *OrigAddr = CGF.EmitLValue(&DRE).getAddress();
+ CodeGenFunction::OMPPrivateScope VarScope(CGF);
VarScope.addPrivate(OrigVD,
[OrigAddr]() -> llvm::Value *{ return OrigAddr; });
(void)VarScope.Privatize();
- EmitIgnoredExpr(F);
+ CGF.EmitIgnoredExpr(F);
++IC;
}
}
}
-static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
- const OMPAlignedClause &Clause) {
- unsigned ClauseAlignment = 0;
- if (auto AlignmentExpr = Clause.getAlignment()) {
- auto AlignmentCI =
- cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
- ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
- }
- for (auto E : Clause.varlists()) {
- unsigned Alignment = ClauseAlignment;
- if (Alignment == 0) {
- // OpenMP [2.8.1, Description]
- // If no optional parameter is specified, implementation-defined default
- // alignments for SIMD instructions on the target platforms are assumed.
- Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
- E->getType());
+static void emitAlignedClause(CodeGenFunction &CGF,
+ const OMPExecutableDirective &D) {
+ for (auto &&I = D.getClausesOfKind(OMPC_aligned); I; ++I) {
+ auto *Clause = cast<OMPAlignedClause>(*I);
+ unsigned ClauseAlignment = 0;
+ if (auto AlignmentExpr = Clause->getAlignment()) {
+ auto AlignmentCI =
+ cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
+ ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
}
- assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
- "alignment is not power of 2");
- if (Alignment != 0) {
- llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
- CGF.EmitAlignmentAssumption(PtrValue, Alignment);
+ for (auto E : Clause->varlists()) {
+ unsigned Alignment = ClauseAlignment;
+ if (Alignment == 0) {
+ // OpenMP [2.8.1, Description]
+ // If no optional parameter is specified, implementation-defined default
+ // alignments for SIMD instructions on the target platforms are assumed.
+ Alignment =
+ CGF.CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
+ E->getType());
+ }
+ assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
+ "alignment is not power of 2");
+ if (Alignment != 0) {
+ llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
+ CGF.EmitAlignmentAssumption(PtrValue, Alignment);
+ }
}
}
}
-static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
+static void emitPrivateLoopCounters(CodeGenFunction &CGF,
CodeGenFunction::OMPPrivateScope &LoopScope,
ArrayRef<Expr *> Counters) {
for (auto *E : Counters) {
@@ -647,37 +679,39 @@ static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
const Expr *Cond, llvm::BasicBlock *TrueBlock,
llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
- CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
- EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
- const VarDecl *IVDecl =
- cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
- bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
- // Emit var without initialization.
- auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
- CGF.EmitAutoVarCleanups(VarEmission);
- return VarEmission.getAllocatedAddress();
- });
- assert(IsRegistered && "counter already registered as private");
- // Silence the warning about unused variable.
- (void)IsRegistered;
- (void)PreCondScope.Privatize();
- // Initialize internal counter to 0 to calculate initial values of real
- // counters.
- LValue IV = CGF.EmitLValue(S.getIterationVariable());
- CGF.EmitStoreOfScalar(
- llvm::ConstantInt::getNullValue(
- IV.getAddress()->getType()->getPointerElementType()),
- CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
- // Get initial values of real counters.
- for (auto I : S.updates()) {
- CGF.EmitIgnoredExpr(I);
+ {
+ CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
+ emitPrivateLoopCounters(CGF, PreCondScope, S.counters());
+ const VarDecl *IVDecl =
+ cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
+ bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
+ // Emit var without initialization.
+ auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
+ CGF.EmitAutoVarCleanups(VarEmission);
+ return VarEmission.getAllocatedAddress();
+ });
+ assert(IsRegistered && "counter already registered as private");
+ // Silence the warning about unused variable.
+ (void)IsRegistered;
+ (void)PreCondScope.Privatize();
+ // Initialize internal counter to 0 to calculate initial values of real
+ // counters.
+ LValue IV = CGF.EmitLValue(S.getIterationVariable());
+ CGF.EmitStoreOfScalar(
+ llvm::ConstantInt::getNullValue(
+ IV.getAddress()->getType()->getPointerElementType()),
+ CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
+ // Get initial values of real counters.
+ for (auto I : S.updates()) {
+ CGF.EmitIgnoredExpr(I);
+ }
}
// Check that loop is executed at least one time.
CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
}
static void
-EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
+emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
CodeGenFunction::OMPPrivateScope &PrivateScope) {
for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
auto *C = cast<OMPLinearClause>(*I);
@@ -696,19 +730,50 @@ EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
}
}
+static void emitSafelenClause(CodeGenFunction &CGF,
+ const OMPExecutableDirective &D) {
+ if (auto *C =
+ cast_or_null<OMPSafelenClause>(D.getSingleClause(OMPC_safelen))) {
+ RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
+ /*ignoreResult=*/true);
+ llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
+ CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
+ // In presence of finite 'safelen', it may be unsafe to mark all
+ // the memory instructions parallel, because loop-carried
+ // dependences of 'safelen' iterations are possible.
+ CGF.LoopStack.setParallel(false);
+ }
+}
+
+void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
+ // Walk clauses and process safelen/lastprivate.
+ LoopStack.setParallel();
+ LoopStack.setVectorizerEnable(true);
+ emitSafelenClause(*this, D);
+}
+
+void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
+ auto IC = D.counters().begin();
+ for (auto F : D.finals()) {
+ auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
+ if (LocalDeclMap.lookup(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
+ DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
+ CapturedStmtInfo->lookup(OrigVD) != nullptr,
+ (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
+ auto *OrigAddr = EmitLValue(&DRE).getAddress();
+ OMPPrivateScope VarScope(*this);
+ VarScope.addPrivate(OrigVD,
+ [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
+ (void)VarScope.Privatize();
+ EmitIgnoredExpr(F);
+ }
+ ++IC;
+ }
+ emitLinearClauseFinal(*this, D);
+}
+
void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
auto &&CodeGen = [&S](CodeGenFunction &CGF) {
- // Pragma 'simd' code depends on presence of 'lastprivate'.
- // If present, we have to separate last iteration of the loop:
- //
- // if (PreCond) {
- // for (IV in 0..LastIteration-1) BODY;
- // BODY with updates of lastprivate vars;
- // <Final counter/linear vars updates>;
- // }
- //
- // otherwise (when there's no lastprivate):
- //
// if (PreCond) {
// for (IV in 0..LastIteration) BODY;
// <Final counter/linear vars updates>;
@@ -731,43 +796,6 @@ void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
CGF.EmitBlock(ThenBlock);
CGF.incrementProfileCounter(&S);
}
- // Walk clauses and process safelen/lastprivate.
- bool SeparateIter = false;
- CGF.LoopStack.setParallel();
- CGF.LoopStack.setVectorizerEnable(true);
- for (auto C : S.clauses()) {
- switch (C->getClauseKind()) {
- case OMPC_safelen: {
- RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
- AggValueSlot::ignored(), true);
- llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
- CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
- // In presence of finite 'safelen', it may be unsafe to mark all
- // the memory instructions parallel, because loop-carried
- // dependences of 'safelen' iterations are possible.
- CGF.LoopStack.setParallel(false);
- break;
- }
- case OMPC_aligned:
- EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
- break;
- case OMPC_lastprivate:
- SeparateIter = true;
- break;
- default:
- // Not handled yet
- ;
- }
- }
-
- // Emit inits for the linear variables.
- for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
- auto *C = cast<OMPLinearClause>(*I);
- for (auto Init : C->inits()) {
- auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
- CGF.EmitVarDecl(*D);
- }
- }
// Emit the loop iteration variable.
const Expr *IVExpr = S.getIterationVariable();
@@ -784,34 +812,31 @@ void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
CGF.EmitIgnoredExpr(S.getCalcLastIteration());
}
- // Emit the linear steps for the linear clauses.
- // If a step is not constant, it is pre-calculated before the loop.
- for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
- auto *C = cast<OMPLinearClause>(*I);
- if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
- if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
- CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
- // Emit calculation of the linear step.
- CGF.EmitIgnoredExpr(CS);
- }
- }
+ CGF.EmitOMPSimdInit(S);
+ emitAlignedClause(CGF, S);
+ CGF.EmitOMPLinearClauseInit(S);
+ bool HasLastprivateClause;
{
OMPPrivateScope LoopScope(CGF);
- EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
- EmitPrivateLinearVars(CGF, S, LoopScope);
+ emitPrivateLoopCounters(CGF, LoopScope, S.counters());
+ emitPrivateLinearVars(CGF, S, LoopScope);
CGF.EmitOMPPrivateClause(S, LoopScope);
+ CGF.EmitOMPReductionClauseInit(S, LoopScope);
+ HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
(void)LoopScope.Privatize();
CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
- S.getCond(SeparateIter), S.getInc(),
+ S.getCond(), S.getInc(),
[&S](CodeGenFunction &CGF) {
CGF.EmitOMPLoopBody(S);
CGF.EmitStopPoint(&S);
},
[](CodeGenFunction &) {});
- if (SeparateIter) {
- CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
+ // Emit final copy of the lastprivate variables at the end of loops.
+ if (HasLastprivateClause) {
+ CGF.EmitOMPLastprivateClauseFinal(S);
}
+ CGF.EmitOMPReductionClauseFinal(S);
}
CGF.EmitOMPSimdFinal(S);
// Emit: if (PreCond) - end.
@@ -912,7 +937,7 @@ void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
// IV = LB
EmitIgnoredExpr(S.getInit());
// IV < UB
- BoolCondVal = EvaluateExprAsBool(S.getCond(false));
+ BoolCondVal = EvaluateExprAsBool(S.getCond());
} else {
BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
IL, LB, UB, ST);
@@ -941,14 +966,19 @@ void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
+ // Generate !llvm.loop.parallel metadata for loads and stores for loops
+ // with dynamic/guided scheduling and without ordered clause.
+ if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
+ LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
+ ScheduleKind == OMPC_SCHEDULE_guided) &&
+ !Ordered);
+ } else {
+ EmitOMPSimdInit(S);
+ }
+
SourceLocation Loc = S.getLocStart();
- // Generate !llvm.loop.parallel metadata for loads and stores for loops with
- // dynamic/guided scheduling and without ordered clause.
- LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
- ScheduleKind == OMPC_SCHEDULE_guided) &&
- !Ordered);
EmitOMPInnerLoop(
- S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
+ S, LoopScope.requiresCleanups(), S.getCond(),
S.getInc(),
[&S](CodeGenFunction &CGF) {
CGF.EmitOMPLoopBody(S);
@@ -1055,6 +1085,9 @@ bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
EmitBlock(ThenBlock);
incrementProfileCounter(&S);
}
+
+ emitAlignedClause(*this, S);
+ EmitOMPLinearClauseInit(S);
// Emit 'then' code.
{
// Emit helper vars inits.
@@ -1077,7 +1110,8 @@ bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
EmitOMPPrivateClause(S, LoopScope);
HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
EmitOMPReductionClauseInit(S, LoopScope);
- EmitPrivateLoopCounters(*this, LoopScope, S.counters());
+ emitPrivateLoopCounters(*this, LoopScope, S.counters());
+ emitPrivateLinearVars(*this, S, LoopScope);
(void)LoopScope.Privatize();
// Detect the loop schedule kind and chunk.
@@ -1093,6 +1127,9 @@ bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
if (RT.isStaticNonchunked(ScheduleKind,
/* Chunked */ Chunk != nullptr) &&
!Ordered) {
+ if (isOpenMPSimdDirective(S.getDirectiveKind())) {
+ EmitOMPSimdInit(S);
+ }
// OpenMP [2.7.1, Loop Construct, Description, table 2-1]
// When no chunk_size is specified, the iteration space is divided into
// chunks that are approximately equal in size, and at most one chunk is
@@ -1106,8 +1143,8 @@ bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
// IV = LB;
EmitIgnoredExpr(S.getInit());
// while (idx <= UB) { BODY; ++idx; }
- EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
- S.getCond(/*SeparateIter=*/false), S.getInc(),
+ EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
+ S.getInc(),
[&S](CodeGenFunction &CGF) {
CGF.EmitOMPLoopBody(S);
CGF.EmitStopPoint(&S);
@@ -1128,6 +1165,9 @@ bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
EmitOMPLastprivateClauseFinal(
S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
}
+ if (isOpenMPSimdDirective(S.getDirectiveKind())) {
+ EmitOMPSimdFinal(S);
+ }
// We're now done with the loop, so jump to the continuation block.
if (ContBlock) {
EmitBranch(ContBlock);
@@ -1151,8 +1191,18 @@ void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
}
}
-void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
- llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
+void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
+ LexicalScope Scope(*this, S.getSourceRange());
+ bool HasLastprivates = false;
+ auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
+ HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
+ };
+ CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
+
+ // Emit an implicit barrier at the end.
+ if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
+ CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
+ }
}
static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
@@ -1407,8 +1457,20 @@ void CodeGenFunction::EmitOMPParallelForDirective(
}
void CodeGenFunction::EmitOMPParallelForSimdDirective(
- const OMPParallelForSimdDirective &) {
- llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
+ const OMPParallelForSimdDirective &S) {
+ // Emit directive as a combined directive that consists of two implicit
+ // directives: 'parallel' with 'for' directive.
+ LexicalScope Scope(*this, S.getSourceRange());
+ (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
+ auto &&CodeGen = [&S](CodeGenFunction &CGF) {
+ CGF.EmitOMPWorksharingLoop(S);
+ // Emit implicit barrier at the end of parallel region, but this barrier
+ // is at the end of 'for' directive, so emit it as the implicit barrier for
+ // this 'for' directive.
+ CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
+ OMPD_parallel);
+ };
+ emitCommonOMPParallelDirective(*this, S, CodeGen);
}
void CodeGenFunction::EmitOMPParallelSectionsDirective(
@@ -1556,6 +1618,16 @@ void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
}
+void CodeGenFunction::EmitOMPTaskgroupDirective(
+ const OMPTaskgroupDirective &S) {
+ LexicalScope Scope(*this, S.getSourceRange());
+ auto &&CodeGen = [&S](CodeGenFunction &CGF) {
+ CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
+ CGF.EnsureInsertPoint();
+ };
+ CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
+}
+
void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
diff --git a/lib/CodeGen/CGVTables.cpp b/lib/CodeGen/CGVTables.cpp
index 57370a6faa2c..17db40138296 100644
--- a/lib/CodeGen/CGVTables.cpp
+++ b/lib/CodeGen/CGVTables.cpp
@@ -848,7 +848,8 @@ void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
!LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
return;
- llvm::Metadata *VTableMD = llvm::ConstantAsMetadata::get(VTable);
+ CharUnits PointerWidth =
+ Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
std::vector<llvm::MDTuple *> BitsetEntries;
// Create a bit set entry for each address point.
@@ -857,23 +858,8 @@ void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
if (AP.first.getBase()->isInStdNamespace())
continue;
- std::string OutName;
- llvm::raw_string_ostream Out(OutName);
- getCXXABI().getMangleContext().mangleCXXVTableBitSet(AP.first.getBase(),
- Out);
-
- CharUnits PointerWidth =
- Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
- uint64_t AddrPointOffset = AP.second * PointerWidth.getQuantity();
-
- llvm::Metadata *BitsetOps[] = {
- llvm::MDString::get(getLLVMContext(), Out.str()),
- VTableMD,
- llvm::ConstantAsMetadata::get(
- llvm::ConstantInt::get(Int64Ty, AddrPointOffset))};
- llvm::MDTuple *BitsetEntry =
- llvm::MDTuple::get(getLLVMContext(), BitsetOps);
- BitsetEntries.push_back(BitsetEntry);
+ BitsetEntries.push_back(CreateVTableBitSetEntry(
+ VTable, PointerWidth * AP.second, AP.first.getBase()));
}
// Sort the bit set entries for determinism.
diff --git a/lib/CodeGen/CodeGenAction.cpp b/lib/CodeGen/CodeGenAction.cpp
index 7e82fcc4b22a..54e6b73b3020 100644
--- a/lib/CodeGen/CodeGenAction.cpp
+++ b/lib/CodeGen/CodeGenAction.cpp
@@ -649,14 +649,14 @@ CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
return nullptr;
}
- ErrorOr<llvm::Module *> ModuleOrErr =
+ ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
if (std::error_code EC = ModuleOrErr.getError()) {
CI.getDiagnostics().Report(diag::err_cannot_open_file)
<< LinkBCFile << EC.message();
return nullptr;
}
- LinkModuleToUse = ModuleOrErr.get();
+ LinkModuleToUse = ModuleOrErr.get().release();
}
CoverageSourceInfo *CoverageInfo = nullptr;
diff --git a/lib/CodeGen/CodeGenFunction.cpp b/lib/CodeGen/CodeGenFunction.cpp
index 01da75005610..bece41e9ecb2 100644
--- a/lib/CodeGen/CodeGenFunction.cpp
+++ b/lib/CodeGen/CodeGenFunction.cpp
@@ -615,12 +615,14 @@ void CodeGenFunction::StartFunction(GlobalDecl GD,
}
// Apply sanitizer attributes to the function.
- if (SanOpts.has(SanitizerKind::Address))
+ if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (SanOpts.has(SanitizerKind::Thread))
Fn->addFnAttr(llvm::Attribute::SanitizeThread);
if (SanOpts.has(SanitizerKind::Memory))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
+ if (SanOpts.has(SanitizerKind::SafeStack))
+ Fn->addFnAttr(llvm::Attribute::SafeStack);
// Pass inline keyword to optimizer if it appears explicitly on any
// declaration. Also, in the case of -fno-inline attach NoInline
diff --git a/lib/CodeGen/CodeGenFunction.h b/lib/CodeGen/CodeGenFunction.h
index 469022dc62ed..45475d1af1c4 100644
--- a/lib/CodeGen/CodeGenFunction.h
+++ b/lib/CodeGen/CodeGenFunction.h
@@ -1311,19 +1311,29 @@ public:
/// to by This.
llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
+ enum CFITypeCheckKind {
+ CFITCK_VCall,
+ CFITCK_NVCall,
+ CFITCK_DerivedCast,
+ CFITCK_UnrelatedCast,
+ };
+
/// \brief Derived is the presumed address of an object of type T after a
/// cast. If T is a polymorphic class type, emit a check that the virtual
/// table for Derived belongs to a class derived from T.
void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
- bool MayBeNull);
+ bool MayBeNull, CFITypeCheckKind TCK,
+ SourceLocation Loc);
/// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
/// If vptr CFI is enabled, emit a check that VTable is valid.
- void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable);
+ void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable,
+ CFITypeCheckKind TCK, SourceLocation Loc);
/// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
/// RD using llvm.bitset.test.
- void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable);
+ void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
+ CFITypeCheckKind TCK, SourceLocation Loc);
/// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
/// expr can be devirtualized.
@@ -2130,9 +2140,9 @@ public:
/// \param D Directive that has at least one 'lastprivate' directives.
/// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
/// it is the last iteration of the loop code in associated directive, or to
- /// 'i1 false' otherwise.
+ /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
- llvm::Value *IsLastIterCond);
+ llvm::Value *IsLastIterCond = nullptr);
/// \brief Emit initial code for reduction variables. Creates reduction copies
/// and initializes them with the values according to OpenMP standard.
///
@@ -2147,6 +2157,11 @@ public:
///
/// \param D Directive that has at least one 'reduction' directives.
void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
+ /// \brief Emit initial code for linear variables. Creates private copies
+ /// and initializes them with the values according to OpenMP standard.
+ ///
+ /// \param D Directive (possibly) with the 'linear' clause.
+ void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
void EmitOMPParallelDirective(const OMPParallelDirective &S);
void EmitOMPSimdDirective(const OMPSimdDirective &S);
@@ -2164,6 +2179,7 @@ public:
void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
+ void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
void EmitOMPFlushDirective(const OMPFlushDirective &S);
void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
@@ -2189,9 +2205,9 @@ public:
private:
/// Helpers for the OpenMP loop directives.
- void EmitOMPLoopBody(const OMPLoopDirective &Directive,
- bool SeparateIter = false);
- void EmitOMPSimdFinal(const OMPLoopDirective &S);
+ void EmitOMPLoopBody(const OMPLoopDirective &D);
+ void EmitOMPSimdInit(const OMPLoopDirective &D);
+ void EmitOMPSimdFinal(const OMPLoopDirective &D);
/// \brief Emit code for the worksharing loop-based directive.
/// \return true, if this construct has any lastprivate clause, false -
/// otherwise.
@@ -2568,7 +2584,7 @@ public:
llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
- llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
+ llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
diff --git a/lib/CodeGen/CodeGenModule.cpp b/lib/CodeGen/CodeGenModule.cpp
index 9496831ea8c8..2dd5414795e7 100644
--- a/lib/CodeGen/CodeGenModule.cpp
+++ b/lib/CodeGen/CodeGenModule.cpp
@@ -205,11 +205,9 @@ void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
}
void CodeGenModule::applyReplacements() {
- for (ReplacementsTy::iterator I = Replacements.begin(),
- E = Replacements.end();
- I != E; ++I) {
- StringRef MangledName = I->first();
- llvm::Constant *Replacement = I->second;
+ for (auto &I : Replacements) {
+ StringRef MangledName = I.first();
+ llvm::Constant *Replacement = I.second;
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (!Entry)
continue;
@@ -261,9 +259,7 @@ void CodeGenModule::checkAliases() {
// and aliases during codegen.
bool Error = false;
DiagnosticsEngine &Diags = getDiags();
- for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
- E = Aliases.end(); I != E; ++I) {
- const GlobalDecl &GD = *I;
+ for (const GlobalDecl &GD : Aliases) {
const auto *D = cast<ValueDecl>(GD.getDecl());
const AliasAttr *AA = D->getAttr<AliasAttr>();
StringRef MangledName = getMangledName(GD);
@@ -310,9 +306,7 @@ void CodeGenModule::checkAliases() {
if (!Error)
return;
- for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
- E = Aliases.end(); I != E; ++I) {
- const GlobalDecl &GD = *I;
+ for (const GlobalDecl &GD : Aliases) {
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
auto *Alias = cast<llvm::GlobalAlias>(Entry);
@@ -637,15 +631,14 @@ void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
// Construct the constructor and destructor arrays.
- SmallVector<llvm::Constant*, 8> Ctors;
- for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
+ SmallVector<llvm::Constant *, 8> Ctors;
+ for (const auto &I : Fns) {
llvm::Constant *S[] = {
- llvm::ConstantInt::get(Int32Ty, I->Priority, false),
- llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
- (I->AssociatedData
- ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
- : llvm::Constant::getNullValue(VoidPtrTy))
- };
+ llvm::ConstantInt::get(Int32Ty, I.Priority, false),
+ llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
+ (I.AssociatedData
+ ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
+ : llvm::Constant::getNullValue(VoidPtrTy))};
Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
}
@@ -1029,12 +1022,9 @@ void CodeGenModule::EmitModuleLinkOptions() {
SmallVector<clang::Module *, 16> Stack;
// Seed the stack with imported modules.
- for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
- MEnd = ImportedModules.end();
- M != MEnd; ++M) {
- if (Visited.insert(*M).second)
- Stack.push_back(*M);
- }
+ for (Module *M : ImportedModules)
+ if (Visited.insert(M).second)
+ Stack.push_back(M);
// Find all of the modules to import, making a little effort to prune
// non-leaf modules.
@@ -1070,12 +1060,9 @@ void CodeGenModule::EmitModuleLinkOptions() {
// to linker options inserted by things like #pragma comment().
SmallVector<llvm::Metadata *, 16> MetadataArgs;
Visited.clear();
- for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
- MEnd = LinkModules.end();
- M != MEnd; ++M) {
- if (Visited.insert(*M).second)
- addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
- }
+ for (Module *M : LinkModules)
+ if (Visited.insert(M).second)
+ addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
std::reverse(MetadataArgs.begin(), MetadataArgs.end());
LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
@@ -1231,8 +1218,9 @@ bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
SourceLocation Loc, QualType Ty,
StringRef Category) const {
- // For now globals can be blacklisted only in ASan.
- if (!LangOpts.Sanitize.has(SanitizerKind::Address))
+ // For now globals can be blacklisted only in ASan and KASan.
+ if (!LangOpts.Sanitize.hasOneOf(
+ SanitizerKind::Address | SanitizerKind::KernelAddress))
return false;
const auto &SanitizerBL = getContext().getSanitizerBlacklist();
if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
@@ -3510,11 +3498,9 @@ static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
/// to such functions with an unmangled name from inline assembly within the
/// same translation unit.
void CodeGenModule::EmitStaticExternCAliases() {
- for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
- E = StaticExternCValues.end();
- I != E; ++I) {
- IdentifierInfo *Name = I->first;
- llvm::GlobalValue *Val = I->second;
+ for (auto &I : StaticExternCValues) {
+ IdentifierInfo *Name = I.first;
+ llvm::GlobalValue *Val = I.second;
if (Val && !getModule().getNamedValue(Name->getName()))
addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
}
@@ -3674,3 +3660,17 @@ void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
CXXGlobalInits.push_back(InitFunction);
}
}
+
+llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
+ llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
+ std::string OutName;
+ llvm::raw_string_ostream Out(OutName);
+ getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
+
+ llvm::Metadata *BitsetOps[] = {
+ llvm::MDString::get(getLLVMContext(), Out.str()),
+ llvm::ConstantAsMetadata::get(VTable),
+ llvm::ConstantAsMetadata::get(
+ llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
+ return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
+}
diff --git a/lib/CodeGen/CodeGenModule.h b/lib/CodeGen/CodeGenModule.h
index edde426e9230..8e671fa7878c 100644
--- a/lib/CodeGen/CodeGenModule.h
+++ b/lib/CodeGen/CodeGenModule.h
@@ -1115,6 +1115,11 @@ public:
void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
const VTableLayout &VTLayout);
+ /// Create a bitset entry for the given vtable.
+ llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
+ CharUnits Offset,
+ const CXXRecordDecl *RD);
+
/// \breif Get the declaration of std::terminate for the platform.
llvm::Constant *getTerminateFn();
diff --git a/lib/CodeGen/CoverageMappingGen.cpp b/lib/CodeGen/CoverageMappingGen.cpp
index 024a45dba2b7..9ad5d14edfdc 100644
--- a/lib/CodeGen/CoverageMappingGen.cpp
+++ b/lib/CodeGen/CoverageMappingGen.cpp
@@ -806,6 +806,9 @@ struct CounterCoverageMappingBuilder
void VisitIfStmt(const IfStmt *S) {
extendRegion(S);
+ // Extend into the condition before we propagate through it below - this is
+ // needed to handle macros that generate the "if" but not the condition.
+ extendRegion(S->getCond());
Counter ParentCount = getRegion().getCounter();
Counter ThenCount = getRegionCounter(S);
diff --git a/lib/CodeGen/ItaniumCXXABI.cpp b/lib/CodeGen/ItaniumCXXABI.cpp
index 0a1a4ceea3ef..3f5ad5db01b5 100644
--- a/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/lib/CodeGen/ItaniumCXXABI.cpp
@@ -204,7 +204,8 @@ public:
llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
llvm::Value *This,
- llvm::Type *Ty) override;
+ llvm::Type *Ty,
+ SourceLocation Loc) override;
llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
@@ -1439,13 +1440,15 @@ llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Value *This,
- llvm::Type *Ty) {
+ llvm::Type *Ty,
+ SourceLocation Loc) {
GD = GD.getCanonicalDecl();
Ty = Ty->getPointerTo()->getPointerTo();
llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
- CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
+ CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
+ CodeGenFunction::CFITCK_VCall, Loc);
uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
llvm::Value *VFuncPtr =
@@ -1463,7 +1466,8 @@ llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
Dtor, getFromDtorType(DtorType));
llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
llvm::Value *Callee =
- getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
+ getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
+ CE ? CE->getLocStart() : SourceLocation());
CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
/*ImplicitParam=*/nullptr, QualType(), CE);
diff --git a/lib/CodeGen/MicrosoftCXXABI.cpp b/lib/CodeGen/MicrosoftCXXABI.cpp
index de30883c545f..679516bfa89a 100644
--- a/lib/CodeGen/MicrosoftCXXABI.cpp
+++ b/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -205,6 +205,9 @@ public:
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, llvm::Value *This) override;
+ void emitVTableBitSetEntries(VPtrInfo *Info, const CXXRecordDecl *RD,
+ llvm::GlobalVariable *VTable);
+
void emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) override;
@@ -221,8 +224,8 @@ public:
CharUnits VPtrOffset) override;
llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
- llvm::Value *This,
- llvm::Type *Ty) override;
+ llvm::Value *This, llvm::Type *Ty,
+ SourceLocation Loc) override;
llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
@@ -1401,6 +1404,58 @@ void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
getFromDtorType(Type));
}
+void MicrosoftCXXABI::emitVTableBitSetEntries(VPtrInfo *Info,
+ const CXXRecordDecl *RD,
+ llvm::GlobalVariable *VTable) {
+ if (!getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIVCall) &&
+ !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFINVCall) &&
+ !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIDerivedCast) &&
+ !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIUnrelatedCast))
+ return;
+
+ llvm::NamedMDNode *BitsetsMD =
+ CGM.getModule().getOrInsertNamedMetadata("llvm.bitsets");
+ CharUnits PointerWidth = getContext().toCharUnitsFromBits(
+ getContext().getTargetInfo().getPointerWidth(0));
+
+ // FIXME: Add blacklisting scheme.
+
+ if (Info->PathToBaseWithVPtr.empty()) {
+ BitsetsMD->addOperand(
+ CGM.CreateVTableBitSetEntry(VTable, PointerWidth, RD));
+ return;
+ }
+
+ // Add a bitset entry for the least derived base belonging to this vftable.
+ BitsetsMD->addOperand(CGM.CreateVTableBitSetEntry(
+ VTable, PointerWidth, Info->PathToBaseWithVPtr.back()));
+
+ // Add a bitset entry for each derived class that is laid out at the same
+ // offset as the least derived base.
+ for (unsigned I = Info->PathToBaseWithVPtr.size() - 1; I != 0; --I) {
+ const CXXRecordDecl *DerivedRD = Info->PathToBaseWithVPtr[I - 1];
+ const CXXRecordDecl *BaseRD = Info->PathToBaseWithVPtr[I];
+
+ const ASTRecordLayout &Layout =
+ getContext().getASTRecordLayout(DerivedRD);
+ CharUnits Offset;
+ auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
+ if (VBI == Layout.getVBaseOffsetsMap().end())
+ Offset = Layout.getBaseClassOffset(BaseRD);
+ else
+ Offset = VBI->second.VBaseOffset;
+ if (!Offset.isZero())
+ return;
+ BitsetsMD->addOperand(
+ CGM.CreateVTableBitSetEntry(VTable, PointerWidth, DerivedRD));
+ }
+
+ // Finally do the same for the most derived class.
+ if (Info->FullOffsetInMDC.isZero())
+ BitsetsMD->addOperand(
+ CGM.CreateVTableBitSetEntry(VTable, PointerWidth, RD));
+}
+
void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) {
MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
@@ -1423,6 +1478,8 @@ void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
VTLayout.getNumVTableThunks(), RTTI);
VTable->setInitializer(Init);
+
+ emitVTableBitSetEntries(Info, RD, VTable);
}
}
@@ -1585,10 +1642,54 @@ llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
return VTable;
}
+// Compute the identity of the most derived class whose virtual table is located
+// at the given offset into RD.
+static const CXXRecordDecl *getClassAtVTableLocation(ASTContext &Ctx,
+ const CXXRecordDecl *RD,
+ CharUnits Offset) {
+ if (Offset.isZero())
+ return RD;
+
+ const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
+ const CXXRecordDecl *MaxBase = nullptr;
+ CharUnits MaxBaseOffset;
+ for (auto &&B : RD->bases()) {
+ const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
+ CharUnits BaseOffset = Layout.getBaseClassOffset(Base);
+ if (BaseOffset <= Offset && BaseOffset > MaxBaseOffset) {
+ MaxBase = Base;
+ MaxBaseOffset = BaseOffset;
+ }
+ }
+ for (auto &&B : RD->vbases()) {
+ const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
+ CharUnits BaseOffset = Layout.getVBaseClassOffset(Base);
+ if (BaseOffset <= Offset && BaseOffset > MaxBaseOffset) {
+ MaxBase = Base;
+ MaxBaseOffset = BaseOffset;
+ }
+ }
+ assert(MaxBase);
+ return getClassAtVTableLocation(Ctx, MaxBase, Offset - MaxBaseOffset);
+}
+
+// Compute the identity of the most derived class whose virtual table is located
+// at the MethodVFTableLocation ML.
+static const CXXRecordDecl *
+getClassAtVTableLocation(ASTContext &Ctx, GlobalDecl GD,
+ MicrosoftVTableContext::MethodVFTableLocation &ML) {
+ const CXXRecordDecl *RD = ML.VBase;
+ if (!RD)
+ RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
+
+ return getClassAtVTableLocation(Ctx, RD, ML.VFPtrOffset);
+}
+
llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Value *This,
- llvm::Type *Ty) {
+ llvm::Type *Ty,
+ SourceLocation Loc) {
GD = GD.getCanonicalDecl();
CGBuilderTy &Builder = CGF.Builder;
@@ -1599,6 +1700,10 @@ llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
MicrosoftVTableContext::MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
+ if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
+ CGF.EmitVTablePtrCheck(getClassAtVTableLocation(getContext(), GD, ML),
+ VTable, CodeGenFunction::CFITCK_VCall, Loc);
+
llvm::Value *VFuncPtr =
Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
return Builder.CreateLoad(VFuncPtr);
@@ -1616,7 +1721,8 @@ llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
Dtor, StructorType::Deleting);
llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
- llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
+ llvm::Value *Callee = getVirtualFunctionPointer(
+ CGF, GD, This, Ty, CE ? CE->getLocStart() : SourceLocation());
ASTContext &Context = getContext();
llvm::Value *ImplicitParam = llvm::ConstantInt::get(
@@ -2351,7 +2457,7 @@ MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
CharUnits Offs = CharUnits::Zero();
- if (RD->getNumVBases())
+ if (VBTableIndex && RD->getNumVBases())
Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
}
@@ -2423,25 +2529,15 @@ MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
FirstField = CGM.GetAddrOfFunction(MD, Ty);
FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
} else {
- if (!CGM.getTypes().isFuncTypeConvertible(
- MD->getType()->castAs<FunctionType>())) {
- CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
- "incomplete return or parameter type");
- FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
- } else if (FPT->getCallConv() == CC_X86FastCall) {
- CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function");
- FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
- } else {
- auto &VTableContext = CGM.getMicrosoftVTableContext();
- MicrosoftVTableContext::MethodVFTableLocation ML =
- VTableContext.getMethodVFTableLocation(MD);
- llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
- FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
- // Include the vfptr adjustment if the method is in a non-primary vftable.
- NonVirtualBaseAdjustment += ML.VFPtrOffset;
- if (ML.VBase)
- VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
- }
+ auto &VTableContext = CGM.getMicrosoftVTableContext();
+ MicrosoftVTableContext::MethodVFTableLocation ML =
+ VTableContext.getMethodVFTableLocation(MD);
+ llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
+ FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
+ // Include the vfptr adjustment if the method is in a non-primary vftable.
+ NonVirtualBaseAdjustment += ML.VFPtrOffset;
+ if (ML.VBase)
+ VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
}
// The rest of the fields are common with data member pointers.
diff --git a/lib/CodeGen/SanitizerMetadata.cpp b/lib/CodeGen/SanitizerMetadata.cpp
index 7c38b2807e95..2a338bac4b41 100644
--- a/lib/CodeGen/SanitizerMetadata.cpp
+++ b/lib/CodeGen/SanitizerMetadata.cpp
@@ -25,7 +25,8 @@ void SanitizerMetadata::reportGlobalToASan(llvm::GlobalVariable *GV,
SourceLocation Loc, StringRef Name,
QualType Ty, bool IsDynInit,
bool IsBlacklisted) {
- if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address))
+ if (!CGM.getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
+ SanitizerKind::KernelAddress))
return;
IsDynInit &= !CGM.isInSanitizerBlacklist(GV, Loc, Ty, "init");
IsBlacklisted |= CGM.isInSanitizerBlacklist(GV, Loc, Ty);
@@ -56,7 +57,8 @@ void SanitizerMetadata::reportGlobalToASan(llvm::GlobalVariable *GV,
void SanitizerMetadata::reportGlobalToASan(llvm::GlobalVariable *GV,
const VarDecl &D, bool IsDynInit) {
- if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address))
+ if (!CGM.getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
+ SanitizerKind::KernelAddress))
return;
std::string QualName;
llvm::raw_string_ostream OS(QualName);
@@ -67,7 +69,8 @@ void SanitizerMetadata::reportGlobalToASan(llvm::GlobalVariable *GV,
void SanitizerMetadata::disableSanitizerForGlobal(llvm::GlobalVariable *GV) {
// For now, just make sure the global is not modified by the ASan
// instrumentation.
- if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address))
+ if (CGM.getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
+ SanitizerKind::KernelAddress))
reportGlobalToASan(GV, SourceLocation(), "", QualType(), false, true);
}
diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp
index 8cca1de0fb2b..0f3ebef2cf2f 100644
--- a/lib/Driver/Driver.cpp
+++ b/lib/Driver/Driver.cpp
@@ -277,7 +277,8 @@ DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
// Add a default value of -mlinker-version=, if one was given and the user
// didn't specify one.
#if defined(HOST_LINK_VERSION)
- if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
+ if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
+ strlen(HOST_LINK_VERSION) > 0) {
DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
HOST_LINK_VERSION);
DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
@@ -814,9 +815,12 @@ bool Driver::HandleImmediateArgs(const Compilation &C) {
return true;
}
+// Display an action graph human-readably. Action A is the "sink" node
+// and latest-occuring action. Traversal is in pre-order, visiting the
+// inputs to each action before printing the action itself.
static unsigned PrintActions1(const Compilation &C, Action *A,
std::map<Action*, unsigned> &Ids) {
- if (Ids.count(A))
+ if (Ids.count(A)) // A was already visited.
return Ids[A];
std::string str;
@@ -847,6 +851,8 @@ static unsigned PrintActions1(const Compilation &C, Action *A,
return Id;
}
+// Print the action graphs in a compilation C.
+// For example "clang -c file1.c file2.c" is composed of two subgraphs.
void Driver::PrintActions(const Compilation &C) const {
std::map<Action*, unsigned> Ids;
for (ActionList::const_iterator it = C.getActions().begin(),
@@ -1356,7 +1362,7 @@ Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
types::TY_LLVM_BC);
}
case phases::Backend: {
- if (IsUsingLTO(TC, Args)) {
+ if (IsUsingLTO(Args)) {
types::ID Output =
Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
@@ -1377,14 +1383,8 @@ Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
llvm_unreachable("invalid phase in ConstructPhaseAction");
}
-bool Driver::IsUsingLTO(const ToolChain &TC, const ArgList &Args) const {
- if (TC.getSanitizerArgs().needsLTO())
- return true;
-
- if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
- return true;
-
- return false;
+bool Driver::IsUsingLTO(const ArgList &Args) const {
+ return Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false);
}
void Driver::BuildJobs(Compilation &C) const {
@@ -1563,8 +1563,9 @@ void Driver::BuildJobsForAction(Compilation &C,
if (Input.getOption().matches(options::OPT_INPUT)) {
const char *Name = Input.getValue();
Result = InputInfo(Name, A->getType(), Name);
- } else
+ } else {
Result = InputInfo(&Input, A->getType(), "");
+ }
return;
}
@@ -1738,7 +1739,7 @@ const char *Driver::GetNamedOutputPath(Compilation &C,
// Determine what the derived output name should be.
const char *NamedOutput;
- if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
+ if (JA.getType() == types::TY_Object &&
C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
// The /Fo or /o flag decides the object filename.
StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fo,
@@ -2099,6 +2100,8 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
TC = new toolchains::Hexagon_TC(*this, Target, Args);
else if (Target.getArch() == llvm::Triple::xcore)
TC = new toolchains::XCore(*this, Target, Args);
+ else if (Target.getArch() == llvm::Triple::shave)
+ TC = new toolchains::SHAVEToolChain(*this, Target, Args);
else if (Target.isOSBinFormatELF())
TC = new toolchains::Generic_ELF(*this, Target, Args);
else if (Target.isOSBinFormatMachO())
@@ -2112,13 +2115,12 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
}
bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
- // Check if user requested no clang, or clang doesn't understand this type (we
- // only handle single inputs for now).
+ // Say "no" if there is not exactly one input of a type clang understands.
if (JA.size() != 1 ||
!types::isAcceptedByClang((*JA.begin())->getType()))
return false;
- // Otherwise make sure this is an action clang understands.
+ // And say "no" if this is not a kind of action clang understands.
if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
!isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
return false;
diff --git a/lib/Driver/MSVCToolChain.cpp b/lib/Driver/MSVCToolChain.cpp
index d824fe4c1083..72161213db05 100644
--- a/lib/Driver/MSVCToolChain.cpp
+++ b/lib/Driver/MSVCToolChain.cpp
@@ -522,3 +522,12 @@ MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
}
return Triple.getTriple();
}
+
+SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
+ SanitizerMask Res = ToolChain::getSupportedSanitizers();
+ Res |= SanitizerKind::Address;
+ // CFI checks are not implemented for MSVC ABI for now.
+ Res &= ~SanitizerKind::CFI;
+ Res &= ~SanitizerKind::CFICastStrict;
+ return Res;
+}
diff --git a/lib/Driver/SanitizerArgs.cpp b/lib/Driver/SanitizerArgs.cpp
index 72530b442f52..14c37025eb39 100644
--- a/lib/Driver/SanitizerArgs.cpp
+++ b/lib/Driver/SanitizerArgs.cpp
@@ -25,7 +25,7 @@ using namespace clang::driver;
using namespace llvm::opt;
enum : SanitizerMask {
- NeedsUbsanRt = Undefined | Integer,
+ NeedsUbsanRt = Undefined | Integer | CFI,
NotAllowedWithTrap = Vptr,
RequiresPIE = Memory | DataFlow,
NeedsUnwindTables = Address | Thread | Memory | DataFlow,
@@ -34,6 +34,9 @@ enum : SanitizerMask {
Unrecoverable = Address | Unreachable | Return,
LegacyFsanitizeRecoverMask = Undefined | Integer,
NeedsLTO = CFI,
+ TrappingSupported =
+ (Undefined & ~Vptr) | UnsignedIntegerOverflow | LocalBounds | CFI,
+ TrappingDefault = CFI,
};
enum CoverageFeature {
@@ -74,27 +77,6 @@ static std::string describeSanitizeArg(const llvm::opt::Arg *A,
/// Sanitizers set.
static std::string toString(const clang::SanitizerSet &Sanitizers);
-static SanitizerMask getToolchainUnsupportedKinds(const ToolChain &TC) {
- bool IsFreeBSD = TC.getTriple().getOS() == llvm::Triple::FreeBSD;
- bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
- bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
- bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
- bool IsMIPS64 = TC.getTriple().getArch() == llvm::Triple::mips64 ||
- TC.getTriple().getArch() == llvm::Triple::mips64el;
-
- SanitizerMask Unsupported = 0;
- if (!(IsLinux && (IsX86_64 || IsMIPS64))) {
- Unsupported |= Memory | DataFlow;
- }
- if (!((IsLinux || IsFreeBSD) && (IsX86_64 || IsMIPS64))) {
- Unsupported |= Thread;
- }
- if (!(IsLinux && (IsX86 || IsX86_64))) {
- Unsupported |= Function;
- }
- return Unsupported;
-}
-
static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
std::string &BLPath) {
const char *BlacklistFile = nullptr;
@@ -116,8 +98,62 @@ static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
return false;
}
+/// Sets group bits for every group that has at least one representative already
+/// enabled in \p Kinds.
+static SanitizerMask setGroupBits(SanitizerMask Kinds) {
+#define SANITIZER(NAME, ID)
+#define SANITIZER_GROUP(NAME, ID, ALIAS) \
+ if (Kinds & SanitizerKind::ID) \
+ Kinds |= SanitizerKind::ID##Group;
+#include "clang/Basic/Sanitizers.def"
+ return Kinds;
+}
+
+static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
+ const llvm::opt::ArgList &Args) {
+ SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
+ // sanitizers disabled by the current sanitizer
+ // argument or any argument after it.
+ SanitizerMask TrappingKinds = 0;
+ SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
+
+ for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
+ I != E; ++I) {
+ const auto *Arg = *I;
+ if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
+ Arg->claim();
+ SanitizerMask Add = parseArgValues(D, Arg, true);
+ Add &= ~TrapRemove;
+ if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
+ SanitizerSet S;
+ S.Mask = InvalidValues;
+ D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
+ << toString(S);
+ }
+ TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
+ } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
+ Arg->claim();
+ TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
+ } else if (Arg->getOption().matches(
+ options::OPT_fsanitize_undefined_trap_on_error)) {
+ Arg->claim();
+ TrappingKinds |=
+ expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
+ } else if (Arg->getOption().matches(
+ options::OPT_fno_sanitize_undefined_trap_on_error)) {
+ Arg->claim();
+ TrapRemove |= expandSanitizerGroups(UndefinedGroup);
+ }
+ }
+
+ // Apply default trapping behavior.
+ TrappingKinds |= TrappingDefault & ~TrapRemove;
+
+ return TrappingKinds;
+}
+
bool SanitizerArgs::needsUbsanRt() const {
- return !UbsanTrapOnError && (Sanitizers.Mask & NeedsUbsanRt) &&
+ return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) &&
!Sanitizers.has(Address) &&
!Sanitizers.has(Memory) &&
!Sanitizers.has(Thread);
@@ -131,19 +167,15 @@ bool SanitizerArgs::needsUnwindTables() const {
return Sanitizers.Mask & NeedsUnwindTables;
}
-bool SanitizerArgs::needsLTO() const {
- return Sanitizers.Mask & NeedsLTO;
-}
-
void SanitizerArgs::clear() {
Sanitizers.clear();
RecoverableSanitizers.clear();
+ TrapSanitizers.clear();
BlacklistFiles.clear();
CoverageFeatures = 0;
MsanTrackOrigins = 0;
AsanFieldPadding = 0;
AsanZeroBaseShadow = false;
- UbsanTrapOnError = false;
AsanSharedRuntime = false;
LinkCXXRuntimes = false;
}
@@ -162,10 +194,13 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
// Used to deduplicate diagnostics.
SanitizerMask Kinds = 0;
- SanitizerMask NotSupported = getToolchainUnsupportedKinds(TC);
+ SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
const Driver &D = TC.getDriver();
+ SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
+ SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
+
for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
I != E; ++I) {
const auto *Arg = *I;
@@ -180,14 +215,20 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
// sanitizers in Add are those which have been explicitly enabled.
// Diagnose them.
if (SanitizerMask KindsToDiagnose =
- Add & NotSupported & ~DiagnosedKinds) {
- // Only diagnose the new kinds.
+ Add & InvalidTrappingKinds & ~DiagnosedKinds) {
+ std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
+ D.Diag(diag::err_drv_argument_not_allowed_with)
+ << Desc << "-fsanitize-trap=undefined";
+ DiagnosedKinds |= KindsToDiagnose;
+ }
+ Add &= ~InvalidTrappingKinds;
+ if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
D.Diag(diag::err_drv_unsupported_opt_for_target)
<< Desc << TC.getTriple().str();
DiagnosedKinds |= KindsToDiagnose;
}
- Add &= ~NotSupported;
+ Add &= Supported;
// Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
// so we don't error out if -fno-rtti and -fsanitize=undefined were
@@ -216,7 +257,8 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
Add &= ~AllRemove;
// Silently discard any unsupported sanitizers implicitly enabled through
// group expansion.
- Add &= ~NotSupported;
+ Add &= ~InvalidTrappingKinds;
+ Add &= Supported;
Kinds |= Add;
} else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
@@ -234,22 +276,20 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
Kinds &= ~Vptr;
}
- // Warn about undefined sanitizer options that require runtime support.
- UbsanTrapOnError =
- Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
- options::OPT_fno_sanitize_undefined_trap_on_error, false);
- if (UbsanTrapOnError && (Kinds & NotAllowedWithTrap)) {
- D.Diag(clang::diag::err_drv_argument_not_allowed_with)
- << lastArgumentForMask(D, Args, NotAllowedWithTrap)
- << "-fsanitize-undefined-trap-on-error";
- Kinds &= ~NotAllowedWithTrap;
+ // Check that LTO is enabled if we need it.
+ if ((Kinds & NeedsLTO) && !D.IsUsingLTO(Args)) {
+ D.Diag(diag::err_drv_argument_only_allowed_with)
+ << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
}
// Warn about incompatible groups of sanitizers.
std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
std::make_pair(Address, Thread), std::make_pair(Address, Memory),
std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
- std::make_pair(Leak, Memory)};
+ std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
+ std::make_pair(KernelAddress, Leak),
+ std::make_pair(KernelAddress, Thread),
+ std::make_pair(KernelAddress, Memory)};
for (auto G : IncompatibleGroups) {
SanitizerMask Group = G.first;
if (Kinds & Group) {
@@ -305,6 +345,8 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
RecoverableKinds &= Kinds;
RecoverableKinds &= ~Unrecoverable;
+ TrappingKinds &= Kinds;
+
// Setup blacklist files.
// Add default blacklist from resource directory.
{
@@ -460,6 +502,7 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
// Finally, initialize the set of available and recoverable sanitizers.
Sanitizers.Mask |= Kinds;
RecoverableSanitizers.Mask |= RecoverableKinds;
+ TrapSanitizers.Mask |= TrappingKinds;
}
static std::string toString(const clang::SanitizerSet &Sanitizers) {
@@ -484,8 +527,9 @@ void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
toString(RecoverableSanitizers)));
- if (UbsanTrapOnError)
- CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
+ if (!TrapSanitizers.empty())
+ CmdArgs.push_back(
+ Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
for (const auto &BLPath : BlacklistFiles) {
SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
@@ -528,7 +572,9 @@ SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
- A->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) &&
+ A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
+ A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
+ A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
"Invalid argument in parseArgValues!");
SanitizerMask Kinds = 0;
for (int i = 0, n = A->getNumValues(); i != n; ++i) {
diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp
index 82eb85411510..da020a2b8c9d 100644
--- a/lib/Driver/ToolChain.cpp
+++ b/lib/Driver/ToolChain.cpp
@@ -481,3 +481,12 @@ bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
CmdArgs.push_back(Args.MakeArgString(Path));
return true;
}
+
+SanitizerMask ToolChain::getSupportedSanitizers() const {
+ // Return sanitizers which don't require runtime support and are not
+ // platform or architecture-dependent.
+ using namespace SanitizerKind;
+ return (Undefined & ~Vptr & ~Function) | CFI | CFICastStrict |
+ UnsignedIntegerOverflow | LocalBounds;
+}
+
diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp
index 115a16f7663d..987e063039ca 100644
--- a/lib/Driver/ToolChains.cpp
+++ b/lib/Driver/ToolChains.cpp
@@ -42,10 +42,6 @@ using namespace llvm::opt;
MachO::MachO(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
: ToolChain(D, Triple, Args) {
- getProgramPaths().push_back(getDriver().getInstalledDir());
- if (getDriver().getInstalledDir() != getDriver().Dir)
- getProgramPaths().push_back(getDriver().Dir);
-
// We expect 'as', 'ld', etc. to be adjacent to our install dir.
getProgramPaths().push_back(getDriver().getInstalledDir());
if (getDriver().getInstalledDir() != getDriver().Dir)
@@ -53,28 +49,8 @@ MachO::MachO(const Driver &D, const llvm::Triple &Triple,
}
/// Darwin - Darwin tool chain for i386 and x86_64.
-Darwin::Darwin(const Driver & D, const llvm::Triple & Triple,
- const ArgList & Args)
- : MachO(D, Triple, Args), TargetInitialized(false) {
- // Compute the initial Darwin version from the triple
- unsigned Major, Minor, Micro;
- if (!Triple.getMacOSXVersion(Major, Minor, Micro))
- getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
- Triple.getOSName();
- llvm::raw_string_ostream(MacosxVersionMin)
- << Major << '.' << Minor << '.' << Micro;
-
- // FIXME: DarwinVersion is only used to find GCC's libexec directory.
- // It should be removed when we stop supporting that.
- DarwinVersion[0] = Minor + 4;
- DarwinVersion[1] = Micro;
- DarwinVersion[2] = 0;
-
- // Compute the initial iOS version from the triple
- Triple.getiOSVersion(Major, Minor, Micro);
- llvm::raw_string_ostream(iOSVersionMin)
- << Major << '.' << Minor << '.' << Micro;
-}
+Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
+ : MachO(D, Triple, Args), TargetInitialized(false) {}
types::ID MachO::LookupTypeForExtension(const char *Ext) const {
types::ID Ty = types::lookupTypeForExtension(Ext);
@@ -403,26 +379,10 @@ void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
const SanitizerArgs &Sanitize = getSanitizerArgs();
-
- if (Sanitize.needsAsanRt()) {
- if (!isTargetMacOS() && !isTargetIOSSimulator()) {
- // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
- getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
- << "-fsanitize=address";
- } else {
- AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
- }
- }
-
- if (Sanitize.needsUbsanRt()) {
- if (!isTargetMacOS() && !isTargetIOSSimulator()) {
- // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
- getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
- << "-fsanitize=undefined";
- } else {
- AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
- }
- }
+ if (Sanitize.needsAsanRt())
+ AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
+ if (Sanitize.needsUbsanRt())
+ AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
// Otherwise link libSystem, then the dynamic runtime library, and finally any
// target specific static runtime library.
@@ -499,8 +459,8 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
} else if (!OSXVersion && !iOSVersion) {
// If no deployment target was specified on the command line, check for
// environment defines.
- StringRef OSXTarget;
- StringRef iOSTarget;
+ std::string OSXTarget;
+ std::string iOSTarget;
if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
OSXTarget = env;
if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
@@ -519,13 +479,26 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
}
}
- // If no OSX or iOS target has been specified and we're compiling for armv7,
- // go ahead as assume we're targeting iOS.
- StringRef MachOArchName = getMachOArchName(Args);
- if (OSXTarget.empty() && iOSTarget.empty() &&
- (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
- MachOArchName == "arm64"))
- iOSTarget = iOSVersionMin;
+ // If no OSX or iOS target has been specified, try to guess platform
+ // from arch name and compute the version from the triple.
+ if (OSXTarget.empty() && iOSTarget.empty()) {
+ StringRef MachOArchName = getMachOArchName(Args);
+ unsigned Major, Minor, Micro;
+ if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
+ MachOArchName == "arm64") {
+ getTriple().getiOSVersion(Major, Minor, Micro);
+ llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
+ << Micro;
+ } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
+ MachOArchName != "armv7em") {
+ if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
+ getDriver().Diag(diag::err_drv_invalid_darwin_version)
+ << getTriple().getOSName();
+ }
+ llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
+ << Micro;
+ }
+ }
// Allow conflicts among OSX and iOS for historical reasons, but choose the
// default platform.
@@ -546,12 +519,6 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
Args.append(iOSVersion);
- } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
- MachOArchName != "armv7em") {
- // Otherwise, assume we are targeting OS X.
- const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
- OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin);
- Args.append(OSXVersion);
}
}
@@ -1101,6 +1068,18 @@ void Darwin::CheckObjCARC() const {
getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
}
+SanitizerMask Darwin::getSupportedSanitizers() const {
+ SanitizerMask Res = ToolChain::getSupportedSanitizers();
+ if (isTargetMacOS() || isTargetIOSSimulator()) {
+ // ASan and UBSan are available on Mac OS and on iOS simulator.
+ Res |= SanitizerKind::Address;
+ Res |= SanitizerKind::Vptr;
+ }
+ if (isTargetMacOS())
+ Res |= SanitizerKind::SafeStack;
+ return Res;
+}
+
/// Generic_GCC - A tool chain using the 'gcc' command to perform
/// all subcommands; this relies on gcc translating the majority of
/// command line options.
@@ -2084,6 +2063,8 @@ bool Generic_GCC::IsIntegratedAssemblerDefault() const {
case llvm::Triple::aarch64_be:
case llvm::Triple::arm:
case llvm::Triple::armeb:
+ case llvm::Triple::bpfel:
+ case llvm::Triple::bpfeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
case llvm::Triple::ppc:
@@ -2739,6 +2720,24 @@ bool FreeBSD::isPIEDefault() const {
return getSanitizerArgs().requiresPIE();
}
+SanitizerMask FreeBSD::getSupportedSanitizers() const {
+ const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
+ const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
+ const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
+ getTriple().getArch() == llvm::Triple::mips64el;
+ SanitizerMask Res = ToolChain::getSupportedSanitizers();
+ Res |= SanitizerKind::Address;
+ Res |= SanitizerKind::Vptr;
+ if (IsX86_64 || IsMIPS64) {
+ Res |= SanitizerKind::Leak;
+ Res |= SanitizerKind::Thread;
+ }
+ if (IsX86 || IsX86_64) {
+ Res |= SanitizerKind::SafeStack;
+ }
+ return Res;
+}
+
/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
@@ -3643,6 +3642,28 @@ bool Linux::isPIEDefault() const {
return getSanitizerArgs().requiresPIE();
}
+SanitizerMask Linux::getSupportedSanitizers() const {
+ const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
+ const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
+ const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
+ getTriple().getArch() == llvm::Triple::mips64el;
+ SanitizerMask Res = ToolChain::getSupportedSanitizers();
+ Res |= SanitizerKind::Address;
+ Res |= SanitizerKind::KernelAddress;
+ Res |= SanitizerKind::Vptr;
+ if (IsX86_64 || IsMIPS64) {
+ Res |= SanitizerKind::DataFlow;
+ Res |= SanitizerKind::Leak;
+ Res |= SanitizerKind::Memory;
+ Res |= SanitizerKind::Thread;
+ }
+ if (IsX86 || IsX86_64) {
+ Res |= SanitizerKind::Function;
+ Res |= SanitizerKind::SafeStack;
+ }
+ return Res;
+}
+
/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
@@ -3742,3 +3763,46 @@ void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
// We don't output any lib args. This is handled by xcc.
}
+
+// SHAVEToolChain does not call Clang's C compiler.
+// We override SelectTool to avoid testing ShouldUseClangCompiler().
+Tool *SHAVEToolChain::SelectTool(const JobAction &JA) const {
+ switch (JA.getKind()) {
+ case Action::CompileJobClass:
+ if (!Compiler)
+ Compiler.reset(new tools::SHAVE::Compile(*this));
+ return Compiler.get();
+ case Action::AssembleJobClass:
+ if (!Assembler)
+ Assembler.reset(new tools::SHAVE::Assemble(*this));
+ return Assembler.get();
+ default:
+ return ToolChain::getTool(JA.getKind());
+ }
+}
+
+SHAVEToolChain::SHAVEToolChain(const Driver &D, const llvm::Triple &Triple,
+ const ArgList &Args)
+ : Generic_GCC(D, Triple, Args) {}
+
+SHAVEToolChain::~SHAVEToolChain() {}
+
+/// Following are methods necessary to avoid having moviClang be an abstract
+/// class.
+
+Tool *SHAVEToolChain::getTool(Action::ActionClass AC) const {
+ // SelectTool() must find a tool using the method in the superclass.
+ // There's nothing we can do if that fails.
+ llvm_unreachable("SHAVEToolChain can't getTool");
+}
+
+Tool *SHAVEToolChain::buildLinker() const {
+ // SHAVEToolChain executables can not be linked except by the vendor tools.
+ llvm_unreachable("SHAVEToolChain can't buildLinker");
+}
+
+Tool *SHAVEToolChain::buildAssembler() const {
+ // This one you'd think should be reachable since we expose an
+ // assembler to the driver, except not the way it expects.
+ llvm_unreachable("SHAVEToolChain can't buildAssembler");
+}
diff --git a/lib/Driver/ToolChains.h b/lib/Driver/ToolChains.h
index 0b7073f2ba0b..a48bb5fa5948 100644
--- a/lib/Driver/ToolChains.h
+++ b/lib/Driver/ToolChains.h
@@ -316,9 +316,6 @@ public:
/// Darwin - The base Darwin tool chain.
class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
public:
- /// The host version.
- unsigned DarwinVersion[3];
-
/// Whether the information on the target has been initialized.
//
// FIXME: This should be eliminated. What we want to do is make this part of
@@ -338,15 +335,6 @@ public:
mutable VersionTuple TargetVersion;
private:
- /// The default macosx-version-min of this tool chain; empty until
- /// initialized.
- std::string MacosxVersionMin;
-
- /// The default ios-version-min of this tool chain; empty until
- /// initialized.
- std::string iOSVersionMin;
-
-private:
void AddDeploymentTarget(llvm::opt::DerivedArgList &Args) const;
public:
@@ -412,6 +400,7 @@ protected:
}
bool isTargetMacOS() const {
+ assert(TargetInitialized && "Target not initialized!");
return TargetPlatform == MacOS;
}
@@ -474,6 +463,8 @@ public:
void CheckObjCARC() const override;
bool UseSjLjExceptions() const override;
+
+ SanitizerMask getSupportedSanitizers() const override;
};
/// DarwinClang - The Darwin toolchain used by Clang.
@@ -616,6 +607,7 @@ public:
bool UseSjLjExceptions() const override;
bool isPIEDefault() const override;
+ SanitizerMask getSupportedSanitizers() const override;
protected:
Tool *buildAssembler() const override;
Tool *buildLinker() const override;
@@ -679,6 +671,7 @@ public:
AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
bool isPIEDefault() const override;
+ SanitizerMask getSupportedSanitizers() const override;
std::string Linker;
std::vector<std::string> ExtraOpts;
@@ -809,6 +802,7 @@ public:
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args,
types::ID InputType) const override;
+ SanitizerMask getSupportedSanitizers() const override;
protected:
void AddSystemIncludeWithSubfolder(const llvm::opt::ArgList &DriverArgs,
@@ -872,6 +866,27 @@ public:
llvm::opt::ArgStringList &CmdArgs) const override;
};
+/// SHAVEToolChain - A tool chain using the compiler installed by the the
+// Movidius SDK into MV_TOOLS_DIR (which we assume will be copied to llvm's
+// installation dir) to perform all subcommands.
+class LLVM_LIBRARY_VISIBILITY SHAVEToolChain : public Generic_GCC {
+public:
+ SHAVEToolChain(const Driver &D, const llvm::Triple &Triple,
+ const llvm::opt::ArgList &Args);
+ ~SHAVEToolChain() override;
+
+ virtual Tool *SelectTool(const JobAction &JA) const override;
+
+protected:
+ Tool *getTool(Action::ActionClass AC) const override;
+ Tool *buildAssembler() const override;
+ Tool *buildLinker() const override;
+
+private:
+ mutable std::unique_ptr<Tool> Compiler;
+ mutable std::unique_ptr<Tool> Assembler;
+};
+
} // end namespace toolchains
} // end namespace driver
} // end namespace clang
diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp
index 711dee273197..2367914cc0b4 100644
--- a/lib/Driver/Tools.cpp
+++ b/lib/Driver/Tools.cpp
@@ -679,7 +679,7 @@ static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
// getARMArch is used here instead of just checking the -march value in order
// to handle -march=native correctly.
if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
- StringRef Arch = arm::getARMArch(Args, Triple);
+ std::string Arch = arm::getARMArch(Args, Triple);
if (llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_INVALID)
D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
}
@@ -689,7 +689,7 @@ static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
// getLLVMArchSuffixForARM which also needs an architecture.
if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
std::string CPU = arm::getARMTargetCPU(Args, Triple);
- StringRef Arch = arm::getARMArch(Args, Triple);
+ std::string Arch = arm::getARMArch(Args, Triple);
if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
}
@@ -850,7 +850,7 @@ static std::string getAArch64TargetCPU(const ArgList &Args) {
CPU = A->getValue();
} else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
StringRef Mcpu = A->getValue();
- CPU = Mcpu.split("+").first;
+ CPU = Mcpu.split("+").first.lower();
}
// Handle CPU name is 'native'.
@@ -1116,7 +1116,7 @@ static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
Features.push_back(Args.MakeArgString("+nooddspreg"));
} else
Features.push_back(Args.MakeArgString("+fp64"));
- } else if (mips::isFPXXDefault(Triple, CPUName, ABIName)) {
+ } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
Features.push_back(Args.MakeArgString("+fpxx"));
Features.push_back(Args.MakeArgString("+nooddspreg"));
}
@@ -1334,47 +1334,26 @@ static std::string getR600TargetGPU(const ArgList &Args) {
return "";
}
-static void getSparcTargetFeatures(const ArgList &Args,
- std::vector<const char *> &Features) {
- bool SoftFloatABI = true;
- if (Arg *A =
- Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
- if (A->getOption().matches(options::OPT_mhard_float))
- SoftFloatABI = false;
- }
- if (SoftFloatABI)
- Features.push_back("+soft-float");
-}
-
void Clang::AddSparcTargetArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
const Driver &D = getToolChain().getDriver();
+ std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
- // Select the float ABI as determined by -msoft-float and -mhard-float.
- StringRef FloatABI;
- if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
- options::OPT_mhard_float)) {
+ bool SoftFloatABI = false;
+ if (Arg *A =
+ Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
if (A->getOption().matches(options::OPT_msoft_float))
- FloatABI = "soft";
- else if (A->getOption().matches(options::OPT_mhard_float))
- FloatABI = "hard";
+ SoftFloatABI = true;
}
- // If unspecified, choose the default based on the platform.
- if (FloatABI.empty()) {
- // Assume "soft", but warn the user we are guessing.
- FloatABI = "soft";
- D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
- }
-
- if (FloatABI == "soft") {
- // Floating point operations and argument passing are soft.
- //
- // FIXME: This changes CPP defines, we need -target-soft-float.
- CmdArgs.push_back("-msoft-float");
- } else {
- assert(FloatABI == "hard" && "Invalid float abi!");
- CmdArgs.push_back("-mhard-float");
+ // Only the hard-float ABI on Sparc is standardized, and it is the
+ // default. GCC also supports a nonstandard soft-float ABI mode, and
+ // perhaps LLVM should implement that, too. However, since llvm
+ // currently does not support Sparc soft-float, at all, display an
+ // error if it's requested.
+ if (SoftFloatABI) {
+ D.Diag(diag::err_drv_unsupported_opt_for_target)
+ << "-msoft-float" << Triple;
}
}
@@ -1550,6 +1529,137 @@ static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
}
+/// This is a helper function for validating the optional refinement step
+/// parameter in reciprocal argument strings. Return false if there is an error
+/// parsing the refinement step. Otherwise, return true and set the Position
+/// of the refinement step in the input string.
+static bool getRefinementStep(const StringRef &In, const Driver &D,
+ const Arg &A, size_t &Position) {
+ const char RefinementStepToken = ':';
+ Position = In.find(RefinementStepToken);
+ if (Position != StringRef::npos) {
+ StringRef Option = A.getOption().getName();
+ StringRef RefStep = In.substr(Position + 1);
+ // Allow exactly one numeric character for the additional refinement
+ // step parameter. This is reasonable for all currently-supported
+ // operations and architectures because we would expect that a larger value
+ // of refinement steps would cause the estimate "optimization" to
+ // under-perform the native operation. Also, if the estimate does not
+ // converge quickly, it probably will not ever converge, so further
+ // refinement steps will not produce a better answer.
+ if (RefStep.size() != 1) {
+ D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
+ return false;
+ }
+ char RefStepChar = RefStep[0];
+ if (RefStepChar < '0' || RefStepChar > '9') {
+ D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
+ return false;
+ }
+ }
+ return true;
+}
+
+/// The -mrecip flag requires processing of many optional parameters.
+static void ParseMRecip(const Driver &D, const ArgList &Args,
+ ArgStringList &OutStrings) {
+ StringRef DisabledPrefixIn = "!";
+ StringRef DisabledPrefixOut = "!";
+ StringRef EnabledPrefixOut = "";
+ StringRef Out = "-mrecip=";
+
+ Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
+ if (!A)
+ return;
+
+ unsigned NumOptions = A->getNumValues();
+ if (NumOptions == 0) {
+ // No option is the same as "all".
+ OutStrings.push_back(Args.MakeArgString(Out + "all"));
+ return;
+ }
+
+ // Pass through "all", "none", or "default" with an optional refinement step.
+ if (NumOptions == 1) {
+ StringRef Val = A->getValue(0);
+ size_t RefStepLoc;
+ if (!getRefinementStep(Val, D, *A, RefStepLoc))
+ return;
+ StringRef ValBase = Val.slice(0, RefStepLoc);
+ if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
+ OutStrings.push_back(Args.MakeArgString(Out + Val));
+ return;
+ }
+ }
+
+ // Each reciprocal type may be enabled or disabled individually.
+ // Check each input value for validity, concatenate them all back together,
+ // and pass through.
+
+ llvm::StringMap<bool> OptionStrings;
+ OptionStrings.insert(std::make_pair("divd", false));
+ OptionStrings.insert(std::make_pair("divf", false));
+ OptionStrings.insert(std::make_pair("vec-divd", false));
+ OptionStrings.insert(std::make_pair("vec-divf", false));
+ OptionStrings.insert(std::make_pair("sqrtd", false));
+ OptionStrings.insert(std::make_pair("sqrtf", false));
+ OptionStrings.insert(std::make_pair("vec-sqrtd", false));
+ OptionStrings.insert(std::make_pair("vec-sqrtf", false));
+
+ for (unsigned i = 0; i != NumOptions; ++i) {
+ StringRef Val = A->getValue(i);
+
+ bool IsDisabled = Val.startswith(DisabledPrefixIn);
+ // Ignore the disablement token for string matching.
+ if (IsDisabled)
+ Val = Val.substr(1);
+
+ size_t RefStep;
+ if (!getRefinementStep(Val, D, *A, RefStep))
+ return;
+
+ StringRef ValBase = Val.slice(0, RefStep);
+ llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
+ if (OptionIter == OptionStrings.end()) {
+ // Try again specifying float suffix.
+ OptionIter = OptionStrings.find(ValBase.str() + 'f');
+ if (OptionIter == OptionStrings.end()) {
+ // The input name did not match any known option string.
+ D.Diag(diag::err_drv_unknown_argument) << Val;
+ return;
+ }
+ // The option was specified without a float or double suffix.
+ // Make sure that the double entry was not already specified.
+ // The float entry will be checked below.
+ if (OptionStrings[ValBase.str() + 'd']) {
+ D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
+ return;
+ }
+ }
+
+ if (OptionIter->second == true) {
+ // Duplicate option specified.
+ D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
+ return;
+ }
+
+ // Mark the matched option as found. Do not allow duplicate specifiers.
+ OptionIter->second = true;
+
+ // If the precision was not specified, also mark the double entry as found.
+ if (ValBase.back() != 'f' && ValBase.back() != 'd')
+ OptionStrings[ValBase.str() + 'd'] = true;
+
+ // Build the output string.
+ StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
+ Out = Args.MakeArgString(Out + Prefix + Val);
+ if (i != NumOptions - 1)
+ Out = Args.MakeArgString(Out + ",");
+ }
+
+ OutStrings.push_back(Args.MakeArgString(Out));
+}
+
static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
std::vector<const char *> &Features) {
@@ -1738,7 +1848,8 @@ static bool
getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
const ArgList &Args,
std::vector<const char *> &Features) {
- std::pair<StringRef, StringRef> Split = March.split("+");
+ std::string MarchLowerCase = March.lower();
+ std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
if (Split.first == "armv8-a" ||
Split.first == "armv8a") {
@@ -1762,7 +1873,8 @@ getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
const ArgList &Args,
std::vector<const char *> &Features) {
StringRef CPU;
- if (!DecodeAArch64Mcpu(D, Mcpu, CPU, Features))
+ std::string McpuLowerCase = Mcpu.lower();
+ if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
return false;
return true;
@@ -1788,7 +1900,8 @@ getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
std::vector<const char *> &Features) {
StringRef CPU;
std::vector<const char *> DecodedFeature;
- if (!DecodeAArch64Mcpu(D, Mcpu, CPU, DecodedFeature))
+ std::string McpuLowerCase = Mcpu.lower();
+ if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
return false;
return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
@@ -1863,11 +1976,6 @@ static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
case llvm::Triple::ppc64le:
getPPCTargetFeatures(Args, Features);
break;
- case llvm::Triple::sparc:
- case llvm::Triple::sparcel:
- case llvm::Triple::sparcv9:
- getSparcTargetFeatures(Args, Features);
- break;
case llvm::Triple::systemz:
getSystemZTargetFeatures(Args, Features);
break;
@@ -2326,6 +2434,8 @@ collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
if (SanArgs.linkCXXRuntimes())
StaticRuntimes.push_back("ubsan_standalone_cxx");
}
+ if (SanArgs.needsSafeStackRt())
+ StaticRuntimes.push_back("safestack");
}
// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
@@ -3151,6 +3261,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
}
}
+
+ ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
// We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
// and if we find them, tell the frontend to provide the appropriate
@@ -3892,7 +4004,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// -stack-protector=0 is default.
unsigned StackProtectorLevel = 0;
- if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
+ if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
+ Args.ClaimAllArgs(options::OPT_fno_stack_protector);
+ Args.ClaimAllArgs(options::OPT_fstack_protector_all);
+ Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
+ Args.ClaimAllArgs(options::OPT_fstack_protector);
+ } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
options::OPT_fstack_protector_all,
options::OPT_fstack_protector_strong,
options::OPT_fstack_protector)) {
@@ -4019,9 +4136,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back("-fblocks-runtime-optional");
}
- // -fmodules enables modules (off by default).
+ // -fmodules enables the use of precompiled modules (off by default).
// Users can pass -fno-cxx-modules to turn off modules support for
- // C++/Objective-C++ programs, which is a little less mature.
+ // C++/Objective-C++ programs.
bool HaveModules = false;
if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
@@ -4033,11 +4150,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
}
}
- // -fmodule-maps enables module map processing (off by default) for header
- // checking. It is implied by -fmodules.
- if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
- false)) {
- CmdArgs.push_back("-fmodule-maps");
+ // -fmodule-maps enables implicit reading of module map files. By default,
+ // this is enabled if we are using precompiled modules.
+ if (Args.hasFlag(options::OPT_fimplicit_module_maps,
+ options::OPT_fno_implicit_module_maps, HaveModules)) {
+ CmdArgs.push_back("-fimplicit-module-maps");
}
// -fmodules-decluse checks that modules used are declared so (off by
@@ -5627,9 +5744,9 @@ void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
}
// Hexagon tools end.
-const StringRef arm::getARMArch(const ArgList &Args,
- const llvm::Triple &Triple) {
- StringRef MArch;
+const std::string arm::getARMArch(const ArgList &Args,
+ const llvm::Triple &Triple) {
+ std::string MArch;
if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
// Otherwise, if we have -march= choose the base CPU for that arch.
MArch = A->getValue();
@@ -5637,6 +5754,7 @@ const StringRef arm::getARMArch(const ArgList &Args,
// Otherwise, use the Arch from the triple.
MArch = Triple.getArchName();
}
+ MArch = StringRef(MArch).lower();
// Handle -march=native.
if (MArch == "native") {
@@ -5658,7 +5776,7 @@ const StringRef arm::getARMArch(const ArgList &Args,
/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
const char *arm::getARMCPUForMArch(const ArgList &Args,
const llvm::Triple &Triple) {
- StringRef MArch = getARMArch(Args, Triple);
+ std::string MArch = getARMArch(Args, Triple);
// getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
// here means an -march=native that we can't handle, so instead return no CPU.
if (MArch.empty())
@@ -5761,7 +5879,7 @@ bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
}
bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
- StringRef ABIName) {
+ StringRef ABIName, StringRef FloatABI) {
if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
Triple.getVendor() != llvm::Triple::MipsTechnologies)
return false;
@@ -5769,6 +5887,11 @@ bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
if (ABIName != "32")
return false;
+ // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
+ // present.
+ if (FloatABI == "soft")
+ return false;
+
return llvm::StringSwitch<bool>(CPUName)
.Cases("mips2", "mips3", "mips4", "mips5", true)
.Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
@@ -5776,6 +5899,20 @@ bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
.Default(false);
}
+bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
+ StringRef CPUName, StringRef ABIName,
+ StringRef FloatABI) {
+ bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
+
+ // FPXX shouldn't be used if -msingle-float is present.
+ if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
+ options::OPT_mdouble_float))
+ if (A->getOption().matches(options::OPT_msingle_float))
+ UseFPXX = false;
+
+ return UseFPXX;
+}
+
llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
// See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
// archs which Darwin doesn't use.
@@ -5901,7 +6038,7 @@ void cloudabi::Link::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
Args.AddAllArgs(CmdArgs, options::OPT_r);
- if (D.IsUsingLTO(ToolChain, Args))
+ if (D.IsUsingLTO(Args))
AddGoldPlugin(ToolChain, Args, CmdArgs);
AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
@@ -6052,8 +6189,7 @@ void darwin::Link::AddLinkArgs(Compilation &C,
// If we are using LTO, then automatically create a temporary file path for
// the linker to use, so that it's lifetime will extend past a possible
// dsymutil step.
- if (Version[0] >= 116 && D.IsUsingLTO(getToolChain(), Args) &&
- NeedsTempPath(Inputs)) {
+ if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
const char *TmpPath = C.getArgs().MakeArgString(
D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
C.addTempFile(TmpPath);
@@ -6254,6 +6390,15 @@ void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
!Args.hasArg(options::OPT_nostartfiles))
getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
+ // SafeStack requires its own runtime libraries
+ // These libraries should be linked first, to make sure the
+ // __safestack_init constructor executes before everything else
+ if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
+ getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
+ "libclang_rt.safestack_osx.a",
+ /*AlwaysLink=*/true);
+ }
+
Args.AddAllArgs(CmdArgs, options::OPT_L);
if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
@@ -7080,7 +7225,7 @@ void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
Args.AddAllArgs(CmdArgs, options::OPT_r);
- if (D.IsUsingLTO(getToolChain(), Args))
+ if (D.IsUsingLTO(Args))
AddGoldPlugin(ToolChain, Args, CmdArgs);
bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
@@ -7577,12 +7722,13 @@ void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
}
// Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
+ StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
options::OPT_mfp64)) {
A->claim();
A->render(Args, CmdArgs);
- } else if (mips::isFPXXDefault(getToolChain().getTriple(), CPUName,
- ABIName))
+ } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
+ ABIName, MIPSFloatABI))
CmdArgs.push_back("-mfpxx");
// Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
@@ -7613,6 +7759,9 @@ void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
options::OPT_msoft_float);
+ Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
+ options::OPT_msingle_float);
+
Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
options::OPT_mno_odd_spreg);
@@ -7936,7 +8085,7 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
for (const auto &Path : Paths)
CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
- if (D.IsUsingLTO(getToolChain(), Args))
+ if (D.IsUsingLTO(Args))
AddGoldPlugin(ToolChain, Args, CmdArgs);
if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
@@ -8948,3 +9097,81 @@ void CrossWindows::Link::ConstructJob(Compilation &C, const JobAction &JA,
C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
}
+
+void tools::SHAVE::Compile::ConstructJob(Compilation &C, const JobAction &JA,
+ const InputInfo &Output,
+ const InputInfoList &Inputs,
+ const ArgList &Args,
+ const char *LinkingOutput) const {
+
+ ArgStringList CmdArgs;
+
+ assert(Inputs.size() == 1);
+ const InputInfo &II = Inputs[0];
+ assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
+ assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
+
+ // Append all -I, -iquote, -isystem paths.
+ Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
+ // These are spelled the same way in clang and moviCompile.
+ Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
+
+ CmdArgs.push_back("-DMYRIAD2");
+ CmdArgs.push_back("-mcpu=myriad2");
+ CmdArgs.push_back("-S");
+
+ // Any -O option passes through without translation. What about -Ofast ?
+ if (Arg *A = Args.getLastArg(options::OPT_O_Group))
+ A->render(Args, CmdArgs);
+
+ if (Args.hasFlag(options::OPT_ffunction_sections,
+ options::OPT_fno_function_sections)) {
+ CmdArgs.push_back("-ffunction-sections");
+ }
+ if (Args.hasArg(options::OPT_fno_inline_functions))
+ CmdArgs.push_back("-fno-inline-functions");
+
+ CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
+
+ CmdArgs.push_back(II.getFilename());
+ CmdArgs.push_back("-o");
+ CmdArgs.push_back(Output.getFilename());
+
+ std::string Exec =
+ Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
+ C.addCommand(
+ llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
+}
+
+void tools::SHAVE::Assemble::ConstructJob(Compilation &C,
+ const JobAction &JA,
+ const InputInfo &Output,
+ const InputInfoList &Inputs,
+ const ArgList &Args,
+ const char *LinkingOutput) const {
+ ArgStringList CmdArgs;
+
+ assert(Inputs.size() == 1);
+ const InputInfo &II = Inputs[0];
+ assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
+ assert(Output.getType() == types::TY_Object);
+
+ CmdArgs.push_back("-no6thSlotCompression");
+ CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
+ CmdArgs.push_back("-noSPrefixing");
+ CmdArgs.push_back("-a"); // Mystery option.
+ for (auto Arg : Args.filtered(options::OPT_I)) {
+ Arg->claim();
+ CmdArgs.push_back(
+ Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
+ }
+ CmdArgs.push_back("-elf"); // Output format.
+ CmdArgs.push_back(II.getFilename());
+ CmdArgs.push_back(
+ Args.MakeArgString(std::string("-o:") + Output.getFilename()));
+
+ std::string Exec =
+ Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
+ C.addCommand(
+ llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
+}
diff --git a/lib/Driver/Tools.h b/lib/Driver/Tools.h
index 133a389e5109..753f542622fe 100644
--- a/lib/Driver/Tools.h
+++ b/lib/Driver/Tools.h
@@ -227,8 +227,8 @@ namespace hexagon {
namespace arm {
std::string getARMTargetCPU(const llvm::opt::ArgList &Args,
const llvm::Triple &Triple);
- const StringRef getARMArch(const llvm::opt::ArgList &Args,
- const llvm::Triple &Triple);
+ const std::string getARMArch(const llvm::opt::ArgList &Args,
+ const llvm::Triple &Triple);
const char* getARMCPUForMArch(const llvm::opt::ArgList &Args,
const llvm::Triple &Triple);
const char* getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch);
@@ -249,7 +249,9 @@ namespace mips {
bool isUCLibc(const llvm::opt::ArgList &Args);
bool isNaN2008(const llvm::opt::ArgList &Args, const llvm::Triple &Triple);
bool isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
- StringRef ABIName);
+ StringRef ABIName, StringRef FloatABI);
+ bool shouldUseFPXX(const llvm::opt::ArgList &Args, const llvm::Triple &Triple,
+ StringRef CPUName, StringRef ABIName, StringRef FloatABI);
}
namespace ppc {
@@ -731,6 +733,33 @@ public:
};
}
+/// SHAVE tools -- Directly call moviCompile and moviAsm
+namespace SHAVE {
+class LLVM_LIBRARY_VISIBILITY Compile : public Tool {
+public:
+ Compile(const ToolChain &TC) : Tool("moviCompile", "movicompile", TC) {}
+
+ bool hasIntegratedCPP() const override { return true; }
+
+ void ConstructJob(Compilation &C, const JobAction &JA,
+ const InputInfo &Output, const InputInfoList &Inputs,
+ const llvm::opt::ArgList &TCArgs,
+ const char *LinkingOutput) const override;
+};
+
+class LLVM_LIBRARY_VISIBILITY Assemble : public Tool {
+public:
+ Assemble(const ToolChain &TC) : Tool("moviAsm", "moviAsm", TC) {}
+
+ bool hasIntegratedCPP() const override { return false; } // not sure.
+
+ void ConstructJob(Compilation &C, const JobAction &JA,
+ const InputInfo &Output, const InputInfoList &Inputs,
+ const llvm::opt::ArgList &TCArgs,
+ const char *LinkingOutput) const override;
+};
+} // end namespace SHAVE
+
} // end namespace tools
} // end namespace driver
} // end namespace clang
diff --git a/lib/Driver/Types.cpp b/lib/Driver/Types.cpp
index 0b0878fdd802..7b281457557b 100644
--- a/lib/Driver/Types.cpp
+++ b/lib/Driver/Types.cpp
@@ -45,7 +45,7 @@ types::ID types::getPreprocessedType(ID Id) {
}
const char *types::getTypeTempSuffix(ID Id, bool CLMode) {
- if ((Id == TY_Object || Id == TY_LTO_BC) && CLMode)
+ if (Id == TY_Object && CLMode)
return "obj";
if (Id == TY_Image && CLMode)
return "exe";
diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp
index e3e162d070f8..36a8c4d8da6d 100644
--- a/lib/Format/BreakableToken.cpp
+++ b/lib/Format/BreakableToken.cpp
@@ -183,7 +183,7 @@ void BreakableStringLiteral::insertBreak(unsigned LineIndex,
}
static StringRef getLineCommentIndentPrefix(StringRef Comment) {
- static const char *const KnownPrefixes[] = { "///", "//", "//!" };
+ static const char *const KnownPrefixes[] = {"///", "//", "//!"};
StringRef LongestPrefix;
for (StringRef KnownPrefix : KnownPrefixes) {
if (Comment.startswith(KnownPrefix)) {
@@ -239,9 +239,8 @@ void BreakableLineComment::replaceWhitespace(unsigned LineIndex,
/*Spaces=*/1);
}
-void
-BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex,
- WhitespaceManager &Whitespaces) {
+void BreakableLineComment::replaceWhitespaceBefore(
+ unsigned LineIndex, WhitespaceManager &Whitespaces) {
if (OriginalPrefix != Prefix) {
Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "",
/*InPPDirective=*/false,
@@ -345,7 +344,7 @@ void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
// Calculate the start of the non-whitespace text in the current line.
size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
if (StartOfLine == StringRef::npos)
- StartOfLine = Lines[LineIndex].size();
+ StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
// Adjust Lines to only contain relevant text.
@@ -415,9 +414,8 @@ void BreakableBlockComment::replaceWhitespace(unsigned LineIndex,
/*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1);
}
-void
-BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex,
- WhitespaceManager &Whitespaces) {
+void BreakableBlockComment::replaceWhitespaceBefore(
+ unsigned LineIndex, WhitespaceManager &Whitespaces) {
if (LineIndex == 0)
return;
StringRef Prefix = Decoration;
diff --git a/lib/Format/ContinuationIndenter.cpp b/lib/Format/ContinuationIndenter.cpp
index 91bc64b2b8b4..2357abd7abdb 100644
--- a/lib/Format/ContinuationIndenter.cpp
+++ b/lib/Format/ContinuationIndenter.cpp
@@ -150,12 +150,6 @@ bool ContinuationIndenter::mustBreak(const LineState &State) {
State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
!Current.isOneOf(tok::r_paren, tok::r_brace))
return true;
- if (Style.AlwaysBreakBeforeMultilineStrings &&
- State.Column > State.Stack.back().Indent && // Breaking saves columns.
- !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
- !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
- nextIsMultilineString(State))
- return true;
if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
Previous.is(TT_ArrayInitializerLSquare)) &&
Style.ColumnLimit > 0 &&
@@ -170,9 +164,18 @@ bool ContinuationIndenter::mustBreak(const LineState &State) {
State.Stack.back().BreakBeforeParameter)
return true;
- if (State.Column < getNewLineColumn(State))
+ unsigned NewLineColumn = getNewLineColumn(State);
+ if (State.Column < NewLineColumn)
return false;
+ if (Style.AlwaysBreakBeforeMultilineStrings &&
+ (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
+ Previous.is(tok::comma) || Current.NestingLevel < 2) &&
+ !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
+ !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
+ nextIsMultilineString(State))
+ return true;
+
// Using CanBreakBefore here and below takes care of the decision whether the
// current style uses wrapping before or after operators for the given
// operator.
@@ -416,7 +419,21 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
Penalty += Style.PenaltyBreakFirstLessLess;
State.Column = getNewLineColumn(State);
- State.Stack.back().NestedBlockIndent = State.Column;
+
+ // Indent nested blocks relative to this column, unless in a very specific
+ // JavaScript special case where:
+ //
+ // var loooooong_name =
+ // function() {
+ // // code
+ // }
+ //
+ // is common and should be formatted like a free-standing function.
+ if (Style.Language != FormatStyle::LK_JavaScript ||
+ Current.NestingLevel != 0 || !PreviousNonComment->is(tok::equal) ||
+ !Current.is(Keywords.kw_function))
+ State.Stack.back().NestedBlockIndent = State.Column;
+
if (NextNonComment->isMemberAccess()) {
if (State.Stack.back().CallContinuation == 0)
State.Stack.back().CallContinuation = State.Column;
@@ -688,7 +705,8 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
// foo();
// bar();
// }, a, b, c);
- if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
+ if (Current.isNot(tok::comment) && Previous &&
+ Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
State.Stack.size() > 1) {
if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
@@ -713,7 +731,7 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
State.StartOfStringLiteral = State.Column + 1;
else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
- !Current.isStringLiteral())
+ !Current.isStringLiteral())
State.StartOfStringLiteral = 0;
State.Column += Current.ColumnWidth;
@@ -891,7 +909,7 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
// be a line break within this call.
for (const FormatToken *Tok = &Current;
Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
- if (Tok->MustBreakBefore ||
+ if (Tok->MustBreakBefore ||
(Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
BreakBeforeParameter = true;
break;
diff --git a/lib/Format/ContinuationIndenter.h b/lib/Format/ContinuationIndenter.h
index 1da6bd95f100..9b9154ed3095 100644
--- a/lib/Format/ContinuationIndenter.h
+++ b/lib/Format/ContinuationIndenter.h
@@ -148,13 +148,10 @@ struct ParenState {
ParenState(unsigned Indent, unsigned IndentLevel, unsigned LastSpace,
bool AvoidBinPacking, bool NoLineBreak)
: Indent(Indent), IndentLevel(IndentLevel), LastSpace(LastSpace),
- NestedBlockIndent(Indent), FirstLessLess(0),
- BreakBeforeClosingBrace(false), QuestionColumn(0),
+ NestedBlockIndent(Indent), BreakBeforeClosingBrace(false),
AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
- NoLineBreak(NoLineBreak), LastOperatorWrapped(true), ColonPos(0),
- StartOfFunctionCall(0), StartOfArraySubscripts(0),
- NestedNameSpecifierContinuation(0), CallContinuation(0), VariablePos(0),
- ContainsLineBreak(false), ContainsUnwrappedBuilder(0),
+ NoLineBreak(NoLineBreak), LastOperatorWrapped(true),
+ ContainsLineBreak(false), ContainsUnwrappedBuilder(false),
AlignColons(true), ObjCSelectorNameFound(false),
HasMultipleNestedBlocks(false), NestedBlockInlined(false) {}
@@ -180,90 +177,90 @@ struct ParenState {
///
/// Used to align "<<" operators. 0 if no such operator has been encountered
/// on a level.
- unsigned FirstLessLess;
-
- /// \brief Whether a newline needs to be inserted before the block's closing
- /// brace.
- ///
- /// We only want to insert a newline before the closing brace if there also
- /// was a newline after the beginning left brace.
- bool BreakBeforeClosingBrace;
+ unsigned FirstLessLess = 0;
/// \brief The column of a \c ? in a conditional expression;
- unsigned QuestionColumn;
-
- /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
- /// lines, in this context.
- bool AvoidBinPacking;
-
- /// \brief Break after the next comma (or all the commas in this context if
- /// \c AvoidBinPacking is \c true).
- bool BreakBeforeParameter;
-
- /// \brief Line breaking in this context would break a formatting rule.
- bool NoLineBreak;
-
- /// \brief True if the last binary operator on this level was wrapped to the
- /// next line.
- bool LastOperatorWrapped;
+ unsigned QuestionColumn = 0;
/// \brief The position of the colon in an ObjC method declaration/call.
- unsigned ColonPos;
+ unsigned ColonPos = 0;
/// \brief The start of the most recent function in a builder-type call.
- unsigned StartOfFunctionCall;
+ unsigned StartOfFunctionCall = 0;
/// \brief Contains the start of array subscript expressions, so that they
/// can be aligned.
- unsigned StartOfArraySubscripts;
+ unsigned StartOfArraySubscripts = 0;
/// \brief If a nested name specifier was broken over multiple lines, this
/// contains the start column of the second line. Otherwise 0.
- unsigned NestedNameSpecifierContinuation;
+ unsigned NestedNameSpecifierContinuation = 0;
/// \brief If a call expression was broken over multiple lines, this
/// contains the start column of the second line. Otherwise 0.
- unsigned CallContinuation;
+ unsigned CallContinuation = 0;
/// \brief The column of the first variable name in a variable declaration.
///
/// Used to align further variables if necessary.
- unsigned VariablePos;
+ unsigned VariablePos = 0;
+
+ /// \brief Whether a newline needs to be inserted before the block's closing
+ /// brace.
+ ///
+ /// We only want to insert a newline before the closing brace if there also
+ /// was a newline after the beginning left brace.
+ bool BreakBeforeClosingBrace : 1;
+
+ /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
+ /// lines, in this context.
+ bool AvoidBinPacking : 1;
+
+ /// \brief Break after the next comma (or all the commas in thi