1 //===- TargetPassConfig.cpp - Target independent code generation passes ---===// 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 // This file defines interfaces to access the target independent code 11 // generation passes provided by the LLVM backend. 12 // 13 //===---------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/TargetPassConfig.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Analysis/BasicAliasAnalysis.h" 20 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 21 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 22 #include "llvm/Analysis/CallGraphSCCPass.h" 23 #include "llvm/Analysis/ScopedNoAliasAA.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachinePassRegistry.h" 28 #include "llvm/CodeGen/Passes.h" 29 #include "llvm/CodeGen/RegAllocRegistry.h" 30 #include "llvm/IR/IRPrintingPasses.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Verifier.h" 33 #include "llvm/MC/MCAsmInfo.h" 34 #include "llvm/MC/MCTargetOptions.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/CodeGen.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Compiler.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/Threading.h" 42 #include "llvm/Target/TargetMachine.h" 43 #include "llvm/Transforms/Scalar.h" 44 #include "llvm/Transforms/Utils/SymbolRewriter.h" 45 #include <cassert> 46 #include <string> 47 48 using namespace llvm; 49 50 cl::opt<bool> EnableIPRA("enable-ipra", cl::init(false), cl::Hidden, 51 cl::desc("Enable interprocedural register allocation " 52 "to reduce load/store at procedure calls.")); 53 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden, 54 cl::desc("Disable Post Regalloc Scheduler")); 55 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 56 cl::desc("Disable branch folding")); 57 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 58 cl::desc("Disable tail duplication")); 59 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 60 cl::desc("Disable pre-register allocation tail duplication")); 61 static cl::opt<bool> DisableBlockPlacement("disable-block-placement", 62 cl::Hidden, cl::desc("Disable probability-driven block placement")); 63 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats", 64 cl::Hidden, cl::desc("Collect probability-driven block placement stats")); 65 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 66 cl::desc("Disable Stack Slot Coloring")); 67 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden, 68 cl::desc("Disable Machine Dead Code Elimination")); 69 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden, 70 cl::desc("Disable Early If-conversion")); 71 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 72 cl::desc("Disable Machine LICM")); 73 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden, 74 cl::desc("Disable Machine Common Subexpression Elimination")); 75 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc( 76 "optimize-regalloc", cl::Hidden, 77 cl::desc("Enable optimized register allocation compilation path.")); 78 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 79 cl::Hidden, 80 cl::desc("Disable Machine LICM")); 81 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 82 cl::desc("Disable Machine Sinking")); 83 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 84 cl::desc("Disable Loop Strength Reduction Pass")); 85 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting", 86 cl::Hidden, cl::desc("Disable ConstantHoisting")); 87 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 88 cl::desc("Disable Codegen Prepare")); 89 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden, 90 cl::desc("Disable Copy Propagation pass")); 91 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining", 92 cl::Hidden, cl::desc("Disable Partial Libcall Inlining")); 93 static cl::opt<bool> EnableImplicitNullChecks( 94 "enable-implicit-null-checks", 95 cl::desc("Fold null checks into faulting memory operations"), 96 cl::init(false)); 97 static cl::opt<bool> EnableMergeICmps( 98 "enable-mergeicmps", 99 cl::desc("Merge ICmp chains into a single memcmp"), 100 cl::init(false)); 101 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 102 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 103 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 104 cl::desc("Print LLVM IR input to isel pass")); 105 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 106 cl::desc("Dump garbage collector data")); 107 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 108 cl::desc("Verify generated machine code"), 109 cl::init(false), 110 cl::ZeroOrMore); 111 static cl::opt<bool> EnableMachineOutliner("enable-machine-outliner", 112 cl::Hidden, 113 cl::desc("Enable machine outliner")); 114 static cl::opt<bool> EnableLinkOnceODROutlining( 115 "enable-linkonceodr-outlining", 116 cl::Hidden, 117 cl::desc("Enable the machine outliner on linkonceodr functions"), 118 cl::init(false)); 119 // Enable or disable FastISel. Both options are needed, because 120 // FastISel is enabled by default with -fast, and we wish to be 121 // able to enable or disable fast-isel independently from -O0. 122 static cl::opt<cl::boolOrDefault> 123 EnableFastISelOption("fast-isel", cl::Hidden, 124 cl::desc("Enable the \"fast\" instruction selector")); 125 126 static cl::opt<cl::boolOrDefault> 127 EnableGlobalISel("global-isel", cl::Hidden, 128 cl::desc("Enable the \"global\" instruction selector")); 129 130 static cl::opt<std::string> 131 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional, 132 cl::desc("Print machine instrs"), 133 cl::value_desc("pass-name"), cl::init("option-unspecified")); 134 135 static cl::opt<int> EnableGlobalISelAbort( 136 "global-isel-abort", cl::Hidden, 137 cl::desc("Enable abort calls when \"global\" instruction selection " 138 "fails to lower/select an instruction: 0 disable the abort, " 139 "1 enable the abort, and " 140 "2 disable the abort but emit a diagnostic on failure"), 141 cl::init(1)); 142 143 // Temporary option to allow experimenting with MachineScheduler as a post-RA 144 // scheduler. Targets can "properly" enable this with 145 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID). 146 // Targets can return true in targetSchedulesPostRAScheduling() and 147 // insert a PostRA scheduling pass wherever it wants. 148 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden, 149 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)")); 150 151 // Experimental option to run live interval analysis early. 152 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden, 153 cl::desc("Run live interval analysis earlier in the pipeline")); 154 155 // Experimental option to use CFL-AA in codegen 156 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 157 static cl::opt<CFLAAType> UseCFLAA( 158 "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden, 159 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"), 160 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 161 clEnumValN(CFLAAType::Steensgaard, "steens", 162 "Enable unification-based CFL-AA"), 163 clEnumValN(CFLAAType::Andersen, "anders", 164 "Enable inclusion-based CFL-AA"), 165 clEnumValN(CFLAAType::Both, "both", 166 "Enable both variants of CFL-AA"))); 167 168 /// Option names for limiting the codegen pipeline. 169 /// Those are used in error reporting and we didn't want 170 /// to duplicate their names all over the place. 171 const char *StartAfterOptName = "start-after"; 172 const char *StartBeforeOptName = "start-before"; 173 const char *StopAfterOptName = "stop-after"; 174 const char *StopBeforeOptName = "stop-before"; 175 176 static cl::opt<std::string> 177 StartAfterOpt(StringRef(StartAfterOptName), 178 cl::desc("Resume compilation after a specific pass"), 179 cl::value_desc("pass-name"), cl::init("")); 180 181 static cl::opt<std::string> 182 StartBeforeOpt(StringRef(StartBeforeOptName), 183 cl::desc("Resume compilation before a specific pass"), 184 cl::value_desc("pass-name"), cl::init("")); 185 186 static cl::opt<std::string> 187 StopAfterOpt(StringRef(StopAfterOptName), 188 cl::desc("Stop compilation after a specific pass"), 189 cl::value_desc("pass-name"), cl::init("")); 190 191 static cl::opt<std::string> 192 StopBeforeOpt(StringRef(StopBeforeOptName), 193 cl::desc("Stop compilation before a specific pass"), 194 cl::value_desc("pass-name"), cl::init("")); 195 196 /// Allow standard passes to be disabled by command line options. This supports 197 /// simple binary flags that either suppress the pass or do nothing. 198 /// i.e. -disable-mypass=false has no effect. 199 /// These should be converted to boolOrDefault in order to use applyOverride. 200 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID, 201 bool Override) { 202 if (Override) 203 return IdentifyingPassPtr(); 204 return PassID; 205 } 206 207 /// Allow standard passes to be disabled by the command line, regardless of who 208 /// is adding the pass. 209 /// 210 /// StandardID is the pass identified in the standard pass pipeline and provided 211 /// to addPass(). It may be a target-specific ID in the case that the target 212 /// directly adds its own pass, but in that case we harmlessly fall through. 213 /// 214 /// TargetID is the pass that the target has configured to override StandardID. 215 /// 216 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real 217 /// pass to run. This allows multiple options to control a single pass depending 218 /// on where in the pipeline that pass is added. 219 static IdentifyingPassPtr overridePass(AnalysisID StandardID, 220 IdentifyingPassPtr TargetID) { 221 if (StandardID == &PostRASchedulerID) 222 return applyDisable(TargetID, DisablePostRASched); 223 224 if (StandardID == &BranchFolderPassID) 225 return applyDisable(TargetID, DisableBranchFold); 226 227 if (StandardID == &TailDuplicateID) 228 return applyDisable(TargetID, DisableTailDuplicate); 229 230 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID) 231 return applyDisable(TargetID, DisableEarlyTailDup); 232 233 if (StandardID == &MachineBlockPlacementID) 234 return applyDisable(TargetID, DisableBlockPlacement); 235 236 if (StandardID == &StackSlotColoringID) 237 return applyDisable(TargetID, DisableSSC); 238 239 if (StandardID == &DeadMachineInstructionElimID) 240 return applyDisable(TargetID, DisableMachineDCE); 241 242 if (StandardID == &EarlyIfConverterID) 243 return applyDisable(TargetID, DisableEarlyIfConversion); 244 245 if (StandardID == &MachineLICMID) 246 return applyDisable(TargetID, DisableMachineLICM); 247 248 if (StandardID == &MachineCSEID) 249 return applyDisable(TargetID, DisableMachineCSE); 250 251 if (StandardID == &TargetPassConfig::PostRAMachineLICMID) 252 return applyDisable(TargetID, DisablePostRAMachineLICM); 253 254 if (StandardID == &MachineSinkingID) 255 return applyDisable(TargetID, DisableMachineSink); 256 257 if (StandardID == &MachineCopyPropagationID) 258 return applyDisable(TargetID, DisableCopyProp); 259 260 return TargetID; 261 } 262 263 //===---------------------------------------------------------------------===// 264 /// TargetPassConfig 265 //===---------------------------------------------------------------------===// 266 267 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig", 268 "Target Pass Configuration", false, false) 269 char TargetPassConfig::ID = 0; 270 271 // Pseudo Pass IDs. 272 char TargetPassConfig::EarlyTailDuplicateID = 0; 273 char TargetPassConfig::PostRAMachineLICMID = 0; 274 275 namespace { 276 277 struct InsertedPass { 278 AnalysisID TargetPassID; 279 IdentifyingPassPtr InsertedPassID; 280 bool VerifyAfter; 281 bool PrintAfter; 282 283 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 284 bool VerifyAfter, bool PrintAfter) 285 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID), 286 VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {} 287 288 Pass *getInsertedPass() const { 289 assert(InsertedPassID.isValid() && "Illegal Pass ID!"); 290 if (InsertedPassID.isInstance()) 291 return InsertedPassID.getInstance(); 292 Pass *NP = Pass::createPass(InsertedPassID.getID()); 293 assert(NP && "Pass ID not registered"); 294 return NP; 295 } 296 }; 297 298 } // end anonymous namespace 299 300 namespace llvm { 301 302 class PassConfigImpl { 303 public: 304 // List of passes explicitly substituted by this target. Normally this is 305 // empty, but it is a convenient way to suppress or replace specific passes 306 // that are part of a standard pass pipeline without overridding the entire 307 // pipeline. This mechanism allows target options to inherit a standard pass's 308 // user interface. For example, a target may disable a standard pass by 309 // default by substituting a pass ID of zero, and the user may still enable 310 // that standard pass with an explicit command line option. 311 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses; 312 313 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass 314 /// is inserted after each instance of the first one. 315 SmallVector<InsertedPass, 4> InsertedPasses; 316 }; 317 318 } // end namespace llvm 319 320 // Out of line virtual method. 321 TargetPassConfig::~TargetPassConfig() { 322 delete Impl; 323 } 324 325 static const PassInfo *getPassInfo(StringRef PassName) { 326 if (PassName.empty()) 327 return nullptr; 328 329 const PassRegistry &PR = *PassRegistry::getPassRegistry(); 330 const PassInfo *PI = PR.getPassInfo(PassName); 331 if (!PI) 332 report_fatal_error(Twine('\"') + Twine(PassName) + 333 Twine("\" pass is not registered.")); 334 return PI; 335 } 336 337 static AnalysisID getPassIDFromName(StringRef PassName) { 338 const PassInfo *PI = getPassInfo(PassName); 339 return PI ? PI->getTypeInfo() : nullptr; 340 } 341 342 void TargetPassConfig::setStartStopPasses() { 343 StartBefore = getPassIDFromName(StartBeforeOpt); 344 StartAfter = getPassIDFromName(StartAfterOpt); 345 StopBefore = getPassIDFromName(StopBeforeOpt); 346 StopAfter = getPassIDFromName(StopAfterOpt); 347 if (StartBefore && StartAfter) 348 report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") + 349 Twine(StartAfterOptName) + Twine(" specified!")); 350 if (StopBefore && StopAfter) 351 report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") + 352 Twine(StopAfterOptName) + Twine(" specified!")); 353 Started = (StartAfter == nullptr) && (StartBefore == nullptr); 354 } 355 356 // Out of line constructor provides default values for pass options and 357 // registers all common codegen passes. 358 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm) 359 : ImmutablePass(ID), PM(&pm), TM(&TM) { 360 Impl = new PassConfigImpl(); 361 362 // Register all target independent codegen passes to activate their PassIDs, 363 // including this pass itself. 364 initializeCodeGen(*PassRegistry::getPassRegistry()); 365 366 // Also register alias analysis passes required by codegen passes. 367 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 368 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 369 370 // Substitute Pseudo Pass IDs for real ones. 371 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID); 372 substitutePass(&PostRAMachineLICMID, &MachineLICMID); 373 374 if (StringRef(PrintMachineInstrs.getValue()).equals("")) 375 TM.Options.PrintMachineCode = true; 376 377 if (EnableIPRA.getNumOccurrences()) 378 TM.Options.EnableIPRA = EnableIPRA; 379 else { 380 // If not explicitly specified, use target default. 381 TM.Options.EnableIPRA = TM.useIPRA(); 382 } 383 384 if (TM.Options.EnableIPRA) 385 setRequiresCodeGenSCCOrder(); 386 387 setStartStopPasses(); 388 } 389 390 CodeGenOpt::Level TargetPassConfig::getOptLevel() const { 391 return TM->getOptLevel(); 392 } 393 394 /// Insert InsertedPassID pass after TargetPassID. 395 void TargetPassConfig::insertPass(AnalysisID TargetPassID, 396 IdentifyingPassPtr InsertedPassID, 397 bool VerifyAfter, bool PrintAfter) { 398 assert(((!InsertedPassID.isInstance() && 399 TargetPassID != InsertedPassID.getID()) || 400 (InsertedPassID.isInstance() && 401 TargetPassID != InsertedPassID.getInstance()->getPassID())) && 402 "Insert a pass after itself!"); 403 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter, 404 PrintAfter); 405 } 406 407 /// createPassConfig - Create a pass configuration object to be used by 408 /// addPassToEmitX methods for generating a pipeline of CodeGen passes. 409 /// 410 /// Targets may override this to extend TargetPassConfig. 411 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) { 412 return new TargetPassConfig(*this, PM); 413 } 414 415 TargetPassConfig::TargetPassConfig() 416 : ImmutablePass(ID) { 417 report_fatal_error("Trying to construct TargetPassConfig without a target " 418 "machine. Scheduling a CodeGen pass without a target " 419 "triple set?"); 420 } 421 422 bool TargetPassConfig::hasLimitedCodeGenPipeline() const { 423 return StartBefore || StartAfter || StopBefore || StopAfter; 424 } 425 426 std::string 427 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) const { 428 if (!hasLimitedCodeGenPipeline()) 429 return std::string(); 430 std::string Res; 431 static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt, 432 &StopAfterOpt, &StopBeforeOpt}; 433 static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName, 434 StopAfterOptName, StopBeforeOptName}; 435 bool IsFirst = true; 436 for (int Idx = 0; Idx < 4; ++Idx) 437 if (!PassNames[Idx]->empty()) { 438 if (!IsFirst) 439 Res += Separator; 440 IsFirst = false; 441 Res += OptNames[Idx]; 442 } 443 return Res; 444 } 445 446 // Helper to verify the analysis is really immutable. 447 void TargetPassConfig::setOpt(bool &Opt, bool Val) { 448 assert(!Initialized && "PassConfig is immutable"); 449 Opt = Val; 450 } 451 452 void TargetPassConfig::substitutePass(AnalysisID StandardID, 453 IdentifyingPassPtr TargetID) { 454 Impl->TargetPasses[StandardID] = TargetID; 455 } 456 457 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const { 458 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator 459 I = Impl->TargetPasses.find(ID); 460 if (I == Impl->TargetPasses.end()) 461 return ID; 462 return I->second; 463 } 464 465 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const { 466 IdentifyingPassPtr TargetID = getPassSubstitution(ID); 467 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID); 468 return !FinalPtr.isValid() || FinalPtr.isInstance() || 469 FinalPtr.getID() != ID; 470 } 471 472 /// Add a pass to the PassManager if that pass is supposed to be run. If the 473 /// Started/Stopped flags indicate either that the compilation should start at 474 /// a later pass or that it should stop after an earlier pass, then do not add 475 /// the pass. Finally, compare the current pass against the StartAfter 476 /// and StopAfter options and change the Started/Stopped flags accordingly. 477 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) { 478 assert(!Initialized && "PassConfig is immutable"); 479 480 // Cache the Pass ID here in case the pass manager finds this pass is 481 // redundant with ones already scheduled / available, and deletes it. 482 // Fundamentally, once we add the pass to the manager, we no longer own it 483 // and shouldn't reference it. 484 AnalysisID PassID = P->getPassID(); 485 486 if (StartBefore == PassID) 487 Started = true; 488 if (StopBefore == PassID) 489 Stopped = true; 490 if (Started && !Stopped) { 491 std::string Banner; 492 // Construct banner message before PM->add() as that may delete the pass. 493 if (AddingMachinePasses && (printAfter || verifyAfter)) 494 Banner = std::string("After ") + std::string(P->getPassName()); 495 PM->add(P); 496 if (AddingMachinePasses) { 497 if (printAfter) 498 addPrintPass(Banner); 499 if (verifyAfter) 500 addVerifyPass(Banner); 501 } 502 503 // Add the passes after the pass P if there is any. 504 for (auto IP : Impl->InsertedPasses) { 505 if (IP.TargetPassID == PassID) 506 addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter); 507 } 508 } else { 509 delete P; 510 } 511 if (StopAfter == PassID) 512 Stopped = true; 513 if (StartAfter == PassID) 514 Started = true; 515 if (Stopped && !Started) 516 report_fatal_error("Cannot stop compilation after pass that is not run"); 517 } 518 519 /// Add a CodeGen pass at this point in the pipeline after checking for target 520 /// and command line overrides. 521 /// 522 /// addPass cannot return a pointer to the pass instance because is internal the 523 /// PassManager and the instance we create here may already be freed. 524 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter, 525 bool printAfter) { 526 IdentifyingPassPtr TargetID = getPassSubstitution(PassID); 527 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID); 528 if (!FinalPtr.isValid()) 529 return nullptr; 530 531 Pass *P; 532 if (FinalPtr.isInstance()) 533 P = FinalPtr.getInstance(); 534 else { 535 P = Pass::createPass(FinalPtr.getID()); 536 if (!P) 537 llvm_unreachable("Pass ID not registered"); 538 } 539 AnalysisID FinalID = P->getPassID(); 540 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P. 541 542 return FinalID; 543 } 544 545 void TargetPassConfig::printAndVerify(const std::string &Banner) { 546 addPrintPass(Banner); 547 addVerifyPass(Banner); 548 } 549 550 void TargetPassConfig::addPrintPass(const std::string &Banner) { 551 if (TM->shouldPrintMachineCode()) 552 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner)); 553 } 554 555 void TargetPassConfig::addVerifyPass(const std::string &Banner) { 556 bool Verify = VerifyMachineCode; 557 #ifdef EXPENSIVE_CHECKS 558 if (VerifyMachineCode == cl::BOU_UNSET) 559 Verify = TM->isMachineVerifierClean(); 560 #endif 561 if (Verify) 562 PM->add(createMachineVerifierPass(Banner)); 563 } 564 565 /// Add common target configurable passes that perform LLVM IR to IR transforms 566 /// following machine independent optimization. 567 void TargetPassConfig::addIRPasses() { 568 switch (UseCFLAA) { 569 case CFLAAType::Steensgaard: 570 addPass(createCFLSteensAAWrapperPass()); 571 break; 572 case CFLAAType::Andersen: 573 addPass(createCFLAndersAAWrapperPass()); 574 break; 575 case CFLAAType::Both: 576 addPass(createCFLAndersAAWrapperPass()); 577 addPass(createCFLSteensAAWrapperPass()); 578 break; 579 default: 580 break; 581 } 582 583 // Basic AliasAnalysis support. 584 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 585 // BasicAliasAnalysis wins if they disagree. This is intended to help 586 // support "obvious" type-punning idioms. 587 addPass(createTypeBasedAAWrapperPass()); 588 addPass(createScopedNoAliasAAWrapperPass()); 589 addPass(createBasicAAWrapperPass()); 590 591 // Before running any passes, run the verifier to determine if the input 592 // coming from the front-end and/or optimizer is valid. 593 if (!DisableVerify) 594 addPass(createVerifierPass()); 595 596 // Run loop strength reduction before anything else. 597 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) { 598 addPass(createLoopStrengthReducePass()); 599 if (PrintLSR) 600 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n")); 601 } 602 603 if (getOptLevel() != CodeGenOpt::None) { 604 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of 605 // loads and compares. ExpandMemCmpPass then tries to expand those calls 606 // into optimally-sized loads and compares. The transforms are enabled by a 607 // target lowering hook. 608 if (EnableMergeICmps) 609 addPass(createMergeICmpsPass()); 610 addPass(createExpandMemCmpPass()); 611 } 612 613 // Run GC lowering passes for builtin collectors 614 // TODO: add a pass insertion point here 615 addPass(createGCLoweringPass()); 616 addPass(createShadowStackGCLoweringPass()); 617 618 // Make sure that no unreachable blocks are instruction selected. 619 addPass(createUnreachableBlockEliminationPass()); 620 621 // Prepare expensive constants for SelectionDAG. 622 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting) 623 addPass(createConstantHoistingPass()); 624 625 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining) 626 addPass(createPartiallyInlineLibCallsPass()); 627 628 // Insert calls to mcount-like functions. 629 addPass(createCountingFunctionInserterPass()); 630 631 // Add scalarization of target's unsupported masked memory intrinsics pass. 632 // the unsupported intrinsic will be replaced with a chain of basic blocks, 633 // that stores/loads element one-by-one if the appropriate mask bit is set. 634 addPass(createScalarizeMaskedMemIntrinPass()); 635 636 // Expand reduction intrinsics into shuffle sequences if the target wants to. 637 addPass(createExpandReductionsPass()); 638 } 639 640 /// Turn exception handling constructs into something the code generators can 641 /// handle. 642 void TargetPassConfig::addPassesToHandleExceptions() { 643 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 644 assert(MCAI && "No MCAsmInfo"); 645 switch (MCAI->getExceptionHandlingType()) { 646 case ExceptionHandling::SjLj: 647 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 648 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 649 // catch info can get misplaced when a selector ends up more than one block 650 // removed from the parent invoke(s). This could happen when a landing 651 // pad is shared by multiple invokes and is also a target of a normal 652 // edge from elsewhere. 653 addPass(createSjLjEHPreparePass()); 654 LLVM_FALLTHROUGH; 655 case ExceptionHandling::DwarfCFI: 656 case ExceptionHandling::ARM: 657 addPass(createDwarfEHPass()); 658 break; 659 case ExceptionHandling::WinEH: 660 // We support using both GCC-style and MSVC-style exceptions on Windows, so 661 // add both preparation passes. Each pass will only actually run if it 662 // recognizes the personality function. 663 addPass(createWinEHPass()); 664 addPass(createDwarfEHPass()); 665 break; 666 case ExceptionHandling::None: 667 addPass(createLowerInvokePass()); 668 669 // The lower invoke pass may create unreachable code. Remove it. 670 addPass(createUnreachableBlockEliminationPass()); 671 break; 672 } 673 } 674 675 /// Add pass to prepare the LLVM IR for code generation. This should be done 676 /// before exception handling preparation passes. 677 void TargetPassConfig::addCodeGenPrepare() { 678 if (getOptLevel() != CodeGenOpt::None && !DisableCGP) 679 addPass(createCodeGenPreparePass()); 680 addPass(createRewriteSymbolsPass()); 681 } 682 683 /// Add common passes that perform LLVM IR to IR transforms in preparation for 684 /// instruction selection. 685 void TargetPassConfig::addISelPrepare() { 686 addPreISel(); 687 688 // Force codegen to run according to the callgraph. 689 if (requiresCodeGenSCCOrder()) 690 addPass(new DummyCGSCCPass); 691 692 // Add both the safe stack and the stack protection passes: each of them will 693 // only protect functions that have corresponding attributes. 694 addPass(createSafeStackPass()); 695 addPass(createStackProtectorPass()); 696 697 if (PrintISelInput) 698 addPass(createPrintFunctionPass( 699 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 700 701 // All passes which modify the LLVM IR are now complete; run the verifier 702 // to ensure that the IR is valid. 703 if (!DisableVerify) 704 addPass(createVerifierPass()); 705 } 706 707 bool TargetPassConfig::addCoreISelPasses() { 708 // Enable FastISel with -fast, but allow that to be overridden. 709 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 710 if (EnableFastISelOption == cl::BOU_TRUE || 711 (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())) 712 TM->setFastISel(true); 713 714 // Ask the target for an isel. 715 // Enable GlobalISel if the target wants to, but allow that to be overriden. 716 if (EnableGlobalISel == cl::BOU_TRUE || 717 (EnableGlobalISel == cl::BOU_UNSET && isGlobalISelEnabled())) { 718 if (addIRTranslator()) 719 return true; 720 721 addPreLegalizeMachineIR(); 722 723 if (addLegalizeMachineIR()) 724 return true; 725 726 // Before running the register bank selector, ask the target if it 727 // wants to run some passes. 728 addPreRegBankSelect(); 729 730 if (addRegBankSelect()) 731 return true; 732 733 addPreGlobalInstructionSelect(); 734 735 if (addGlobalInstructionSelect()) 736 return true; 737 738 // Pass to reset the MachineFunction if the ISel failed. 739 addPass(createResetMachineFunctionPass( 740 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled())); 741 742 // Provide a fallback path when we do not want to abort on 743 // not-yet-supported input. 744 if (!isGlobalISelAbortEnabled() && addInstSelector()) 745 return true; 746 747 } else if (addInstSelector()) 748 return true; 749 750 return false; 751 } 752 753 bool TargetPassConfig::addISelPasses() { 754 if (TM->Options.EmulatedTLS) 755 addPass(createLowerEmuTLSPass()); 756 757 addPass(createPreISelIntrinsicLoweringPass()); 758 addPass(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 759 addIRPasses(); 760 addCodeGenPrepare(); 761 addPassesToHandleExceptions(); 762 addISelPrepare(); 763 764 return addCoreISelPasses(); 765 } 766 767 /// -regalloc=... command line option. 768 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 769 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 770 RegisterPassParser<RegisterRegAlloc> > 771 RegAlloc("regalloc", 772 cl::init(&useDefaultRegisterAllocator), 773 cl::desc("Register allocator to use")); 774 775 /// Add the complete set of target-independent postISel code generator passes. 776 /// 777 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 778 /// with nontrivial configuration or multiple passes are broken out below in 779 /// add%Stage routines. 780 /// 781 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 782 /// addPre/Post methods with empty header implementations allow injecting 783 /// target-specific fixups just before or after major stages. Additionally, 784 /// targets have the flexibility to change pass order within a stage by 785 /// overriding default implementation of add%Stage routines below. Each 786 /// technique has maintainability tradeoffs because alternate pass orders are 787 /// not well supported. addPre/Post works better if the target pass is easily 788 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 789 /// the target should override the stage instead. 790 /// 791 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 792 /// before/after any target-independent pass. But it's currently overkill. 793 void TargetPassConfig::addMachinePasses() { 794 AddingMachinePasses = true; 795 796 // Insert a machine instr printer pass after the specified pass. 797 if (!StringRef(PrintMachineInstrs.getValue()).equals("") && 798 !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) { 799 const PassRegistry *PR = PassRegistry::getPassRegistry(); 800 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue()); 801 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer")); 802 assert (TPI && IPI && "Pass ID not registered!"); 803 const char *TID = (const char *)(TPI->getTypeInfo()); 804 const char *IID = (const char *)(IPI->getTypeInfo()); 805 insertPass(TID, IID); 806 } 807 808 // Print the instruction selected machine code... 809 printAndVerify("After Instruction Selection"); 810 811 // Expand pseudo-instructions emitted by ISel. 812 addPass(&ExpandISelPseudosID); 813 814 // Add passes that optimize machine instructions in SSA form. 815 if (getOptLevel() != CodeGenOpt::None) { 816 addMachineSSAOptimization(); 817 } else { 818 // If the target requests it, assign local variables to stack slots relative 819 // to one another and simplify frame index references where possible. 820 addPass(&LocalStackSlotAllocationID, false); 821 } 822 823 if (TM->Options.EnableIPRA) 824 addPass(createRegUsageInfoPropPass()); 825 826 // Run pre-ra passes. 827 addPreRegAlloc(); 828 829 // Run register allocation and passes that are tightly coupled with it, 830 // including phi elimination and scheduling. 831 if (getOptimizeRegAlloc()) 832 addOptimizedRegAlloc(createRegAllocPass(true)); 833 else { 834 if (RegAlloc != &useDefaultRegisterAllocator && 835 RegAlloc != &createFastRegisterAllocator) 836 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc."); 837 addFastRegAlloc(createRegAllocPass(false)); 838 } 839 840 // Run post-ra passes. 841 addPostRegAlloc(); 842 843 // Insert prolog/epilog code. Eliminate abstract frame index references... 844 if (getOptLevel() != CodeGenOpt::None) 845 addPass(&ShrinkWrapID); 846 847 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 848 // do so if it hasn't been disabled, substituted, or overridden. 849 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 850 addPass(createPrologEpilogInserterPass()); 851 852 /// Add passes that optimize machine instructions after register allocation. 853 if (getOptLevel() != CodeGenOpt::None) 854 addMachineLateOptimization(); 855 856 // Expand pseudo instructions before second scheduling pass. 857 addPass(&ExpandPostRAPseudosID); 858 859 // Run pre-sched2 passes. 860 addPreSched2(); 861 862 if (EnableImplicitNullChecks) 863 addPass(&ImplicitNullChecksID); 864 865 // Second pass scheduler. 866 // Let Target optionally insert this pass by itself at some other 867 // point. 868 if (getOptLevel() != CodeGenOpt::None && 869 !TM->targetSchedulesPostRAScheduling()) { 870 if (MISchedPostRA) 871 addPass(&PostMachineSchedulerID); 872 else 873 addPass(&PostRASchedulerID); 874 } 875 876 // GC 877 if (addGCPasses()) { 878 if (PrintGCInfo) 879 addPass(createGCInfoPrinter(dbgs()), false, false); 880 } 881 882 // Basic block placement. 883 if (getOptLevel() != CodeGenOpt::None) 884 addBlockPlacement(); 885 886 addPreEmitPass(); 887 888 if (TM->Options.EnableIPRA) 889 // Collect register usage information and produce a register mask of 890 // clobbered registers, to be used to optimize call sites. 891 addPass(createRegUsageInfoCollector()); 892 893 addPass(&FuncletLayoutID, false); 894 895 addPass(&StackMapLivenessID, false); 896 addPass(&LiveDebugValuesID, false); 897 898 // Insert before XRay Instrumentation. 899 addPass(&FEntryInserterID, false); 900 901 addPass(&XRayInstrumentationID, false); 902 addPass(&PatchableFunctionID, false); 903 904 if (EnableMachineOutliner) 905 PM->add(createMachineOutlinerPass(EnableLinkOnceODROutlining)); 906 907 AddingMachinePasses = false; 908 } 909 910 /// Add passes that optimize machine instructions in SSA form. 911 void TargetPassConfig::addMachineSSAOptimization() { 912 // Pre-ra tail duplication. 913 addPass(&EarlyTailDuplicateID); 914 915 // Optimize PHIs before DCE: removing dead PHI cycles may make more 916 // instructions dead. 917 addPass(&OptimizePHIsID, false); 918 919 // This pass merges large allocas. StackSlotColoring is a different pass 920 // which merges spill slots. 921 addPass(&StackColoringID, false); 922 923 // If the target requests it, assign local variables to stack slots relative 924 // to one another and simplify frame index references where possible. 925 addPass(&LocalStackSlotAllocationID, false); 926 927 // With optimization, dead code should already be eliminated. However 928 // there is one known exception: lowered code for arguments that are only 929 // used by tail calls, where the tail calls reuse the incoming stack 930 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 931 addPass(&DeadMachineInstructionElimID); 932 933 // Allow targets to insert passes that improve instruction level parallelism, 934 // like if-conversion. Such passes will typically need dominator trees and 935 // loop info, just like LICM and CSE below. 936 addILPOpts(); 937 938 addPass(&MachineLICMID, false); 939 addPass(&MachineCSEID, false); 940 941 addPass(&MachineSinkingID); 942 943 addPass(&PeepholeOptimizerID); 944 // Clean-up the dead code that may have been generated by peephole 945 // rewriting. 946 addPass(&DeadMachineInstructionElimID); 947 } 948 949 //===---------------------------------------------------------------------===// 950 /// Register Allocation Pass Configuration 951 //===---------------------------------------------------------------------===// 952 953 bool TargetPassConfig::getOptimizeRegAlloc() const { 954 switch (OptimizeRegAlloc) { 955 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None; 956 case cl::BOU_TRUE: return true; 957 case cl::BOU_FALSE: return false; 958 } 959 llvm_unreachable("Invalid optimize-regalloc state"); 960 } 961 962 /// RegisterRegAlloc's global Registry tracks allocator registration. 963 MachinePassRegistry RegisterRegAlloc::Registry; 964 965 /// A dummy default pass factory indicates whether the register allocator is 966 /// overridden on the command line. 967 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 968 969 static RegisterRegAlloc 970 defaultRegAlloc("default", 971 "pick register allocator based on -O option", 972 useDefaultRegisterAllocator); 973 974 static void initializeDefaultRegisterAllocatorOnce() { 975 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 976 977 if (!Ctor) { 978 Ctor = RegAlloc; 979 RegisterRegAlloc::setDefault(RegAlloc); 980 } 981 } 982 983 /// Instantiate the default register allocator pass for this target for either 984 /// the optimized or unoptimized allocation path. This will be added to the pass 985 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 986 /// in the optimized case. 987 /// 988 /// A target that uses the standard regalloc pass order for fast or optimized 989 /// allocation may still override this for per-target regalloc 990 /// selection. But -regalloc=... always takes precedence. 991 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 992 if (Optimized) 993 return createGreedyRegisterAllocator(); 994 else 995 return createFastRegisterAllocator(); 996 } 997 998 /// Find and instantiate the register allocation pass requested by this target 999 /// at the current optimization level. Different register allocators are 1000 /// defined as separate passes because they may require different analysis. 1001 /// 1002 /// This helper ensures that the regalloc= option is always available, 1003 /// even for targets that override the default allocator. 1004 /// 1005 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 1006 /// this can be folded into addPass. 1007 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 1008 // Initialize the global default. 1009 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 1010 initializeDefaultRegisterAllocatorOnce); 1011 1012 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 1013 if (Ctor != useDefaultRegisterAllocator) 1014 return Ctor(); 1015 1016 // With no -regalloc= override, ask the target for a regalloc pass. 1017 return createTargetRegisterAllocator(Optimized); 1018 } 1019 1020 /// Return true if the default global register allocator is in use and 1021 /// has not be overriden on the command line with '-regalloc=...' 1022 bool TargetPassConfig::usingDefaultRegAlloc() const { 1023 return RegAlloc.getNumOccurrences() == 0; 1024 } 1025 1026 /// Add the minimum set of target-independent passes that are required for 1027 /// register allocation. No coalescing or scheduling. 1028 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { 1029 addPass(&PHIEliminationID, false); 1030 addPass(&TwoAddressInstructionPassID, false); 1031 1032 if (RegAllocPass) 1033 addPass(RegAllocPass); 1034 } 1035 1036 /// Add standard target-independent passes that are tightly coupled with 1037 /// optimized register allocation, including coalescing, machine instruction 1038 /// scheduling, and register allocation itself. 1039 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { 1040 addPass(&DetectDeadLanesID, false); 1041 1042 addPass(&ProcessImplicitDefsID, false); 1043 1044 // LiveVariables currently requires pure SSA form. 1045 // 1046 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 1047 // LiveVariables can be removed completely, and LiveIntervals can be directly 1048 // computed. (We still either need to regenerate kill flags after regalloc, or 1049 // preferably fix the scavenger to not depend on them). 1050 addPass(&LiveVariablesID, false); 1051 1052 // Edge splitting is smarter with machine loop info. 1053 addPass(&MachineLoopInfoID, false); 1054 addPass(&PHIEliminationID, false); 1055 1056 // Eventually, we want to run LiveIntervals before PHI elimination. 1057 if (EarlyLiveIntervals) 1058 addPass(&LiveIntervalsID, false); 1059 1060 addPass(&TwoAddressInstructionPassID, false); 1061 addPass(&RegisterCoalescerID); 1062 1063 // The machine scheduler may accidentally create disconnected components 1064 // when moving subregister definitions around, avoid this by splitting them to 1065 // separate vregs before. Splitting can also improve reg. allocation quality. 1066 addPass(&RenameIndependentSubregsID); 1067 1068 // PreRA instruction scheduling. 1069 addPass(&MachineSchedulerID); 1070 1071 if (RegAllocPass) { 1072 // Add the selected register allocation pass. 1073 addPass(RegAllocPass); 1074 1075 // Allow targets to change the register assignments before rewriting. 1076 addPreRewrite(); 1077 1078 // Finally rewrite virtual registers. 1079 addPass(&VirtRegRewriterID); 1080 1081 // Perform stack slot coloring and post-ra machine LICM. 1082 // 1083 // FIXME: Re-enable coloring with register when it's capable of adding 1084 // kill markers. 1085 addPass(&StackSlotColoringID); 1086 1087 // Run post-ra machine LICM to hoist reloads / remats. 1088 // 1089 // FIXME: can this move into MachineLateOptimization? 1090 addPass(&PostRAMachineLICMID); 1091 } 1092 } 1093 1094 //===---------------------------------------------------------------------===// 1095 /// Post RegAlloc Pass Configuration 1096 //===---------------------------------------------------------------------===// 1097 1098 /// Add passes that optimize machine instructions after register allocation. 1099 void TargetPassConfig::addMachineLateOptimization() { 1100 // Branch folding must be run after regalloc and prolog/epilog insertion. 1101 addPass(&BranchFolderPassID); 1102 1103 // Tail duplication. 1104 // Note that duplicating tail just increases code size and degrades 1105 // performance for targets that require Structured Control Flow. 1106 // In addition it can also make CFG irreducible. Thus we disable it. 1107 if (!TM->requiresStructuredCFG()) 1108 addPass(&TailDuplicateID); 1109 1110 // Copy propagation. 1111 addPass(&MachineCopyPropagationID); 1112 } 1113 1114 /// Add standard GC passes. 1115 bool TargetPassConfig::addGCPasses() { 1116 addPass(&GCMachineCodeAnalysisID, false); 1117 return true; 1118 } 1119 1120 /// Add standard basic block placement passes. 1121 void TargetPassConfig::addBlockPlacement() { 1122 if (addPass(&MachineBlockPlacementID)) { 1123 // Run a separate pass to collect block placement statistics. 1124 if (EnableBlockPlacementStats) 1125 addPass(&MachineBlockPlacementStatsID); 1126 } 1127 } 1128 1129 //===---------------------------------------------------------------------===// 1130 /// GlobalISel Configuration 1131 //===---------------------------------------------------------------------===// 1132 1133 bool TargetPassConfig::isGlobalISelEnabled() const { 1134 return false; 1135 } 1136 1137 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 1138 return EnableGlobalISelAbort == 1; 1139 } 1140 1141 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 1142 return EnableGlobalISelAbort == 2; 1143 } 1144