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