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 "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeWriterPass.h" 23 #include "llvm/Bitcode/ReaderWriter.h" 24 #include "llvm/CodeGen/RegAllocRegistry.h" 25 #include "llvm/CodeGen/SchedulerRegistry.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/ModuleSummaryIndex.h" 28 #include "llvm/IR/IRPrintingPasses.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IR/Verifier.h" 32 #include "llvm/MC/SubtargetFeature.h" 33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/PrettyStackTrace.h" 36 #include "llvm/Support/TargetRegistry.h" 37 #include "llvm/Support/Timer.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetMachine.h" 40 #include "llvm/Target/TargetOptions.h" 41 #include "llvm/Target/TargetSubtargetInfo.h" 42 #include "llvm/Transforms/IPO.h" 43 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 44 #include "llvm/Transforms/Instrumentation.h" 45 #include "llvm/Transforms/ObjCARC.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Scalar/GVN.h" 48 #include "llvm/Transforms/Utils/SymbolRewriter.h" 49 #include <memory> 50 using namespace clang; 51 using namespace llvm; 52 53 namespace { 54 55 class EmitAssemblyHelper { 56 DiagnosticsEngine &Diags; 57 const CodeGenOptions &CodeGenOpts; 58 const clang::TargetOptions &TargetOpts; 59 const LangOptions &LangOpts; 60 Module *TheModule; 61 62 Timer CodeGenerationTime; 63 64 std::unique_ptr<raw_pwrite_stream> OS; 65 66 private: 67 TargetIRAnalysis getTargetIRAnalysis() const { 68 if (TM) 69 return TM->getTargetIRAnalysis(); 70 71 return TargetIRAnalysis(); 72 } 73 74 /// Set LLVM command line options passed through -backend-option. 75 void setCommandLineOpts(); 76 77 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM, 78 ModuleSummaryIndex *ModuleSummary); 79 80 /// Generates the TargetMachine. 81 /// Leaves TM unchanged if it is unable to create the target machine. 82 /// Some of our clang tests specify triples which are not built 83 /// into clang. This is okay because these tests check the generated 84 /// IR, and they require DataLayout which depends on the triple. 85 /// In this case, we allow this method to fail and not report an error. 86 /// When MustCreateTM is used, we print an error if we are unable to load 87 /// the requested target. 88 void CreateTargetMachine(bool MustCreateTM); 89 90 /// Add passes necessary to emit assembly or LLVM IR. 91 /// 92 /// \return True on success. 93 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 94 raw_pwrite_stream &OS); 95 96 public: 97 EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts, 98 const clang::TargetOptions &TOpts, 99 const LangOptions &LOpts, Module *M) 100 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), 101 TheModule(M), CodeGenerationTime("Code Generation Time") {} 102 103 ~EmitAssemblyHelper() { 104 if (CodeGenOpts.DisableFree) 105 BuryPointer(std::move(TM)); 106 } 107 108 std::unique_ptr<TargetMachine> TM; 109 110 void EmitAssembly(BackendAction Action, 111 std::unique_ptr<raw_pwrite_stream> OS); 112 }; 113 114 // We need this wrapper to access LangOpts and CGOpts from extension functions 115 // that we add to the PassManagerBuilder. 116 class PassManagerBuilderWrapper : public PassManagerBuilder { 117 public: 118 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 119 const LangOptions &LangOpts) 120 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 121 const CodeGenOptions &getCGOpts() const { return CGOpts; } 122 const LangOptions &getLangOpts() const { return LangOpts; } 123 private: 124 const CodeGenOptions &CGOpts; 125 const LangOptions &LangOpts; 126 }; 127 128 } 129 130 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 131 if (Builder.OptLevel > 0) 132 PM.add(createObjCARCAPElimPass()); 133 } 134 135 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 136 if (Builder.OptLevel > 0) 137 PM.add(createObjCARCExpandPass()); 138 } 139 140 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 141 if (Builder.OptLevel > 0) 142 PM.add(createObjCARCOptPass()); 143 } 144 145 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 146 legacy::PassManagerBase &PM) { 147 PM.add(createAddDiscriminatorsPass()); 148 } 149 150 static void addCleanupPassesForSampleProfiler( 151 const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { 152 // instcombine is needed before sample profile annotation because it converts 153 // certain function calls to be inlinable. simplifycfg and sroa are needed 154 // before instcombine for necessary preparation. E.g. load store is eliminated 155 // properly so that instcombine will not introduce unecessary liverange. 156 PM.add(createCFGSimplificationPass()); 157 PM.add(createSROAPass()); 158 PM.add(createInstructionCombiningPass()); 159 } 160 161 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 162 legacy::PassManagerBase &PM) { 163 PM.add(createBoundsCheckingPass()); 164 } 165 166 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 167 legacy::PassManagerBase &PM) { 168 const PassManagerBuilderWrapper &BuilderWrapper = 169 static_cast<const PassManagerBuilderWrapper&>(Builder); 170 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 171 SanitizerCoverageOptions Opts; 172 Opts.CoverageType = 173 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 174 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 175 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 176 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 177 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 178 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 179 PM.add(createSanitizerCoverageModulePass(Opts)); 180 } 181 182 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 183 legacy::PassManagerBase &PM) { 184 const PassManagerBuilderWrapper &BuilderWrapper = 185 static_cast<const PassManagerBuilderWrapper&>(Builder); 186 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 187 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 188 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 189 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 190 UseAfterScope)); 191 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover)); 192 } 193 194 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 195 legacy::PassManagerBase &PM) { 196 PM.add(createAddressSanitizerFunctionPass( 197 /*CompileKernel*/ true, 198 /*Recover*/ true, /*UseAfterScope*/ false)); 199 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true, 200 /*Recover*/true)); 201 } 202 203 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 204 legacy::PassManagerBase &PM) { 205 const PassManagerBuilderWrapper &BuilderWrapper = 206 static_cast<const PassManagerBuilderWrapper&>(Builder); 207 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 208 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins)); 209 210 // MemorySanitizer inserts complex instrumentation that mostly follows 211 // the logic of the original code, but operates on "shadow" values. 212 // It can benefit from re-running some general purpose optimization passes. 213 if (Builder.OptLevel > 0) { 214 PM.add(createEarlyCSEPass()); 215 PM.add(createReassociatePass()); 216 PM.add(createLICMPass()); 217 PM.add(createGVNPass()); 218 PM.add(createInstructionCombiningPass()); 219 PM.add(createDeadStoreEliminationPass()); 220 } 221 } 222 223 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 224 legacy::PassManagerBase &PM) { 225 PM.add(createThreadSanitizerPass()); 226 } 227 228 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 229 legacy::PassManagerBase &PM) { 230 const PassManagerBuilderWrapper &BuilderWrapper = 231 static_cast<const PassManagerBuilderWrapper&>(Builder); 232 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 233 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 234 } 235 236 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder, 237 legacy::PassManagerBase &PM) { 238 const PassManagerBuilderWrapper &BuilderWrapper = 239 static_cast<const PassManagerBuilderWrapper&>(Builder); 240 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 241 EfficiencySanitizerOptions Opts; 242 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag)) 243 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag; 244 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet)) 245 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet; 246 PM.add(createEfficiencySanitizerPass(Opts)); 247 } 248 249 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 250 const CodeGenOptions &CodeGenOpts) { 251 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 252 if (!CodeGenOpts.SimplifyLibCalls) 253 TLII->disableAllFunctions(); 254 else { 255 // Disable individual libc/libm calls in TargetLibraryInfo. 256 LibFunc::Func F; 257 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 258 if (TLII->getLibFunc(FuncName, F)) 259 TLII->setUnavailable(F); 260 } 261 262 switch (CodeGenOpts.getVecLib()) { 263 case CodeGenOptions::Accelerate: 264 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 265 break; 266 default: 267 break; 268 } 269 return TLII; 270 } 271 272 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 273 legacy::PassManager *MPM) { 274 llvm::SymbolRewriter::RewriteDescriptorList DL; 275 276 llvm::SymbolRewriter::RewriteMapParser MapParser; 277 for (const auto &MapFile : Opts.RewriteMapFiles) 278 MapParser.parse(MapFile, &DL); 279 280 MPM->add(createRewriteSymbolsPass(DL)); 281 } 282 283 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 284 legacy::FunctionPassManager &FPM, 285 ModuleSummaryIndex *ModuleSummary) { 286 if (CodeGenOpts.DisableLLVMPasses) 287 return; 288 289 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 290 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 291 292 // Handle disabling of LLVM optimization, where we want to preserve the 293 // internal module before any optimization. 294 if (CodeGenOpts.DisableLLVMOpts) { 295 OptLevel = 0; 296 Inlining = CodeGenOpts.NoInlining; 297 } 298 299 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 300 301 // Figure out TargetLibraryInfo. 302 Triple TargetTriple(TheModule->getTargetTriple()); 303 PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts); 304 305 switch (Inlining) { 306 case CodeGenOptions::NoInlining: 307 break; 308 case CodeGenOptions::NormalInlining: 309 case CodeGenOptions::OnlyHintInlining: { 310 PMBuilder.Inliner = 311 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize); 312 break; 313 } 314 case CodeGenOptions::OnlyAlwaysInlining: 315 // Respect always_inline. 316 if (OptLevel == 0) 317 // Do not insert lifetime intrinsics at -O0. 318 PMBuilder.Inliner = createAlwaysInlinerPass(false); 319 else 320 PMBuilder.Inliner = createAlwaysInlinerPass(); 321 break; 322 } 323 324 PMBuilder.OptLevel = OptLevel; 325 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 326 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 327 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 328 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 329 330 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 331 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 332 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex; 333 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 334 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 335 336 // If we are performing a ThinLTO importing compile, invoke the LTO 337 // pipeline and pass down the in-memory module summary index. 338 if (ModuleSummary) { 339 PMBuilder.ModuleSummary = ModuleSummary; 340 PMBuilder.populateThinLTOPassManager(MPM); 341 return; 342 } 343 344 // Add target-specific passes that need to run as early as possible. 345 if (TM) 346 PMBuilder.addExtension( 347 PassManagerBuilder::EP_EarlyAsPossible, 348 [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { 349 TM->addEarlyAsPossiblePasses(PM); 350 }); 351 352 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 353 addAddDiscriminatorsPass); 354 355 // In ObjC ARC mode, add the main ARC optimization passes. 356 if (LangOpts.ObjCAutoRefCount) { 357 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 358 addObjCARCExpandPass); 359 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 360 addObjCARCAPElimPass); 361 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 362 addObjCARCOptPass); 363 } 364 365 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 366 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 367 addBoundsCheckingPass); 368 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 369 addBoundsCheckingPass); 370 } 371 372 if (CodeGenOpts.SanitizeCoverageType || 373 CodeGenOpts.SanitizeCoverageIndirectCalls || 374 CodeGenOpts.SanitizeCoverageTraceCmp) { 375 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 376 addSanitizerCoveragePass); 377 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 378 addSanitizerCoveragePass); 379 } 380 381 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 382 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 383 addAddressSanitizerPasses); 384 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 385 addAddressSanitizerPasses); 386 } 387 388 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 389 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 390 addKernelAddressSanitizerPasses); 391 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 392 addKernelAddressSanitizerPasses); 393 } 394 395 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 396 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 397 addMemorySanitizerPass); 398 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 399 addMemorySanitizerPass); 400 } 401 402 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 403 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 404 addThreadSanitizerPass); 405 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 406 addThreadSanitizerPass); 407 } 408 409 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 410 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 411 addDataFlowSanitizerPass); 412 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 413 addDataFlowSanitizerPass); 414 } 415 416 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) { 417 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 418 addEfficiencySanitizerPass); 419 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 420 addEfficiencySanitizerPass); 421 } 422 423 // Set up the per-function pass manager. 424 if (CodeGenOpts.VerifyModule) 425 FPM.add(createVerifierPass()); 426 427 // Set up the per-module pass manager. 428 if (!CodeGenOpts.RewriteMapFiles.empty()) 429 addSymbolRewriterPass(CodeGenOpts, &MPM); 430 431 if (!CodeGenOpts.DisableGCov && 432 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 433 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 434 // LLVM's -default-gcov-version flag is set to something invalid. 435 GCOVOptions Options; 436 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 437 Options.EmitData = CodeGenOpts.EmitGcovArcs; 438 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 439 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 440 Options.NoRedZone = CodeGenOpts.DisableRedZone; 441 Options.FunctionNamesInData = 442 !CodeGenOpts.CoverageNoFunctionNamesInData; 443 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 444 MPM.add(createGCOVProfilerPass(Options)); 445 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 446 MPM.add(createStripSymbolsPass(true)); 447 } 448 449 if (CodeGenOpts.hasProfileClangInstr()) { 450 InstrProfOptions Options; 451 Options.NoRedZone = CodeGenOpts.DisableRedZone; 452 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 453 MPM.add(createInstrProfilingLegacyPass(Options)); 454 } 455 if (CodeGenOpts.hasProfileIRInstr()) { 456 if (!CodeGenOpts.InstrProfileOutput.empty()) 457 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 458 else 459 PMBuilder.PGOInstrGen = "default.profraw"; 460 } 461 if (CodeGenOpts.hasProfileIRUse()) 462 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 463 464 if (!CodeGenOpts.SampleProfileFile.empty()) { 465 MPM.add(createPruneEHPass()); 466 MPM.add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile)); 467 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 468 addCleanupPassesForSampleProfiler); 469 } 470 471 PMBuilder.populateFunctionPassManager(FPM); 472 PMBuilder.populateModulePassManager(MPM); 473 } 474 475 void EmitAssemblyHelper::setCommandLineOpts() { 476 SmallVector<const char *, 16> BackendArgs; 477 BackendArgs.push_back("clang"); // Fake program name. 478 if (!CodeGenOpts.DebugPass.empty()) { 479 BackendArgs.push_back("-debug-pass"); 480 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 481 } 482 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 483 BackendArgs.push_back("-limit-float-precision"); 484 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 485 } 486 for (const std::string &BackendOption : CodeGenOpts.BackendOptions) 487 BackendArgs.push_back(BackendOption.c_str()); 488 BackendArgs.push_back(nullptr); 489 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 490 BackendArgs.data()); 491 } 492 493 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 494 // Create the TargetMachine for generating code. 495 std::string Error; 496 std::string Triple = TheModule->getTargetTriple(); 497 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 498 if (!TheTarget) { 499 if (MustCreateTM) 500 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 501 return; 502 } 503 504 unsigned CodeModel = 505 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 506 .Case("small", llvm::CodeModel::Small) 507 .Case("kernel", llvm::CodeModel::Kernel) 508 .Case("medium", llvm::CodeModel::Medium) 509 .Case("large", llvm::CodeModel::Large) 510 .Case("default", llvm::CodeModel::Default) 511 .Default(~0u); 512 assert(CodeModel != ~0u && "invalid code model!"); 513 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 514 515 std::string FeaturesStr = 516 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 517 518 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp. 519 llvm::Optional<llvm::Reloc::Model> RM; 520 if (CodeGenOpts.RelocationModel == "static") { 521 RM = llvm::Reloc::Static; 522 } else if (CodeGenOpts.RelocationModel == "pic") { 523 RM = llvm::Reloc::PIC_; 524 } else { 525 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 526 "Invalid PIC model!"); 527 RM = llvm::Reloc::DynamicNoPIC; 528 } 529 530 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 531 switch (CodeGenOpts.OptimizationLevel) { 532 default: break; 533 case 0: OptLevel = CodeGenOpt::None; break; 534 case 3: OptLevel = CodeGenOpt::Aggressive; break; 535 } 536 537 llvm::TargetOptions Options; 538 539 if (!TargetOpts.Reciprocals.empty()) 540 Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals); 541 542 Options.ThreadModel = 543 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 544 .Case("posix", llvm::ThreadModel::POSIX) 545 .Case("single", llvm::ThreadModel::Single); 546 547 // Set float ABI type. 548 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 549 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 550 "Invalid Floating Point ABI!"); 551 Options.FloatABIType = 552 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 553 .Case("soft", llvm::FloatABI::Soft) 554 .Case("softfp", llvm::FloatABI::Soft) 555 .Case("hard", llvm::FloatABI::Hard) 556 .Default(llvm::FloatABI::Default); 557 558 // Set FP fusion mode. 559 switch (CodeGenOpts.getFPContractMode()) { 560 case CodeGenOptions::FPC_Off: 561 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 562 break; 563 case CodeGenOptions::FPC_On: 564 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 565 break; 566 case CodeGenOptions::FPC_Fast: 567 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 568 break; 569 } 570 571 Options.UseInitArray = CodeGenOpts.UseInitArray; 572 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 573 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections; 574 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 575 576 // Set EABI version. 577 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion) 578 .Case("4", llvm::EABI::EABI4) 579 .Case("5", llvm::EABI::EABI5) 580 .Case("gnu", llvm::EABI::GNU) 581 .Default(llvm::EABI::Default); 582 583 if (LangOpts.SjLjExceptions) 584 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 585 586 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 587 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 588 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 589 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 590 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 591 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 592 Options.FunctionSections = CodeGenOpts.FunctionSections; 593 Options.DataSections = CodeGenOpts.DataSections; 594 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 595 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 596 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 597 598 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 599 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 600 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 601 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 602 Options.MCOptions.MCIncrementalLinkerCompatible = 603 CodeGenOpts.IncrementalLinkerCompatible; 604 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 605 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 606 Options.MCOptions.ABIName = TargetOpts.ABI; 607 608 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 609 Options, RM, CM, OptLevel)); 610 } 611 612 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 613 BackendAction Action, 614 raw_pwrite_stream &OS) { 615 // Add LibraryInfo. 616 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 617 std::unique_ptr<TargetLibraryInfoImpl> TLII( 618 createTLII(TargetTriple, CodeGenOpts)); 619 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 620 621 // Normal mode, emit a .s or .o file by running the code generator. Note, 622 // this also adds codegenerator level optimization passes. 623 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 624 if (Action == Backend_EmitObj) 625 CGFT = TargetMachine::CGFT_ObjectFile; 626 else if (Action == Backend_EmitMCNull) 627 CGFT = TargetMachine::CGFT_Null; 628 else 629 assert(Action == Backend_EmitAssembly && "Invalid action!"); 630 631 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 632 // "codegen" passes so that it isn't run multiple times when there is 633 // inlining happening. 634 if (CodeGenOpts.OptimizationLevel > 0) 635 CodeGenPasses.add(createObjCARCContractPass()); 636 637 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT, 638 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 639 Diags.Report(diag::err_fe_unable_to_interface_with_target); 640 return false; 641 } 642 643 return true; 644 } 645 646 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 647 std::unique_ptr<raw_pwrite_stream> OS) { 648 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 649 650 setCommandLineOpts(); 651 652 bool UsesCodeGen = (Action != Backend_EmitNothing && 653 Action != Backend_EmitBC && 654 Action != Backend_EmitLL); 655 CreateTargetMachine(UsesCodeGen); 656 657 if (UsesCodeGen && !TM) 658 return; 659 if (TM) 660 TheModule->setDataLayout(TM->createDataLayout()); 661 662 // If we are performing a ThinLTO importing compile, load the function 663 // index into memory and pass it into CreatePasses, which will add it 664 // to the PassManagerBuilder and invoke LTO passes. 665 std::unique_ptr<ModuleSummaryIndex> ModuleSummary; 666 if (!CodeGenOpts.ThinLTOIndexFile.empty()) { 667 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 668 llvm::getModuleSummaryIndexForFile( 669 CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) { 670 TheModule->getContext().diagnose(DI); 671 }); 672 if (std::error_code EC = IndexOrErr.getError()) { 673 std::string Error = EC.message(); 674 errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile 675 << "': " << Error << "\n"; 676 return; 677 } 678 ModuleSummary = std::move(IndexOrErr.get()); 679 assert(ModuleSummary && "Expected non-empty module summary index"); 680 } 681 682 legacy::PassManager PerModulePasses; 683 PerModulePasses.add( 684 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 685 686 legacy::FunctionPassManager PerFunctionPasses(TheModule); 687 PerFunctionPasses.add( 688 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 689 690 CreatePasses(PerModulePasses, PerFunctionPasses, ModuleSummary.get()); 691 692 legacy::PassManager CodeGenPasses; 693 CodeGenPasses.add( 694 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 695 696 switch (Action) { 697 case Backend_EmitNothing: 698 break; 699 700 case Backend_EmitBC: 701 PerModulePasses.add(createBitcodeWriterPass( 702 *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex, 703 CodeGenOpts.EmitSummaryIndex)); 704 break; 705 706 case Backend_EmitLL: 707 PerModulePasses.add( 708 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 709 break; 710 711 default: 712 if (!AddEmitPasses(CodeGenPasses, Action, *OS)) 713 return; 714 } 715 716 // Before executing passes, print the final values of the LLVM options. 717 cl::PrintOptionValues(); 718 719 // Run passes. For now we do all passes at once, but eventually we 720 // would like to have the option of streaming code generation. 721 722 { 723 PrettyStackTraceString CrashInfo("Per-function optimization"); 724 725 PerFunctionPasses.doInitialization(); 726 for (Function &F : *TheModule) 727 if (!F.isDeclaration()) 728 PerFunctionPasses.run(F); 729 PerFunctionPasses.doFinalization(); 730 } 731 732 { 733 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 734 PerModulePasses.run(*TheModule); 735 } 736 737 { 738 PrettyStackTraceString CrashInfo("Code generation"); 739 CodeGenPasses.run(*TheModule); 740 } 741 } 742 743 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 744 const CodeGenOptions &CGOpts, 745 const clang::TargetOptions &TOpts, 746 const LangOptions &LOpts, const llvm::DataLayout &TDesc, 747 Module *M, BackendAction Action, 748 std::unique_ptr<raw_pwrite_stream> OS) { 749 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M); 750 751 AsmHelper.EmitAssembly(Action, std::move(OS)); 752 753 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 754 // DataLayout. 755 if (AsmHelper.TM) { 756 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 757 if (DLDesc != TDesc.getStringRepresentation()) { 758 unsigned DiagID = Diags.getCustomDiagID( 759 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 760 "expected target description '%1'"); 761 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 762 } 763 } 764 } 765 766 static const char* getSectionNameForBitcode(const Triple &T) { 767 switch (T.getObjectFormat()) { 768 case Triple::MachO: 769 return "__LLVM,__bitcode"; 770 case Triple::COFF: 771 case Triple::ELF: 772 case Triple::UnknownObjectFormat: 773 return ".llvmbc"; 774 } 775 llvm_unreachable("Unimplemented ObjectFormatType"); 776 } 777 778 static const char* getSectionNameForCommandline(const Triple &T) { 779 switch (T.getObjectFormat()) { 780 case Triple::MachO: 781 return "__LLVM,__cmdline"; 782 case Triple::COFF: 783 case Triple::ELF: 784 case Triple::UnknownObjectFormat: 785 return ".llvmcmd"; 786 } 787 llvm_unreachable("Unimplemented ObjectFormatType"); 788 } 789 790 // With -fembed-bitcode, save a copy of the llvm IR as data in the 791 // __LLVM,__bitcode section. 792 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 793 llvm::MemoryBufferRef Buf) { 794 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 795 return; 796 797 // Save llvm.compiler.used and remote it. 798 SmallVector<Constant*, 2> UsedArray; 799 SmallSet<GlobalValue*, 4> UsedGlobals; 800 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0); 801 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true); 802 for (auto *GV : UsedGlobals) { 803 if (GV->getName() != "llvm.embedded.module" && 804 GV->getName() != "llvm.cmdline") 805 UsedArray.push_back( 806 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 807 } 808 if (Used) 809 Used->eraseFromParent(); 810 811 // Embed the bitcode for the llvm module. 812 std::string Data; 813 ArrayRef<uint8_t> ModuleData; 814 Triple T(M->getTargetTriple()); 815 // Create a constant that contains the bitcode. 816 // In case of embedding a marker, ignore the input Buf and use the empty 817 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 818 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) { 819 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 820 (const unsigned char *)Buf.getBufferEnd())) { 821 // If the input is LLVM Assembly, bitcode is produced by serializing 822 // the module. Use-lists order need to be perserved in this case. 823 llvm::raw_string_ostream OS(Data); 824 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 825 ModuleData = 826 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 827 } else 828 // If the input is LLVM bitcode, write the input byte stream directly. 829 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 830 Buf.getBufferSize()); 831 } 832 llvm::Constant *ModuleConstant = 833 llvm::ConstantDataArray::get(M->getContext(), ModuleData); 834 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 835 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 836 ModuleConstant); 837 GV->setSection(getSectionNameForBitcode(T)); 838 UsedArray.push_back( 839 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 840 if (llvm::GlobalVariable *Old = 841 M->getGlobalVariable("llvm.embedded.module", true)) { 842 assert(Old->hasOneUse() && 843 "llvm.embedded.module can only be used once in llvm.compiler.used"); 844 GV->takeName(Old); 845 Old->eraseFromParent(); 846 } else { 847 GV->setName("llvm.embedded.module"); 848 } 849 850 // Skip if only bitcode needs to be embedded. 851 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) { 852 // Embed command-line options. 853 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()), 854 CGOpts.CmdArgs.size()); 855 llvm::Constant *CmdConstant = 856 llvm::ConstantDataArray::get(M->getContext(), CmdData); 857 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, 858 llvm::GlobalValue::PrivateLinkage, 859 CmdConstant); 860 GV->setSection(getSectionNameForCommandline(T)); 861 UsedArray.push_back( 862 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 863 if (llvm::GlobalVariable *Old = 864 M->getGlobalVariable("llvm.cmdline", true)) { 865 assert(Old->hasOneUse() && 866 "llvm.cmdline can only be used once in llvm.compiler.used"); 867 GV->takeName(Old); 868 Old->eraseFromParent(); 869 } else { 870 GV->setName("llvm.cmdline"); 871 } 872 } 873 874 if (UsedArray.empty()) 875 return; 876 877 // Recreate llvm.compiler.used. 878 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 879 auto *NewUsed = new GlobalVariable( 880 *M, ATy, false, llvm::GlobalValue::AppendingLinkage, 881 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 882 NewUsed->setSection("llvm.metadata"); 883 } 884