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/FunctionInfo.h" 26 #include "llvm/IR/IRPrintingPasses.h" 27 #include "llvm/IR/LegacyPassManager.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/Verifier.h" 30 #include "llvm/MC/SubtargetFeature.h" 31 #include "llvm/Object/FunctionIndexObjectFile.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/PrettyStackTrace.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/Timer.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include "llvm/Transforms/IPO.h" 41 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 42 #include "llvm/Transforms/Instrumentation.h" 43 #include "llvm/Transforms/ObjCARC.h" 44 #include "llvm/Transforms/Scalar.h" 45 #include "llvm/Transforms/Utils/SymbolRewriter.h" 46 #include <memory> 47 using namespace clang; 48 using namespace llvm; 49 50 namespace { 51 52 class EmitAssemblyHelper { 53 DiagnosticsEngine &Diags; 54 const CodeGenOptions &CodeGenOpts; 55 const clang::TargetOptions &TargetOpts; 56 const LangOptions &LangOpts; 57 Module *TheModule; 58 59 Timer CodeGenerationTime; 60 61 mutable legacy::PassManager *CodeGenPasses; 62 mutable legacy::PassManager *PerModulePasses; 63 mutable legacy::FunctionPassManager *PerFunctionPasses; 64 65 private: 66 TargetIRAnalysis getTargetIRAnalysis() const { 67 if (TM) 68 return TM->getTargetIRAnalysis(); 69 70 return TargetIRAnalysis(); 71 } 72 73 legacy::PassManager *getCodeGenPasses() const { 74 if (!CodeGenPasses) { 75 CodeGenPasses = new legacy::PassManager(); 76 CodeGenPasses->add( 77 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 78 } 79 return CodeGenPasses; 80 } 81 82 legacy::PassManager *getPerModulePasses() const { 83 if (!PerModulePasses) { 84 PerModulePasses = new legacy::PassManager(); 85 PerModulePasses->add( 86 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 87 } 88 return PerModulePasses; 89 } 90 91 legacy::FunctionPassManager *getPerFunctionPasses() const { 92 if (!PerFunctionPasses) { 93 PerFunctionPasses = new legacy::FunctionPassManager(TheModule); 94 PerFunctionPasses->add( 95 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 96 } 97 return PerFunctionPasses; 98 } 99 100 void CreatePasses(FunctionInfoIndex *FunctionIndex); 101 102 /// Generates the TargetMachine. 103 /// Returns Null if it is unable to create the target machine. 104 /// Some of our clang tests specify triples which are not built 105 /// into clang. This is okay because these tests check the generated 106 /// IR, and they require DataLayout which depends on the triple. 107 /// In this case, we allow this method to fail and not report an error. 108 /// When MustCreateTM is used, we print an error if we are unable to load 109 /// the requested target. 110 TargetMachine *CreateTargetMachine(bool MustCreateTM); 111 112 /// Add passes necessary to emit assembly or LLVM IR. 113 /// 114 /// \return True on success. 115 bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS); 116 117 public: 118 EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts, 119 const clang::TargetOptions &TOpts, 120 const LangOptions &LOpts, 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 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 193 PM.add(createSanitizerCoverageModulePass(Opts)); 194 } 195 196 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 197 legacy::PassManagerBase &PM) { 198 const PassManagerBuilderWrapper &BuilderWrapper = 199 static_cast<const PassManagerBuilderWrapper&>(Builder); 200 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 201 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 202 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover)); 203 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover)); 204 } 205 206 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 207 legacy::PassManagerBase &PM) { 208 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true, 209 /*Recover*/true)); 210 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true, 211 /*Recover*/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 else { 253 // Disable individual libc/libm calls in TargetLibraryInfo. 254 LibFunc::Func F; 255 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 256 if (TLII->getLibFunc(FuncName, F)) 257 TLII->setUnavailable(F); 258 } 259 260 switch (CodeGenOpts.getVecLib()) { 261 case CodeGenOptions::Accelerate: 262 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 263 break; 264 default: 265 break; 266 } 267 return TLII; 268 } 269 270 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 271 legacy::PassManager *MPM) { 272 llvm::SymbolRewriter::RewriteDescriptorList DL; 273 274 llvm::SymbolRewriter::RewriteMapParser MapParser; 275 for (const auto &MapFile : Opts.RewriteMapFiles) 276 MapParser.parse(MapFile, &DL); 277 278 MPM->add(createRewriteSymbolsPass(DL)); 279 } 280 281 void EmitAssemblyHelper::CreatePasses(FunctionInfoIndex *FunctionIndex) { 282 if (CodeGenOpts.DisableLLVMPasses) 283 return; 284 285 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 286 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 287 288 // Handle disabling of LLVM optimization, where we want to preserve the 289 // internal module before any optimization. 290 if (CodeGenOpts.DisableLLVMOpts) { 291 OptLevel = 0; 292 Inlining = CodeGenOpts.NoInlining; 293 } 294 295 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 296 297 // Figure out TargetLibraryInfo. 298 Triple TargetTriple(TheModule->getTargetTriple()); 299 PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts); 300 301 switch (Inlining) { 302 case CodeGenOptions::NoInlining: 303 break; 304 case CodeGenOptions::NormalInlining: { 305 PMBuilder.Inliner = 306 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize); 307 break; 308 } 309 case CodeGenOptions::OnlyAlwaysInlining: 310 // Respect always_inline. 311 if (OptLevel == 0) 312 // Do not insert lifetime intrinsics at -O0. 313 PMBuilder.Inliner = createAlwaysInlinerPass(false); 314 else 315 PMBuilder.Inliner = createAlwaysInlinerPass(); 316 break; 317 } 318 319 PMBuilder.OptLevel = OptLevel; 320 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 321 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 322 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 323 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 324 325 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime; 326 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 327 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 328 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitFunctionSummary; 329 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 330 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 331 332 legacy::PassManager *MPM = getPerModulePasses(); 333 334 // If we are performing a ThinLTO importing compile, invoke the LTO 335 // pipeline and pass down the in-memory function index. 336 if (FunctionIndex) { 337 PMBuilder.FunctionIndex = FunctionIndex; 338 PMBuilder.populateThinLTOPassManager(*MPM); 339 return; 340 } 341 342 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 343 addAddDiscriminatorsPass); 344 345 // In ObjC ARC mode, add the main ARC optimization passes. 346 if (LangOpts.ObjCAutoRefCount) { 347 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 348 addObjCARCExpandPass); 349 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 350 addObjCARCAPElimPass); 351 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 352 addObjCARCOptPass); 353 } 354 355 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 356 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 357 addBoundsCheckingPass); 358 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 359 addBoundsCheckingPass); 360 } 361 362 if (CodeGenOpts.SanitizeCoverageType || 363 CodeGenOpts.SanitizeCoverageIndirectCalls || 364 CodeGenOpts.SanitizeCoverageTraceCmp) { 365 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 366 addSanitizerCoveragePass); 367 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 368 addSanitizerCoveragePass); 369 } 370 371 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 372 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 373 addAddressSanitizerPasses); 374 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 375 addAddressSanitizerPasses); 376 } 377 378 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 379 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 380 addKernelAddressSanitizerPasses); 381 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 382 addKernelAddressSanitizerPasses); 383 } 384 385 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 386 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 387 addMemorySanitizerPass); 388 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 389 addMemorySanitizerPass); 390 } 391 392 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 393 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 394 addThreadSanitizerPass); 395 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 396 addThreadSanitizerPass); 397 } 398 399 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 400 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 401 addDataFlowSanitizerPass); 402 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 403 addDataFlowSanitizerPass); 404 } 405 406 // Set up the per-function pass manager. 407 legacy::FunctionPassManager *FPM = getPerFunctionPasses(); 408 if (CodeGenOpts.VerifyModule) 409 FPM->add(createVerifierPass()); 410 PMBuilder.populateFunctionPassManager(*FPM); 411 412 // Set up the per-module pass manager. 413 if (!CodeGenOpts.RewriteMapFiles.empty()) 414 addSymbolRewriterPass(CodeGenOpts, MPM); 415 416 if (!CodeGenOpts.DisableGCov && 417 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 418 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 419 // LLVM's -default-gcov-version flag is set to something invalid. 420 GCOVOptions Options; 421 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 422 Options.EmitData = CodeGenOpts.EmitGcovArcs; 423 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 424 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 425 Options.NoRedZone = CodeGenOpts.DisableRedZone; 426 Options.FunctionNamesInData = 427 !CodeGenOpts.CoverageNoFunctionNamesInData; 428 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 429 MPM->add(createGCOVProfilerPass(Options)); 430 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 431 MPM->add(createStripSymbolsPass(true)); 432 } 433 434 if (CodeGenOpts.hasProfileClangInstr()) { 435 InstrProfOptions Options; 436 Options.NoRedZone = CodeGenOpts.DisableRedZone; 437 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 438 MPM->add(createInstrProfilingPass(Options)); 439 } 440 441 if (!CodeGenOpts.SampleProfileFile.empty()) 442 MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile)); 443 444 PMBuilder.populateModulePassManager(*MPM); 445 } 446 447 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 448 // Create the TargetMachine for generating code. 449 std::string Error; 450 std::string Triple = TheModule->getTargetTriple(); 451 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 452 if (!TheTarget) { 453 if (MustCreateTM) 454 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 455 return nullptr; 456 } 457 458 unsigned CodeModel = 459 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 460 .Case("small", llvm::CodeModel::Small) 461 .Case("kernel", llvm::CodeModel::Kernel) 462 .Case("medium", llvm::CodeModel::Medium) 463 .Case("large", llvm::CodeModel::Large) 464 .Case("default", llvm::CodeModel::Default) 465 .Default(~0u); 466 assert(CodeModel != ~0u && "invalid code model!"); 467 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 468 469 SmallVector<const char *, 16> BackendArgs; 470 BackendArgs.push_back("clang"); // Fake program name. 471 if (!CodeGenOpts.DebugPass.empty()) { 472 BackendArgs.push_back("-debug-pass"); 473 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 474 } 475 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 476 BackendArgs.push_back("-limit-float-precision"); 477 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 478 } 479 for (const std::string &BackendOption : CodeGenOpts.BackendOptions) 480 BackendArgs.push_back(BackendOption.c_str()); 481 BackendArgs.push_back(nullptr); 482 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 483 BackendArgs.data()); 484 485 std::string FeaturesStr = 486 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 487 488 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp. 489 llvm::Reloc::Model RM = llvm::Reloc::Default; 490 if (CodeGenOpts.RelocationModel == "static") { 491 RM = llvm::Reloc::Static; 492 } else if (CodeGenOpts.RelocationModel == "pic") { 493 RM = llvm::Reloc::PIC_; 494 } else { 495 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 496 "Invalid PIC model!"); 497 RM = llvm::Reloc::DynamicNoPIC; 498 } 499 500 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 501 switch (CodeGenOpts.OptimizationLevel) { 502 default: break; 503 case 0: OptLevel = CodeGenOpt::None; break; 504 case 3: OptLevel = CodeGenOpt::Aggressive; break; 505 } 506 507 llvm::TargetOptions Options; 508 509 if (!TargetOpts.Reciprocals.empty()) 510 Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals); 511 512 Options.ThreadModel = 513 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 514 .Case("posix", llvm::ThreadModel::POSIX) 515 .Case("single", llvm::ThreadModel::Single); 516 517 // Set float ABI type. 518 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 519 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 520 "Invalid Floating Point ABI!"); 521 Options.FloatABIType = 522 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 523 .Case("soft", llvm::FloatABI::Soft) 524 .Case("softfp", llvm::FloatABI::Soft) 525 .Case("hard", llvm::FloatABI::Hard) 526 .Default(llvm::FloatABI::Default); 527 528 // Set FP fusion mode. 529 switch (CodeGenOpts.getFPContractMode()) { 530 case CodeGenOptions::FPC_Off: 531 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 532 break; 533 case CodeGenOptions::FPC_On: 534 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 535 break; 536 case CodeGenOptions::FPC_Fast: 537 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 538 break; 539 } 540 541 Options.UseInitArray = CodeGenOpts.UseInitArray; 542 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 543 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections; 544 545 // Set EABI version. 546 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(CodeGenOpts.EABIVersion) 547 .Case("4", llvm::EABI::EABI4) 548 .Case("5", llvm::EABI::EABI5) 549 .Case("gnu", llvm::EABI::GNU) 550 .Default(llvm::EABI::Default); 551 552 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 553 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 554 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 555 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 556 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 557 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 558 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0; 559 Options.FunctionSections = CodeGenOpts.FunctionSections; 560 Options.DataSections = CodeGenOpts.DataSections; 561 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 562 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 563 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 564 565 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 566 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 567 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 568 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 569 Options.MCOptions.MCIncrementalLinkerCompatible = 570 CodeGenOpts.IncrementalLinkerCompatible; 571 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 572 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 573 Options.MCOptions.ABIName = TargetOpts.ABI; 574 575 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU, 576 FeaturesStr, Options, 577 RM, CM, OptLevel); 578 579 return TM; 580 } 581 582 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action, 583 raw_pwrite_stream &OS) { 584 585 // Create the code generator passes. 586 legacy::PassManager *PM = getCodeGenPasses(); 587 588 // Add LibraryInfo. 589 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 590 std::unique_ptr<TargetLibraryInfoImpl> TLII( 591 createTLII(TargetTriple, CodeGenOpts)); 592 PM->add(new TargetLibraryInfoWrapperPass(*TLII)); 593 594 // Normal mode, emit a .s or .o file by running the code generator. Note, 595 // this also adds codegenerator level optimization passes. 596 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 597 if (Action == Backend_EmitObj) 598 CGFT = TargetMachine::CGFT_ObjectFile; 599 else if (Action == Backend_EmitMCNull) 600 CGFT = TargetMachine::CGFT_Null; 601 else 602 assert(Action == Backend_EmitAssembly && "Invalid action!"); 603 604 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 605 // "codegen" passes so that it isn't run multiple times when there is 606 // inlining happening. 607 if (CodeGenOpts.OptimizationLevel > 0) 608 PM->add(createObjCARCContractPass()); 609 610 if (TM->addPassesToEmitFile(*PM, OS, CGFT, 611 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 612 Diags.Report(diag::err_fe_unable_to_interface_with_target); 613 return false; 614 } 615 616 return true; 617 } 618 619 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 620 raw_pwrite_stream *OS) { 621 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 622 623 bool UsesCodeGen = (Action != Backend_EmitNothing && 624 Action != Backend_EmitBC && 625 Action != Backend_EmitLL); 626 if (!TM) 627 TM.reset(CreateTargetMachine(UsesCodeGen)); 628 629 if (UsesCodeGen && !TM) 630 return; 631 if (TM) 632 TheModule->setDataLayout(TM->createDataLayout()); 633 634 // If we are performing a ThinLTO importing compile, load the function 635 // index into memory and pass it into CreatePasses, which will add it 636 // to the PassManagerBuilder and invoke LTO passes. 637 std::unique_ptr<FunctionInfoIndex> FunctionIndex; 638 if (!CodeGenOpts.ThinLTOIndexFile.empty()) { 639 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr = 640 llvm::getFunctionIndexForFile(CodeGenOpts.ThinLTOIndexFile, 641 [&](const DiagnosticInfo &DI) { 642 TheModule->getContext().diagnose(DI); 643 }); 644 if (std::error_code EC = IndexOrErr.getError()) { 645 std::string Error = EC.message(); 646 errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile 647 << "': " << Error << "\n"; 648 return; 649 } 650 FunctionIndex = std::move(IndexOrErr.get()); 651 assert(FunctionIndex && "Expected non-empty function index"); 652 } 653 654 CreatePasses(FunctionIndex.get()); 655 656 switch (Action) { 657 case Backend_EmitNothing: 658 break; 659 660 case Backend_EmitBC: 661 getPerModulePasses()->add(createBitcodeWriterPass( 662 *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitFunctionSummary)); 663 break; 664 665 case Backend_EmitLL: 666 getPerModulePasses()->add( 667 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 668 break; 669 670 default: 671 if (!AddEmitPasses(Action, *OS)) 672 return; 673 } 674 675 // Before executing passes, print the final values of the LLVM options. 676 cl::PrintOptionValues(); 677 678 // Run passes. For now we do all passes at once, but eventually we 679 // would like to have the option of streaming code generation. 680 681 if (PerFunctionPasses) { 682 PrettyStackTraceString CrashInfo("Per-function optimization"); 683 684 PerFunctionPasses->doInitialization(); 685 for (Function &F : *TheModule) 686 if (!F.isDeclaration()) 687 PerFunctionPasses->run(F); 688 PerFunctionPasses->doFinalization(); 689 } 690 691 if (PerModulePasses) { 692 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 693 PerModulePasses->run(*TheModule); 694 } 695 696 if (CodeGenPasses) { 697 PrettyStackTraceString CrashInfo("Code generation"); 698 CodeGenPasses->run(*TheModule); 699 } 700 } 701 702 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 703 const CodeGenOptions &CGOpts, 704 const clang::TargetOptions &TOpts, 705 const LangOptions &LOpts, StringRef TDesc, 706 Module *M, BackendAction Action, 707 raw_pwrite_stream *OS) { 708 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M); 709 710 AsmHelper.EmitAssembly(Action, OS); 711 712 // If an optional clang TargetInfo description string was passed in, use it to 713 // verify the LLVM TargetMachine's DataLayout. 714 if (AsmHelper.TM && !TDesc.empty()) { 715 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 716 if (DLDesc != TDesc) { 717 unsigned DiagID = Diags.getCustomDiagID( 718 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 719 "expected target description '%1'"); 720 Diags.Report(DiagID) << DLDesc << TDesc; 721 } 722 } 723 } 724