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/StringSwitch.h" 18 #include "llvm/Analysis/TargetLibraryInfo.h" 19 #include "llvm/Analysis/TargetTransformInfo.h" 20 #include "llvm/Bitcode/BitcodeWriterPass.h" 21 #include "llvm/CodeGen/RegAllocRegistry.h" 22 #include "llvm/CodeGen/SchedulerRegistry.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/IRPrintingPasses.h" 25 #include "llvm/IR/LegacyPassManager.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/IR/Verifier.h" 28 #include "llvm/MC/SubtargetFeature.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/PrettyStackTrace.h" 31 #include "llvm/Support/TargetRegistry.h" 32 #include "llvm/Support/Timer.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Target/TargetMachine.h" 35 #include "llvm/Target/TargetOptions.h" 36 #include "llvm/Target/TargetSubtargetInfo.h" 37 #include "llvm/Transforms/IPO.h" 38 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 39 #include "llvm/Transforms/Instrumentation.h" 40 #include "llvm/Transforms/ObjCARC.h" 41 #include "llvm/Transforms/Scalar.h" 42 #include "llvm/Transforms/Utils/SymbolRewriter.h" 43 #include <memory> 44 using namespace clang; 45 using namespace llvm; 46 47 namespace { 48 49 class EmitAssemblyHelper { 50 DiagnosticsEngine &Diags; 51 const CodeGenOptions &CodeGenOpts; 52 const clang::TargetOptions &TargetOpts; 53 const LangOptions &LangOpts; 54 Module *TheModule; 55 56 Timer CodeGenerationTime; 57 58 mutable legacy::PassManager *CodeGenPasses; 59 mutable legacy::PassManager *PerModulePasses; 60 mutable legacy::FunctionPassManager *PerFunctionPasses; 61 62 private: 63 TargetIRAnalysis getTargetIRAnalysis() const { 64 if (TM) 65 return TM->getTargetIRAnalysis(); 66 67 return TargetIRAnalysis(); 68 } 69 70 legacy::PassManager *getCodeGenPasses() const { 71 if (!CodeGenPasses) { 72 CodeGenPasses = new legacy::PassManager(); 73 CodeGenPasses->add( 74 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 75 } 76 return CodeGenPasses; 77 } 78 79 legacy::PassManager *getPerModulePasses() const { 80 if (!PerModulePasses) { 81 PerModulePasses = new legacy::PassManager(); 82 PerModulePasses->add( 83 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 84 } 85 return PerModulePasses; 86 } 87 88 legacy::FunctionPassManager *getPerFunctionPasses() const { 89 if (!PerFunctionPasses) { 90 PerFunctionPasses = new legacy::FunctionPassManager(TheModule); 91 PerFunctionPasses->add( 92 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 93 } 94 return PerFunctionPasses; 95 } 96 97 void CreatePasses(); 98 99 /// Generates the TargetMachine. 100 /// Returns Null if it is unable to create the target machine. 101 /// Some of our clang tests specify triples which are not built 102 /// into clang. This is okay because these tests check the generated 103 /// IR, and they require DataLayout which depends on the triple. 104 /// In this case, we allow this method to fail and not report an error. 105 /// When MustCreateTM is used, we print an error if we are unable to load 106 /// the requested target. 107 TargetMachine *CreateTargetMachine(bool MustCreateTM); 108 109 /// Add passes necessary to emit assembly or LLVM IR. 110 /// 111 /// \return True on success. 112 bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS); 113 114 public: 115 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 116 const CodeGenOptions &CGOpts, 117 const clang::TargetOptions &TOpts, 118 const LangOptions &LOpts, 119 Module *M) 120 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), 121 TheModule(M), CodeGenerationTime("Code Generation Time"), 122 CodeGenPasses(nullptr), PerModulePasses(nullptr), 123 PerFunctionPasses(nullptr) {} 124 125 ~EmitAssemblyHelper() { 126 delete CodeGenPasses; 127 delete PerModulePasses; 128 delete PerFunctionPasses; 129 if (CodeGenOpts.DisableFree) 130 BuryPointer(std::move(TM)); 131 } 132 133 std::unique_ptr<TargetMachine> TM; 134 135 void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS); 136 }; 137 138 // We need this wrapper to access LangOpts and CGOpts from extension functions 139 // that we add to the PassManagerBuilder. 140 class PassManagerBuilderWrapper : public PassManagerBuilder { 141 public: 142 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 143 const LangOptions &LangOpts) 144 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 145 const CodeGenOptions &getCGOpts() const { return CGOpts; } 146 const LangOptions &getLangOpts() const { return LangOpts; } 147 private: 148 const CodeGenOptions &CGOpts; 149 const LangOptions &LangOpts; 150 }; 151 152 } 153 154 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 155 if (Builder.OptLevel > 0) 156 PM.add(createObjCARCAPElimPass()); 157 } 158 159 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 160 if (Builder.OptLevel > 0) 161 PM.add(createObjCARCExpandPass()); 162 } 163 164 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 165 if (Builder.OptLevel > 0) 166 PM.add(createObjCARCOptPass()); 167 } 168 169 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder, 170 legacy::PassManagerBase &PM) { 171 const PassManagerBuilderWrapper &BuilderWrapper = 172 static_cast<const PassManagerBuilderWrapper &>(Builder); 173 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 174 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile)); 175 } 176 177 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 178 legacy::PassManagerBase &PM) { 179 PM.add(createAddDiscriminatorsPass()); 180 } 181 182 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 183 legacy::PassManagerBase &PM) { 184 PM.add(createBoundsCheckingPass()); 185 } 186 187 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 188 legacy::PassManagerBase &PM) { 189 const PassManagerBuilderWrapper &BuilderWrapper = 190 static_cast<const PassManagerBuilderWrapper&>(Builder); 191 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 192 SanitizerCoverageOptions Opts; 193 Opts.CoverageType = 194 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 195 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 196 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 197 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 198 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 199 PM.add(createSanitizerCoverageModulePass(Opts)); 200 } 201 202 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 203 legacy::PassManagerBase &PM) { 204 PM.add(createAddressSanitizerFunctionPass()); 205 PM.add(createAddressSanitizerModulePass()); 206 } 207 208 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 209 legacy::PassManagerBase &PM) { 210 const PassManagerBuilderWrapper &BuilderWrapper = 211 static_cast<const PassManagerBuilderWrapper&>(Builder); 212 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 213 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins)); 214 215 // MemorySanitizer inserts complex instrumentation that mostly follows 216 // the logic of the original code, but operates on "shadow" values. 217 // It can benefit from re-running some general purpose optimization passes. 218 if (Builder.OptLevel > 0) { 219 PM.add(createEarlyCSEPass()); 220 PM.add(createReassociatePass()); 221 PM.add(createLICMPass()); 222 PM.add(createGVNPass()); 223 PM.add(createInstructionCombiningPass()); 224 PM.add(createDeadStoreEliminationPass()); 225 } 226 } 227 228 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 229 legacy::PassManagerBase &PM) { 230 PM.add(createThreadSanitizerPass()); 231 } 232 233 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 234 legacy::PassManagerBase &PM) { 235 const PassManagerBuilderWrapper &BuilderWrapper = 236 static_cast<const PassManagerBuilderWrapper&>(Builder); 237 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 238 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 239 } 240 241 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 242 const CodeGenOptions &CodeGenOpts) { 243 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 244 if (!CodeGenOpts.SimplifyLibCalls) 245 TLII->disableAllFunctions(); 246 247 switch (CodeGenOpts.getVecLib()) { 248 case CodeGenOptions::Accelerate: 249 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 250 break; 251 default: 252 break; 253 } 254 return TLII; 255 } 256 257 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 258 legacy::PassManager *MPM) { 259 llvm::SymbolRewriter::RewriteDescriptorList DL; 260 261 llvm::SymbolRewriter::RewriteMapParser MapParser; 262 for (const auto &MapFile : Opts.RewriteMapFiles) 263 MapParser.parse(MapFile, &DL); 264 265 MPM->add(createRewriteSymbolsPass(DL)); 266 } 267 268 void EmitAssemblyHelper::CreatePasses() { 269 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 270 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 271 272 // Handle disabling of LLVM optimization, where we want to preserve the 273 // internal module before any optimization. 274 if (CodeGenOpts.DisableLLVMOpts) { 275 OptLevel = 0; 276 Inlining = CodeGenOpts.NoInlining; 277 } 278 279 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 280 PMBuilder.OptLevel = OptLevel; 281 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 282 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 283 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 284 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 285 286 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime; 287 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 288 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 289 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 290 291 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 292 addAddDiscriminatorsPass); 293 294 if (!CodeGenOpts.SampleProfileFile.empty()) 295 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 296 addSampleProfileLoaderPass); 297 298 // In ObjC ARC mode, add the main ARC optimization passes. 299 if (LangOpts.ObjCAutoRefCount) { 300 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 301 addObjCARCExpandPass); 302 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 303 addObjCARCAPElimPass); 304 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 305 addObjCARCOptPass); 306 } 307 308 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 309 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 310 addBoundsCheckingPass); 311 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 312 addBoundsCheckingPass); 313 } 314 315 if (CodeGenOpts.SanitizeCoverageType || 316 CodeGenOpts.SanitizeCoverageIndirectCalls || 317 CodeGenOpts.SanitizeCoverageTraceCmp) { 318 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 319 addSanitizerCoveragePass); 320 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 321 addSanitizerCoveragePass); 322 } 323 324 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 325 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 326 addAddressSanitizerPasses); 327 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 328 addAddressSanitizerPasses); 329 } 330 331 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 332 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 333 addMemorySanitizerPass); 334 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 335 addMemorySanitizerPass); 336 } 337 338 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 339 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 340 addThreadSanitizerPass); 341 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 342 addThreadSanitizerPass); 343 } 344 345 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 346 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 347 addDataFlowSanitizerPass); 348 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 349 addDataFlowSanitizerPass); 350 } 351 352 // Figure out TargetLibraryInfo. 353 Triple TargetTriple(TheModule->getTargetTriple()); 354 PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts); 355 356 switch (Inlining) { 357 case CodeGenOptions::NoInlining: break; 358 case CodeGenOptions::NormalInlining: { 359 PMBuilder.Inliner = 360 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize); 361 break; 362 } 363 case CodeGenOptions::OnlyAlwaysInlining: 364 // Respect always_inline. 365 if (OptLevel == 0) 366 // Do not insert lifetime intrinsics at -O0. 367 PMBuilder.Inliner = createAlwaysInlinerPass(false); 368 else 369 PMBuilder.Inliner = createAlwaysInlinerPass(); 370 break; 371 } 372 373 // Set up the per-function pass manager. 374 legacy::FunctionPassManager *FPM = getPerFunctionPasses(); 375 if (CodeGenOpts.VerifyModule) 376 FPM->add(createVerifierPass()); 377 PMBuilder.populateFunctionPassManager(*FPM); 378 379 // Set up the per-module pass manager. 380 legacy::PassManager *MPM = getPerModulePasses(); 381 if (!CodeGenOpts.RewriteMapFiles.empty()) 382 addSymbolRewriterPass(CodeGenOpts, MPM); 383 384 if (!CodeGenOpts.DisableGCov && 385 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 386 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 387 // LLVM's -default-gcov-version flag is set to something invalid. 388 GCOVOptions Options; 389 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 390 Options.EmitData = CodeGenOpts.EmitGcovArcs; 391 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 392 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 393 Options.NoRedZone = CodeGenOpts.DisableRedZone; 394 Options.FunctionNamesInData = 395 !CodeGenOpts.CoverageNoFunctionNamesInData; 396 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 397 MPM->add(createGCOVProfilerPass(Options)); 398 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo) 399 MPM->add(createStripSymbolsPass(true)); 400 } 401 402 if (CodeGenOpts.ProfileInstrGenerate) { 403 InstrProfOptions Options; 404 Options.NoRedZone = CodeGenOpts.DisableRedZone; 405 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 406 MPM->add(createInstrProfilingPass(Options)); 407 } 408 409 PMBuilder.populateModulePassManager(*MPM); 410 } 411 412 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 413 // Create the TargetMachine for generating code. 414 std::string Error; 415 std::string Triple = TheModule->getTargetTriple(); 416 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 417 if (!TheTarget) { 418 if (MustCreateTM) 419 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 420 return nullptr; 421 } 422 423 unsigned CodeModel = 424 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 425 .Case("small", llvm::CodeModel::Small) 426 .Case("kernel", llvm::CodeModel::Kernel) 427 .Case("medium", llvm::CodeModel::Medium) 428 .Case("large", llvm::CodeModel::Large) 429 .Case("default", llvm::CodeModel::Default) 430 .Default(~0u); 431 assert(CodeModel != ~0u && "invalid code model!"); 432 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 433 434 SmallVector<const char *, 16> BackendArgs; 435 BackendArgs.push_back("clang"); // Fake program name. 436 if (!CodeGenOpts.DebugPass.empty()) { 437 BackendArgs.push_back("-debug-pass"); 438 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 439 } 440 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 441 BackendArgs.push_back("-limit-float-precision"); 442 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 443 } 444 if (llvm::TimePassesIsEnabled) 445 BackendArgs.push_back("-time-passes"); 446 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i) 447 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str()); 448 BackendArgs.push_back(nullptr); 449 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 450 BackendArgs.data()); 451 452 std::string FeaturesStr; 453 if (!TargetOpts.Features.empty()) { 454 SubtargetFeatures Features; 455 for (const std::string &Feature : TargetOpts.Features) 456 Features.AddFeature(Feature); 457 FeaturesStr = Features.getString(); 458 } 459 460 llvm::Reloc::Model RM = llvm::Reloc::Default; 461 if (CodeGenOpts.RelocationModel == "static") { 462 RM = llvm::Reloc::Static; 463 } else if (CodeGenOpts.RelocationModel == "pic") { 464 RM = llvm::Reloc::PIC_; 465 } else { 466 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 467 "Invalid PIC model!"); 468 RM = llvm::Reloc::DynamicNoPIC; 469 } 470 471 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 472 switch (CodeGenOpts.OptimizationLevel) { 473 default: break; 474 case 0: OptLevel = CodeGenOpt::None; break; 475 case 3: OptLevel = CodeGenOpt::Aggressive; break; 476 } 477 478 llvm::TargetOptions Options; 479 480 if (!TargetOpts.Reciprocals.empty()) 481 Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals); 482 483 Options.ThreadModel = 484 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 485 .Case("posix", llvm::ThreadModel::POSIX) 486 .Case("single", llvm::ThreadModel::Single); 487 488 if (CodeGenOpts.DisableIntegratedAS) 489 Options.DisableIntegratedAS = true; 490 491 if (CodeGenOpts.CompressDebugSections) 492 Options.CompressDebugSections = true; 493 494 if (CodeGenOpts.UseInitArray) 495 Options.UseInitArray = true; 496 497 // Set float ABI type. 498 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp") 499 Options.FloatABIType = llvm::FloatABI::Soft; 500 else if (CodeGenOpts.FloatABI == "hard") 501 Options.FloatABIType = llvm::FloatABI::Hard; 502 else { 503 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!"); 504 Options.FloatABIType = llvm::FloatABI::Default; 505 } 506 507 // Set FP fusion mode. 508 switch (CodeGenOpts.getFPContractMode()) { 509 case CodeGenOptions::FPC_Off: 510 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 511 break; 512 case CodeGenOptions::FPC_On: 513 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 514 break; 515 case CodeGenOptions::FPC_Fast: 516 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 517 break; 518 } 519 520 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 521 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 522 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 523 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 524 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 525 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 526 Options.TrapFuncName = CodeGenOpts.TrapFuncName; 527 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0; 528 Options.FunctionSections = CodeGenOpts.FunctionSections; 529 Options.DataSections = CodeGenOpts.DataSections; 530 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 531 532 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 533 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 534 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 535 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 536 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 537 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 538 Options.MCOptions.ABIName = TargetOpts.ABI; 539 540 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU, 541 FeaturesStr, Options, 542 RM, CM, OptLevel); 543 544 return TM; 545 } 546 547 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action, 548 raw_pwrite_stream &OS) { 549 550 // Create the code generator passes. 551 legacy::PassManager *PM = getCodeGenPasses(); 552 553 // Add LibraryInfo. 554 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 555 std::unique_ptr<TargetLibraryInfoImpl> TLII( 556 createTLII(TargetTriple, CodeGenOpts)); 557 PM->add(new TargetLibraryInfoWrapperPass(*TLII)); 558 559 // Normal mode, emit a .s or .o file by running the code generator. Note, 560 // this also adds codegenerator level optimization passes. 561 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 562 if (Action == Backend_EmitObj) 563 CGFT = TargetMachine::CGFT_ObjectFile; 564 else if (Action == Backend_EmitMCNull) 565 CGFT = TargetMachine::CGFT_Null; 566 else 567 assert(Action == Backend_EmitAssembly && "Invalid action!"); 568 569 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 570 // "codegen" passes so that it isn't run multiple times when there is 571 // inlining happening. 572 if (CodeGenOpts.OptimizationLevel > 0) 573 PM->add(createObjCARCContractPass()); 574 575 if (TM->addPassesToEmitFile(*PM, OS, CGFT, 576 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 577 Diags.Report(diag::err_fe_unable_to_interface_with_target); 578 return false; 579 } 580 581 return true; 582 } 583 584 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 585 raw_pwrite_stream *OS) { 586 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 587 588 bool UsesCodeGen = (Action != Backend_EmitNothing && 589 Action != Backend_EmitBC && 590 Action != Backend_EmitLL); 591 if (!TM) 592 TM.reset(CreateTargetMachine(UsesCodeGen)); 593 594 if (UsesCodeGen && !TM) return; 595 CreatePasses(); 596 597 switch (Action) { 598 case Backend_EmitNothing: 599 break; 600 601 case Backend_EmitBC: 602 getPerModulePasses()->add( 603 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists)); 604 break; 605 606 case Backend_EmitLL: 607 getPerModulePasses()->add( 608 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 609 break; 610 611 default: 612 if (!AddEmitPasses(Action, *OS)) 613 return; 614 } 615 616 // Before executing passes, print the final values of the LLVM options. 617 cl::PrintOptionValues(); 618 619 // Run passes. For now we do all passes at once, but eventually we 620 // would like to have the option of streaming code generation. 621 622 if (PerFunctionPasses) { 623 PrettyStackTraceString CrashInfo("Per-function optimization"); 624 625 PerFunctionPasses->doInitialization(); 626 for (Function &F : *TheModule) 627 if (!F.isDeclaration()) 628 PerFunctionPasses->run(F); 629 PerFunctionPasses->doFinalization(); 630 } 631 632 if (PerModulePasses) { 633 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 634 PerModulePasses->run(*TheModule); 635 } 636 637 if (CodeGenPasses) { 638 PrettyStackTraceString CrashInfo("Code generation"); 639 CodeGenPasses->run(*TheModule); 640 } 641 } 642 643 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 644 const CodeGenOptions &CGOpts, 645 const clang::TargetOptions &TOpts, 646 const LangOptions &LOpts, StringRef TDesc, 647 Module *M, BackendAction Action, 648 raw_pwrite_stream *OS) { 649 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M); 650 651 AsmHelper.EmitAssembly(Action, OS); 652 653 // If an optional clang TargetInfo description string was passed in, use it to 654 // verify the LLVM TargetMachine's DataLayout. 655 if (AsmHelper.TM && !TDesc.empty()) { 656 std::string DLDesc = 657 AsmHelper.TM->getDataLayout()->getStringRepresentation(); 658 if (DLDesc != TDesc) { 659 unsigned DiagID = Diags.getCustomDiagID( 660 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 661 "expected target description '%1'"); 662 Diags.Report(DiagID) << DLDesc << TDesc; 663 } 664 } 665 } 666