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