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