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