1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/CodeGen/BackendUtil.h" 10 #include "clang/Basic/CodeGenOptions.h" 11 #include "clang/Basic/Diagnostic.h" 12 #include "clang/Basic/LangOptions.h" 13 #include "clang/Basic/TargetOptions.h" 14 #include "clang/Frontend/FrontendDiagnostic.h" 15 #include "clang/Frontend/Utils.h" 16 #include "clang/Lex/HeaderSearchOptions.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/Bitcode/BitcodeWriter.h" 25 #include "llvm/Bitcode/BitcodeWriterPass.h" 26 #include "llvm/CodeGen/RegAllocRegistry.h" 27 #include "llvm/CodeGen/SchedulerRegistry.h" 28 #include "llvm/CodeGen/TargetSubtargetInfo.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/IRPrintingPasses.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSummaryIndex.h" 34 #include "llvm/IR/Verifier.h" 35 #include "llvm/LTO/LTOBackend.h" 36 #include "llvm/MC/MCAsmInfo.h" 37 #include "llvm/MC/SubtargetFeature.h" 38 #include "llvm/Passes/PassBuilder.h" 39 #include "llvm/Passes/PassPlugin.h" 40 #include "llvm/Support/BuryPointer.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/MemoryBuffer.h" 43 #include "llvm/Support/PrettyStackTrace.h" 44 #include "llvm/Support/TargetRegistry.h" 45 #include "llvm/Support/TimeProfiler.h" 46 #include "llvm/Support/Timer.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Target/TargetMachine.h" 49 #include "llvm/Target/TargetOptions.h" 50 #include "llvm/Transforms/Coroutines.h" 51 #include "llvm/Transforms/IPO.h" 52 #include "llvm/Transforms/IPO/AlwaysInliner.h" 53 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 54 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 55 #include "llvm/Transforms/InstCombine/InstCombine.h" 56 #include "llvm/Transforms/Instrumentation.h" 57 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 58 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 59 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 60 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 61 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 62 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 63 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 64 #include "llvm/Transforms/ObjCARC.h" 65 #include "llvm/Transforms/Scalar.h" 66 #include "llvm/Transforms/Scalar/GVN.h" 67 #include "llvm/Transforms/Utils.h" 68 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 69 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 70 #include "llvm/Transforms/Utils/SymbolRewriter.h" 71 #include <memory> 72 using namespace clang; 73 using namespace llvm; 74 75 namespace { 76 77 // Default filename used for profile generation. 78 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw"; 79 80 class EmitAssemblyHelper { 81 DiagnosticsEngine &Diags; 82 const HeaderSearchOptions &HSOpts; 83 const CodeGenOptions &CodeGenOpts; 84 const clang::TargetOptions &TargetOpts; 85 const LangOptions &LangOpts; 86 Module *TheModule; 87 88 Timer CodeGenerationTime; 89 90 std::unique_ptr<raw_pwrite_stream> OS; 91 92 TargetIRAnalysis getTargetIRAnalysis() const { 93 if (TM) 94 return TM->getTargetIRAnalysis(); 95 96 return TargetIRAnalysis(); 97 } 98 99 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); 100 101 /// Generates the TargetMachine. 102 /// Leaves TM unchanged if it is unable to create the target machine. 103 /// Some of our clang tests specify triples which are not built 104 /// into clang. This is okay because these tests check the generated 105 /// IR, and they require DataLayout which depends on the triple. 106 /// In this case, we allow this method to fail and not report an error. 107 /// When MustCreateTM is used, we print an error if we are unable to load 108 /// the requested target. 109 void CreateTargetMachine(bool MustCreateTM); 110 111 /// Add passes necessary to emit assembly or LLVM IR. 112 /// 113 /// \return True on success. 114 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 115 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); 116 117 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) { 118 std::error_code EC; 119 auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC, 120 llvm::sys::fs::F_None); 121 if (EC) { 122 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); 123 F.reset(); 124 } 125 return F; 126 } 127 128 public: 129 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 130 const HeaderSearchOptions &HeaderSearchOpts, 131 const CodeGenOptions &CGOpts, 132 const clang::TargetOptions &TOpts, 133 const LangOptions &LOpts, Module *M) 134 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 135 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 136 CodeGenerationTime("codegen", "Code Generation Time") {} 137 138 ~EmitAssemblyHelper() { 139 if (CodeGenOpts.DisableFree) 140 BuryPointer(std::move(TM)); 141 } 142 143 std::unique_ptr<TargetMachine> TM; 144 145 void EmitAssembly(BackendAction Action, 146 std::unique_ptr<raw_pwrite_stream> OS); 147 148 void EmitAssemblyWithNewPassManager(BackendAction Action, 149 std::unique_ptr<raw_pwrite_stream> OS); 150 }; 151 152 // We need this wrapper to access LangOpts and CGOpts from extension functions 153 // that we add to the PassManagerBuilder. 154 class PassManagerBuilderWrapper : public PassManagerBuilder { 155 public: 156 PassManagerBuilderWrapper(const Triple &TargetTriple, 157 const CodeGenOptions &CGOpts, 158 const LangOptions &LangOpts) 159 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts), 160 LangOpts(LangOpts) {} 161 const Triple &getTargetTriple() const { return TargetTriple; } 162 const CodeGenOptions &getCGOpts() const { return CGOpts; } 163 const LangOptions &getLangOpts() const { return LangOpts; } 164 165 private: 166 const Triple &TargetTriple; 167 const CodeGenOptions &CGOpts; 168 const LangOptions &LangOpts; 169 }; 170 } 171 172 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 173 if (Builder.OptLevel > 0) 174 PM.add(createObjCARCAPElimPass()); 175 } 176 177 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 178 if (Builder.OptLevel > 0) 179 PM.add(createObjCARCExpandPass()); 180 } 181 182 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 183 if (Builder.OptLevel > 0) 184 PM.add(createObjCARCOptPass()); 185 } 186 187 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 188 legacy::PassManagerBase &PM) { 189 PM.add(createAddDiscriminatorsPass()); 190 } 191 192 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 193 legacy::PassManagerBase &PM) { 194 PM.add(createBoundsCheckingLegacyPass()); 195 } 196 197 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 198 legacy::PassManagerBase &PM) { 199 const PassManagerBuilderWrapper &BuilderWrapper = 200 static_cast<const PassManagerBuilderWrapper&>(Builder); 201 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 202 SanitizerCoverageOptions Opts; 203 Opts.CoverageType = 204 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 205 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 206 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 207 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 208 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 209 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 210 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 211 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 212 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 213 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; 214 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; 215 Opts.PCTable = CGOpts.SanitizeCoveragePCTable; 216 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; 217 PM.add(createSanitizerCoverageModulePass(Opts)); 218 } 219 220 // Check if ASan should use GC-friendly instrumentation for globals. 221 // First of all, there is no point if -fdata-sections is off (expect for MachO, 222 // where this is not a factor). Also, on ELF this feature requires an assembler 223 // extension that only works with -integrated-as at the moment. 224 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { 225 if (!CGOpts.SanitizeAddressGlobalsDeadStripping) 226 return false; 227 switch (T.getObjectFormat()) { 228 case Triple::MachO: 229 case Triple::COFF: 230 return true; 231 case Triple::ELF: 232 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS; 233 default: 234 return false; 235 } 236 } 237 238 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 239 legacy::PassManagerBase &PM) { 240 const PassManagerBuilderWrapper &BuilderWrapper = 241 static_cast<const PassManagerBuilderWrapper&>(Builder); 242 const Triple &T = BuilderWrapper.getTargetTriple(); 243 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 244 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 245 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 246 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator; 247 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts); 248 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 249 UseAfterScope)); 250 PM.add(createModuleAddressSanitizerLegacyPassPass( 251 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator)); 252 } 253 254 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 255 legacy::PassManagerBase &PM) { 256 PM.add(createAddressSanitizerFunctionPass( 257 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false)); 258 PM.add(createModuleAddressSanitizerLegacyPassPass( 259 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true, 260 /*UseOdrIndicator*/ false)); 261 } 262 263 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 264 legacy::PassManagerBase &PM) { 265 const PassManagerBuilderWrapper &BuilderWrapper = 266 static_cast<const PassManagerBuilderWrapper &>(Builder); 267 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 268 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 269 PM.add( 270 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover)); 271 } 272 273 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, 274 legacy::PassManagerBase &PM) { 275 PM.add(createHWAddressSanitizerLegacyPassPass( 276 /*CompileKernel*/ true, /*Recover*/ true)); 277 } 278 279 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, 280 legacy::PassManagerBase &PM, 281 bool CompileKernel) { 282 const PassManagerBuilderWrapper &BuilderWrapper = 283 static_cast<const PassManagerBuilderWrapper&>(Builder); 284 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 285 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; 286 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); 287 PM.add(createMemorySanitizerLegacyPassPass( 288 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel})); 289 290 // MemorySanitizer inserts complex instrumentation that mostly follows 291 // the logic of the original code, but operates on "shadow" values. 292 // It can benefit from re-running some general purpose optimization passes. 293 if (Builder.OptLevel > 0) { 294 PM.add(createEarlyCSEPass()); 295 PM.add(createReassociatePass()); 296 PM.add(createLICMPass()); 297 PM.add(createGVNPass()); 298 PM.add(createInstructionCombiningPass()); 299 PM.add(createDeadStoreEliminationPass()); 300 } 301 } 302 303 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 304 legacy::PassManagerBase &PM) { 305 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false); 306 } 307 308 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, 309 legacy::PassManagerBase &PM) { 310 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true); 311 } 312 313 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 314 legacy::PassManagerBase &PM) { 315 PM.add(createThreadSanitizerLegacyPassPass()); 316 } 317 318 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 319 legacy::PassManagerBase &PM) { 320 const PassManagerBuilderWrapper &BuilderWrapper = 321 static_cast<const PassManagerBuilderWrapper&>(Builder); 322 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 323 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 324 } 325 326 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 327 const CodeGenOptions &CodeGenOpts) { 328 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 329 if (!CodeGenOpts.SimplifyLibCalls) 330 TLII->disableAllFunctions(); 331 else { 332 // Disable individual libc/libm calls in TargetLibraryInfo. 333 LibFunc F; 334 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 335 if (TLII->getLibFunc(FuncName, F)) 336 TLII->setUnavailable(F); 337 } 338 339 switch (CodeGenOpts.getVecLib()) { 340 case CodeGenOptions::Accelerate: 341 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 342 break; 343 case CodeGenOptions::SVML: 344 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 345 break; 346 default: 347 break; 348 } 349 return TLII; 350 } 351 352 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 353 legacy::PassManager *MPM) { 354 llvm::SymbolRewriter::RewriteDescriptorList DL; 355 356 llvm::SymbolRewriter::RewriteMapParser MapParser; 357 for (const auto &MapFile : Opts.RewriteMapFiles) 358 MapParser.parse(MapFile, &DL); 359 360 MPM->add(createRewriteSymbolsPass(DL)); 361 } 362 363 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { 364 switch (CodeGenOpts.OptimizationLevel) { 365 default: 366 llvm_unreachable("Invalid optimization level!"); 367 case 0: 368 return CodeGenOpt::None; 369 case 1: 370 return CodeGenOpt::Less; 371 case 2: 372 return CodeGenOpt::Default; // O2/Os/Oz 373 case 3: 374 return CodeGenOpt::Aggressive; 375 } 376 } 377 378 static Optional<llvm::CodeModel::Model> 379 getCodeModel(const CodeGenOptions &CodeGenOpts) { 380 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 381 .Case("tiny", llvm::CodeModel::Tiny) 382 .Case("small", llvm::CodeModel::Small) 383 .Case("kernel", llvm::CodeModel::Kernel) 384 .Case("medium", llvm::CodeModel::Medium) 385 .Case("large", llvm::CodeModel::Large) 386 .Case("default", ~1u) 387 .Default(~0u); 388 assert(CodeModel != ~0u && "invalid code model!"); 389 if (CodeModel == ~1u) 390 return None; 391 return static_cast<llvm::CodeModel::Model>(CodeModel); 392 } 393 394 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) { 395 if (Action == Backend_EmitObj) 396 return TargetMachine::CGFT_ObjectFile; 397 else if (Action == Backend_EmitMCNull) 398 return TargetMachine::CGFT_Null; 399 else { 400 assert(Action == Backend_EmitAssembly && "Invalid action!"); 401 return TargetMachine::CGFT_AssemblyFile; 402 } 403 } 404 405 static void initTargetOptions(llvm::TargetOptions &Options, 406 const CodeGenOptions &CodeGenOpts, 407 const clang::TargetOptions &TargetOpts, 408 const LangOptions &LangOpts, 409 const HeaderSearchOptions &HSOpts) { 410 Options.ThreadModel = 411 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 412 .Case("posix", llvm::ThreadModel::POSIX) 413 .Case("single", llvm::ThreadModel::Single); 414 415 // Set float ABI type. 416 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 417 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 418 "Invalid Floating Point ABI!"); 419 Options.FloatABIType = 420 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 421 .Case("soft", llvm::FloatABI::Soft) 422 .Case("softfp", llvm::FloatABI::Soft) 423 .Case("hard", llvm::FloatABI::Hard) 424 .Default(llvm::FloatABI::Default); 425 426 // Set FP fusion mode. 427 switch (LangOpts.getDefaultFPContractMode()) { 428 case LangOptions::FPC_Off: 429 // Preserve any contraction performed by the front-end. (Strict performs 430 // splitting of the muladd intrinsic in the backend.) 431 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 432 break; 433 case LangOptions::FPC_On: 434 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 435 break; 436 case LangOptions::FPC_Fast: 437 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 438 break; 439 } 440 441 Options.UseInitArray = CodeGenOpts.UseInitArray; 442 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 443 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); 444 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 445 446 // Set EABI version. 447 Options.EABIVersion = TargetOpts.EABIVersion; 448 449 if (LangOpts.SjLjExceptions) 450 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 451 if (LangOpts.SEHExceptions) 452 Options.ExceptionModel = llvm::ExceptionHandling::WinEH; 453 if (LangOpts.DWARFExceptions) 454 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; 455 456 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 457 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 458 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 459 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 460 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 461 Options.FunctionSections = CodeGenOpts.FunctionSections; 462 Options.DataSections = CodeGenOpts.DataSections; 463 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 464 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 465 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; 466 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 467 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; 468 Options.EmitAddrsig = CodeGenOpts.Addrsig; 469 470 if (CodeGenOpts.getSplitDwarfMode() != CodeGenOptions::NoFission) 471 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; 472 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 473 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 474 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 475 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 476 Options.MCOptions.MCIncrementalLinkerCompatible = 477 CodeGenOpts.IncrementalLinkerCompatible; 478 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations; 479 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 480 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 481 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 482 Options.MCOptions.ABIName = TargetOpts.ABI; 483 for (const auto &Entry : HSOpts.UserEntries) 484 if (!Entry.IsFramework && 485 (Entry.Group == frontend::IncludeDirGroup::Quoted || 486 Entry.Group == frontend::IncludeDirGroup::Angled || 487 Entry.Group == frontend::IncludeDirGroup::System)) 488 Options.MCOptions.IASSearchPaths.push_back( 489 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 490 } 491 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) { 492 if (CodeGenOpts.DisableGCov) 493 return None; 494 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) 495 return None; 496 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 497 // LLVM's -default-gcov-version flag is set to something invalid. 498 GCOVOptions Options; 499 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 500 Options.EmitData = CodeGenOpts.EmitGcovArcs; 501 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); 502 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 503 Options.NoRedZone = CodeGenOpts.DisableRedZone; 504 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData; 505 Options.Filter = CodeGenOpts.ProfileFilterFiles; 506 Options.Exclude = CodeGenOpts.ProfileExcludeFiles; 507 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 508 return Options; 509 } 510 511 static Optional<InstrProfOptions> 512 getInstrProfOptions(const CodeGenOptions &CodeGenOpts, 513 const LangOptions &LangOpts) { 514 if (!CodeGenOpts.hasProfileClangInstr()) 515 return None; 516 InstrProfOptions Options; 517 Options.NoRedZone = CodeGenOpts.DisableRedZone; 518 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 519 520 // TODO: Surface the option to emit atomic profile counter increments at 521 // the driver level. 522 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread); 523 return Options; 524 } 525 526 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 527 legacy::FunctionPassManager &FPM) { 528 // Handle disabling of all LLVM passes, where we want to preserve the 529 // internal module before any optimization. 530 if (CodeGenOpts.DisableLLVMPasses) 531 return; 532 533 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 534 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 535 // are inserted before PMBuilder ones - they'd get the default-constructed 536 // TLI with an unknown target otherwise. 537 Triple TargetTriple(TheModule->getTargetTriple()); 538 std::unique_ptr<TargetLibraryInfoImpl> TLII( 539 createTLII(TargetTriple, CodeGenOpts)); 540 541 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts); 542 543 // At O0 and O1 we only run the always inliner which is more efficient. At 544 // higher optimization levels we run the normal inliner. 545 if (CodeGenOpts.OptimizationLevel <= 1) { 546 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 && 547 !CodeGenOpts.DisableLifetimeMarkers); 548 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 549 } else { 550 // We do not want to inline hot callsites for SamplePGO module-summary build 551 // because profile annotation will happen again in ThinLTO backend, and we 552 // want the IR of the hot path to match the profile. 553 PMBuilder.Inliner = createFunctionInliningPass( 554 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize, 555 (!CodeGenOpts.SampleProfileFile.empty() && 556 CodeGenOpts.PrepareForThinLTO)); 557 } 558 559 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 560 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 561 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 562 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 563 564 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 565 // Loop interleaving in the loop vectorizer has historically been set to be 566 // enabled when loop unrolling is enabled. 567 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops; 568 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 569 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; 570 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 571 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 572 573 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 574 575 if (TM) 576 TM->adjustPassManager(PMBuilder); 577 578 if (CodeGenOpts.DebugInfoForProfiling || 579 !CodeGenOpts.SampleProfileFile.empty()) 580 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 581 addAddDiscriminatorsPass); 582 583 // In ObjC ARC mode, add the main ARC optimization passes. 584 if (LangOpts.ObjCAutoRefCount) { 585 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 586 addObjCARCExpandPass); 587 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 588 addObjCARCAPElimPass); 589 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 590 addObjCARCOptPass); 591 } 592 593 if (LangOpts.Coroutines) 594 addCoroutinePassesToExtensionPoints(PMBuilder); 595 596 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 597 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 598 addBoundsCheckingPass); 599 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 600 addBoundsCheckingPass); 601 } 602 603 if (CodeGenOpts.SanitizeCoverageType || 604 CodeGenOpts.SanitizeCoverageIndirectCalls || 605 CodeGenOpts.SanitizeCoverageTraceCmp) { 606 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 607 addSanitizerCoveragePass); 608 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 609 addSanitizerCoveragePass); 610 } 611 612 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 613 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 614 addAddressSanitizerPasses); 615 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 616 addAddressSanitizerPasses); 617 } 618 619 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 620 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 621 addKernelAddressSanitizerPasses); 622 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 623 addKernelAddressSanitizerPasses); 624 } 625 626 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 627 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 628 addHWAddressSanitizerPasses); 629 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 630 addHWAddressSanitizerPasses); 631 } 632 633 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 634 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 635 addKernelHWAddressSanitizerPasses); 636 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 637 addKernelHWAddressSanitizerPasses); 638 } 639 640 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 641 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 642 addMemorySanitizerPass); 643 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 644 addMemorySanitizerPass); 645 } 646 647 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 648 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 649 addKernelMemorySanitizerPass); 650 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 651 addKernelMemorySanitizerPass); 652 } 653 654 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 655 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 656 addThreadSanitizerPass); 657 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 658 addThreadSanitizerPass); 659 } 660 661 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 662 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 663 addDataFlowSanitizerPass); 664 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 665 addDataFlowSanitizerPass); 666 } 667 668 // Set up the per-function pass manager. 669 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 670 if (CodeGenOpts.VerifyModule) 671 FPM.add(createVerifierPass()); 672 673 // Set up the per-module pass manager. 674 if (!CodeGenOpts.RewriteMapFiles.empty()) 675 addSymbolRewriterPass(CodeGenOpts, &MPM); 676 677 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) { 678 MPM.add(createGCOVProfilerPass(*Options)); 679 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 680 MPM.add(createStripSymbolsPass(true)); 681 } 682 683 if (Optional<InstrProfOptions> Options = 684 getInstrProfOptions(CodeGenOpts, LangOpts)) 685 MPM.add(createInstrProfilingLegacyPass(*Options, false)); 686 687 bool hasIRInstr = false; 688 if (CodeGenOpts.hasProfileIRInstr()) { 689 PMBuilder.EnablePGOInstrGen = true; 690 hasIRInstr = true; 691 } 692 if (CodeGenOpts.hasProfileCSIRInstr()) { 693 assert(!CodeGenOpts.hasProfileCSIRUse() && 694 "Cannot have both CSProfileUse pass and CSProfileGen pass at the " 695 "same time"); 696 assert(!hasIRInstr && 697 "Cannot have both ProfileGen pass and CSProfileGen pass at the " 698 "same time"); 699 PMBuilder.EnablePGOCSInstrGen = true; 700 hasIRInstr = true; 701 } 702 if (hasIRInstr) { 703 if (!CodeGenOpts.InstrProfileOutput.empty()) 704 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 705 else 706 PMBuilder.PGOInstrGen = DefaultProfileGenName; 707 } 708 if (CodeGenOpts.hasProfileIRUse()) { 709 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 710 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse(); 711 } 712 713 if (!CodeGenOpts.SampleProfileFile.empty()) 714 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 715 716 PMBuilder.populateFunctionPassManager(FPM); 717 PMBuilder.populateModulePassManager(MPM); 718 } 719 720 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { 721 SmallVector<const char *, 16> BackendArgs; 722 BackendArgs.push_back("clang"); // Fake program name. 723 if (!CodeGenOpts.DebugPass.empty()) { 724 BackendArgs.push_back("-debug-pass"); 725 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 726 } 727 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 728 BackendArgs.push_back("-limit-float-precision"); 729 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 730 } 731 BackendArgs.push_back(nullptr); 732 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 733 BackendArgs.data()); 734 } 735 736 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 737 // Create the TargetMachine for generating code. 738 std::string Error; 739 std::string Triple = TheModule->getTargetTriple(); 740 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 741 if (!TheTarget) { 742 if (MustCreateTM) 743 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 744 return; 745 } 746 747 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts); 748 std::string FeaturesStr = 749 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 750 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; 751 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); 752 753 llvm::TargetOptions Options; 754 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts); 755 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 756 Options, RM, CM, OptLevel)); 757 } 758 759 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 760 BackendAction Action, 761 raw_pwrite_stream &OS, 762 raw_pwrite_stream *DwoOS) { 763 // Add LibraryInfo. 764 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 765 std::unique_ptr<TargetLibraryInfoImpl> TLII( 766 createTLII(TargetTriple, CodeGenOpts)); 767 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 768 769 // Normal mode, emit a .s or .o file by running the code generator. Note, 770 // this also adds codegenerator level optimization passes. 771 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action); 772 773 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 774 // "codegen" passes so that it isn't run multiple times when there is 775 // inlining happening. 776 if (CodeGenOpts.OptimizationLevel > 0) 777 CodeGenPasses.add(createObjCARCContractPass()); 778 779 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, 780 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 781 Diags.Report(diag::err_fe_unable_to_interface_with_target); 782 return false; 783 } 784 785 return true; 786 } 787 788 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 789 std::unique_ptr<raw_pwrite_stream> OS) { 790 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 791 792 setCommandLineOpts(CodeGenOpts); 793 794 bool UsesCodeGen = (Action != Backend_EmitNothing && 795 Action != Backend_EmitBC && 796 Action != Backend_EmitLL); 797 CreateTargetMachine(UsesCodeGen); 798 799 if (UsesCodeGen && !TM) 800 return; 801 if (TM) 802 TheModule->setDataLayout(TM->createDataLayout()); 803 804 legacy::PassManager PerModulePasses; 805 PerModulePasses.add( 806 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 807 808 legacy::FunctionPassManager PerFunctionPasses(TheModule); 809 PerFunctionPasses.add( 810 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 811 812 CreatePasses(PerModulePasses, PerFunctionPasses); 813 814 legacy::PassManager CodeGenPasses; 815 CodeGenPasses.add( 816 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 817 818 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 819 820 switch (Action) { 821 case Backend_EmitNothing: 822 break; 823 824 case Backend_EmitBC: 825 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 826 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 827 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 828 if (!ThinLinkOS) 829 return; 830 } 831 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 832 CodeGenOpts.EnableSplitLTOUnit); 833 PerModulePasses.add(createWriteThinLTOBitcodePass( 834 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); 835 } else { 836 // Emit a module summary by default for Regular LTO except for ld64 837 // targets 838 bool EmitLTOSummary = 839 (CodeGenOpts.PrepareForLTO && 840 !CodeGenOpts.DisableLLVMPasses && 841 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 842 llvm::Triple::Apple); 843 if (EmitLTOSummary) { 844 if (!TheModule->getModuleFlag("ThinLTO")) 845 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 846 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 847 CodeGenOpts.EnableSplitLTOUnit); 848 } 849 850 PerModulePasses.add(createBitcodeWriterPass( 851 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 852 } 853 break; 854 855 case Backend_EmitLL: 856 PerModulePasses.add( 857 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 858 break; 859 860 default: 861 if (!CodeGenOpts.SplitDwarfFile.empty() && 862 (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) { 863 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile); 864 if (!DwoOS) 865 return; 866 } 867 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 868 DwoOS ? &DwoOS->os() : nullptr)) 869 return; 870 } 871 872 // Before executing passes, print the final values of the LLVM options. 873 cl::PrintOptionValues(); 874 875 // Run passes. For now we do all passes at once, but eventually we 876 // would like to have the option of streaming code generation. 877 878 { 879 PrettyStackTraceString CrashInfo("Per-function optimization"); 880 881 PerFunctionPasses.doInitialization(); 882 for (Function &F : *TheModule) 883 if (!F.isDeclaration()) 884 PerFunctionPasses.run(F); 885 PerFunctionPasses.doFinalization(); 886 } 887 888 { 889 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 890 PerModulePasses.run(*TheModule); 891 } 892 893 { 894 PrettyStackTraceString CrashInfo("Code generation"); 895 CodeGenPasses.run(*TheModule); 896 } 897 898 if (ThinLinkOS) 899 ThinLinkOS->keep(); 900 if (DwoOS) 901 DwoOS->keep(); 902 } 903 904 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 905 switch (Opts.OptimizationLevel) { 906 default: 907 llvm_unreachable("Invalid optimization level!"); 908 909 case 1: 910 return PassBuilder::O1; 911 912 case 2: 913 switch (Opts.OptimizeSize) { 914 default: 915 llvm_unreachable("Invalid optimization level for size!"); 916 917 case 0: 918 return PassBuilder::O2; 919 920 case 1: 921 return PassBuilder::Os; 922 923 case 2: 924 return PassBuilder::Oz; 925 } 926 927 case 3: 928 return PassBuilder::O3; 929 } 930 } 931 932 static void addSanitizersAtO0(ModulePassManager &MPM, 933 const Triple &TargetTriple, 934 const LangOptions &LangOpts, 935 const CodeGenOptions &CodeGenOpts) { 936 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { 937 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 938 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); 939 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass( 940 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope))); 941 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 942 MPM.addPass( 943 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope, 944 CodeGenOpts.SanitizeAddressUseOdrIndicator)); 945 }; 946 947 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 948 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false); 949 } 950 951 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 952 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true); 953 } 954 955 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 956 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({}))); 957 } 958 959 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { 960 MPM.addPass(createModuleToFunctionPassAdaptor( 961 MemorySanitizerPass({0, false, /*Kernel=*/true}))); 962 } 963 964 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 965 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); 966 } 967 968 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 969 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 970 MPM.addPass(createModuleToFunctionPassAdaptor( 971 HWAddressSanitizerPass(/*CompileKernel=*/false, Recover))); 972 } 973 974 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 975 MPM.addPass(createModuleToFunctionPassAdaptor( 976 HWAddressSanitizerPass(/*CompileKernel=*/true, /*Recover=*/true))); 977 } 978 } 979 980 /// A clean version of `EmitAssembly` that uses the new pass manager. 981 /// 982 /// Not all features are currently supported in this system, but where 983 /// necessary it falls back to the legacy pass manager to at least provide 984 /// basic functionality. 985 /// 986 /// This API is planned to have its functionality finished and then to replace 987 /// `EmitAssembly` at some point in the future when the default switches. 988 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 989 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 990 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); 991 setCommandLineOpts(CodeGenOpts); 992 993 bool RequiresCodeGen = (Action != Backend_EmitNothing && 994 Action != Backend_EmitBC && 995 Action != Backend_EmitLL); 996 CreateTargetMachine(RequiresCodeGen); 997 998 if (RequiresCodeGen && !TM) 999 return; 1000 if (TM) 1001 TheModule->setDataLayout(TM->createDataLayout()); 1002 1003 Optional<PGOOptions> PGOOpt; 1004 1005 if (CodeGenOpts.hasProfileIRInstr()) 1006 // -fprofile-generate. 1007 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() 1008 ? DefaultProfileGenName 1009 : CodeGenOpts.InstrProfileOutput, 1010 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction, 1011 CodeGenOpts.DebugInfoForProfiling); 1012 else if (CodeGenOpts.hasProfileIRUse()) { 1013 // -fprofile-use. 1014 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse 1015 : PGOOptions::NoCSAction; 1016 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", 1017 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, 1018 CSAction, CodeGenOpts.DebugInfoForProfiling); 1019 } else if (!CodeGenOpts.SampleProfileFile.empty()) 1020 // -fprofile-sample-use 1021 PGOOpt = 1022 PGOOptions(CodeGenOpts.SampleProfileFile, "", 1023 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse, 1024 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling); 1025 else if (CodeGenOpts.DebugInfoForProfiling) 1026 // -fdebug-info-for-profiling 1027 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction, 1028 PGOOptions::NoCSAction, true); 1029 1030 // Check to see if we want to generate a CS profile. 1031 if (CodeGenOpts.hasProfileCSIRInstr()) { 1032 assert(!CodeGenOpts.hasProfileCSIRUse() && 1033 "Cannot have both CSProfileUse pass and CSProfileGen pass at " 1034 "the same time"); 1035 if (PGOOpt.hasValue()) { 1036 assert(PGOOpt->Action != PGOOptions::IRInstr && 1037 PGOOpt->Action != PGOOptions::SampleUse && 1038 "Cannot run CSProfileGen pass with ProfileGen or SampleUse " 1039 " pass"); 1040 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() 1041 ? DefaultProfileGenName 1042 : CodeGenOpts.InstrProfileOutput; 1043 PGOOpt->CSAction = PGOOptions::CSIRInstr; 1044 } else 1045 PGOOpt = PGOOptions("", 1046 CodeGenOpts.InstrProfileOutput.empty() 1047 ? DefaultProfileGenName 1048 : CodeGenOpts.InstrProfileOutput, 1049 "", PGOOptions::NoAction, PGOOptions::CSIRInstr, 1050 CodeGenOpts.DebugInfoForProfiling); 1051 } 1052 1053 PipelineTuningOptions PTO; 1054 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; 1055 // For historical reasons, loop interleaving is set to mirror setting for loop 1056 // unrolling. 1057 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; 1058 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; 1059 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; 1060 1061 PassBuilder PB(TM.get(), PTO, PGOOpt); 1062 1063 // Attempt to load pass plugins and register their callbacks with PB. 1064 for (auto &PluginFN : CodeGenOpts.PassPlugins) { 1065 auto PassPlugin = PassPlugin::Load(PluginFN); 1066 if (PassPlugin) { 1067 PassPlugin->registerPassBuilderCallbacks(PB); 1068 } else { 1069 Diags.Report(diag::err_fe_unable_to_load_plugin) 1070 << PluginFN << toString(PassPlugin.takeError()); 1071 } 1072 } 1073 1074 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager); 1075 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager); 1076 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager); 1077 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager); 1078 1079 // Register the AA manager first so that our version is the one used. 1080 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 1081 1082 // Register the target library analysis directly and give it a customized 1083 // preset TLI. 1084 Triple TargetTriple(TheModule->getTargetTriple()); 1085 std::unique_ptr<TargetLibraryInfoImpl> TLII( 1086 createTLII(TargetTriple, CodeGenOpts)); 1087 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1088 MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 1089 1090 // Register all the basic analyses with the managers. 1091 PB.registerModuleAnalyses(MAM); 1092 PB.registerCGSCCAnalyses(CGAM); 1093 PB.registerFunctionAnalyses(FAM); 1094 PB.registerLoopAnalyses(LAM); 1095 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 1096 1097 ModulePassManager MPM(CodeGenOpts.DebugPassManager); 1098 1099 if (!CodeGenOpts.DisableLLVMPasses) { 1100 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; 1101 bool IsLTO = CodeGenOpts.PrepareForLTO; 1102 1103 if (CodeGenOpts.OptimizationLevel == 0) { 1104 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) 1105 MPM.addPass(GCOVProfilerPass(*Options)); 1106 if (Optional<InstrProfOptions> Options = 1107 getInstrProfOptions(CodeGenOpts, LangOpts)) 1108 MPM.addPass(InstrProfiling(*Options, false)); 1109 1110 // Build a minimal pipeline based on the semantics required by Clang, 1111 // which is just that always inlining occurs. 1112 MPM.addPass(AlwaysInlinerPass()); 1113 1114 // At -O0 we directly run necessary sanitizer passes. 1115 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1116 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass())); 1117 1118 // Lastly, add semantically necessary passes for LTO. 1119 if (IsLTO || IsThinLTO) { 1120 MPM.addPass(CanonicalizeAliasesPass()); 1121 MPM.addPass(NameAnonGlobalPass()); 1122 } 1123 } else { 1124 // Map our optimization levels into one of the distinct levels used to 1125 // configure the pipeline. 1126 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 1127 1128 // Register callbacks to schedule sanitizer passes at the appropriate part of 1129 // the pipeline. 1130 // FIXME: either handle asan/the remaining sanitizers or error out 1131 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) 1132 PB.registerScalarOptimizerLateEPCallback( 1133 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1134 FPM.addPass(BoundsCheckingPass()); 1135 }); 1136 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) 1137 PB.registerOptimizerLastEPCallback( 1138 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1139 FPM.addPass(MemorySanitizerPass({})); 1140 }); 1141 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) 1142 PB.registerOptimizerLastEPCallback( 1143 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1144 FPM.addPass(ThreadSanitizerPass()); 1145 }); 1146 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 1147 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) { 1148 MPM.addPass( 1149 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 1150 }); 1151 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address); 1152 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; 1153 PB.registerOptimizerLastEPCallback( 1154 [Recover, UseAfterScope](FunctionPassManager &FPM, 1155 PassBuilder::OptimizationLevel Level) { 1156 FPM.addPass(AddressSanitizerPass( 1157 /*CompileKernel=*/false, Recover, UseAfterScope)); 1158 }); 1159 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); 1160 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; 1161 PB.registerPipelineStartEPCallback( 1162 [Recover, ModuleUseAfterScope, 1163 UseOdrIndicator](ModulePassManager &MPM) { 1164 MPM.addPass(ModuleAddressSanitizerPass( 1165 /*CompileKernel=*/false, Recover, ModuleUseAfterScope, 1166 UseOdrIndicator)); 1167 }); 1168 } 1169 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { 1170 bool Recover = 1171 CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); 1172 PB.registerOptimizerLastEPCallback( 1173 [Recover](FunctionPassManager &FPM, 1174 PassBuilder::OptimizationLevel Level) { 1175 FPM.addPass(HWAddressSanitizerPass( 1176 /*CompileKernel=*/false, Recover)); 1177 }); 1178 } 1179 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { 1180 PB.registerOptimizerLastEPCallback( 1181 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 1182 FPM.addPass(HWAddressSanitizerPass( 1183 /*CompileKernel=*/true, /*Recover=*/true)); 1184 }); 1185 } 1186 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) 1187 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { 1188 MPM.addPass(GCOVProfilerPass(*Options)); 1189 }); 1190 if (Optional<InstrProfOptions> Options = 1191 getInstrProfOptions(CodeGenOpts, LangOpts)) 1192 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { 1193 MPM.addPass(InstrProfiling(*Options, false)); 1194 }); 1195 1196 if (IsThinLTO) { 1197 MPM = PB.buildThinLTOPreLinkDefaultPipeline( 1198 Level, CodeGenOpts.DebugPassManager); 1199 MPM.addPass(CanonicalizeAliasesPass()); 1200 MPM.addPass(NameAnonGlobalPass()); 1201 } else if (IsLTO) { 1202 MPM = PB.buildLTOPreLinkDefaultPipeline(Level, 1203 CodeGenOpts.DebugPassManager); 1204 MPM.addPass(CanonicalizeAliasesPass()); 1205 MPM.addPass(NameAnonGlobalPass()); 1206 } else { 1207 MPM = PB.buildPerModuleDefaultPipeline(Level, 1208 CodeGenOpts.DebugPassManager); 1209 } 1210 } 1211 1212 if (CodeGenOpts.OptimizationLevel == 0) 1213 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts); 1214 } 1215 1216 // FIXME: We still use the legacy pass manager to do code generation. We 1217 // create that pass manager here and use it as needed below. 1218 legacy::PassManager CodeGenPasses; 1219 bool NeedCodeGen = false; 1220 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS; 1221 1222 // Append any output we need to the pass manager. 1223 switch (Action) { 1224 case Backend_EmitNothing: 1225 break; 1226 1227 case Backend_EmitBC: 1228 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { 1229 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { 1230 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); 1231 if (!ThinLinkOS) 1232 return; 1233 } 1234 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1235 CodeGenOpts.EnableSplitLTOUnit); 1236 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() 1237 : nullptr)); 1238 } else { 1239 // Emit a module summary by default for Regular LTO except for ld64 1240 // targets 1241 bool EmitLTOSummary = 1242 (CodeGenOpts.PrepareForLTO && 1243 !CodeGenOpts.DisableLLVMPasses && 1244 llvm::Triple(TheModule->getTargetTriple()).getVendor() != 1245 llvm::Triple::Apple); 1246 if (EmitLTOSummary) { 1247 if (!TheModule->getModuleFlag("ThinLTO")) 1248 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 1249 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit", 1250 CodeGenOpts.EnableSplitLTOUnit); 1251 } 1252 MPM.addPass( 1253 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); 1254 } 1255 break; 1256 1257 case Backend_EmitLL: 1258 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 1259 break; 1260 1261 case Backend_EmitAssembly: 1262 case Backend_EmitMCNull: 1263 case Backend_EmitObj: 1264 NeedCodeGen = true; 1265 CodeGenPasses.add( 1266 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 1267 if (!CodeGenOpts.SplitDwarfFile.empty()) { 1268 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile); 1269 if (!DwoOS) 1270 return; 1271 } 1272 if (!AddEmitPasses(CodeGenPasses, Action, *OS, 1273 DwoOS ? &DwoOS->os() : nullptr)) 1274 // FIXME: Should we handle this error differently? 1275 return; 1276 break; 1277 } 1278 1279 // Before executing passes, print the final values of the LLVM options. 1280 cl::PrintOptionValues(); 1281 1282 // Now that we have all of the passes ready, run them. 1283 { 1284 PrettyStackTraceString CrashInfo("Optimizer"); 1285 MPM.run(*TheModule, MAM); 1286 } 1287 1288 // Now if needed, run the legacy PM for codegen. 1289 if (NeedCodeGen) { 1290 PrettyStackTraceString CrashInfo("Code generation"); 1291 CodeGenPasses.run(*TheModule); 1292 } 1293 1294 if (ThinLinkOS) 1295 ThinLinkOS->keep(); 1296 if (DwoOS) 1297 DwoOS->keep(); 1298 } 1299 1300 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) { 1301 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1302 if (!BMsOrErr) 1303 return BMsOrErr.takeError(); 1304 1305 // The bitcode file may contain multiple modules, we want the one that is 1306 // marked as being the ThinLTO module. 1307 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr)) 1308 return *Bm; 1309 1310 return make_error<StringError>("Could not find module summary", 1311 inconvertibleErrorCode()); 1312 } 1313 1314 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) { 1315 for (BitcodeModule &BM : BMs) { 1316 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo(); 1317 if (LTOInfo && LTOInfo->IsThinLTO) 1318 return &BM; 1319 } 1320 return nullptr; 1321 } 1322 1323 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M, 1324 const HeaderSearchOptions &HeaderOpts, 1325 const CodeGenOptions &CGOpts, 1326 const clang::TargetOptions &TOpts, 1327 const LangOptions &LOpts, 1328 std::unique_ptr<raw_pwrite_stream> OS, 1329 std::string SampleProfile, 1330 std::string ProfileRemapping, 1331 BackendAction Action) { 1332 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>> 1333 ModuleToDefinedGVSummaries; 1334 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 1335 1336 setCommandLineOpts(CGOpts); 1337 1338 // We can simply import the values mentioned in the combined index, since 1339 // we should only invoke this using the individual indexes written out 1340 // via a WriteIndexesThinBackend. 1341 FunctionImporter::ImportMapTy ImportList; 1342 for (auto &GlobalList : *CombinedIndex) { 1343 // Ignore entries for undefined references. 1344 if (GlobalList.second.SummaryList.empty()) 1345 continue; 1346 1347 auto GUID = GlobalList.first; 1348 for (auto &Summary : GlobalList.second.SummaryList) { 1349 // Skip the summaries for the importing module. These are included to 1350 // e.g. record required linkage changes. 1351 if (Summary->modulePath() == M->getModuleIdentifier()) 1352 continue; 1353 // Add an entry to provoke importing by thinBackend. 1354 ImportList[Summary->modulePath()].insert(GUID); 1355 } 1356 } 1357 1358 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 1359 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 1360 1361 for (auto &I : ImportList) { 1362 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr = 1363 llvm::MemoryBuffer::getFile(I.first()); 1364 if (!MBOrErr) { 1365 errs() << "Error loading imported file '" << I.first() 1366 << "': " << MBOrErr.getError().message() << "\n"; 1367 return; 1368 } 1369 1370 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr); 1371 if (!BMOrErr) { 1372 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { 1373 errs() << "Error loading imported file '" << I.first() 1374 << "': " << EIB.message() << '\n'; 1375 }); 1376 return; 1377 } 1378 ModuleMap.insert({I.first(), *BMOrErr}); 1379 1380 OwnedImports.push_back(std::move(*MBOrErr)); 1381 } 1382 auto AddStream = [&](size_t Task) { 1383 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS)); 1384 }; 1385 lto::Config Conf; 1386 if (CGOpts.SaveTempsFilePrefix != "") { 1387 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".", 1388 /* UseInputModulePath */ false)) { 1389 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1390 errs() << "Error setting up ThinLTO save-temps: " << EIB.message() 1391 << '\n'; 1392 }); 1393 } 1394 } 1395 Conf.CPU = TOpts.CPU; 1396 Conf.CodeModel = getCodeModel(CGOpts); 1397 Conf.MAttrs = TOpts.Features; 1398 Conf.RelocModel = CGOpts.RelocationModel; 1399 Conf.CGOptLevel = getCGOptLevel(CGOpts); 1400 Conf.OptLevel = CGOpts.OptimizationLevel; 1401 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); 1402 Conf.SampleProfile = std::move(SampleProfile); 1403 1404 // Context sensitive profile. 1405 if (CGOpts.hasProfileCSIRInstr()) { 1406 Conf.RunCSIRInstr = true; 1407 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); 1408 } else if (CGOpts.hasProfileCSIRUse()) { 1409 Conf.RunCSIRInstr = false; 1410 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); 1411 } 1412 1413 Conf.ProfileRemapping = std::move(ProfileRemapping); 1414 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager; 1415 Conf.DebugPassManager = CGOpts.DebugPassManager; 1416 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; 1417 Conf.RemarksFilename = CGOpts.OptRecordFile; 1418 Conf.RemarksPasses = CGOpts.OptRecordPasses; 1419 Conf.DwoPath = CGOpts.SplitDwarfFile; 1420 switch (Action) { 1421 case Backend_EmitNothing: 1422 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { 1423 return false; 1424 }; 1425 break; 1426 case Backend_EmitLL: 1427 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1428 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); 1429 return false; 1430 }; 1431 break; 1432 case Backend_EmitBC: 1433 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { 1434 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); 1435 return false; 1436 }; 1437 break; 1438 default: 1439 Conf.CGFileType = getCodeGenFileType(Action); 1440 break; 1441 } 1442 if (Error E = thinBackend( 1443 Conf, -1, AddStream, *M, *CombinedIndex, ImportList, 1444 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) { 1445 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1446 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 1447 }); 1448 } 1449 } 1450 1451 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 1452 const HeaderSearchOptions &HeaderOpts, 1453 const CodeGenOptions &CGOpts, 1454 const clang::TargetOptions &TOpts, 1455 const LangOptions &LOpts, 1456 const llvm::DataLayout &TDesc, Module *M, 1457 BackendAction Action, 1458 std::unique_ptr<raw_pwrite_stream> OS) { 1459 1460 llvm::TimeTraceScope TimeScope("Backend", StringRef("")); 1461 1462 std::unique_ptr<llvm::Module> EmptyModule; 1463 if (!CGOpts.ThinLTOIndexFile.empty()) { 1464 // If we are performing a ThinLTO importing compile, load the function index 1465 // into memory and pass it into runThinLTOBackend, which will run the 1466 // function importer and invoke LTO passes. 1467 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 1468 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, 1469 /*IgnoreEmptyThinLTOIndexFile*/true); 1470 if (!IndexOrErr) { 1471 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 1472 "Error loading index file '" + 1473 CGOpts.ThinLTOIndexFile + "': "); 1474 return; 1475 } 1476 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 1477 // A null CombinedIndex means we should skip ThinLTO compilation 1478 // (LLVM will optionally ignore empty index files, returning null instead 1479 // of an error). 1480 if (CombinedIndex) { 1481 if (!CombinedIndex->skipModuleByDistributedBackend()) { 1482 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts, 1483 LOpts, std::move(OS), CGOpts.SampleProfileFile, 1484 CGOpts.ProfileRemappingFile, Action); 1485 return; 1486 } 1487 // Distributed indexing detected that nothing from the module is needed 1488 // for the final linking. So we can skip the compilation. We sill need to 1489 // output an empty object file to make sure that a linker does not fail 1490 // trying to read it. Also for some features, like CFI, we must skip 1491 // the compilation as CombinedIndex does not contain all required 1492 // information. 1493 EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext()); 1494 EmptyModule->setTargetTriple(M->getTargetTriple()); 1495 M = EmptyModule.get(); 1496 } 1497 } 1498 1499 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 1500 1501 if (CGOpts.ExperimentalNewPassManager) 1502 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 1503 else 1504 AsmHelper.EmitAssembly(Action, std::move(OS)); 1505 1506 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 1507 // DataLayout. 1508 if (AsmHelper.TM) { 1509 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 1510 if (DLDesc != TDesc.getStringRepresentation()) { 1511 unsigned DiagID = Diags.getCustomDiagID( 1512 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 1513 "expected target description '%1'"); 1514 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 1515 } 1516 } 1517 } 1518 1519 static const char* getSectionNameForBitcode(const Triple &T) { 1520 switch (T.getObjectFormat()) { 1521 case Triple::MachO: 1522 return "__LLVM,__bitcode"; 1523 case Triple::COFF: 1524 case Triple::ELF: 1525 case Triple::Wasm: 1526 case Triple::UnknownObjectFormat: 1527 return ".llvmbc"; 1528 case Triple::XCOFF: 1529 llvm_unreachable("XCOFF is not yet implemented"); 1530 break; 1531 } 1532 llvm_unreachable("Unimplemented ObjectFormatType"); 1533 } 1534 1535 static const char* getSectionNameForCommandline(const Triple &T) { 1536 switch (T.getObjectFormat()) { 1537 case Triple::MachO: 1538 return "__LLVM,__cmdline"; 1539 case Triple::COFF: 1540 case Triple::ELF: 1541 case Triple::Wasm: 1542 case Triple::UnknownObjectFormat: 1543 return ".llvmcmd"; 1544 case Triple::XCOFF: 1545 llvm_unreachable("XCOFF is not yet implemented"); 1546 break; 1547 } 1548 llvm_unreachable("Unimplemented ObjectFormatType"); 1549 } 1550 1551 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1552 // __LLVM,__bitcode section. 1553 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1554 llvm::MemoryBufferRef Buf) { 1555 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1556 return; 1557 1558 // Save llvm.compiler.used and remote it. 1559 SmallVector<Constant*, 2> UsedArray; 1560 SmallPtrSet<GlobalValue*, 4> UsedGlobals; 1561 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0); 1562 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true); 1563 for (auto *GV : UsedGlobals) { 1564 if (GV->getName() != "llvm.embedded.module" && 1565 GV->getName() != "llvm.cmdline") 1566 UsedArray.push_back( 1567 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1568 } 1569 if (Used) 1570 Used->eraseFromParent(); 1571 1572 // Embed the bitcode for the llvm module. 1573 std::string Data; 1574 ArrayRef<uint8_t> ModuleData; 1575 Triple T(M->getTargetTriple()); 1576 // Create a constant that contains the bitcode. 1577 // In case of embedding a marker, ignore the input Buf and use the empty 1578 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 1579 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) { 1580 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 1581 (const unsigned char *)Buf.getBufferEnd())) { 1582 // If the input is LLVM Assembly, bitcode is produced by serializing 1583 // the module. Use-lists order need to be perserved in this case. 1584 llvm::raw_string_ostream OS(Data); 1585 llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true); 1586 ModuleData = 1587 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 1588 } else 1589 // If the input is LLVM bitcode, write the input byte stream directly. 1590 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 1591 Buf.getBufferSize()); 1592 } 1593 llvm::Constant *ModuleConstant = 1594 llvm::ConstantDataArray::get(M->getContext(), ModuleData); 1595 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1596 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 1597 ModuleConstant); 1598 GV->setSection(getSectionNameForBitcode(T)); 1599 UsedArray.push_back( 1600 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1601 if (llvm::GlobalVariable *Old = 1602 M->getGlobalVariable("llvm.embedded.module", true)) { 1603 assert(Old->hasOneUse() && 1604 "llvm.embedded.module can only be used once in llvm.compiler.used"); 1605 GV->takeName(Old); 1606 Old->eraseFromParent(); 1607 } else { 1608 GV->setName("llvm.embedded.module"); 1609 } 1610 1611 // Skip if only bitcode needs to be embedded. 1612 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) { 1613 // Embed command-line options. 1614 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()), 1615 CGOpts.CmdArgs.size()); 1616 llvm::Constant *CmdConstant = 1617 llvm::ConstantDataArray::get(M->getContext(), CmdData); 1618 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, 1619 llvm::GlobalValue::PrivateLinkage, 1620 CmdConstant); 1621 GV->setSection(getSectionNameForCommandline(T)); 1622 UsedArray.push_back( 1623 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1624 if (llvm::GlobalVariable *Old = 1625 M->getGlobalVariable("llvm.cmdline", true)) { 1626 assert(Old->hasOneUse() && 1627 "llvm.cmdline can only be used once in llvm.compiler.used"); 1628 GV->takeName(Old); 1629 Old->eraseFromParent(); 1630 } else { 1631 GV->setName("llvm.cmdline"); 1632 } 1633 } 1634 1635 if (UsedArray.empty()) 1636 return; 1637 1638 // Recreate llvm.compiler.used. 1639 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 1640 auto *NewUsed = new GlobalVariable( 1641 *M, ATy, false, llvm::GlobalValue::AppendingLinkage, 1642 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 1643 NewUsed->setSection("llvm.metadata"); 1644 } 1645