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