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