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