LLVM  8.0.0svn
TargetPassConfig.cpp
Go to the documentation of this file.
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 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
28 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Threading.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils.h"
46 #include <cassert>
47 #include <string>
48 
49 using namespace llvm;
50 
51 cl::opt<bool> EnableIPRA("enable-ipra", cl::init(false), cl::Hidden,
52  cl::desc("Enable interprocedural register allocation "
53  "to reduce load/store at procedure calls."));
54 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
55  cl::desc("Disable Post Regalloc Scheduler"));
56 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
57  cl::desc("Disable branch folding"));
58 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
59  cl::desc("Disable tail duplication"));
60 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
61  cl::desc("Disable pre-register allocation tail duplication"));
62 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
63  cl::Hidden, cl::desc("Disable probability-driven block placement"));
64 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
65  cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
66 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
67  cl::desc("Disable Stack Slot Coloring"));
68 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
69  cl::desc("Disable Machine Dead Code Elimination"));
70 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
71  cl::desc("Disable Early If-conversion"));
72 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
73  cl::desc("Disable Machine LICM"));
74 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
75  cl::desc("Disable Machine Common Subexpression Elimination"));
77  "optimize-regalloc", cl::Hidden,
78  cl::desc("Enable optimized register allocation compilation path."));
79 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
80  cl::Hidden,
81  cl::desc("Disable Machine LICM"));
82 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
83  cl::desc("Disable Machine Sinking"));
84 static cl::opt<bool> DisablePostRAMachineSink("disable-postra-machine-sink",
85  cl::Hidden,
86  cl::desc("Disable PostRA Machine Sinking"));
87 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
88  cl::desc("Disable Loop Strength Reduction Pass"));
89 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
90  cl::Hidden, cl::desc("Disable ConstantHoisting"));
91 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
92  cl::desc("Disable Codegen Prepare"));
93 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
94  cl::desc("Disable Copy Propagation pass"));
95 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
96  cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
98  "enable-implicit-null-checks",
99  cl::desc("Fold null checks into faulting memory operations"),
100  cl::init(false), cl::Hidden);
101 static cl::opt<bool> DisableMergeICmps("disable-mergeicmps",
102  cl::desc("Disable MergeICmps Pass"),
103  cl::init(false), cl::Hidden);
104 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
105  cl::desc("Print LLVM IR produced by the loop-reduce pass"));
106 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
107  cl::desc("Print LLVM IR input to isel pass"));
108 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
109  cl::desc("Dump garbage collector data"));
110 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
111  cl::desc("Verify generated machine code"),
112  cl::init(false),
115 // Enable or disable the MachineOutliner.
117  "enable-machine-outliner", cl::desc("Enable the machine outliner"),
118  cl::Hidden, cl::ValueOptional, cl::init(TargetDefault),
120  "Run on all functions guaranteed to be beneficial"),
121  clEnumValN(NeverOutline, "never", "Disable all outlining"),
122  // Sentinel value for unspecified option.
123  clEnumValN(AlwaysOutline, "", "")));
124 // Enable or disable FastISel. Both options are needed, because
125 // FastISel is enabled by default with -fast, and we wish to be
126 // able to enable or disable fast-isel independently from -O0.
128 EnableFastISelOption("fast-isel", cl::Hidden,
129  cl::desc("Enable the \"fast\" instruction selector"));
130 
132  "global-isel", cl::Hidden,
133  cl::desc("Enable the \"global\" instruction selector"));
134 
136  "print-machineinstrs", cl::ValueOptional, cl::desc("Print machine instrs"),
137  cl::value_desc("pass-name"), cl::init("option-unspecified"), cl::Hidden);
138 
140  "global-isel-abort", cl::Hidden,
141  cl::desc("Enable abort calls when \"global\" instruction selection "
142  "fails to lower/select an instruction: 0 disable the abort, "
143  "1 enable the abort, and "
144  "2 disable the abort but emit a diagnostic on failure"),
145  cl::init(1));
146 
147 // Temporary option to allow experimenting with MachineScheduler as a post-RA
148 // scheduler. Targets can "properly" enable this with
149 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
150 // Targets can return true in targetSchedulesPostRAScheduling() and
151 // insert a PostRA scheduling pass wherever it wants.
152 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
153  cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
154 
155 // Experimental option to run live interval analysis early.
156 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
157  cl::desc("Run live interval analysis earlier in the pipeline"));
158 
159 // Experimental option to use CFL-AA in codegen
162  "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
163  cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
164  cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
166  "Enable unification-based CFL-AA"),
168  "Enable inclusion-based CFL-AA"),
169  clEnumValN(CFLAAType::Both, "both",
170  "Enable both variants of CFL-AA")));
171 
172 /// Option names for limiting the codegen pipeline.
173 /// Those are used in error reporting and we didn't want
174 /// to duplicate their names all over the place.
175 const char *StartAfterOptName = "start-after";
176 const char *StartBeforeOptName = "start-before";
177 const char *StopAfterOptName = "stop-after";
178 const char *StopBeforeOptName = "stop-before";
179 
181  StartAfterOpt(StringRef(StartAfterOptName),
182  cl::desc("Resume compilation after a specific pass"),
183  cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
184 
186  StartBeforeOpt(StringRef(StartBeforeOptName),
187  cl::desc("Resume compilation before a specific pass"),
188  cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
189 
191  StopAfterOpt(StringRef(StopAfterOptName),
192  cl::desc("Stop compilation after a specific pass"),
193  cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
194 
196  StopBeforeOpt(StringRef(StopBeforeOptName),
197  cl::desc("Stop compilation before a specific pass"),
198  cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
199 
200 /// Allow standard passes to be disabled by command line options. This supports
201 /// simple binary flags that either suppress the pass or do nothing.
202 /// i.e. -disable-mypass=false has no effect.
203 /// These should be converted to boolOrDefault in order to use applyOverride.
205  bool Override) {
206  if (Override)
207  return IdentifyingPassPtr();
208  return PassID;
209 }
210 
211 /// Allow standard passes to be disabled by the command line, regardless of who
212 /// is adding the pass.
213 ///
214 /// StandardID is the pass identified in the standard pass pipeline and provided
215 /// to addPass(). It may be a target-specific ID in the case that the target
216 /// directly adds its own pass, but in that case we harmlessly fall through.
217 ///
218 /// TargetID is the pass that the target has configured to override StandardID.
219 ///
220 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
221 /// pass to run. This allows multiple options to control a single pass depending
222 /// on where in the pipeline that pass is added.
224  IdentifyingPassPtr TargetID) {
225  if (StandardID == &PostRASchedulerID)
226  return applyDisable(TargetID, DisablePostRASched);
227 
228  if (StandardID == &BranchFolderPassID)
229  return applyDisable(TargetID, DisableBranchFold);
230 
231  if (StandardID == &TailDuplicateID)
232  return applyDisable(TargetID, DisableTailDuplicate);
233 
234  if (StandardID == &EarlyTailDuplicateID)
235  return applyDisable(TargetID, DisableEarlyTailDup);
236 
237  if (StandardID == &MachineBlockPlacementID)
238  return applyDisable(TargetID, DisableBlockPlacement);
239 
240  if (StandardID == &StackSlotColoringID)
241  return applyDisable(TargetID, DisableSSC);
242 
243  if (StandardID == &DeadMachineInstructionElimID)
244  return applyDisable(TargetID, DisableMachineDCE);
245 
246  if (StandardID == &EarlyIfConverterID)
247  return applyDisable(TargetID, DisableEarlyIfConversion);
248 
249  if (StandardID == &EarlyMachineLICMID)
250  return applyDisable(TargetID, DisableMachineLICM);
251 
252  if (StandardID == &MachineCSEID)
253  return applyDisable(TargetID, DisableMachineCSE);
254 
255  if (StandardID == &MachineLICMID)
256  return applyDisable(TargetID, DisablePostRAMachineLICM);
257 
258  if (StandardID == &MachineSinkingID)
259  return applyDisable(TargetID, DisableMachineSink);
260 
261  if (StandardID == &PostRAMachineSinkingID)
262  return applyDisable(TargetID, DisablePostRAMachineSink);
263 
264  if (StandardID == &MachineCopyPropagationID)
265  return applyDisable(TargetID, DisableCopyProp);
266 
267  return TargetID;
268 }
269 
270 //===---------------------------------------------------------------------===//
271 /// TargetPassConfig
272 //===---------------------------------------------------------------------===//
273 
274 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
275  "Target Pass Configuration", false, false)
276 char TargetPassConfig::ID = 0;
277 
278 namespace {
279 
280 struct InsertedPass {
285 
286  InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
287  bool VerifyAfter, bool PrintAfter)
288  : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
289  VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
290 
292  assert(InsertedPassID.isValid() && "Illegal Pass ID!");
293  if (InsertedPassID.isInstance())
294  return InsertedPassID.getInstance();
295  Pass *NP = Pass::createPass(InsertedPassID.getID());
296  assert(NP && "Pass ID not registered");
297  return NP;
298  }
299 };
300 
301 } // end anonymous namespace
302 
303 namespace llvm {
304 
306 public:
307  // List of passes explicitly substituted by this target. Normally this is
308  // empty, but it is a convenient way to suppress or replace specific passes
309  // that are part of a standard pass pipeline without overridding the entire
310  // pipeline. This mechanism allows target options to inherit a standard pass's
311  // user interface. For example, a target may disable a standard pass by
312  // default by substituting a pass ID of zero, and the user may still enable
313  // that standard pass with an explicit command line option.
315 
316  /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
317  /// is inserted after each instance of the first one.
319 };
320 
321 } // end namespace llvm
322 
323 // Out of line virtual method.
325  delete Impl;
326 }
327 
328 static const PassInfo *getPassInfo(StringRef PassName) {
329  if (PassName.empty())
330  return nullptr;
331 
333  const PassInfo *PI = PR.getPassInfo(PassName);
334  if (!PI)
335  report_fatal_error(Twine('\"') + Twine(PassName) +
336  Twine("\" pass is not registered."));
337  return PI;
338 }
339 
341  const PassInfo *PI = getPassInfo(PassName);
342  return PI ? PI->getTypeInfo() : nullptr;
343 }
344 
345 void TargetPassConfig::setStartStopPasses() {
346  StartBefore = getPassIDFromName(StartBeforeOpt);
347  StartAfter = getPassIDFromName(StartAfterOpt);
348  StopBefore = getPassIDFromName(StopBeforeOpt);
349  StopAfter = getPassIDFromName(StopAfterOpt);
350  if (StartBefore && StartAfter)
351  report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
352  Twine(StartAfterOptName) + Twine(" specified!"));
353  if (StopBefore && StopAfter)
354  report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
355  Twine(StopAfterOptName) + Twine(" specified!"));
356  Started = (StartAfter == nullptr) && (StartBefore == nullptr);
357 }
358 
359 // Out of line constructor provides default values for pass options and
360 // registers all common codegen passes.
362  : ImmutablePass(ID), PM(&pm), TM(&TM) {
363  Impl = new PassConfigImpl();
364 
365  // Register all target independent codegen passes to activate their PassIDs,
366  // including this pass itself.
368 
369  // Also register alias analysis passes required by codegen passes.
372 
373  if (StringRef(PrintMachineInstrs.getValue()).equals(""))
374  TM.Options.PrintMachineCode = true;
375 
376  if (EnableIPRA.getNumOccurrences())
378  else {
379  // If not explicitly specified, use target default.
380  TM.Options.EnableIPRA = TM.useIPRA();
381  }
382 
383  if (TM.Options.EnableIPRA)
385 
386  setStartStopPasses();
387 }
388 
390  return TM->getOptLevel();
391 }
392 
393 /// Insert InsertedPassID pass after TargetPassID.
395  IdentifyingPassPtr InsertedPassID,
396  bool VerifyAfter, bool PrintAfter) {
397  assert(((!InsertedPassID.isInstance() &&
398  TargetPassID != InsertedPassID.getID()) ||
399  (InsertedPassID.isInstance() &&
400  TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
401  "Insert a pass after itself!");
402  Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
403  PrintAfter);
404 }
405 
406 /// createPassConfig - Create a pass configuration object to be used by
407 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
408 ///
409 /// Targets may override this to extend TargetPassConfig.
411  return new TargetPassConfig(*this, PM);
412 }
413 
415  : ImmutablePass(ID) {
416  report_fatal_error("Trying to construct TargetPassConfig without a target "
417  "machine. Scheduling a CodeGen pass without a target "
418  "triple set?");
419 }
420 
422  return StartBefore || StartAfter || StopBefore || StopAfter;
423 }
424 
425 std::string
428  return std::string();
429  std::string Res;
430  static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
432  static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
433  StopAfterOptName, StopBeforeOptName};
434  bool IsFirst = true;
435  for (int Idx = 0; Idx < 4; ++Idx)
436  if (!PassNames[Idx]->empty()) {
437  if (!IsFirst)
438  Res += Separator;
439  IsFirst = false;
440  Res += OptNames[Idx];
441  }
442  return Res;
443 }
444 
445 // Helper to verify the analysis is really immutable.
446 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
447  assert(!Initialized && "PassConfig is immutable");
448  Opt = Val;
449 }
450 
452  IdentifyingPassPtr TargetID) {
453  Impl->TargetPasses[StandardID] = TargetID;
454 }
455 
458  I = Impl->TargetPasses.find(ID);
459  if (I == Impl->TargetPasses.end())
460  return ID;
461  return I->second;
462 }
463 
466  IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
467  return !FinalPtr.isValid() || FinalPtr.isInstance() ||
468  FinalPtr.getID() != ID;
469 }
470 
471 /// Add a pass to the PassManager if that pass is supposed to be run. If the
472 /// Started/Stopped flags indicate either that the compilation should start at
473 /// a later pass or that it should stop after an earlier pass, then do not add
474 /// the pass. Finally, compare the current pass against the StartAfter
475 /// and StopAfter options and change the Started/Stopped flags accordingly.
476 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
477  assert(!Initialized && "PassConfig is immutable");
478 
479  // Cache the Pass ID here in case the pass manager finds this pass is
480  // redundant with ones already scheduled / available, and deletes it.
481  // Fundamentally, once we add the pass to the manager, we no longer own it
482  // and shouldn't reference it.
483  AnalysisID PassID = P->getPassID();
484 
485  if (StartBefore == PassID)
486  Started = true;
487  if (StopBefore == PassID)
488  Stopped = true;
489  if (Started && !Stopped) {
490  std::string Banner;
491  // Construct banner message before PM->add() as that may delete the pass.
492  if (AddingMachinePasses && (printAfter || verifyAfter))
493  Banner = std::string("After ") + std::string(P->getPassName());
494  PM->add(P);
495  if (AddingMachinePasses) {
496  if (printAfter)
497  addPrintPass(Banner);
498  if (verifyAfter)
499  addVerifyPass(Banner);
500  }
501 
502  // Add the passes after the pass P if there is any.
503  for (auto IP : Impl->InsertedPasses) {
504  if (IP.TargetPassID == PassID)
505  addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
506  }
507  } else {
508  delete P;
509  }
510  if (StopAfter == PassID)
511  Stopped = true;
512  if (StartAfter == PassID)
513  Started = true;
514  if (Stopped && !Started)
515  report_fatal_error("Cannot stop compilation after pass that is not run");
516 }
517 
518 /// Add a CodeGen pass at this point in the pipeline after checking for target
519 /// and command line overrides.
520 ///
521 /// addPass cannot return a pointer to the pass instance because is internal the
522 /// PassManager and the instance we create here may already be freed.
524  bool printAfter) {
525  IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
526  IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
527  if (!FinalPtr.isValid())
528  return nullptr;
529 
530  Pass *P;
531  if (FinalPtr.isInstance())
532  P = FinalPtr.getInstance();
533  else {
534  P = Pass::createPass(FinalPtr.getID());
535  if (!P)
536  llvm_unreachable("Pass ID not registered");
537  }
538  AnalysisID FinalID = P->getPassID();
539  addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
540 
541  return FinalID;
542 }
543 
544 void TargetPassConfig::printAndVerify(const std::string &Banner) {
545  addPrintPass(Banner);
546  addVerifyPass(Banner);
547 }
548 
549 void TargetPassConfig::addPrintPass(const std::string &Banner) {
550  if (TM->shouldPrintMachineCode())
551  PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
552 }
553 
554 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
555  bool Verify = VerifyMachineCode;
556 #ifdef EXPENSIVE_CHECKS
558  Verify = TM->isMachineVerifierClean();
559 #endif
560  if (Verify)
561  PM->add(createMachineVerifierPass(Banner));
562 }
563 
564 /// Add common target configurable passes that perform LLVM IR to IR transforms
565 /// following machine independent optimization.
567  switch (UseCFLAA) {
570  break;
571  case CFLAAType::Andersen:
573  break;
574  case CFLAAType::Both:
577  break;
578  default:
579  break;
580  }
581 
582  // Basic AliasAnalysis support.
583  // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
584  // BasicAliasAnalysis wins if they disagree. This is intended to help
585  // support "obvious" type-punning idioms.
589 
590  // Before running any passes, run the verifier to determine if the input
591  // coming from the front-end and/or optimizer is valid.
592  if (!DisableVerify)
594 
595  // Run loop strength reduction before anything else.
596  if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
598  if (PrintLSR)
599  addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
600  }
601 
602  if (getOptLevel() != CodeGenOpt::None) {
603  // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
604  // loads and compares. ExpandMemCmpPass then tries to expand those calls
605  // into optimally-sized loads and compares. The transforms are enabled by a
606  // target lowering hook.
607  if (!DisableMergeICmps)
610  }
611 
612  // Run GC lowering passes for builtin collectors
613  // TODO: add a pass insertion point here
616 
617  // Make sure that no unreachable blocks are instruction selected.
619 
620  // Prepare expensive constants for SelectionDAG.
623 
626 
627  // Instrument function entry and exit, e.g. with calls to mcount().
629 
630  // Add scalarization of target's unsupported masked memory intrinsics pass.
631  // the unsupported intrinsic will be replaced with a chain of basic blocks,
632  // that stores/loads element one-by-one if the appropriate mask bit is set.
634 
635  // Expand reduction intrinsics into shuffle sequences if the target wants to.
637 }
638 
639 /// Turn exception handling constructs into something the code generators can
640 /// handle.
642  const MCAsmInfo *MCAI = TM->getMCAsmInfo();
643  assert(MCAI && "No MCAsmInfo");
644  switch (MCAI->getExceptionHandlingType()) {
646  // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
647  // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
648  // catch info can get misplaced when a selector ends up more than one block
649  // removed from the parent invoke(s). This could happen when a landing
650  // pad is shared by multiple invokes and is also a target of a normal
651  // edge from elsewhere.
657  break;
659  // We support using both GCC-style and MSVC-style exceptions on Windows, so
660  // add both preparation passes. Each pass will only actually run if it
661  // recognizes the personality function.
664  break;
666  // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
667  // on catchpads and cleanuppads because it does not outline them into
668  // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
669  // should remove PHIs there.
670  addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
672  break;
675 
676  // The lower invoke pass may create unreachable code. Remove it.
678  break;
679  }
680 }
681 
682 /// Add pass to prepare the LLVM IR for code generation. This should be done
683 /// before exception handling preparation passes.
688 }
689 
690 /// Add common passes that perform LLVM IR to IR transforms in preparation for
691 /// instruction selection.
693  addPreISel();
694 
695  // Force codegen to run according to the callgraph.
697  addPass(new DummyCGSCCPass);
698 
699  // Add both the safe stack and the stack protection passes: each of them will
700  // only protect functions that have corresponding attributes.
703 
704  if (PrintISelInput)
706  dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
707 
708  // All passes which modify the LLVM IR are now complete; run the verifier
709  // to ensure that the IR is valid.
710  if (!DisableVerify)
712 }
713 
715  // Enable FastISel with -fast-isel, but allow that to be overridden.
716  TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
717  if (EnableFastISelOption == cl::BOU_TRUE ||
719  TM->setFastISel(true);
720 
721  // Ask the target for an instruction selector.
722  // Explicitly enabling fast-isel should override implicitly enabled
723  // global-isel.
724  if (EnableGlobalISelOption == cl::BOU_TRUE ||
725  (EnableGlobalISelOption == cl::BOU_UNSET &&
726  TM->Options.EnableGlobalISel && EnableFastISelOption != cl::BOU_TRUE)) {
727  TM->setFastISel(false);
728 
729  if (addIRTranslator())
730  return true;
731 
733 
734  if (addLegalizeMachineIR())
735  return true;
736 
737  // Before running the register bank selector, ask the target if it
738  // wants to run some passes.
740 
741  if (addRegBankSelect())
742  return true;
743 
745 
747  return true;
748 
749  // Pass to reset the MachineFunction if the ISel failed.
752 
753  // Provide a fallback path when we do not want to abort on
754  // not-yet-supported input.
756  return true;
757 
758  } else if (addInstSelector())
759  return true;
760 
761  return false;
762 }
763 
765  if (TM->useEmulatedTLS())
767 
770  addIRPasses();
773  addISelPrepare();
774 
775  return addCoreISelPasses();
776 }
777 
778 /// -regalloc=... command line option.
779 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
783  cl::desc("Register allocator to use"));
784 
785 /// Add the complete set of target-independent postISel code generator passes.
786 ///
787 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
788 /// with nontrivial configuration or multiple passes are broken out below in
789 /// add%Stage routines.
790 ///
791 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
792 /// addPre/Post methods with empty header implementations allow injecting
793 /// target-specific fixups just before or after major stages. Additionally,
794 /// targets have the flexibility to change pass order within a stage by
795 /// overriding default implementation of add%Stage routines below. Each
796 /// technique has maintainability tradeoffs because alternate pass orders are
797 /// not well supported. addPre/Post works better if the target pass is easily
798 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
799 /// the target should override the stage instead.
800 ///
801 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
802 /// before/after any target-independent pass. But it's currently overkill.
804  AddingMachinePasses = true;
805 
806  // Insert a machine instr printer pass after the specified pass.
807  if (!StringRef(PrintMachineInstrs.getValue()).equals("") &&
808  !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) {
810  const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
811  const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
812  assert (TPI && IPI && "Pass ID not registered!");
813  const char *TID = (const char *)(TPI->getTypeInfo());
814  const char *IID = (const char *)(IPI->getTypeInfo());
815  insertPass(TID, IID);
816  }
817 
818  // Print the instruction selected machine code...
819  printAndVerify("After Instruction Selection");
820 
821  // Expand pseudo-instructions emitted by ISel.
823 
824  // Add passes that optimize machine instructions in SSA form.
825  if (getOptLevel() != CodeGenOpt::None) {
827  } else {
828  // If the target requests it, assign local variables to stack slots relative
829  // to one another and simplify frame index references where possible.
831  }
832 
833  if (TM->Options.EnableIPRA)
835 
836  // Run pre-ra passes.
837  addPreRegAlloc();
838 
839  // Run register allocation and passes that are tightly coupled with it,
840  // including phi elimination and scheduling.
841  if (getOptimizeRegAlloc())
843  else {
844  if (RegAlloc != &useDefaultRegisterAllocator &&
845  RegAlloc != &createFastRegisterAllocator)
846  report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
848  }
849 
850  // Run post-ra passes.
851  addPostRegAlloc();
852 
853  // Insert prolog/epilog code. Eliminate abstract frame index references...
854  if (getOptLevel() != CodeGenOpt::None) {
857  }
858 
859  // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
860  // do so if it hasn't been disabled, substituted, or overridden.
863 
864  /// Add passes that optimize machine instructions after register allocation.
865  if (getOptLevel() != CodeGenOpt::None)
867 
868  // Expand pseudo instructions before second scheduling pass.
870 
871  // Run pre-sched2 passes.
872  addPreSched2();
873 
876 
877  // Second pass scheduler.
878  // Let Target optionally insert this pass by itself at some other
879  // point.
880  if (getOptLevel() != CodeGenOpt::None &&
882  if (MISchedPostRA)
884  else
886  }
887 
888  // GC
889  if (addGCPasses()) {
890  if (PrintGCInfo)
891  addPass(createGCInfoPrinter(dbgs()), false, false);
892  }
893 
894  // Basic block placement.
895  if (getOptLevel() != CodeGenOpt::None)
897 
898  addPreEmitPass();
899 
900  if (TM->Options.EnableIPRA)
901  // Collect register usage information and produce a register mask of
902  // clobbered registers, to be used to optimize call sites.
904 
905  addPass(&FuncletLayoutID, false);
906 
907  addPass(&StackMapLivenessID, false);
908  addPass(&LiveDebugValuesID, false);
909 
910  // Insert before XRay Instrumentation.
911  addPass(&FEntryInserterID, false);
912 
914  addPass(&PatchableFunctionID, false);
915 
917  EnableMachineOutliner != NeverOutline) {
918  bool RunOnAllFunctions = (EnableMachineOutliner == AlwaysOutline);
919  bool AddOutliner = RunOnAllFunctions ||
921  if (AddOutliner)
922  addPass(createMachineOutlinerPass(RunOnAllFunctions));
923  }
924 
925  // Add passes that directly emit MI after all other MI passes.
926  addPreEmitPass2();
927 
928  AddingMachinePasses = false;
929 }
930 
931 /// Add passes that optimize machine instructions in SSA form.
933  // Pre-ra tail duplication.
935 
936  // Optimize PHIs before DCE: removing dead PHI cycles may make more
937  // instructions dead.
938  addPass(&OptimizePHIsID, false);
939 
940  // This pass merges large allocas. StackSlotColoring is a different pass
941  // which merges spill slots.
942  addPass(&StackColoringID, false);
943 
944  // If the target requests it, assign local variables to stack slots relative
945  // to one another and simplify frame index references where possible.
947 
948  // With optimization, dead code should already be eliminated. However
949  // there is one known exception: lowered code for arguments that are only
950  // used by tail calls, where the tail calls reuse the incoming stack
951  // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
953 
954  // Allow targets to insert passes that improve instruction level parallelism,
955  // like if-conversion. Such passes will typically need dominator trees and
956  // loop info, just like LICM and CSE below.
957  addILPOpts();
958 
959  addPass(&EarlyMachineLICMID, false);
960  addPass(&MachineCSEID, false);
961 
963 
965  // Clean-up the dead code that may have been generated by peephole
966  // rewriting.
968 }
969 
970 //===---------------------------------------------------------------------===//
971 /// Register Allocation Pass Configuration
972 //===---------------------------------------------------------------------===//
973 
975  switch (OptimizeRegAlloc) {
976  case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
977  case cl::BOU_TRUE: return true;
978  case cl::BOU_FALSE: return false;
979  }
980  llvm_unreachable("Invalid optimize-regalloc state");
981 }
982 
983 /// RegisterRegAlloc's global Registry tracks allocator registration.
985 
986 /// A dummy default pass factory indicates whether the register allocator is
987 /// overridden on the command line.
989 
990 static RegisterRegAlloc
991 defaultRegAlloc("default",
992  "pick register allocator based on -O option",
994 
996  RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
997 
998  if (!Ctor) {
999  Ctor = RegAlloc;
1000  RegisterRegAlloc::setDefault(RegAlloc);
1001  }
1002 }
1003 
1004 /// Instantiate the default register allocator pass for this target for either
1005 /// the optimized or unoptimized allocation path. This will be added to the pass
1006 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1007 /// in the optimized case.
1008 ///
1009 /// A target that uses the standard regalloc pass order for fast or optimized
1010 /// allocation may still override this for per-target regalloc
1011 /// selection. But -regalloc=... always takes precedence.
1013  if (Optimized)
1015  else
1016  return createFastRegisterAllocator();
1017 }
1018 
1019 /// Find and instantiate the register allocation pass requested by this target
1020 /// at the current optimization level. Different register allocators are
1021 /// defined as separate passes because they may require different analysis.
1022 ///
1023 /// This helper ensures that the regalloc= option is always available,
1024 /// even for targets that override the default allocator.
1025 ///
1026 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
1027 /// this can be folded into addPass.
1029  // Initialize the global default.
1030  llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
1032 
1033  RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1034  if (Ctor != useDefaultRegisterAllocator)
1035  return Ctor();
1036 
1037  // With no -regalloc= override, ask the target for a regalloc pass.
1038  return createTargetRegisterAllocator(Optimized);
1039 }
1040 
1041 /// Return true if the default global register allocator is in use and
1042 /// has not be overriden on the command line with '-regalloc=...'
1044  return RegAlloc.getNumOccurrences() == 0;
1045 }
1046 
1047 /// Add the minimum set of target-independent passes that are required for
1048 /// register allocation. No coalescing or scheduling.
1050  addPass(&PHIEliminationID, false);
1052 
1053  if (RegAllocPass)
1054  addPass(RegAllocPass);
1055 }
1056 
1057 /// Add standard target-independent passes that are tightly coupled with
1058 /// optimized register allocation, including coalescing, machine instruction
1059 /// scheduling, and register allocation itself.
1061  addPass(&DetectDeadLanesID, false);
1062 
1063  addPass(&ProcessImplicitDefsID, false);
1064 
1065  // LiveVariables currently requires pure SSA form.
1066  //
1067  // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1068  // LiveVariables can be removed completely, and LiveIntervals can be directly
1069  // computed. (We still either need to regenerate kill flags after regalloc, or
1070  // preferably fix the scavenger to not depend on them).
1071  addPass(&LiveVariablesID, false);
1072 
1073  // Edge splitting is smarter with machine loop info.
1074  addPass(&MachineLoopInfoID, false);
1075  addPass(&PHIEliminationID, false);
1076 
1077  // Eventually, we want to run LiveIntervals before PHI elimination.
1078  if (EarlyLiveIntervals)
1079  addPass(&LiveIntervalsID, false);
1080 
1083 
1084  // The machine scheduler may accidentally create disconnected components
1085  // when moving subregister definitions around, avoid this by splitting them to
1086  // separate vregs before. Splitting can also improve reg. allocation quality.
1088 
1089  // PreRA instruction scheduling.
1091 
1092  if (RegAllocPass) {
1093  // Add the selected register allocation pass.
1094  addPass(RegAllocPass);
1095 
1096  // Allow targets to change the register assignments before rewriting.
1097  addPreRewrite();
1098 
1099  // Finally rewrite virtual registers.
1101 
1102  // Perform stack slot coloring and post-ra machine LICM.
1103  //
1104  // FIXME: Re-enable coloring with register when it's capable of adding
1105  // kill markers.
1107 
1108  // Copy propagate to forward register uses and try to eliminate COPYs that
1109  // were not coalesced.
1111 
1112  // Run post-ra machine LICM to hoist reloads / remats.
1113  //
1114  // FIXME: can this move into MachineLateOptimization?
1116  }
1117 }
1118 
1119 //===---------------------------------------------------------------------===//
1120 /// Post RegAlloc Pass Configuration
1121 //===---------------------------------------------------------------------===//
1122 
1123 /// Add passes that optimize machine instructions after register allocation.
1125  // Branch folding must be run after regalloc and prolog/epilog insertion.
1127 
1128  // Tail duplication.
1129  // Note that duplicating tail just increases code size and degrades
1130  // performance for targets that require Structured Control Flow.
1131  // In addition it can also make CFG irreducible. Thus we disable it.
1132  if (!TM->requiresStructuredCFG())
1134 
1135  // Copy propagation.
1137 }
1138 
1139 /// Add standard GC passes.
1142  return true;
1143 }
1144 
1145 /// Add standard basic block placement passes.
1148  // Run a separate pass to collect block placement statistics.
1151  }
1152 }
1153 
1154 //===---------------------------------------------------------------------===//
1155 /// GlobalISel Configuration
1156 //===---------------------------------------------------------------------===//
1158  if (EnableGlobalISelAbort.getNumOccurrences() > 0)
1159  return EnableGlobalISelAbort == 1;
1160 
1161  // When no abort behaviour is specified, we don't abort if the target says
1162  // that GISel is enabled.
1163  return !TM->Options.EnableGlobalISel;
1164 }
1165 
1167  return EnableGlobalISelAbort == 2;
1168 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
const PassInfo * getPassInfo(const void *TI) const
getPassInfo - Look up a pass&#39; corresponding PassInfo, indexed by the pass&#39; type identifier (&MyPass::...
static cl::opt< bool > EnableBlockPlacementStats("enable-block-placement-stats", cl::Hidden, cl::desc("Collect probability-driven block placement stats"))
FunctionPass * createExpandReductionsPass()
This pass expands the experimental reduction intrinsics into sequences of shuffles.
static cl::opt< std::string > StartBeforeOpt(StringRef(StartBeforeOptName), cl::desc("Resume compilation before a specific pass"), cl::value_desc("pass-name"), cl::init(""), cl::Hidden)
static cl::opt< bool > DisableCopyProp("disable-copyprop", cl::Hidden, cl::desc("Disable Copy Propagation pass"))
static cl::opt< bool > DisableCGP("disable-cgp", cl::Hidden, cl::desc("Disable Codegen Prepare"))
unsigned PrintMachineCode
PrintMachineCode - This flag is enabled when the -print-machineinstrs option is specified on the comm...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static cl::opt< bool > DisableMachineLICM("disable-machine-licm", cl::Hidden, cl::desc("Disable Machine LICM"))
char & RenameIndependentSubregsID
This pass detects subregister lanes in a virtual register that are used independently of other lanes ...
static cl::opt< bool > PrintISelInput("print-isel-input", cl::Hidden, cl::desc("Print LLVM IR input to isel pass"))
Pass * createLoopStrengthReducePass()
This is the interface for LLVM&#39;s inclusion-based alias analysis implemented with CFL graph reachabili...
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:119
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
bool getOptimizeRegAlloc() const
Return true if the optimized regalloc pipeline is enabled.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
char & FEntryInserterID
This pass inserts FEntry calls.
virtual void addPreEmitPass2()
Targets may add passes immediately before machine code is emitted in this callback.
static llvm::once_flag InitializeDefaultRegisterAllocatorFlag
A dummy default pass factory indicates whether the register allocator is overridden on the command li...
char & MachineLICMID
This pass performs loop invariant code motion on machine instructions.
DWARF-like instruction based exceptions.
virtual bool addPreRewrite()
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
char & FuncletLayoutID
This pass lays out funclets contiguously.
bool requiresStructuredCFG() const
static cl::opt< bool > DisablePostRAMachineSink("disable-postra-machine-sink", cl::Hidden, cl::desc("Disable PostRA Machine Sinking"))
virtual bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path...
unsigned EnableMachineOutliner
Enables the MachineOutliner pass.
This is the interface for a metadata-based scoped no-alias analysis.
FunctionPass * createExpandMemCmpPass()
FunctionPass * createPrintFunctionPass(raw_ostream &OS, const std::string &Banner="")
Create and return a pass that prints functions to the specified raw_ostream as they are processed...
bool addISelPasses()
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
FunctionPass * createVerifierPass(bool FatalErrors=true)
Definition: Verifier.cpp:5094
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
void setO0WantsFastISel(bool Enable)
char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
char & EarlyIfConverterID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions...
static cl::opt< bool > DisablePartialLibcallInlining("disable-partial-libcall-inlining", cl::Hidden, cl::desc("Disable Partial Libcall Inlining"))
bool requiresCodeGenSCCOrder() const
static cl::opt< bool > DisableLSR("disable-lsr", cl::Hidden, cl::desc("Disable Loop Strength Reduction Pass"))
bool isPassSubstitutedOrOverridden(AnalysisID ID) const
Return true if the pass has been substituted by the target or overridden on the command line...
static void setDefault(FunctionPassCtor C)
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
static cl::opt< bool > EarlyLiveIntervals("early-live-intervals", cl::Hidden, cl::desc("Run live interval analysis earlier in the pipeline"))
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
setjmp/longjmp based exceptions
RegisterPassParser class - Handle the addition of new machine passes.
static cl::opt< bool > PrintGCInfo("print-gc", cl::Hidden, cl::desc("Dump garbage collector data"))
static MachinePassRegistry Registry
RegisterRegAlloc&#39;s global Registry tracks allocator registration.
char & ProcessImplicitDefsID
ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
static void initializeDefaultRegisterAllocatorOnce()
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form...
FunctionPass * createShadowStackGCLoweringPass()
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC...
char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:75
void setRequiresCodeGenSCCOrder(bool Enable=true)
char & MachineBlockPlacementStatsID
MachineBlockPlacementStats - This pass collects statistics about the basic block placement using bran...
ImmutablePass * createScopedNoAliasAAWrapperPass()
CodeGenOpt::Level getOptLevel() const
const char * StopBeforeOptName
bool hasLimitedCodeGenPipeline() const
Describe the status of the codegen pipeline set by this target pass config.
virtual TargetPassConfig * createPassConfig(PassManagerBase &PM)
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
cl::opt< bool > EnableIPRA("enable-ipra", cl::init(false), cl::Hidden, cl::desc("Enable interprocedural register allocation " "to reduce load/store at procedure calls."))
FunctionPass * createScalarizeMaskedMemIntrinPass()
createScalarizeMaskedMemIntrinPass - Replace masked load, store, gather and scatter intrinsics with s...
virtual void addPreEmitPass()
This pass may be implemented by targets that want to run passes immediately before machine code is em...
MachineFunctionPass * createResetMachineFunctionPass(bool EmitFallbackDiag, bool AbortOnFailedISel)
This pass resets a MachineFunction when it has the FailedISel property as if it was just created...
FunctionPass * createMachineVerifierPass(const std::string &Banner)
createMachineVerifierPass - This pass verifies cenerated machine code instructions for correctness...
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
FunctionPass * createGCLoweringPass()
GCLowering Pass - Used by gc.root to perform its default lowering operations.
virtual bool addLegalizeMachineIR()
This method should install a legalize pass, which converts the instruction sequence into one that can...
unsigned EnableIPRA
This flag enables InterProcedural Register Allocation (IPRA).
FunctionPass * createLowerInvokePass()
Definition: LowerInvoke.cpp:86
char & StackColoringID
StackSlotColoring - This pass performs stack coloring and merging.
FunctionPass * createSafeStackPass()
This pass splits the stack into a safe stack and an unsafe stack to protect against stack-based overf...
Definition: SafeStack.cpp:903
static const PassInfo * getPassInfo(StringRef PassName)
virtual void addPreSched2()
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
Pass * createMergeICmpsPass()
Definition: MergeICmps.cpp:797
FunctionPass * createRegAllocPass(bool Optimized)
addMachinePasses helper to create the target-selected or overriden regalloc pass. ...
FunctionPass * createRegUsageInfoCollector()
This pass is executed POST-RA to collect which physical registers are preserved by given machine func...
MachineFunctionPass * createPrologEpilogInserterPass()
Target-Independent Code Generator Pass Configuration Options.
virtual bool isMachineVerifierClean() const
Returns true if the target is expected to pass all machine verifier checks.
void initializeAAResultsWrapperPassPass(PassRegistry &)
static cl::opt< bool > DisableMergeICmps("disable-mergeicmps", cl::desc("Disable MergeICmps Pass"), cl::init(false), cl::Hidden)
char & XRayInstrumentationID
This pass inserts the XRay instrumentation sleds if they are supported by the target platform...
static cl::opt< bool > DisableConstantHoisting("disable-constant-hoisting", cl::Hidden, cl::desc("Disable ConstantHoisting"))
FunctionPass * createPartiallyInlineLibCallsPass()
char & EarlyTailDuplicateID
Duplicate blocks with unconditional branches into tails of their predecessors.
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
ppc ctr loops PowerPC CTR Loops Verify
char & MachineCSEID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:134
static IdentifyingPassPtr overridePass(AnalysisID StandardID, IdentifyingPassPtr TargetID)
Allow standard passes to be disabled by the command line, regardless of who is adding the pass...
static cl::opt< RunOutliner > EnableMachineOutliner("enable-machine-outliner", cl::desc("Enable the machine outliner"), cl::Hidden, cl::ValueOptional, cl::init(TargetDefault), cl::values(clEnumValN(AlwaysOutline, "always", "Run on all functions guaranteed to be beneficial"), clEnumValN(NeverOutline, "never", "Disable all outlining"), clEnumValN(AlwaysOutline, "", "")))
AnalysisID getID() const
virtual void addPreLegalizeMachineIR()
This method may be implemented by targets that want to run passes immediately before legalization...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
LLVMTargetMachine * TM
char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
virtual void addPreRegAlloc()
This method may be implemented by targets that want to run passes immediately before register allocat...
char & ExpandPostRAPseudosID
ExpandPostRAPseudos - This pass expands pseudo instructions after register allocation.
static cl::opt< bool > DisablePostRAMachineLICM("disable-postra-machine-licm", cl::Hidden, cl::desc("Disable Machine LICM"))
char & ExpandISelPseudosID
ExpandISelPseudos - This pass expands pseudo-instructions.
char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
static cl::opt< bool > DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, cl::desc("Disable tail duplication"))
void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID)
Allow the target to override a specific pass without overriding the pass pipeline.
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
RegisterRegAlloc class - Track the registration of register allocators.
MachinePassRegistry - Track the registration of machine passes.
char & LiveIntervalsID
LiveIntervals - This analysis keeps track of the live ranges of virtual and physical registers...
virtual bool addILPOpts()
Add passes that optimize instruction level parallelism for out-of-order targets.
const void * getTypeInfo() const
getTypeInfo - Return the id object for the pass...
Definition: PassInfo.h:72
FunctionPass * createWasmEHPass()
createWasmEHPass - This pass adapts exception handling code to use WebAssembly&#39;s exception handling s...
static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID, bool Override)
Allow standard passes to be disabled by command line options.
const char * StartBeforeOptName
unsigned SupportsDefaultOutlining
Set if the target supports default outlining behaviour.
void call_once(once_flag &flag, Function &&F, Args &&... ArgList)
Execute the function specified as a parameter once.
Definition: Threading.h:99
FunctionPass * createGCInfoPrinter(raw_ostream &OS)
Creates a pass to print GC metadata.
Definition: GCMetadata.cpp:92
Windows Exception Handling.
unsigned EnableGlobalISel
EnableGlobalISel - This flag enables global instruction selection.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
DenseMap< AnalysisID, IdentifyingPassPtr > TargetPasses
char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions...
FunctionPass * createRegUsageInfoPropPass()
Return a MachineFunction pass that identifies call sites and propagates register usage information of...
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
SmallVector< InsertedPass, 4 > InsertedPasses
Store the pairs of <AnalysisID, AnalysisID> of which the second pass is inserted after each instance ...
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
virtual FunctionPass * createTargetRegisterAllocator(bool Optimized)
createTargetRegisterAllocator - Create the register allocator pass for this target at the current opt...
virtual bool addGCPasses()
addGCPasses - Add late codegen passes that analyze code for garbage collection.
static PassOptionList PrintAfter("print-after", llvm::cl::desc("Print IR after specified passes"), cl::Hidden)
#define P(N)
static cl::opt< bool > DisableEarlyTailDup("disable-early-taildup", cl::Hidden, cl::desc("Disable pre-register allocation tail duplication"))
This is the interface for LLVM&#39;s unification-based alias analysis implemented with CFL graph reachabi...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
This pass is required by interprocedural register allocation.
static cl::opt< bool > DisableSSC("disable-ssc", cl::Hidden, cl::desc("Disable Stack Slot Coloring"))
bool addCoreISelPasses()
Add the actual instruction selection passes.
This is the interface for a metadata-based TBAA.
void printAndVerify(const std::string &Banner)
printAndVerify - Add a pass to dump then verify the machine function, if those steps are enabled...
static cl::opt< std::string > PrintMachineInstrs("print-machineinstrs", cl::ValueOptional, cl::desc("Print machine instrs"), cl::value_desc("pass-name"), cl::init("option-unspecified"), cl::Hidden)
static cl::opt< cl::boolOrDefault > EnableGlobalISelOption("global-isel", cl::Hidden, cl::desc("Enable the \lobal\instruction selector"))
AnalysisID getPassID() const
getPassID - Return the PassID number that corresponds to this pass.
Definition: Pass.h:100
virtual bool useIPRA() const
True if the target wants to use interprocedural register allocation by default.
static cl::opt< std::string > StartAfterOpt(StringRef(StartAfterOptName), cl::desc("Resume compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""), cl::Hidden)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:630
static cl::opt< std::string > StopBeforeOpt(StringRef(StopBeforeOptName), cl::desc("Stop compilation before a specific pass"), cl::value_desc("pass-name"), cl::init(""), cl::Hidden)
virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass)
addOptimizedRegAlloc - Add passes related to register allocation.
char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
static cl::opt< bool > VerifyMachineCode("verify-machineinstrs", cl::Hidden, cl::desc("Verify generated machine code"), cl::init(false), cl::ZeroOrMore)
int getNumOccurrences() const
Definition: CommandLine.h:371
virtual void addMachineLateOptimization()
Add passes that optimize machine instructions after register allocation.
virtual bool addInstSelector()
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
char & LiveDebugValuesID
LiveDebugValues pass.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
virtual bool addPreISel()
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, bool VerifyAfter=true, bool PrintAfter=true)
Insert InsertedPassID pass after TargetPassID pass.
FunctionPass * createWinEHPass(bool DemoteCatchSwitchPHIOnly=false)
createWinEHPass - Prepares personality functions used by MSVC on Windows, in addition to the Itanium ...
virtual void addISelPrepare()
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection...
static cl::opt< bool > DisableMachineSink("disable-machine-sink", cl::Hidden, cl::desc("Disable Machine Sinking"))
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
std::once_flag once_flag
Definition: Threading.h:69
void pm(uint64_t &Value)
Adjusts a program memory address.
PassInfo class - An instance of this class exists for every pass known by the system, and can be obtained from a live Pass by calling its getPassInfo() method.
Definition: PassInfo.h:31
char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
static cl::opt< int > EnableGlobalISelAbort("global-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \lobal\instruction selection " "fails to lower/select an instruction: 0 disable the abort, " "1 enable the abort, and " "2 disable the abort but emit a diagnostic on failure"), cl::init(1))
char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
cl::opt< bool > MISchedPostRA("misched-postra", cl::Hidden, cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"))
void addPrintPass(const std::string &Banner)
Add a pass to print the machine function if printing is enabled.
ModulePass * createMachineOutlinerPass(bool RunOnAllFunctions=true)
This pass performs outlining on machine instructions directly before printing assembly.
char & ImplicitNullChecksID
ImplicitNullChecks - This pass folds null pointer checks into nearby memory operations.
void addPassesToHandleExceptions()
Add passes to lower exception handling for the code generator.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static cl::opt< bool > PrintLSR("print-lsr-output", cl::Hidden, cl::desc("Print LLVM IR produced by the loop-reduce pass"))
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
virtual void addPreRegBankSelect()
This method may be implemented by targets that want to run passes immediately before the register ban...
char & PostRASchedulerID
createPostRAScheduler - This pass performs post register allocation scheduling.
static cl::opt< bool > DisableBranchFold("disable-branch-fold", cl::Hidden, cl::desc("Disable branch folding"))
static FunctionPassCtor getDefault()
ModulePass * createLowerEmuTLSPass()
LowerEmuTLS - This pass generates __emutls_[vt].xyz variables for all TLS variables for the emulated ...
bool usingDefaultRegAlloc() const
Return true if the default global register allocator is in use and has not be overriden on the comman...
FunctionPass *(*)() FunctionPassCtor
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:256
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
static cl::opt< bool > DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden, cl::desc("Disable Early If-conversion"))
char & TailDuplicateID
TailDuplicate - Duplicate blocks with unconditional branches into tails of their predecessors.
char & MachineSinkingID
MachineSinking - This pass performs sinking on machine instructions.
static cl::opt< RegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< RegisterRegAlloc > > RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use"))
static cl::opt< cl::boolOrDefault > OptimizeRegAlloc("optimize-regalloc", cl::Hidden, cl::desc("Enable optimized register allocation compilation path."))
void setFastISel(bool Enable)
static cl::opt< bool > DisableMachineDCE("disable-machine-dce", cl::Hidden, cl::desc("Disable Machine Dead Code Elimination"))
char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
virtual bool addGlobalInstructionSelect()
This method should install a (global) instruction selector pass, which converts possibly generic inst...
virtual bool targetSchedulesPostRAScheduling() const
True if subtarget inserts the final scheduling pass on its own.
MachineFunctionPass * createMachineFunctionPrinterPass(raw_ostream &OS, const std::string &Banner="")
MachineFunctionPrinter pass - This pass prints out the machine function to the given stream as a debu...
ModulePass * createRewriteSymbolsPass()
char & OptimizePHIsID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, bool VerifyAfter, bool PrintAfter)
const void * AnalysisID
Definition: Pass.h:49
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
FunctionPass * createBasicAAWrapperPass()
std::string getLimitedCodeGenPipelineReason(const char *Separator="/") const
If hasLimitedCodeGenPipeline is true, this method returns a string with the name of the options...
char & PeepholeOptimizerID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
const char * StartAfterOptName
Option names for limiting the codegen pipeline.
FunctionPass * createPostInlineEntryExitInstrumenterPass()
Discriminated union of Pass ID types.
virtual bool addRegBankSelect()
This method should install a register bank selector pass, which assigns register banks to virtual reg...
virtual void addFastRegAlloc(FunctionPass *RegAllocPass)
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
FunctionPass * createCodeGenPreparePass()
createCodeGenPreparePass - Transform the code to expose more pattern matching during instruction sele...
char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:605
static cl::opt< std::string > StopAfterOpt(StringRef(StopAfterOptName), cl::desc("Stop compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""), cl::Hidden)
char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
static RegisterRegAlloc defaultRegAlloc("default", "pick register allocator based on -O option", useDefaultRegisterAllocator)
char & GCMachineCodeAnalysisID
GCMachineCodeAnalysis - Target-independent pass to mark safe points in machine code.
static cl::opt< bool > DisableBlockPlacement("disable-block-placement", cl::Hidden, cl::desc("Disable probability-driven block placement"))
virtual void addPreGlobalInstructionSelect()
This method may be implemented by targets that want to run passes immediately before the (global) ins...
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:652
char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
AnalysisID addPass(AnalysisID PassID, bool verifyAfter=true, bool printAfter=true)
Utilities for targets to add passes to the pass manager.
TargetOptions Options
Definition: TargetMachine.h:98
virtual void addBlockPlacement()
Add standard basic block placement passes.
FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
#define I(x, y, z)
Definition: MD5.cpp:58
char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const
Return the pass substituted for StandardID by the target.
void setOpt(bool &Opt, bool Val)
static cl::opt< bool > DisablePostRASched("disable-post-ra", cl::Hidden, cl::desc("Disable Post Regalloc Scheduler"))
ImmutablePass * createCFLSteensAAWrapperPass()
ImmutablePass * createTypeBasedAAWrapperPass()
bool shouldPrintMachineCode() const
This file defines passes to print out IR in various granularities.
void addVerifyPass(const std::string &Banner)
Add a pass to perform basic verification of the machine function if verification is enabled...
FunctionPass * createSjLjEHPreparePass()
createSjLjEHPreparePass - This pass adapts exception handling code to use the GCC-style builtin setjm...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Pass * createPass(AnalysisID ID)
Definition: Pass.cpp:217
void initializeCodeGen(PassRegistry &)
Initialize all passes linked into the CodeGen library.
Definition: CodeGen.cpp:22
FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
const char * StopAfterOptName
ModulePass * createPreISelIntrinsicLoweringPass()
This pass lowers the @llvm.load.relative intrinsic to instructions.
char & VirtRegRewriterID
VirtRegRewriter pass.
Definition: VirtRegMap.cpp:213
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:570
static cl::opt< CFLAAType > UseCFLAA("use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden, cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"), cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), clEnumValN(CFLAAType::Steensgaard, "steens", "Enable unification-based CFL-AA"), clEnumValN(CFLAAType::Andersen, "anders", "Enable inclusion-based CFL-AA"), clEnumValN(CFLAAType::Both, "both", "Enable both variants of CFL-AA")))
static cl::opt< cl::boolOrDefault > EnableFastISelOption("fast-isel", cl::Hidden, cl::desc("Enable the \ast\instruction selector"))
char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
static AnalysisID getPassIDFromName(StringRef PassName)
char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
Definition: ShrinkWrap.cpp:250
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:238
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:39
This pass exposes codegen information to IR-level passes.
No exception support.
static cl::opt< bool > EnableImplicitNullChecks("enable-implicit-null-checks", cl::desc("Fold null checks into faulting memory operations"), cl::init(false), cl::Hidden)
ImmutablePass * createCFLAndersAAWrapperPass()
char & LocalStackSlotAllocationID
LocalStackSlotAllocation - This pass assigns local frame indices to stack slots relative to one anoth...
virtual bool addIRTranslator()
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
static cl::opt< bool > DisableMachineCSE("disable-machine-cse", cl::Hidden, cl::desc("Disable Machine Common Subexpression Elimination"))
void initializeBasicAAWrapperPassPass(PassRegistry &)
FunctionPass * createConstantHoistingPass()
FunctionPass * createDwarfEHPass()
createDwarfEHPass - This pass mulches exception handling code into a form adapted to code generation...