1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/CodeGen/BackendUtil.h" 11 #include "clang/Basic/Diagnostic.h" 12 #include "clang/Basic/LangOptions.h" 13 #include "clang/Basic/TargetOptions.h" 14 #include "clang/Frontend/CodeGenOptions.h" 15 #include "clang/Frontend/FrontendDiagnostic.h" 16 #include "clang/Frontend/Utils.h" 17 #include "clang/Lex/HeaderSearchOptions.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitcodeWriter.h" 26 #include "llvm/Bitcode/BitcodeWriterPass.h" 27 #include "llvm/CodeGen/RegAllocRegistry.h" 28 #include "llvm/CodeGen/SchedulerRegistry.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/Object/ModuleSummaryIndexObjectFile.h" 39 #include "llvm/Passes/PassBuilder.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/PrettyStackTrace.h" 43 #include "llvm/Support/TargetRegistry.h" 44 #include "llvm/Support/Timer.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include "llvm/Target/TargetSubtargetInfo.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/Instrumentation.h" 54 #include "llvm/Transforms/ObjCARC.h" 55 #include "llvm/Transforms/Scalar.h" 56 #include "llvm/Transforms/Scalar/GVN.h" 57 #include "llvm/Transforms/Utils/SymbolRewriter.h" 58 #include <memory> 59 using namespace clang; 60 using namespace llvm; 61 62 namespace { 63 64 class EmitAssemblyHelper { 65 DiagnosticsEngine &Diags; 66 const HeaderSearchOptions &HSOpts; 67 const CodeGenOptions &CodeGenOpts; 68 const clang::TargetOptions &TargetOpts; 69 const LangOptions &LangOpts; 70 Module *TheModule; 71 72 Timer CodeGenerationTime; 73 74 std::unique_ptr<raw_pwrite_stream> OS; 75 76 TargetIRAnalysis getTargetIRAnalysis() const { 77 if (TM) 78 return TM->getTargetIRAnalysis(); 79 80 return TargetIRAnalysis(); 81 } 82 83 /// Set LLVM command line options passed through -backend-option. 84 void setCommandLineOpts(); 85 86 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); 87 88 /// Generates the TargetMachine. 89 /// Leaves TM unchanged if it is unable to create the target machine. 90 /// Some of our clang tests specify triples which are not built 91 /// into clang. This is okay because these tests check the generated 92 /// IR, and they require DataLayout which depends on the triple. 93 /// In this case, we allow this method to fail and not report an error. 94 /// When MustCreateTM is used, we print an error if we are unable to load 95 /// the requested target. 96 void CreateTargetMachine(bool MustCreateTM); 97 98 /// Add passes necessary to emit assembly or LLVM IR. 99 /// 100 /// \return True on success. 101 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 102 raw_pwrite_stream &OS); 103 104 public: 105 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 106 const HeaderSearchOptions &HeaderSearchOpts, 107 const CodeGenOptions &CGOpts, 108 const clang::TargetOptions &TOpts, 109 const LangOptions &LOpts, Module *M) 110 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 111 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 112 CodeGenerationTime("codegen", "Code Generation Time") {} 113 114 ~EmitAssemblyHelper() { 115 if (CodeGenOpts.DisableFree) 116 BuryPointer(std::move(TM)); 117 } 118 119 std::unique_ptr<TargetMachine> TM; 120 121 void EmitAssembly(BackendAction Action, 122 std::unique_ptr<raw_pwrite_stream> OS); 123 124 void EmitAssemblyWithNewPassManager(BackendAction Action, 125 std::unique_ptr<raw_pwrite_stream> OS); 126 }; 127 128 // We need this wrapper to access LangOpts and CGOpts from extension functions 129 // that we add to the PassManagerBuilder. 130 class PassManagerBuilderWrapper : public PassManagerBuilder { 131 public: 132 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 133 const LangOptions &LangOpts) 134 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 135 const CodeGenOptions &getCGOpts() const { return CGOpts; } 136 const LangOptions &getLangOpts() const { return LangOpts; } 137 private: 138 const CodeGenOptions &CGOpts; 139 const LangOptions &LangOpts; 140 }; 141 142 } 143 144 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 145 if (Builder.OptLevel > 0) 146 PM.add(createObjCARCAPElimPass()); 147 } 148 149 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 150 if (Builder.OptLevel > 0) 151 PM.add(createObjCARCExpandPass()); 152 } 153 154 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 155 if (Builder.OptLevel > 0) 156 PM.add(createObjCARCOptPass()); 157 } 158 159 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 160 legacy::PassManagerBase &PM) { 161 PM.add(createAddDiscriminatorsPass()); 162 } 163 164 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 165 legacy::PassManagerBase &PM) { 166 PM.add(createBoundsCheckingPass()); 167 } 168 169 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 170 legacy::PassManagerBase &PM) { 171 const PassManagerBuilderWrapper &BuilderWrapper = 172 static_cast<const PassManagerBuilderWrapper&>(Builder); 173 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 174 SanitizerCoverageOptions Opts; 175 Opts.CoverageType = 176 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 177 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 178 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 179 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 180 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 181 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 182 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 183 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 184 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 185 PM.add(createSanitizerCoverageModulePass(Opts)); 186 } 187 188 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 189 legacy::PassManagerBase &PM) { 190 const PassManagerBuilderWrapper &BuilderWrapper = 191 static_cast<const PassManagerBuilderWrapper&>(Builder); 192 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 193 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 194 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 195 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 196 UseAfterScope)); 197 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover)); 198 } 199 200 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 201 legacy::PassManagerBase &PM) { 202 PM.add(createAddressSanitizerFunctionPass( 203 /*CompileKernel*/ true, 204 /*Recover*/ true, /*UseAfterScope*/ false)); 205 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true, 206 /*Recover*/true)); 207 } 208 209 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 210 legacy::PassManagerBase &PM) { 211 const PassManagerBuilderWrapper &BuilderWrapper = 212 static_cast<const PassManagerBuilderWrapper&>(Builder); 213 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 214 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; 215 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); 216 PM.add(createMemorySanitizerPass(TrackOrigins, Recover)); 217 218 // MemorySanitizer inserts complex instrumentation that mostly follows 219 // the logic of the original code, but operates on "shadow" values. 220 // It can benefit from re-running some general purpose optimization passes. 221 if (Builder.OptLevel > 0) { 222 PM.add(createEarlyCSEPass()); 223 PM.add(createReassociatePass()); 224 PM.add(createLICMPass()); 225 PM.add(createGVNPass()); 226 PM.add(createInstructionCombiningPass()); 227 PM.add(createDeadStoreEliminationPass()); 228 } 229 } 230 231 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 232 legacy::PassManagerBase &PM) { 233 PM.add(createThreadSanitizerPass()); 234 } 235 236 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 237 legacy::PassManagerBase &PM) { 238 const PassManagerBuilderWrapper &BuilderWrapper = 239 static_cast<const PassManagerBuilderWrapper&>(Builder); 240 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 241 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 242 } 243 244 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder, 245 legacy::PassManagerBase &PM) { 246 const PassManagerBuilderWrapper &BuilderWrapper = 247 static_cast<const PassManagerBuilderWrapper&>(Builder); 248 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 249 EfficiencySanitizerOptions Opts; 250 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag)) 251 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag; 252 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet)) 253 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet; 254 PM.add(createEfficiencySanitizerPass(Opts)); 255 } 256 257 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 258 const CodeGenOptions &CodeGenOpts) { 259 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 260 if (!CodeGenOpts.SimplifyLibCalls) 261 TLII->disableAllFunctions(); 262 else { 263 // Disable individual libc/libm calls in TargetLibraryInfo. 264 LibFunc F; 265 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 266 if (TLII->getLibFunc(FuncName, F)) 267 TLII->setUnavailable(F); 268 } 269 270 switch (CodeGenOpts.getVecLib()) { 271 case CodeGenOptions::Accelerate: 272 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 273 break; 274 case CodeGenOptions::SVML: 275 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 276 break; 277 default: 278 break; 279 } 280 return TLII; 281 } 282 283 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 284 legacy::PassManager *MPM) { 285 llvm::SymbolRewriter::RewriteDescriptorList DL; 286 287 llvm::SymbolRewriter::RewriteMapParser MapParser; 288 for (const auto &MapFile : Opts.RewriteMapFiles) 289 MapParser.parse(MapFile, &DL); 290 291 MPM->add(createRewriteSymbolsPass(DL)); 292 } 293 294 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 295 legacy::FunctionPassManager &FPM) { 296 // Handle disabling of all LLVM passes, where we want to preserve the 297 // internal module before any optimization. 298 if (CodeGenOpts.DisableLLVMPasses) 299 return; 300 301 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 302 303 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 304 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 305 // are inserted before PMBuilder ones - they'd get the default-constructed 306 // TLI with an unknown target otherwise. 307 Triple TargetTriple(TheModule->getTargetTriple()); 308 std::unique_ptr<TargetLibraryInfoImpl> TLII( 309 createTLII(TargetTriple, CodeGenOpts)); 310 311 // At O0 and O1 we only run the always inliner which is more efficient. At 312 // higher optimization levels we run the normal inliner. 313 if (CodeGenOpts.OptimizationLevel <= 1) { 314 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 && 315 !CodeGenOpts.DisableLifetimeMarkers); 316 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 317 } else { 318 PMBuilder.Inliner = createFunctionInliningPass( 319 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize); 320 } 321 322 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 323 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 324 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 325 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 326 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 327 328 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 329 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 330 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex; 331 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 332 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 333 334 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 335 336 if (TM) 337 TM->adjustPassManager(PMBuilder); 338 339 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 340 addAddDiscriminatorsPass); 341 342 // In ObjC ARC mode, add the main ARC optimization passes. 343 if (LangOpts.ObjCAutoRefCount) { 344 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 345 addObjCARCExpandPass); 346 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 347 addObjCARCAPElimPass); 348 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 349 addObjCARCOptPass); 350 } 351 352 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 353 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 354 addBoundsCheckingPass); 355 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 356 addBoundsCheckingPass); 357 } 358 359 if (CodeGenOpts.SanitizeCoverageType || 360 CodeGenOpts.SanitizeCoverageIndirectCalls || 361 CodeGenOpts.SanitizeCoverageTraceCmp) { 362 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 363 addSanitizerCoveragePass); 364 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 365 addSanitizerCoveragePass); 366 } 367 368 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 369 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 370 addAddressSanitizerPasses); 371 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 372 addAddressSanitizerPasses); 373 } 374 375 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 376 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 377 addKernelAddressSanitizerPasses); 378 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 379 addKernelAddressSanitizerPasses); 380 } 381 382 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 383 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 384 addMemorySanitizerPass); 385 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 386 addMemorySanitizerPass); 387 } 388 389 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 390 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 391 addThreadSanitizerPass); 392 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 393 addThreadSanitizerPass); 394 } 395 396 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 397 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 398 addDataFlowSanitizerPass); 399 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 400 addDataFlowSanitizerPass); 401 } 402 403 if (LangOpts.CoroutinesTS) 404 addCoroutinePassesToExtensionPoints(PMBuilder); 405 406 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) { 407 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 408 addEfficiencySanitizerPass); 409 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 410 addEfficiencySanitizerPass); 411 } 412 413 // Set up the per-function pass manager. 414 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 415 if (CodeGenOpts.VerifyModule) 416 FPM.add(createVerifierPass()); 417 418 // Set up the per-module pass manager. 419 if (!CodeGenOpts.RewriteMapFiles.empty()) 420 addSymbolRewriterPass(CodeGenOpts, &MPM); 421 422 if (!CodeGenOpts.DisableGCov && 423 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 424 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 425 // LLVM's -default-gcov-version flag is set to something invalid. 426 GCOVOptions Options; 427 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 428 Options.EmitData = CodeGenOpts.EmitGcovArcs; 429 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 430 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 431 Options.NoRedZone = CodeGenOpts.DisableRedZone; 432 Options.FunctionNamesInData = 433 !CodeGenOpts.CoverageNoFunctionNamesInData; 434 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 435 MPM.add(createGCOVProfilerPass(Options)); 436 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 437 MPM.add(createStripSymbolsPass(true)); 438 } 439 440 if (CodeGenOpts.hasProfileClangInstr()) { 441 InstrProfOptions Options; 442 Options.NoRedZone = CodeGenOpts.DisableRedZone; 443 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 444 MPM.add(createInstrProfilingLegacyPass(Options)); 445 } 446 if (CodeGenOpts.hasProfileIRInstr()) { 447 PMBuilder.EnablePGOInstrGen = true; 448 if (!CodeGenOpts.InstrProfileOutput.empty()) 449 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 450 else 451 PMBuilder.PGOInstrGen = "default_%m.profraw"; 452 } 453 if (CodeGenOpts.hasProfileIRUse()) 454 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 455 456 if (!CodeGenOpts.SampleProfileFile.empty()) 457 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 458 459 PMBuilder.populateFunctionPassManager(FPM); 460 PMBuilder.populateModulePassManager(MPM); 461 } 462 463 void EmitAssemblyHelper::setCommandLineOpts() { 464 SmallVector<const char *, 16> BackendArgs; 465 BackendArgs.push_back("clang"); // Fake program name. 466 if (!CodeGenOpts.DebugPass.empty()) { 467 BackendArgs.push_back("-debug-pass"); 468 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 469 } 470 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 471 BackendArgs.push_back("-limit-float-precision"); 472 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 473 } 474 for (const std::string &BackendOption : CodeGenOpts.BackendOptions) 475 BackendArgs.push_back(BackendOption.c_str()); 476 BackendArgs.push_back(nullptr); 477 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 478 BackendArgs.data()); 479 } 480 481 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 482 // Create the TargetMachine for generating code. 483 std::string Error; 484 std::string Triple = TheModule->getTargetTriple(); 485 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 486 if (!TheTarget) { 487 if (MustCreateTM) 488 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 489 return; 490 } 491 492 unsigned CodeModel = 493 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 494 .Case("small", llvm::CodeModel::Small) 495 .Case("kernel", llvm::CodeModel::Kernel) 496 .Case("medium", llvm::CodeModel::Medium) 497 .Case("large", llvm::CodeModel::Large) 498 .Case("default", llvm::CodeModel::Default) 499 .Default(~0u); 500 assert(CodeModel != ~0u && "invalid code model!"); 501 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 502 503 std::string FeaturesStr = 504 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 505 506 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp. 507 llvm::Optional<llvm::Reloc::Model> RM; 508 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel) 509 .Case("static", llvm::Reloc::Static) 510 .Case("pic", llvm::Reloc::PIC_) 511 .Case("ropi", llvm::Reloc::ROPI) 512 .Case("rwpi", llvm::Reloc::RWPI) 513 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 514 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC); 515 assert(RM.hasValue() && "invalid PIC model!"); 516 517 CodeGenOpt::Level OptLevel; 518 switch (CodeGenOpts.OptimizationLevel) { 519 default: 520 llvm_unreachable("Invalid optimization level!"); 521 case 0: 522 OptLevel = CodeGenOpt::None; 523 break; 524 case 1: 525 OptLevel = CodeGenOpt::Less; 526 break; 527 case 2: 528 OptLevel = CodeGenOpt::Default; 529 break; // O2/Os/Oz 530 case 3: 531 OptLevel = CodeGenOpt::Aggressive; 532 break; 533 } 534 535 llvm::TargetOptions Options; 536 537 Options.ThreadModel = 538 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 539 .Case("posix", llvm::ThreadModel::POSIX) 540 .Case("single", llvm::ThreadModel::Single); 541 542 // Set float ABI type. 543 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 544 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 545 "Invalid Floating Point ABI!"); 546 Options.FloatABIType = 547 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 548 .Case("soft", llvm::FloatABI::Soft) 549 .Case("softfp", llvm::FloatABI::Soft) 550 .Case("hard", llvm::FloatABI::Hard) 551 .Default(llvm::FloatABI::Default); 552 553 // Set FP fusion mode. 554 switch (CodeGenOpts.getFPContractMode()) { 555 case CodeGenOptions::FPC_Off: 556 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 557 break; 558 case CodeGenOptions::FPC_On: 559 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 560 break; 561 case CodeGenOptions::FPC_Fast: 562 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 563 break; 564 } 565 566 Options.UseInitArray = CodeGenOpts.UseInitArray; 567 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 568 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections; 569 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 570 571 // Set EABI version. 572 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion) 573 .Case("4", llvm::EABI::EABI4) 574 .Case("5", llvm::EABI::EABI5) 575 .Case("gnu", llvm::EABI::GNU) 576 .Default(llvm::EABI::Default); 577 578 if (LangOpts.SjLjExceptions) 579 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 580 581 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 582 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 583 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 584 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 585 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 586 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 587 Options.FunctionSections = CodeGenOpts.FunctionSections; 588 Options.DataSections = CodeGenOpts.DataSections; 589 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 590 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 591 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 592 593 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 594 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 595 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 596 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 597 Options.MCOptions.MCIncrementalLinkerCompatible = 598 CodeGenOpts.IncrementalLinkerCompatible; 599 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations; 600 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 601 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 602 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 603 Options.MCOptions.ABIName = TargetOpts.ABI; 604 for (const auto &Entry : HSOpts.UserEntries) 605 if (!Entry.IsFramework && 606 (Entry.Group == frontend::IncludeDirGroup::Quoted || 607 Entry.Group == frontend::IncludeDirGroup::Angled || 608 Entry.Group == frontend::IncludeDirGroup::System)) 609 Options.MCOptions.IASSearchPaths.push_back( 610 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 611 612 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 613 Options, RM, CM, OptLevel)); 614 } 615 616 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 617 BackendAction Action, 618 raw_pwrite_stream &OS) { 619 // Add LibraryInfo. 620 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 621 std::unique_ptr<TargetLibraryInfoImpl> TLII( 622 createTLII(TargetTriple, CodeGenOpts)); 623 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 624 625 // Normal mode, emit a .s or .o file by running the code generator. Note, 626 // this also adds codegenerator level optimization passes. 627 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 628 if (Action == Backend_EmitObj) 629 CGFT = TargetMachine::CGFT_ObjectFile; 630 else if (Action == Backend_EmitMCNull) 631 CGFT = TargetMachine::CGFT_Null; 632 else 633 assert(Action == Backend_EmitAssembly && "Invalid action!"); 634 635 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 636 // "codegen" passes so that it isn't run multiple times when there is 637 // inlining happening. 638 if (CodeGenOpts.OptimizationLevel > 0) 639 CodeGenPasses.add(createObjCARCContractPass()); 640 641 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT, 642 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 643 Diags.Report(diag::err_fe_unable_to_interface_with_target); 644 return false; 645 } 646 647 return true; 648 } 649 650 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 651 std::unique_ptr<raw_pwrite_stream> OS) { 652 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 653 654 setCommandLineOpts(); 655 656 bool UsesCodeGen = (Action != Backend_EmitNothing && 657 Action != Backend_EmitBC && 658 Action != Backend_EmitLL); 659 CreateTargetMachine(UsesCodeGen); 660 661 if (UsesCodeGen && !TM) 662 return; 663 if (TM) 664 TheModule->setDataLayout(TM->createDataLayout()); 665 666 legacy::PassManager PerModulePasses; 667 PerModulePasses.add( 668 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 669 670 legacy::FunctionPassManager PerFunctionPasses(TheModule); 671 PerFunctionPasses.add( 672 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 673 674 CreatePasses(PerModulePasses, PerFunctionPasses); 675 676 legacy::PassManager CodeGenPasses; 677 CodeGenPasses.add( 678 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 679 680 switch (Action) { 681 case Backend_EmitNothing: 682 break; 683 684 case Backend_EmitBC: 685 if (CodeGenOpts.EmitSummaryIndex) 686 PerModulePasses.add(createWriteThinLTOBitcodePass(*OS)); 687 else 688 PerModulePasses.add( 689 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists)); 690 break; 691 692 case Backend_EmitLL: 693 PerModulePasses.add( 694 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 695 break; 696 697 default: 698 if (!AddEmitPasses(CodeGenPasses, Action, *OS)) 699 return; 700 } 701 702 // Before executing passes, print the final values of the LLVM options. 703 cl::PrintOptionValues(); 704 705 // Run passes. For now we do all passes at once, but eventually we 706 // would like to have the option of streaming code generation. 707 708 { 709 PrettyStackTraceString CrashInfo("Per-function optimization"); 710 711 PerFunctionPasses.doInitialization(); 712 for (Function &F : *TheModule) 713 if (!F.isDeclaration()) 714 PerFunctionPasses.run(F); 715 PerFunctionPasses.doFinalization(); 716 } 717 718 { 719 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 720 PerModulePasses.run(*TheModule); 721 } 722 723 { 724 PrettyStackTraceString CrashInfo("Code generation"); 725 CodeGenPasses.run(*TheModule); 726 } 727 } 728 729 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 730 switch (Opts.OptimizationLevel) { 731 default: 732 llvm_unreachable("Invalid optimization level!"); 733 734 case 1: 735 return PassBuilder::O1; 736 737 case 2: 738 switch (Opts.OptimizeSize) { 739 default: 740 llvm_unreachable("Invalide optimization level for size!"); 741 742 case 0: 743 return PassBuilder::O2; 744 745 case 1: 746 return PassBuilder::Os; 747 748 case 2: 749 return PassBuilder::Oz; 750 } 751 752 case 3: 753 return PassBuilder::O3; 754 } 755 } 756 757 /// A clean version of `EmitAssembly` that uses the new pass manager. 758 /// 759 /// Not all features are currently supported in this system, but where 760 /// necessary it falls back to the legacy pass manager to at least provide 761 /// basic functionality. 762 /// 763 /// This API is planned to have its functionality finished and then to replace 764 /// `EmitAssembly` at some point in the future when the default switches. 765 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 766 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 767 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 768 setCommandLineOpts(); 769 770 // The new pass manager always makes a target machine available to passes 771 // during construction. 772 CreateTargetMachine(/*MustCreateTM*/ true); 773 if (!TM) 774 // This will already be diagnosed, just bail. 775 return; 776 TheModule->setDataLayout(TM->createDataLayout()); 777 778 PassBuilder PB(TM.get()); 779 780 LoopAnalysisManager LAM; 781 FunctionAnalysisManager FAM; 782 CGSCCAnalysisManager CGAM; 783 ModuleAnalysisManager MAM; 784 785 // Register the AA manager first so that our version is the one used. 786 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 787 788 // Register all the basic analyses with the managers. 789 PB.registerModuleAnalyses(MAM); 790 PB.registerCGSCCAnalyses(CGAM); 791 PB.registerFunctionAnalyses(FAM); 792 PB.registerLoopAnalyses(LAM); 793 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 794 795 ModulePassManager MPM; 796 797 if (!CodeGenOpts.DisableLLVMPasses) { 798 if (CodeGenOpts.OptimizationLevel == 0) { 799 // Build a minimal pipeline based on the semantics required by Clang, 800 // which is just that always inlining occurs. 801 MPM.addPass(AlwaysInlinerPass()); 802 } else { 803 // Otherwise, use the default pass pipeline. We also have to map our 804 // optimization levels into one of the distinct levels used to configure 805 // the pipeline. 806 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 807 808 MPM = PB.buildPerModuleDefaultPipeline(Level); 809 } 810 } 811 812 // FIXME: We still use the legacy pass manager to do code generation. We 813 // create that pass manager here and use it as needed below. 814 legacy::PassManager CodeGenPasses; 815 bool NeedCodeGen = false; 816 817 // Append any output we need to the pass manager. 818 switch (Action) { 819 case Backend_EmitNothing: 820 break; 821 822 case Backend_EmitBC: 823 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 824 CodeGenOpts.EmitSummaryIndex, 825 CodeGenOpts.EmitSummaryIndex)); 826 break; 827 828 case Backend_EmitLL: 829 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 830 break; 831 832 case Backend_EmitAssembly: 833 case Backend_EmitMCNull: 834 case Backend_EmitObj: 835 NeedCodeGen = true; 836 CodeGenPasses.add( 837 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 838 if (!AddEmitPasses(CodeGenPasses, Action, *OS)) 839 // FIXME: Should we handle this error differently? 840 return; 841 break; 842 } 843 844 // Before executing passes, print the final values of the LLVM options. 845 cl::PrintOptionValues(); 846 847 // Now that we have all of the passes ready, run them. 848 { 849 PrettyStackTraceString CrashInfo("Optimizer"); 850 MPM.run(*TheModule, MAM); 851 } 852 853 // Now if needed, run the legacy PM for codegen. 854 if (NeedCodeGen) { 855 PrettyStackTraceString CrashInfo("Code generation"); 856 CodeGenPasses.run(*TheModule); 857 } 858 } 859 860 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) { 861 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 862 if (!BMsOrErr) 863 return BMsOrErr.takeError(); 864 865 // The bitcode file may contain multiple modules, we want the one with a 866 // summary. 867 for (BitcodeModule &BM : *BMsOrErr) { 868 Expected<bool> HasSummary = BM.hasSummary(); 869 if (HasSummary && *HasSummary) 870 return BM; 871 } 872 873 return make_error<StringError>("Could not find module summary", 874 inconvertibleErrorCode()); 875 } 876 877 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M, 878 std::unique_ptr<raw_pwrite_stream> OS, 879 std::string SampleProfile) { 880 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> 881 ModuleToDefinedGVSummaries; 882 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 883 884 // We can simply import the values mentioned in the combined index, since 885 // we should only invoke this using the individual indexes written out 886 // via a WriteIndexesThinBackend. 887 FunctionImporter::ImportMapTy ImportList; 888 for (auto &GlobalList : *CombinedIndex) { 889 auto GUID = GlobalList.first; 890 assert(GlobalList.second.size() == 1 && 891 "Expected individual combined index to have one summary per GUID"); 892 auto &Summary = GlobalList.second[0]; 893 // Skip the summaries for the importing module. These are included to 894 // e.g. record required linkage changes. 895 if (Summary->modulePath() == M->getModuleIdentifier()) 896 continue; 897 // Doesn't matter what value we plug in to the map, just needs an entry 898 // to provoke importing by thinBackend. 899 ImportList[Summary->modulePath()][GUID] = 1; 900 } 901 902 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 903 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 904 905 for (auto &I : ImportList) { 906 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr = 907 llvm::MemoryBuffer::getFile(I.first()); 908 if (!MBOrErr) { 909 errs() << "Error loading imported file '" << I.first() 910 << "': " << MBOrErr.getError().message() << "\n"; 911 return; 912 } 913 914 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr); 915 if (!BMOrErr) { 916 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { 917 errs() << "Error loading imported file '" << I.first() 918 << "': " << EIB.message() << '\n'; 919 }); 920 return; 921 } 922 ModuleMap.insert({I.first(), *BMOrErr}); 923 924 OwnedImports.push_back(std::move(*MBOrErr)); 925 } 926 auto AddStream = [&](size_t Task) { 927 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS)); 928 }; 929 lto::Config Conf; 930 Conf.SampleProfile = SampleProfile; 931 if (Error E = thinBackend( 932 Conf, 0, AddStream, *M, *CombinedIndex, ImportList, 933 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) { 934 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 935 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 936 }); 937 } 938 } 939 940 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 941 const HeaderSearchOptions &HeaderOpts, 942 const CodeGenOptions &CGOpts, 943 const clang::TargetOptions &TOpts, 944 const LangOptions &LOpts, 945 const llvm::DataLayout &TDesc, Module *M, 946 BackendAction Action, 947 std::unique_ptr<raw_pwrite_stream> OS) { 948 if (!CGOpts.ThinLTOIndexFile.empty()) { 949 // If we are performing a ThinLTO importing compile, load the function index 950 // into memory and pass it into runThinLTOBackend, which will run the 951 // function importer and invoke LTO passes. 952 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 953 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile); 954 if (!IndexOrErr) { 955 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 956 "Error loading index file '" + 957 CGOpts.ThinLTOIndexFile + "': "); 958 return; 959 } 960 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 961 // A null CombinedIndex means we should skip ThinLTO compilation 962 // (LLVM will optionally ignore empty index files, returning null instead 963 // of an error). 964 bool DoThinLTOBackend = CombinedIndex != nullptr; 965 if (DoThinLTOBackend) { 966 runThinLTOBackend(CombinedIndex.get(), M, std::move(OS), 967 CGOpts.SampleProfileFile); 968 return; 969 } 970 } 971 972 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 973 974 if (CGOpts.ExperimentalNewPassManager) 975 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 976 else 977 AsmHelper.EmitAssembly(Action, std::move(OS)); 978 979 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 980 // DataLayout. 981 if (AsmHelper.TM) { 982 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 983 if (DLDesc != TDesc.getStringRepresentation()) { 984 unsigned DiagID = Diags.getCustomDiagID( 985 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 986 "expected target description '%1'"); 987 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 988 } 989 } 990 } 991 992 static const char* getSectionNameForBitcode(const Triple &T) { 993 switch (T.getObjectFormat()) { 994 case Triple::MachO: 995 return "__LLVM,__bitcode"; 996 case Triple::COFF: 997 case Triple::ELF: 998 case Triple::Wasm: 999 case Triple::UnknownObjectFormat: 1000 return ".llvmbc"; 1001 } 1002 llvm_unreachable("Unimplemented ObjectFormatType"); 1003 } 1004 1005 static const char* getSectionNameForCommandline(const Triple &T) { 1006 switch (T.getObjectFormat()) { 1007 case Triple::MachO: 1008 return "__LLVM,__cmdline"; 1009 case Triple::COFF: 1010 case Triple::ELF: 1011 case Triple::Wasm: 1012 case Triple::UnknownObjectFormat: 1013 return ".llvmcmd"; 1014 } 1015 llvm_unreachable("Unimplemented ObjectFormatType"); 1016 } 1017 1018 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1019 // __LLVM,__bitcode section. 1020 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1021 llvm::MemoryBufferRef Buf) { 1022 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1023 return; 1024 1025 // Save llvm.compiler.used and remote it. 1026 SmallVector<Constant*, 2> UsedArray; 1027 SmallSet<GlobalValue*, 4> UsedGlobals; 1028 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0); 1029 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true); 1030 for (auto *GV : UsedGlobals) { 1031 if (GV->getName() != "llvm.embedded.module" && 1032 GV->getName() != "llvm.cmdline") 1033 UsedArray.push_back( 1034 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1035 } 1036 if (Used) 1037 Used->eraseFromParent(); 1038 1039 // Embed the bitcode for the llvm module. 1040 std::string Data; 1041 ArrayRef<uint8_t> ModuleData; 1042 Triple T(M->getTargetTriple()); 1043 // Create a constant that contains the bitcode. 1044 // In case of embedding a marker, ignore the input Buf and use the empty 1045 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 1046 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) { 1047 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 1048 (const unsigned char *)Buf.getBufferEnd())) { 1049 // If the input is LLVM Assembly, bitcode is produced by serializing 1050 // the module. Use-lists order need to be perserved in this case. 1051 llvm::raw_string_ostream OS(Data); 1052 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 1053 ModuleData = 1054 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 1055 } else 1056 // If the input is LLVM bitcode, write the input byte stream directly. 1057 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 1058 Buf.getBufferSize()); 1059 } 1060 llvm::Constant *ModuleConstant = 1061 llvm::ConstantDataArray::get(M->getContext(), ModuleData); 1062 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1063 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 1064 ModuleConstant); 1065 GV->setSection(getSectionNameForBitcode(T)); 1066 UsedArray.push_back( 1067 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1068 if (llvm::GlobalVariable *Old = 1069 M->getGlobalVariable("llvm.embedded.module", true)) { 1070 assert(Old->hasOneUse() && 1071 "llvm.embedded.module can only be used once in llvm.compiler.used"); 1072 GV->takeName(Old); 1073 Old->eraseFromParent(); 1074 } else { 1075 GV->setName("llvm.embedded.module"); 1076 } 1077 1078 // Skip if only bitcode needs to be embedded. 1079 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) { 1080 // Embed command-line options. 1081 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()), 1082 CGOpts.CmdArgs.size()); 1083 llvm::Constant *CmdConstant = 1084 llvm::ConstantDataArray::get(M->getContext(), CmdData); 1085 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, 1086 llvm::GlobalValue::PrivateLinkage, 1087 CmdConstant); 1088 GV->setSection(getSectionNameForCommandline(T)); 1089 UsedArray.push_back( 1090 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1091 if (llvm::GlobalVariable *Old = 1092 M->getGlobalVariable("llvm.cmdline", true)) { 1093 assert(Old->hasOneUse() && 1094 "llvm.cmdline can only be used once in llvm.compiler.used"); 1095 GV->takeName(Old); 1096 Old->eraseFromParent(); 1097 } else { 1098 GV->setName("llvm.cmdline"); 1099 } 1100 } 1101 1102 if (UsedArray.empty()) 1103 return; 1104 1105 // Recreate llvm.compiler.used. 1106 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 1107 auto *NewUsed = new GlobalVariable( 1108 *M, ATy, false, llvm::GlobalValue::AppendingLinkage, 1109 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 1110 NewUsed->setSection("llvm.metadata"); 1111 } 1112