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