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/ADT/Triple.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeWriterPass.h" 23 #include "llvm/Bitcode/ReaderWriter.h" 24 #include "llvm/CodeGen/RegAllocRegistry.h" 25 #include "llvm/CodeGen/SchedulerRegistry.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/ModuleSummaryIndex.h" 28 #include "llvm/IR/IRPrintingPasses.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IR/Verifier.h" 32 #include "llvm/MC/SubtargetFeature.h" 33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/PrettyStackTrace.h" 36 #include "llvm/Support/TargetRegistry.h" 37 #include "llvm/Support/Timer.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetMachine.h" 40 #include "llvm/Target/TargetOptions.h" 41 #include "llvm/Target/TargetSubtargetInfo.h" 42 #include "llvm/Transforms/IPO.h" 43 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 44 #include "llvm/Transforms/Instrumentation.h" 45 #include "llvm/Transforms/ObjCARC.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Scalar/GVN.h" 48 #include "llvm/Transforms/Utils/SymbolRewriter.h" 49 #include <memory> 50 using namespace clang; 51 using namespace llvm; 52 53 namespace { 54 55 class EmitAssemblyHelper { 56 DiagnosticsEngine &Diags; 57 const CodeGenOptions &CodeGenOpts; 58 const clang::TargetOptions &TargetOpts; 59 const LangOptions &LangOpts; 60 Module *TheModule; 61 62 Timer CodeGenerationTime; 63 64 mutable legacy::PassManager *CodeGenPasses; 65 mutable legacy::PassManager *PerModulePasses; 66 mutable legacy::FunctionPassManager *PerFunctionPasses; 67 68 private: 69 TargetIRAnalysis getTargetIRAnalysis() const { 70 if (TM) 71 return TM->getTargetIRAnalysis(); 72 73 return TargetIRAnalysis(); 74 } 75 76 legacy::PassManager *getCodeGenPasses() const { 77 if (!CodeGenPasses) { 78 CodeGenPasses = new legacy::PassManager(); 79 CodeGenPasses->add( 80 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 81 } 82 return CodeGenPasses; 83 } 84 85 legacy::PassManager *getPerModulePasses() const { 86 if (!PerModulePasses) { 87 PerModulePasses = new legacy::PassManager(); 88 PerModulePasses->add( 89 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 90 } 91 return PerModulePasses; 92 } 93 94 legacy::FunctionPassManager *getPerFunctionPasses() const { 95 if (!PerFunctionPasses) { 96 PerFunctionPasses = new legacy::FunctionPassManager(TheModule); 97 PerFunctionPasses->add( 98 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 99 } 100 return PerFunctionPasses; 101 } 102 103 /// Set LLVM command line options passed through -backend-option. 104 void setCommandLineOpts(); 105 106 void CreatePasses(ModuleSummaryIndex *ModuleSummary); 107 108 /// Generates the TargetMachine. 109 /// Returns Null if it is unable to create the target machine. 110 /// Some of our clang tests specify triples which are not built 111 /// into clang. This is okay because these tests check the generated 112 /// IR, and they require DataLayout which depends on the triple. 113 /// In this case, we allow this method to fail and not report an error. 114 /// When MustCreateTM is used, we print an error if we are unable to load 115 /// the requested target. 116 TargetMachine *CreateTargetMachine(bool MustCreateTM); 117 118 /// Add passes necessary to emit assembly or LLVM IR. 119 /// 120 /// \return True on success. 121 bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS); 122 123 public: 124 EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts, 125 const clang::TargetOptions &TOpts, 126 const LangOptions &LOpts, Module *M) 127 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), 128 TheModule(M), CodeGenerationTime("Code Generation Time"), 129 CodeGenPasses(nullptr), PerModulePasses(nullptr), 130 PerFunctionPasses(nullptr) {} 131 132 ~EmitAssemblyHelper() { 133 delete CodeGenPasses; 134 delete PerModulePasses; 135 delete PerFunctionPasses; 136 if (CodeGenOpts.DisableFree) 137 BuryPointer(std::move(TM)); 138 } 139 140 std::unique_ptr<TargetMachine> TM; 141 142 void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS); 143 }; 144 145 // We need this wrapper to access LangOpts and CGOpts from extension functions 146 // that we add to the PassManagerBuilder. 147 class PassManagerBuilderWrapper : public PassManagerBuilder { 148 public: 149 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 150 const LangOptions &LangOpts) 151 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 152 const CodeGenOptions &getCGOpts() const { return CGOpts; } 153 const LangOptions &getLangOpts() const { return LangOpts; } 154 private: 155 const CodeGenOptions &CGOpts; 156 const LangOptions &LangOpts; 157 }; 158 159 } 160 161 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 162 if (Builder.OptLevel > 0) 163 PM.add(createObjCARCAPElimPass()); 164 } 165 166 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 167 if (Builder.OptLevel > 0) 168 PM.add(createObjCARCExpandPass()); 169 } 170 171 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 172 if (Builder.OptLevel > 0) 173 PM.add(createObjCARCOptPass()); 174 } 175 176 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 177 legacy::PassManagerBase &PM) { 178 PM.add(createAddDiscriminatorsPass()); 179 } 180 181 static void addInstructionCombiningPass(const PassManagerBuilder &Builder, 182 legacy::PassManagerBase &PM) { 183 PM.add(createInstructionCombiningPass()); 184 } 185 186 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 187 legacy::PassManagerBase &PM) { 188 PM.add(createBoundsCheckingPass()); 189 } 190 191 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 192 legacy::PassManagerBase &PM) { 193 const PassManagerBuilderWrapper &BuilderWrapper = 194 static_cast<const PassManagerBuilderWrapper&>(Builder); 195 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 196 SanitizerCoverageOptions Opts; 197 Opts.CoverageType = 198 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 199 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 200 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 201 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 202 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 203 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 204 PM.add(createSanitizerCoverageModulePass(Opts)); 205 } 206 207 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 208 legacy::PassManagerBase &PM) { 209 const PassManagerBuilderWrapper &BuilderWrapper = 210 static_cast<const PassManagerBuilderWrapper&>(Builder); 211 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 212 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 213 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover)); 214 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover)); 215 } 216 217 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 218 legacy::PassManagerBase &PM) { 219 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true, 220 /*Recover*/true)); 221 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true, 222 /*Recover*/true)); 223 } 224 225 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 226 legacy::PassManagerBase &PM) { 227 const PassManagerBuilderWrapper &BuilderWrapper = 228 static_cast<const PassManagerBuilderWrapper&>(Builder); 229 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 230 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins)); 231 232 // MemorySanitizer inserts complex instrumentation that mostly follows 233 // the logic of the original code, but operates on "shadow" values. 234 // It can benefit from re-running some general purpose optimization passes. 235 if (Builder.OptLevel > 0) { 236 PM.add(createEarlyCSEPass()); 237 PM.add(createReassociatePass()); 238 PM.add(createLICMPass()); 239 PM.add(createGVNPass()); 240 PM.add(createInstructionCombiningPass()); 241 PM.add(createDeadStoreEliminationPass()); 242 } 243 } 244 245 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 246 legacy::PassManagerBase &PM) { 247 PM.add(createThreadSanitizerPass()); 248 } 249 250 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 251 legacy::PassManagerBase &PM) { 252 const PassManagerBuilderWrapper &BuilderWrapper = 253 static_cast<const PassManagerBuilderWrapper&>(Builder); 254 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 255 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 256 } 257 258 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder, 259 legacy::PassManagerBase &PM) { 260 const PassManagerBuilderWrapper &BuilderWrapper = 261 static_cast<const PassManagerBuilderWrapper&>(Builder); 262 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 263 EfficiencySanitizerOptions Opts; 264 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag)) 265 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag; 266 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet)) 267 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet; 268 PM.add(createEfficiencySanitizerPass(Opts)); 269 } 270 271 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 272 const CodeGenOptions &CodeGenOpts) { 273 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 274 if (!CodeGenOpts.SimplifyLibCalls) 275 TLII->disableAllFunctions(); 276 else { 277 // Disable individual libc/libm calls in TargetLibraryInfo. 278 LibFunc::Func F; 279 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 280 if (TLII->getLibFunc(FuncName, F)) 281 TLII->setUnavailable(F); 282 } 283 284 switch (CodeGenOpts.getVecLib()) { 285 case CodeGenOptions::Accelerate: 286 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 287 break; 288 default: 289 break; 290 } 291 return TLII; 292 } 293 294 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 295 legacy::PassManager *MPM) { 296 llvm::SymbolRewriter::RewriteDescriptorList DL; 297 298 llvm::SymbolRewriter::RewriteMapParser MapParser; 299 for (const auto &MapFile : Opts.RewriteMapFiles) 300 MapParser.parse(MapFile, &DL); 301 302 MPM->add(createRewriteSymbolsPass(DL)); 303 } 304 305 void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) { 306 if (CodeGenOpts.DisableLLVMPasses) 307 return; 308 309 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 310 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 311 312 // Handle disabling of LLVM optimization, where we want to preserve the 313 // internal module before any optimization. 314 if (CodeGenOpts.DisableLLVMOpts) { 315 OptLevel = 0; 316 Inlining = CodeGenOpts.NoInlining; 317 } 318 319 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 320 321 // Figure out TargetLibraryInfo. 322 Triple TargetTriple(TheModule->getTargetTriple()); 323 PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts); 324 325 switch (Inlining) { 326 case CodeGenOptions::NoInlining: 327 break; 328 case CodeGenOptions::NormalInlining: { 329 PMBuilder.Inliner = 330 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize); 331 break; 332 } 333 case CodeGenOptions::OnlyAlwaysInlining: 334 // Respect always_inline. 335 if (OptLevel == 0) 336 // Do not insert lifetime intrinsics at -O0. 337 PMBuilder.Inliner = createAlwaysInlinerPass(false); 338 else 339 PMBuilder.Inliner = createAlwaysInlinerPass(); 340 break; 341 } 342 343 PMBuilder.OptLevel = OptLevel; 344 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 345 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 346 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 347 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 348 349 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime; 350 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 351 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 352 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex; 353 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 354 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 355 356 legacy::PassManager *MPM = getPerModulePasses(); 357 358 // If we are performing a ThinLTO importing compile, invoke the LTO 359 // pipeline and pass down the in-memory module summary index. 360 if (ModuleSummary) { 361 PMBuilder.ModuleSummary = ModuleSummary; 362 PMBuilder.populateThinLTOPassManager(*MPM); 363 return; 364 } 365 366 // Add target-specific passes that need to run as early as possible. 367 if (TM) 368 PMBuilder.addExtension( 369 PassManagerBuilder::EP_EarlyAsPossible, 370 [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { 371 TM->addEarlyAsPossiblePasses(PM); 372 }); 373 374 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 375 addAddDiscriminatorsPass); 376 377 // In ObjC ARC mode, add the main ARC optimization passes. 378 if (LangOpts.ObjCAutoRefCount) { 379 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 380 addObjCARCExpandPass); 381 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 382 addObjCARCAPElimPass); 383 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 384 addObjCARCOptPass); 385 } 386 387 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 388 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 389 addBoundsCheckingPass); 390 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 391 addBoundsCheckingPass); 392 } 393 394 if (CodeGenOpts.SanitizeCoverageType || 395 CodeGenOpts.SanitizeCoverageIndirectCalls || 396 CodeGenOpts.SanitizeCoverageTraceCmp) { 397 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 398 addSanitizerCoveragePass); 399 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 400 addSanitizerCoveragePass); 401 } 402 403 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 404 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 405 addAddressSanitizerPasses); 406 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 407 addAddressSanitizerPasses); 408 } 409 410 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 411 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 412 addKernelAddressSanitizerPasses); 413 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 414 addKernelAddressSanitizerPasses); 415 } 416 417 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 418 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 419 addMemorySanitizerPass); 420 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 421 addMemorySanitizerPass); 422 } 423 424 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 425 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 426 addThreadSanitizerPass); 427 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 428 addThreadSanitizerPass); 429 } 430 431 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 432 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 433 addDataFlowSanitizerPass); 434 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 435 addDataFlowSanitizerPass); 436 } 437 438 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) { 439 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 440 addEfficiencySanitizerPass); 441 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 442 addEfficiencySanitizerPass); 443 } 444 445 // Set up the per-function pass manager. 446 legacy::FunctionPassManager *FPM = getPerFunctionPasses(); 447 if (CodeGenOpts.VerifyModule) 448 FPM->add(createVerifierPass()); 449 450 // Set up the per-module pass manager. 451 if (!CodeGenOpts.RewriteMapFiles.empty()) 452 addSymbolRewriterPass(CodeGenOpts, MPM); 453 454 if (!CodeGenOpts.DisableGCov && 455 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 456 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 457 // LLVM's -default-gcov-version flag is set to something invalid. 458 GCOVOptions Options; 459 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 460 Options.EmitData = CodeGenOpts.EmitGcovArcs; 461 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 462 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 463 Options.NoRedZone = CodeGenOpts.DisableRedZone; 464 Options.FunctionNamesInData = 465 !CodeGenOpts.CoverageNoFunctionNamesInData; 466 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 467 MPM->add(createGCOVProfilerPass(Options)); 468 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 469 MPM->add(createStripSymbolsPass(true)); 470 } 471 472 if (CodeGenOpts.hasProfileClangInstr()) { 473 InstrProfOptions Options; 474 Options.NoRedZone = CodeGenOpts.DisableRedZone; 475 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 476 MPM->add(createInstrProfilingLegacyPass(Options)); 477 } 478 if (CodeGenOpts.hasProfileIRInstr()) { 479 if (!CodeGenOpts.InstrProfileOutput.empty()) 480 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 481 else 482 PMBuilder.PGOInstrGen = "default.profraw"; 483 } 484 if (CodeGenOpts.hasProfileIRUse()) 485 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 486 487 if (!CodeGenOpts.SampleProfileFile.empty()) { 488 MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile)); 489 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 490 addInstructionCombiningPass); 491 } 492 493 PMBuilder.populateFunctionPassManager(*FPM); 494 PMBuilder.populateModulePassManager(*MPM); 495 } 496 497 void EmitAssemblyHelper::setCommandLineOpts() { 498 SmallVector<const char *, 16> BackendArgs; 499 BackendArgs.push_back("clang"); // Fake program name. 500 if (!CodeGenOpts.DebugPass.empty()) { 501 BackendArgs.push_back("-debug-pass"); 502 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 503 } 504 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 505 BackendArgs.push_back("-limit-float-precision"); 506 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 507 } 508 for (const std::string &BackendOption : CodeGenOpts.BackendOptions) 509 BackendArgs.push_back(BackendOption.c_str()); 510 BackendArgs.push_back(nullptr); 511 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 512 BackendArgs.data()); 513 } 514 515 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 516 // Create the TargetMachine for generating code. 517 std::string Error; 518 std::string Triple = TheModule->getTargetTriple(); 519 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 520 if (!TheTarget) { 521 if (MustCreateTM) 522 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 523 return nullptr; 524 } 525 526 unsigned CodeModel = 527 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 528 .Case("small", llvm::CodeModel::Small) 529 .Case("kernel", llvm::CodeModel::Kernel) 530 .Case("medium", llvm::CodeModel::Medium) 531 .Case("large", llvm::CodeModel::Large) 532 .Case("default", llvm::CodeModel::Default) 533 .Default(~0u); 534 assert(CodeModel != ~0u && "invalid code model!"); 535 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 536 537 std::string FeaturesStr = 538 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 539 540 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp. 541 llvm::Optional<llvm::Reloc::Model> RM; 542 if (CodeGenOpts.RelocationModel == "static") { 543 RM = llvm::Reloc::Static; 544 } else if (CodeGenOpts.RelocationModel == "pic") { 545 RM = llvm::Reloc::PIC_; 546 } else { 547 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 548 "Invalid PIC model!"); 549 RM = llvm::Reloc::DynamicNoPIC; 550 } 551 552 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 553 switch (CodeGenOpts.OptimizationLevel) { 554 default: break; 555 case 0: OptLevel = CodeGenOpt::None; break; 556 case 3: OptLevel = CodeGenOpt::Aggressive; break; 557 } 558 559 llvm::TargetOptions Options; 560 561 if (!TargetOpts.Reciprocals.empty()) 562 Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals); 563 564 Options.ThreadModel = 565 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 566 .Case("posix", llvm::ThreadModel::POSIX) 567 .Case("single", llvm::ThreadModel::Single); 568 569 // Set float ABI type. 570 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 571 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 572 "Invalid Floating Point ABI!"); 573 Options.FloatABIType = 574 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 575 .Case("soft", llvm::FloatABI::Soft) 576 .Case("softfp", llvm::FloatABI::Soft) 577 .Case("hard", llvm::FloatABI::Hard) 578 .Default(llvm::FloatABI::Default); 579 580 // Set FP fusion mode. 581 switch (CodeGenOpts.getFPContractMode()) { 582 case CodeGenOptions::FPC_Off: 583 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 584 break; 585 case CodeGenOptions::FPC_On: 586 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 587 break; 588 case CodeGenOptions::FPC_Fast: 589 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 590 break; 591 } 592 593 Options.UseInitArray = CodeGenOpts.UseInitArray; 594 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 595 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections; 596 597 // Set EABI version. 598 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion) 599 .Case("4", llvm::EABI::EABI4) 600 .Case("5", llvm::EABI::EABI5) 601 .Case("gnu", llvm::EABI::GNU) 602 .Default(llvm::EABI::Default); 603 604 if (LangOpts.SjLjExceptions) 605 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 606 607 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 608 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 609 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 610 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 611 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 612 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 613 Options.FunctionSections = CodeGenOpts.FunctionSections; 614 Options.DataSections = CodeGenOpts.DataSections; 615 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 616 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 617 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 618 619 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 620 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 621 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 622 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 623 Options.MCOptions.MCIncrementalLinkerCompatible = 624 CodeGenOpts.IncrementalLinkerCompatible; 625 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 626 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 627 Options.MCOptions.ABIName = TargetOpts.ABI; 628 629 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU, 630 FeaturesStr, Options, 631 RM, CM, OptLevel); 632 633 return TM; 634 } 635 636 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action, 637 raw_pwrite_stream &OS) { 638 639 // Create the code generator passes. 640 legacy::PassManager *PM = getCodeGenPasses(); 641 642 // Add LibraryInfo. 643 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 644 std::unique_ptr<TargetLibraryInfoImpl> TLII( 645 createTLII(TargetTriple, CodeGenOpts)); 646 PM->add(new TargetLibraryInfoWrapperPass(*TLII)); 647 648 // Normal mode, emit a .s or .o file by running the code generator. Note, 649 // this also adds codegenerator level optimization passes. 650 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 651 if (Action == Backend_EmitObj) 652 CGFT = TargetMachine::CGFT_ObjectFile; 653 else if (Action == Backend_EmitMCNull) 654 CGFT = TargetMachine::CGFT_Null; 655 else 656 assert(Action == Backend_EmitAssembly && "Invalid action!"); 657 658 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 659 // "codegen" passes so that it isn't run multiple times when there is 660 // inlining happening. 661 if (CodeGenOpts.OptimizationLevel > 0) 662 PM->add(createObjCARCContractPass()); 663 664 if (TM->addPassesToEmitFile(*PM, OS, CGFT, 665 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 666 Diags.Report(diag::err_fe_unable_to_interface_with_target); 667 return false; 668 } 669 670 return true; 671 } 672 673 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 674 raw_pwrite_stream *OS) { 675 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 676 677 setCommandLineOpts(); 678 679 bool UsesCodeGen = (Action != Backend_EmitNothing && 680 Action != Backend_EmitBC && 681 Action != Backend_EmitLL); 682 if (!TM) 683 TM.reset(CreateTargetMachine(UsesCodeGen)); 684 685 if (UsesCodeGen && !TM) 686 return; 687 if (TM) 688 TheModule->setDataLayout(TM->createDataLayout()); 689 690 // If we are performing a ThinLTO importing compile, load the function 691 // index into memory and pass it into CreatePasses, which will add it 692 // to the PassManagerBuilder and invoke LTO passes. 693 std::unique_ptr<ModuleSummaryIndex> ModuleSummary; 694 if (!CodeGenOpts.ThinLTOIndexFile.empty()) { 695 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 696 llvm::getModuleSummaryIndexForFile( 697 CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) { 698 TheModule->getContext().diagnose(DI); 699 }); 700 if (std::error_code EC = IndexOrErr.getError()) { 701 std::string Error = EC.message(); 702 errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile 703 << "': " << Error << "\n"; 704 return; 705 } 706 ModuleSummary = std::move(IndexOrErr.get()); 707 assert(ModuleSummary && "Expected non-empty module summary index"); 708 } 709 710 CreatePasses(ModuleSummary.get()); 711 712 switch (Action) { 713 case Backend_EmitNothing: 714 break; 715 716 case Backend_EmitBC: 717 getPerModulePasses()->add(createBitcodeWriterPass( 718 *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex, 719 CodeGenOpts.EmitSummaryIndex)); 720 break; 721 722 case Backend_EmitLL: 723 getPerModulePasses()->add( 724 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 725 break; 726 727 default: 728 if (!AddEmitPasses(Action, *OS)) 729 return; 730 } 731 732 // Before executing passes, print the final values of the LLVM options. 733 cl::PrintOptionValues(); 734 735 // Run passes. For now we do all passes at once, but eventually we 736 // would like to have the option of streaming code generation. 737 738 if (PerFunctionPasses) { 739 PrettyStackTraceString CrashInfo("Per-function optimization"); 740 741 PerFunctionPasses->doInitialization(); 742 for (Function &F : *TheModule) 743 if (!F.isDeclaration()) 744 PerFunctionPasses->run(F); 745 PerFunctionPasses->doFinalization(); 746 } 747 748 if (PerModulePasses) { 749 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 750 PerModulePasses->run(*TheModule); 751 } 752 753 if (CodeGenPasses) { 754 PrettyStackTraceString CrashInfo("Code generation"); 755 CodeGenPasses->run(*TheModule); 756 } 757 } 758 759 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 760 const CodeGenOptions &CGOpts, 761 const clang::TargetOptions &TOpts, 762 const LangOptions &LOpts, const llvm::DataLayout &TDesc, 763 Module *M, BackendAction Action, 764 raw_pwrite_stream *OS) { 765 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M); 766 767 AsmHelper.EmitAssembly(Action, OS); 768 769 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 770 // DataLayout. 771 if (AsmHelper.TM) { 772 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 773 if (DLDesc != TDesc.getStringRepresentation()) { 774 unsigned DiagID = Diags.getCustomDiagID( 775 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 776 "expected target description '%1'"); 777 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 778 } 779 } 780 } 781 782 static const char* getSectionNameForBitcode(const Triple &T) { 783 switch (T.getObjectFormat()) { 784 case Triple::MachO: 785 return "__LLVM,__bitcode"; 786 case Triple::COFF: 787 case Triple::ELF: 788 case Triple::UnknownObjectFormat: 789 return ".llvmbc"; 790 } 791 llvm_unreachable("Unimplemented ObjectFormatType"); 792 } 793 794 static const char* getSectionNameForCommandline(const Triple &T) { 795 switch (T.getObjectFormat()) { 796 case Triple::MachO: 797 return "__LLVM,__cmdline"; 798 case Triple::COFF: 799 case Triple::ELF: 800 case Triple::UnknownObjectFormat: 801 return ".llvmcmd"; 802 } 803 llvm_unreachable("Unimplemented ObjectFormatType"); 804 } 805 806 // With -fembed-bitcode, save a copy of the llvm IR as data in the 807 // __LLVM,__bitcode section. 808 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 809 llvm::MemoryBufferRef Buf) { 810 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 811 return; 812 813 // Save llvm.compiler.used and remote it. 814 SmallVector<Constant*, 2> UsedArray; 815 SmallSet<GlobalValue*, 4> UsedGlobals; 816 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0); 817 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true); 818 for (auto *GV : UsedGlobals) { 819 if (GV->getName() != "llvm.embedded.module" && 820 GV->getName() != "llvm.cmdline") 821 UsedArray.push_back( 822 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 823 } 824 if (Used) 825 Used->eraseFromParent(); 826 827 // Embed the bitcode for the llvm module. 828 std::string Data; 829 ArrayRef<uint8_t> ModuleData; 830 Triple T(M->getTargetTriple()); 831 // Create a constant that contains the bitcode. 832 // In case of embedding a marker, ignore the input Buf and use the empty 833 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 834 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) { 835 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 836 (const unsigned char *)Buf.getBufferEnd())) { 837 // If the input is LLVM Assembly, bitcode is produced by serializing 838 // the module. Use-lists order need to be perserved in this case. 839 llvm::raw_string_ostream OS(Data); 840 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 841 ModuleData = 842 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 843 } else 844 // If the input is LLVM bitcode, write the input byte stream directly. 845 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 846 Buf.getBufferSize()); 847 } 848 llvm::Constant *ModuleConstant = 849 llvm::ConstantDataArray::get(M->getContext(), ModuleData); 850 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 851 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 852 ModuleConstant); 853 GV->setSection(getSectionNameForBitcode(T)); 854 UsedArray.push_back( 855 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 856 if (llvm::GlobalVariable *Old = 857 M->getGlobalVariable("llvm.embedded.module", true)) { 858 assert(Old->hasOneUse() && 859 "llvm.embedded.module can only be used once in llvm.compiler.used"); 860 GV->takeName(Old); 861 Old->eraseFromParent(); 862 } else { 863 GV->setName("llvm.embedded.module"); 864 } 865 866 // Skip if only bitcode needs to be embedded. 867 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) { 868 // Embed command-line options. 869 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()), 870 CGOpts.CmdArgs.size()); 871 llvm::Constant *CmdConstant = 872 llvm::ConstantDataArray::get(M->getContext(), CmdData); 873 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, 874 llvm::GlobalValue::PrivateLinkage, 875 CmdConstant); 876 GV->setSection(getSectionNameForCommandline(T)); 877 UsedArray.push_back( 878 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 879 if (llvm::GlobalVariable *Old = 880 M->getGlobalVariable("llvm.cmdline", true)) { 881 assert(Old->hasOneUse() && 882 "llvm.cmdline can only be used once in llvm.compiler.used"); 883 GV->takeName(Old); 884 Old->eraseFromParent(); 885 } else { 886 GV->setName("llvm.cmdline"); 887 } 888 } 889 890 if (UsedArray.empty()) 891 return; 892 893 // Recreate llvm.compiler.used. 894 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 895 auto *NewUsed = new GlobalVariable( 896 *M, ATy, false, llvm::GlobalValue::AppendingLinkage, 897 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 898 NewUsed->setSection("llvm.metadata"); 899 } 900