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