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/Bitcode/BitcodeWriterPass.h" 18 #include "llvm/CodeGen/RegAllocRegistry.h" 19 #include "llvm/CodeGen/SchedulerRegistry.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/IRPrintingPasses.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/IR/Verifier.h" 24 #include "llvm/MC/SubtargetFeature.h" 25 #include "llvm/PassManager.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/FormattedStream.h" 28 #include "llvm/Support/PrettyStackTrace.h" 29 #include "llvm/Support/TargetRegistry.h" 30 #include "llvm/Support/Timer.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Target/TargetLibraryInfo.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Target/TargetOptions.h" 35 #include "llvm/Transforms/IPO.h" 36 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 37 #include "llvm/Transforms/Instrumentation.h" 38 #include "llvm/Transforms/ObjCARC.h" 39 #include "llvm/Transforms/Scalar.h" 40 #include <memory> 41 using namespace clang; 42 using namespace llvm; 43 44 namespace { 45 46 class EmitAssemblyHelper { 47 DiagnosticsEngine &Diags; 48 const CodeGenOptions &CodeGenOpts; 49 const clang::TargetOptions &TargetOpts; 50 const LangOptions &LangOpts; 51 Module *TheModule; 52 53 Timer CodeGenerationTime; 54 55 mutable PassManager *CodeGenPasses; 56 mutable PassManager *PerModulePasses; 57 mutable FunctionPassManager *PerFunctionPasses; 58 59 private: 60 PassManager *getCodeGenPasses() const { 61 if (!CodeGenPasses) { 62 CodeGenPasses = new PassManager(); 63 CodeGenPasses->add(new DataLayoutPass(TheModule)); 64 if (TM) 65 TM->addAnalysisPasses(*CodeGenPasses); 66 } 67 return CodeGenPasses; 68 } 69 70 PassManager *getPerModulePasses() const { 71 if (!PerModulePasses) { 72 PerModulePasses = new PassManager(); 73 PerModulePasses->add(new DataLayoutPass(TheModule)); 74 if (TM) 75 TM->addAnalysisPasses(*PerModulePasses); 76 } 77 return PerModulePasses; 78 } 79 80 FunctionPassManager *getPerFunctionPasses() const { 81 if (!PerFunctionPasses) { 82 PerFunctionPasses = new FunctionPassManager(TheModule); 83 PerFunctionPasses->add(new DataLayoutPass(TheModule)); 84 if (TM) 85 TM->addAnalysisPasses(*PerFunctionPasses); 86 } 87 return PerFunctionPasses; 88 } 89 90 void CreatePasses(); 91 92 /// CreateTargetMachine - Generates the TargetMachine. 93 /// Returns Null if it is unable to create the target machine. 94 /// Some of our clang tests specify triples which are not built 95 /// into clang. This is okay because these tests check the generated 96 /// IR, and they require DataLayout which depends on the triple. 97 /// In this case, we allow this method to fail and not report an error. 98 /// When MustCreateTM is used, we print an error if we are unable to load 99 /// the requested target. 100 TargetMachine *CreateTargetMachine(bool MustCreateTM); 101 102 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR. 103 /// 104 /// \return True on success. 105 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS); 106 107 public: 108 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 109 const CodeGenOptions &CGOpts, 110 const clang::TargetOptions &TOpts, 111 const LangOptions &LOpts, 112 Module *M) 113 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), 114 TheModule(M), CodeGenerationTime("Code Generation Time"), 115 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {} 116 117 ~EmitAssemblyHelper() { 118 delete CodeGenPasses; 119 delete PerModulePasses; 120 delete PerFunctionPasses; 121 if (CodeGenOpts.DisableFree) 122 BuryPointer(TM.release()); 123 } 124 125 std::unique_ptr<TargetMachine> TM; 126 127 void EmitAssembly(BackendAction Action, raw_ostream *OS); 128 }; 129 130 // We need this wrapper to access LangOpts and CGOpts from extension functions 131 // that we add to the PassManagerBuilder. 132 class PassManagerBuilderWrapper : public PassManagerBuilder { 133 public: 134 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 135 const LangOptions &LangOpts) 136 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 137 const CodeGenOptions &getCGOpts() const { return CGOpts; } 138 const LangOptions &getLangOpts() const { return LangOpts; } 139 private: 140 const CodeGenOptions &CGOpts; 141 const LangOptions &LangOpts; 142 }; 143 144 } 145 146 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 147 if (Builder.OptLevel > 0) 148 PM.add(createObjCARCAPElimPass()); 149 } 150 151 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 152 if (Builder.OptLevel > 0) 153 PM.add(createObjCARCExpandPass()); 154 } 155 156 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 157 if (Builder.OptLevel > 0) 158 PM.add(createObjCARCOptPass()); 159 } 160 161 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder, 162 PassManagerBase &PM) { 163 const PassManagerBuilderWrapper &BuilderWrapper = 164 static_cast<const PassManagerBuilderWrapper &>(Builder); 165 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 166 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile)); 167 } 168 169 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 170 PassManagerBase &PM) { 171 PM.add(createAddDiscriminatorsPass()); 172 } 173 174 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 175 PassManagerBase &PM) { 176 PM.add(createBoundsCheckingPass()); 177 } 178 179 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 180 PassManagerBase &PM) { 181 const PassManagerBuilderWrapper &BuilderWrapper = 182 static_cast<const PassManagerBuilderWrapper&>(Builder); 183 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 184 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 185 PM.add(createAddressSanitizerFunctionPass( 186 LangOpts.Sanitize.InitOrder, 187 LangOpts.Sanitize.UseAfterReturn, 188 LangOpts.Sanitize.UseAfterScope, 189 CGOpts.SanitizerBlacklistFile)); 190 PM.add(createAddressSanitizerModulePass( 191 LangOpts.Sanitize.InitOrder, 192 CGOpts.SanitizerBlacklistFile)); 193 } 194 195 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 196 PassManagerBase &PM) { 197 const PassManagerBuilderWrapper &BuilderWrapper = 198 static_cast<const PassManagerBuilderWrapper&>(Builder); 199 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 200 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins, 201 CGOpts.SanitizerBlacklistFile)); 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 const PassManagerBuilderWrapper &BuilderWrapper = 219 static_cast<const PassManagerBuilderWrapper&>(Builder); 220 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 221 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile)); 222 } 223 224 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 225 PassManagerBase &PM) { 226 const PassManagerBuilderWrapper &BuilderWrapper = 227 static_cast<const PassManagerBuilderWrapper&>(Builder); 228 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 229 PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile)); 230 } 231 232 void EmitAssemblyHelper::CreatePasses() { 233 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 234 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 235 236 // Handle disabling of LLVM optimization, where we want to preserve the 237 // internal module before any optimization. 238 if (CodeGenOpts.DisableLLVMOpts) { 239 OptLevel = 0; 240 Inlining = CodeGenOpts.NoInlining; 241 } 242 243 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 244 PMBuilder.OptLevel = OptLevel; 245 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 246 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 247 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 248 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 249 250 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime; 251 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 252 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 253 254 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 255 addAddDiscriminatorsPass); 256 257 if (!CodeGenOpts.SampleProfileFile.empty()) 258 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 259 addSampleProfileLoaderPass); 260 261 // In ObjC ARC mode, add the main ARC optimization passes. 262 if (LangOpts.ObjCAutoRefCount) { 263 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 264 addObjCARCExpandPass); 265 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 266 addObjCARCAPElimPass); 267 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 268 addObjCARCOptPass); 269 } 270 271 if (LangOpts.Sanitize.LocalBounds) { 272 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 273 addBoundsCheckingPass); 274 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 275 addBoundsCheckingPass); 276 } 277 278 if (LangOpts.Sanitize.Address) { 279 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 280 addAddressSanitizerPasses); 281 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 282 addAddressSanitizerPasses); 283 } 284 285 if (LangOpts.Sanitize.Memory) { 286 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 287 addMemorySanitizerPass); 288 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 289 addMemorySanitizerPass); 290 } 291 292 if (LangOpts.Sanitize.Thread) { 293 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 294 addThreadSanitizerPass); 295 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 296 addThreadSanitizerPass); 297 } 298 299 if (LangOpts.Sanitize.DataFlow) { 300 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 301 addDataFlowSanitizerPass); 302 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 303 addDataFlowSanitizerPass); 304 } 305 306 // Figure out TargetLibraryInfo. 307 Triple TargetTriple(TheModule->getTargetTriple()); 308 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple); 309 if (!CodeGenOpts.SimplifyLibCalls) 310 PMBuilder.LibraryInfo->disableAllFunctions(); 311 312 switch (Inlining) { 313 case CodeGenOptions::NoInlining: break; 314 case CodeGenOptions::NormalInlining: { 315 PMBuilder.Inliner = 316 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize); 317 break; 318 } 319 case CodeGenOptions::OnlyAlwaysInlining: 320 // Respect always_inline. 321 if (OptLevel == 0) 322 // Do not insert lifetime intrinsics at -O0. 323 PMBuilder.Inliner = createAlwaysInlinerPass(false); 324 else 325 PMBuilder.Inliner = createAlwaysInlinerPass(); 326 break; 327 } 328 329 // Set up the per-function pass manager. 330 FunctionPassManager *FPM = getPerFunctionPasses(); 331 if (CodeGenOpts.VerifyModule) 332 FPM->add(createVerifierPass()); 333 PMBuilder.populateFunctionPassManager(*FPM); 334 335 // Set up the per-module pass manager. 336 PassManager *MPM = getPerModulePasses(); 337 338 if (!CodeGenOpts.DisableGCov && 339 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 340 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 341 // LLVM's -default-gcov-version flag is set to something invalid. 342 GCOVOptions Options; 343 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 344 Options.EmitData = CodeGenOpts.EmitGcovArcs; 345 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 346 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 347 Options.NoRedZone = CodeGenOpts.DisableRedZone; 348 Options.FunctionNamesInData = 349 !CodeGenOpts.CoverageNoFunctionNamesInData; 350 MPM->add(createGCOVProfilerPass(Options)); 351 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo) 352 MPM->add(createStripSymbolsPass(true)); 353 } 354 355 PMBuilder.populateModulePassManager(*MPM); 356 } 357 358 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 359 // Create the TargetMachine for generating code. 360 std::string Error; 361 std::string Triple = TheModule->getTargetTriple(); 362 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 363 if (!TheTarget) { 364 if (MustCreateTM) 365 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 366 return 0; 367 } 368 369 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just 370 // being gross, this is also totally broken if we ever care about 371 // concurrency. 372 373 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose); 374 375 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections); 376 TargetMachine::setDataSections (CodeGenOpts.DataSections); 377 378 // FIXME: Parse this earlier. 379 llvm::CodeModel::Model CM; 380 if (CodeGenOpts.CodeModel == "small") { 381 CM = llvm::CodeModel::Small; 382 } else if (CodeGenOpts.CodeModel == "kernel") { 383 CM = llvm::CodeModel::Kernel; 384 } else if (CodeGenOpts.CodeModel == "medium") { 385 CM = llvm::CodeModel::Medium; 386 } else if (CodeGenOpts.CodeModel == "large") { 387 CM = llvm::CodeModel::Large; 388 } else { 389 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!"); 390 CM = llvm::CodeModel::Default; 391 } 392 393 SmallVector<const char *, 16> BackendArgs; 394 BackendArgs.push_back("clang"); // Fake program name. 395 if (!CodeGenOpts.DebugPass.empty()) { 396 BackendArgs.push_back("-debug-pass"); 397 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 398 } 399 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 400 BackendArgs.push_back("-limit-float-precision"); 401 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 402 } 403 if (llvm::TimePassesIsEnabled) 404 BackendArgs.push_back("-time-passes"); 405 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i) 406 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str()); 407 if (CodeGenOpts.NoGlobalMerge) 408 BackendArgs.push_back("-global-merge=false"); 409 BackendArgs.push_back(0); 410 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 411 BackendArgs.data()); 412 413 std::string FeaturesStr; 414 if (TargetOpts.Features.size()) { 415 SubtargetFeatures Features; 416 for (std::vector<std::string>::const_iterator 417 it = TargetOpts.Features.begin(), 418 ie = TargetOpts.Features.end(); it != ie; ++it) 419 Features.AddFeature(*it); 420 FeaturesStr = Features.getString(); 421 } 422 423 llvm::Reloc::Model RM = llvm::Reloc::Default; 424 if (CodeGenOpts.RelocationModel == "static") { 425 RM = llvm::Reloc::Static; 426 } else if (CodeGenOpts.RelocationModel == "pic") { 427 RM = llvm::Reloc::PIC_; 428 } else { 429 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 430 "Invalid PIC model!"); 431 RM = llvm::Reloc::DynamicNoPIC; 432 } 433 434 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 435 switch (CodeGenOpts.OptimizationLevel) { 436 default: break; 437 case 0: OptLevel = CodeGenOpt::None; break; 438 case 3: OptLevel = CodeGenOpt::Aggressive; break; 439 } 440 441 llvm::TargetOptions Options; 442 443 if (CodeGenOpts.DisableIntegratedAS) 444 Options.DisableIntegratedAS = true; 445 446 if (CodeGenOpts.CompressDebugSections) 447 Options.CompressDebugSections = true; 448 449 // Set frame pointer elimination mode. 450 if (!CodeGenOpts.DisableFPElim) { 451 Options.NoFramePointerElim = false; 452 } else if (CodeGenOpts.OmitLeafFramePointer) { 453 Options.NoFramePointerElim = false; 454 } else { 455 Options.NoFramePointerElim = true; 456 } 457 458 if (CodeGenOpts.UseInitArray) 459 Options.UseInitArray = true; 460 461 // Set float ABI type. 462 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp") 463 Options.FloatABIType = llvm::FloatABI::Soft; 464 else if (CodeGenOpts.FloatABI == "hard") 465 Options.FloatABIType = llvm::FloatABI::Hard; 466 else { 467 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!"); 468 Options.FloatABIType = llvm::FloatABI::Default; 469 } 470 471 // Set FP fusion mode. 472 switch (CodeGenOpts.getFPContractMode()) { 473 case CodeGenOptions::FPC_Off: 474 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 475 break; 476 case CodeGenOptions::FPC_On: 477 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 478 break; 479 case CodeGenOptions::FPC_Fast: 480 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 481 break; 482 } 483 484 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 485 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 486 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 487 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 488 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 489 Options.UseSoftFloat = CodeGenOpts.SoftFloat; 490 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 491 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls; 492 Options.TrapFuncName = CodeGenOpts.TrapFuncName; 493 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0; 494 Options.EnableSegmentedStacks = CodeGenOpts.EnableSegmentedStacks; 495 496 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU, 497 FeaturesStr, Options, 498 RM, CM, OptLevel); 499 500 if (CodeGenOpts.RelaxAll) 501 TM->setMCRelaxAll(true); 502 if (CodeGenOpts.SaveTempLabels) 503 TM->setMCSaveTempLabels(true); 504 if (CodeGenOpts.NoDwarf2CFIAsm) 505 TM->setMCUseCFI(false); 506 if (!CodeGenOpts.NoDwarfDirectoryAsm) 507 TM->setMCUseDwarfDirectory(true); 508 if (CodeGenOpts.NoExecStack) 509 TM->setMCNoExecStack(true); 510 511 return TM; 512 } 513 514 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action, 515 formatted_raw_ostream &OS) { 516 517 // Create the code generator passes. 518 PassManager *PM = getCodeGenPasses(); 519 520 // Add LibraryInfo. 521 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 522 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple); 523 if (!CodeGenOpts.SimplifyLibCalls) 524 TLI->disableAllFunctions(); 525 PM->add(TLI); 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 : 0); 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 = 630 AsmHelper.TM->getDataLayout()->getStringRepresentation(); 631 if (DLDesc != TDesc) { 632 unsigned DiagID = Diags.getCustomDiagID( 633 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 634 "expected target description '%1'"); 635 Diags.Report(DiagID) << DLDesc << TDesc; 636 } 637 } 638 } 639