LLVM 22.0.0git
CodeGenPassBuilder.h
Go to the documentation of this file.
1//===- Construction of codegen pass pipelines ------------------*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// Interfaces for producing common pass manager configurations.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_PASSES_CODEGENPASSBUILDER_H
15#define LLVM_PASSES_CODEGENPASSBUILDER_H
16
18#include "llvm/ADT/StringRef.h"
69#include "llvm/CodeGen/PEI.h"
106#include "llvm/IR/PassManager.h"
107#include "llvm/IR/Verifier.h"
109#include "llvm/MC/MCAsmInfo.h"
111#include "llvm/Support/CodeGen.h"
112#include "llvm/Support/Debug.h"
113#include "llvm/Support/Error.h"
130#include <cassert>
131#include <utility>
132
133namespace llvm {
134
135// FIXME: Dummy target independent passes definitions that have not yet been
136// ported to new pass manager. Once they do, remove these.
137#define DUMMY_FUNCTION_PASS(NAME, PASS_NAME) \
138 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
139 template <typename... Ts> PASS_NAME(Ts &&...) {} \
140 PreservedAnalyses run(Function &, FunctionAnalysisManager &) { \
141 return PreservedAnalyses::all(); \
142 } \
143 };
144#define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME) \
145 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
146 template <typename... Ts> PASS_NAME(Ts &&...) {} \
147 PreservedAnalyses run(Module &, ModuleAnalysisManager &) { \
148 return PreservedAnalyses::all(); \
149 } \
150 };
151#define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME) \
152 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
153 template <typename... Ts> PASS_NAME(Ts &&...) {} \
154 PreservedAnalyses run(MachineFunction &, \
155 MachineFunctionAnalysisManager &) { \
156 return PreservedAnalyses::all(); \
157 } \
158 };
159#include "llvm/Passes/MachinePassRegistry.def"
160
161/// This class provides access to building LLVM's passes.
162///
163/// Its members provide the baseline state available to passes during their
164/// construction. The \c MachinePassRegistry.def file specifies how to construct
165/// all of the built-in passes, and those may reference these members during
166/// construction.
167template <typename DerivedT, typename TargetMachineT> class CodeGenPassBuilder {
168public:
169 explicit CodeGenPassBuilder(TargetMachineT &TM,
170 const CGPassBuilderOption &Opts,
172 : TM(TM), Opt(Opts), PIC(PIC) {
173 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
174 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
175
176 // Target should override TM.Options.EnableIPRA in their target-specific
177 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
178 if (Opt.EnableIPRA) {
179 TM.Options.EnableIPRA = *Opt.EnableIPRA;
180 } else {
181 // If not explicitly specified, use target default.
182 TM.Options.EnableIPRA |= TM.useIPRA();
183 }
184
185 if (Opt.EnableGlobalISelAbort)
186 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
187
188 if (!Opt.OptimizeRegAlloc)
189 Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOptLevel::None;
190 }
191
193 raw_pwrite_stream *DwoOut,
194 CodeGenFileType FileType) const;
195
199
200protected:
201 template <typename PassT>
202 using is_module_pass_t = decltype(std::declval<PassT &>().run(
203 std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
204
205 template <typename PassT>
206 using is_function_pass_t = decltype(std::declval<PassT &>().run(
207 std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
208
209 template <typename PassT>
210 using is_machine_function_pass_t = decltype(std::declval<PassT &>().run(
211 std::declval<MachineFunction &>(),
212 std::declval<MachineFunctionAnalysisManager &>()));
213
214 // Function object to maintain state while adding codegen IR passes.
215 // TODO: add a Function -> MachineFunction adaptor and merge
216 // AddIRPass/AddMachinePass so we can have a function pipeline that runs both
217 // function passes and machine function passes.
218 class AddIRPass {
219 public:
220 AddIRPass(ModulePassManager &MPM, const DerivedT &PB) : MPM(MPM), PB(PB) {}
221 ~AddIRPass() { flushFPMToMPM(); }
222
223 template <typename PassT>
224 void operator()(PassT &&Pass, bool Force = false,
225 StringRef Name = PassT::name()) {
228 "Only module pass and function pass are supported.");
229 if (!Force && !PB.runBeforeAdding(Name))
230 return;
231
232 // Add Function Pass
234 FPM.addPass(std::forward<PassT>(Pass));
235 } else {
236 // Add Module Pass
237 flushFPMToMPM();
238 MPM.addPass(std::forward<PassT>(Pass));
239 }
240 }
241
242 /// Setting this will add passes to the CGSCC pass manager.
244 if (PB.AddInCGSCCOrder)
245 return;
246 flushFPMToMPM();
247 PB.AddInCGSCCOrder = true;
248 }
249
250 /// Stop adding passes to the CGSCC pass manager.
251 /// Existing passes won't be removed.
253 if (!PB.AddInCGSCCOrder)
254 return;
255 flushFPMToMPM();
256 PB.AddInCGSCCOrder = false;
257 }
258
259 private:
260 void flushFPMToMPM() {
261 if (FPM.isEmpty())
262 return;
263 if (PB.AddInCGSCCOrder) {
265 createCGSCCToFunctionPassAdaptor(std::move(FPM))));
266 } else {
267 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
268 }
269 FPM = FunctionPassManager();
270 }
273 const DerivedT &PB;
274 };
275
276 // Function object to maintain state while adding codegen machine passes.
278 public:
279 AddMachinePass(ModulePassManager &MPM, const DerivedT &PB)
280 : MPM(MPM), PB(PB) {}
282 if (MFPM.isEmpty())
283 return;
284
288 if (this->PB.AddInCGSCCOrder) {
290 createCGSCCToFunctionPassAdaptor(std::move(FPM))));
291 } else
292 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
293 }
294
295 template <typename PassT>
296 void operator()(PassT &&Pass, bool Force = false,
297 StringRef Name = PassT::name()) {
300 "Only module pass and function pass are supported.");
301
302 if (!Force && !PB.runBeforeAdding(Name))
303 return;
304
305 // Add Function Pass
307 MFPM.addPass(std::forward<PassT>(Pass));
308 } else {
309 // Add Module Pass
310 flushMFPMToMPM();
311 MPM.addPass(std::forward<PassT>(Pass));
312 }
313
314 for (auto &C : PB.AfterCallbacks)
315 C(Name, MFPM);
316 }
317
318 /// Setting this will add passes to the CGSCC pass manager.
320 if (PB.AddInCGSCCOrder)
321 return;
322 flushMFPMToMPM();
323 PB.AddInCGSCCOrder = true;
324 }
325
326 /// Stop adding passes to the CGSCC pass manager.
327 /// Existing passes won't be removed.
329 if (!PB.AddInCGSCCOrder)
330 return;
331 flushMFPMToMPM();
332 PB.AddInCGSCCOrder = false;
333 }
334
335 private:
336 void flushMFPMToMPM() {
337 if (MFPM.isEmpty())
338 return;
339
340 if (PB.AddInCGSCCOrder) {
344 } else {
347 }
349 }
350
353 const DerivedT &PB;
354 };
355
356 TargetMachineT &TM;
359
360 template <typename TMC> TMC &getTM() const { return static_cast<TMC &>(TM); }
361 CodeGenOptLevel getOptLevel() const { return TM.getOptLevel(); }
362
363 /// Check whether or not GlobalISel should abort on error.
364 /// When this is disabled, GlobalISel will fall back on SDISel instead of
365 /// erroring out.
367 return TM.Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
368 }
369
370 /// Check whether or not a diagnostic should be emitted when GlobalISel
371 /// uses the fallback path. In other words, it will emit a diagnostic
372 /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
374 return TM.Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
375 }
376
377 /// addInstSelector - This method should install an instruction selector pass,
378 /// which converts from LLVM code to machine instructions.
379 Error addInstSelector(AddMachinePass &) const {
380 return make_error<StringError>("addInstSelector is not overridden",
382 }
383
384 /// Target can override this to add GlobalMergePass before all IR passes.
385 void addGlobalMergePass(AddIRPass &) const {}
386
387 /// Add passes that optimize instruction level parallelism for out-of-order
388 /// targets. These passes are run while the machine code is still in SSA
389 /// form, so they can use MachineTraceMetrics to control their heuristics.
390 ///
391 /// All passes added here should preserve the MachineDominatorTree,
392 /// MachineLoopInfo, and MachineTraceMetrics analyses.
393 void addILPOpts(AddMachinePass &) const {}
394
395 /// This method may be implemented by targets that want to run passes
396 /// immediately before register allocation.
397 void addPreRegAlloc(AddMachinePass &) const {}
398
399 /// addPreRewrite - Add passes to the optimized register allocation pipeline
400 /// after register allocation is complete, but before virtual registers are
401 /// rewritten to physical registers.
402 ///
403 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
404 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
405 /// When these passes run, VirtRegMap contains legal physreg assignments for
406 /// all virtual registers.
407 ///
408 /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
409 /// be honored. This is also not generally used for the fast variant,
410 /// where the allocation and rewriting are done in one pass.
411 void addPreRewrite(AddMachinePass &) const {}
412
413 /// Add passes to be run immediately after virtual registers are rewritten
414 /// to physical registers.
415 void addPostRewrite(AddMachinePass &) const {}
416
417 /// This method may be implemented by targets that want to run passes after
418 /// register allocation pass pipeline but before prolog-epilog insertion.
419 void addPostRegAlloc(AddMachinePass &) const {}
420
421 /// This method may be implemented by targets that want to run passes after
422 /// prolog-epilog insertion and before the second instruction scheduling pass.
423 void addPreSched2(AddMachinePass &) const {}
424
425 /// This pass may be implemented by targets that want to run passes
426 /// immediately before machine code is emitted.
427 void addPreEmitPass(AddMachinePass &) const {}
428
429 /// Targets may add passes immediately before machine code is emitted in this
430 /// callback. This is called even later than `addPreEmitPass`.
431 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
432 // position and remove the `2` suffix here as this callback is what
433 // `addPreEmitPass` *should* be but in reality isn't.
434 void addPreEmitPass2(AddMachinePass &) const {}
435
436 /// {{@ For GlobalISel
437 ///
438
439 /// addPreISel - This method should add any "last minute" LLVM->LLVM
440 /// passes (which are run just before instruction selector).
441 void addPreISel(AddIRPass &) const {
442 llvm_unreachable("addPreISel is not overridden");
443 }
444
445 /// This method should install an IR translator pass, which converts from
446 /// LLVM code to machine instructions with possibly generic opcodes.
447 Error addIRTranslator(AddMachinePass &) const {
448 return make_error<StringError>("addIRTranslator is not overridden",
450 }
451
452 /// This method may be implemented by targets that want to run passes
453 /// immediately before legalization.
454 void addPreLegalizeMachineIR(AddMachinePass &) const {}
455
456 /// This method should install a legalize pass, which converts the instruction
457 /// sequence into one that can be selected by the target.
458 Error addLegalizeMachineIR(AddMachinePass &) const {
459 return make_error<StringError>("addLegalizeMachineIR is not overridden",
461 }
462
463 /// This method may be implemented by targets that want to run passes
464 /// immediately before the register bank selection.
465 void addPreRegBankSelect(AddMachinePass &) const {}
466
467 /// This method should install a register bank selector pass, which
468 /// assigns register banks to virtual registers without a register
469 /// class or register banks.
470 Error addRegBankSelect(AddMachinePass &) const {
471 return make_error<StringError>("addRegBankSelect is not overridden",
473 }
474
475 /// This method may be implemented by targets that want to run passes
476 /// immediately before the (global) instruction selection.
477 void addPreGlobalInstructionSelect(AddMachinePass &) const {}
478
479 /// This method should install a (global) instruction selector pass, which
480 /// converts possibly generic instructions to fully target-specific
481 /// instructions, thereby constraining all generic virtual registers to
482 /// register classes.
483 Error addGlobalInstructionSelect(AddMachinePass &) const {
485 "addGlobalInstructionSelect is not overridden",
487 }
488 /// @}}
489
490 /// High level function that adds all passes necessary to go from llvm IR
491 /// representation to the MI representation.
492 /// Adds IR based lowering and target specific optimization passes and finally
493 /// the core instruction selection passes.
494 void addISelPasses(AddIRPass &) const;
495
496 /// Add the actual instruction selection passes. This does not include
497 /// preparation passes on IR.
498 Error addCoreISelPasses(AddMachinePass &) const;
499
500 /// Add the complete, standard set of LLVM CodeGen passes.
501 /// Fully developed targets will not generally override this.
502 Error addMachinePasses(AddMachinePass &) const;
503
504 /// Add passes to lower exception handling for the code generator.
505 void addPassesToHandleExceptions(AddIRPass &) const;
506
507 /// Add common target configurable passes that perform LLVM IR to IR
508 /// transforms following machine independent optimization.
509 void addIRPasses(AddIRPass &) const;
510
511 /// Add pass to prepare the LLVM IR for code generation. This should be done
512 /// before exception handling preparation passes.
513 void addCodeGenPrepare(AddIRPass &) const;
514
515 /// Add common passes that perform LLVM IR to IR transforms in preparation for
516 /// instruction selection.
517 void addISelPrepare(AddIRPass &) const;
518
519 /// Methods with trivial inline returns are convenient points in the common
520 /// codegen pass pipeline where targets may insert passes. Methods with
521 /// out-of-line standard implementations are major CodeGen stages called by
522 /// addMachinePasses. Some targets may override major stages when inserting
523 /// passes is insufficient, but maintaining overriden stages is more work.
524 ///
525
526 /// addMachineSSAOptimization - Add standard passes that optimize machine
527 /// instructions in SSA form.
528 void addMachineSSAOptimization(AddMachinePass &) const;
529
530 /// addFastRegAlloc - Add the minimum set of target-independent passes that
531 /// are required for fast register allocation.
532 Error addFastRegAlloc(AddMachinePass &) const;
533
534 /// addOptimizedRegAlloc - Add passes related to register allocation.
535 /// CodeGenTargetMachineImpl provides standard regalloc passes for most
536 /// targets.
537 void addOptimizedRegAlloc(AddMachinePass &) const;
538
539 /// Add passes that optimize machine instructions after register allocation.
540 void addMachineLateOptimization(AddMachinePass &) const;
541
542 /// addGCPasses - Add late codegen passes that analyze code for garbage
543 /// collection. This should return true if GC info should be printed after
544 /// these passes.
545 void addGCPasses(AddMachinePass &) const {}
546
547 /// Add standard basic block placement passes.
548 void addBlockPlacement(AddMachinePass &) const;
549
551 std::function<Expected<std::unique_ptr<MCStreamer>>(MCContext &)>;
552 void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const {
553 llvm_unreachable("addAsmPrinter is not overridden");
554 }
555
556 /// Utilities for targets to add passes to the pass manager.
557 ///
558
559 /// createTargetRegisterAllocator - Create the register allocator pass for
560 /// this target at the current optimization level.
561 void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const;
562
563 /// addMachinePasses helper to create the target-selected or overriden
564 /// regalloc pass.
565 void addRegAllocPass(AddMachinePass &, bool Optimized) const;
566
567 /// Add core register alloator passes which do the actual register assignment
568 /// and rewriting. \returns true if any passes were added.
569 Error addRegAssignmentFast(AddMachinePass &) const;
570 Error addRegAssignmentOptimized(AddMachinePass &) const;
571
572 /// Allow the target to disable a specific pass by default.
573 /// Backend can declare unwanted passes in constructor.
574 template <typename... PassTs> void disablePass() {
575 BeforeCallbacks.emplace_back(
576 [](StringRef Name) { return ((Name != PassTs::name()) && ...); });
577 }
578
579 /// Insert InsertedPass pass after TargetPass pass.
580 /// Only machine function passes are supported.
581 template <typename TargetPassT, typename InsertedPassT>
582 void insertPass(InsertedPassT &&Pass) const {
583 AfterCallbacks.emplace_back(
584 [&](StringRef Name, MachineFunctionPassManager &MFPM) mutable {
585 if (Name == TargetPassT::name() &&
586 runBeforeAdding(InsertedPassT::name())) {
587 MFPM.addPass(std::forward<InsertedPassT>(Pass));
588 }
589 });
590 }
591
592private:
593 DerivedT &derived() { return static_cast<DerivedT &>(*this); }
594 const DerivedT &derived() const {
595 return static_cast<const DerivedT &>(*this);
596 }
597
598 bool runBeforeAdding(StringRef Name) const {
599 bool ShouldAdd = true;
600 for (auto &C : BeforeCallbacks)
601 ShouldAdd &= C(Name);
602 return ShouldAdd;
603 }
604
605 void setStartStopPasses(const TargetPassConfig::StartStopInfo &Info) const;
606
607 Error verifyStartStop(const TargetPassConfig::StartStopInfo &Info) const;
608
609 mutable SmallVector<llvm::unique_function<bool(StringRef)>, 4>
610 BeforeCallbacks;
611 mutable SmallVector<
612 llvm::unique_function<void(StringRef, MachineFunctionPassManager &)>, 4>
613 AfterCallbacks;
614
615 /// Helper variable for `-start-before/-start-after/-stop-before/-stop-after`
616 mutable bool Started = true;
617 mutable bool Stopped = true;
618 mutable bool AddInCGSCCOrder = false;
619};
620
621template <typename Derived, typename TargetMachineT>
624 CodeGenFileType FileType) const {
625 auto StartStopInfo = TargetPassConfig::getStartStopInfo(*PIC);
626 if (!StartStopInfo)
627 return StartStopInfo.takeError();
628 setStartStopPasses(*StartStopInfo);
629
631 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
632
633 {
634 AddIRPass addIRPass(MPM, derived());
636 /*Force=*/true);
638 /*Force=*/true);
640 /*Force=*/true);
642 /*Force=*/true);
643 addISelPasses(addIRPass);
644 }
645
646 AddMachinePass addPass(MPM, derived());
647
648 if (PrintMIR)
649 addPass(PrintMIRPreparePass(Out), /*Force=*/true);
650
651 if (auto Err = addCoreISelPasses(addPass))
652 return std::move(Err);
653
654 if (auto Err = derived().addMachinePasses(addPass))
655 return std::move(Err);
656
657 if (!Opt.DisableVerify)
658 addPass(MachineVerifierPass());
659
660 if (PrintAsm) {
661 derived().addAsmPrinter(
662 addPass, [this, &Out, DwoOut, FileType](MCContext &Ctx) {
663 return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
664 });
665 }
666
667 if (PrintMIR)
668 addPass(PrintMIRPass(Out), /*Force=*/true);
669
670 return verifyStartStop(*StartStopInfo);
671}
672
673template <typename Derived, typename TargetMachineT>
674void CodeGenPassBuilder<Derived, TargetMachineT>::setStartStopPasses(
675 const TargetPassConfig::StartStopInfo &Info) const {
676 if (!Info.StartPass.empty()) {
677 Started = false;
678 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
679 Count = 0u](StringRef ClassName) mutable {
680 if (Count == Info.StartInstanceNum) {
681 if (AfterFlag) {
682 AfterFlag = false;
683 Started = true;
684 }
685 return Started;
686 }
687
688 auto PassName = PIC->getPassNameForClassName(ClassName);
689 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
690 Started = !Info.StartAfter;
691
692 return Started;
693 });
694 }
695
696 if (!Info.StopPass.empty()) {
697 Stopped = false;
698 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
699 Count = 0u](StringRef ClassName) mutable {
700 if (Count == Info.StopInstanceNum) {
701 if (AfterFlag) {
702 AfterFlag = false;
703 Stopped = true;
704 }
705 return !Stopped;
706 }
707
708 auto PassName = PIC->getPassNameForClassName(ClassName);
709 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
710 Stopped = !Info.StopAfter;
711 return !Stopped;
712 });
713 }
714}
715
716template <typename Derived, typename TargetMachineT>
717Error CodeGenPassBuilder<Derived, TargetMachineT>::verifyStartStop(
719 if (Started && Stopped)
720 return Error::success();
721
722 if (!Started)
724 "Can't find start pass \"" + Info.StartPass + "\".",
725 std::make_error_code(std::errc::invalid_argument));
726 if (!Stopped)
728 "Can't find stop pass \"" + Info.StopPass + "\".",
729 std::make_error_code(std::errc::invalid_argument));
730 return Error::success();
731}
732
733template <typename Derived, typename TargetMachineT>
735 AddIRPass &addPass) const {
736 derived().addGlobalMergePass(addPass);
737 if (TM.useEmulatedTLS())
738 addPass(LowerEmuTLSPass());
739
741 addPass(ExpandLargeDivRemPass(TM));
742 addPass(ExpandFpPass(TM, getOptLevel()));
743
744 derived().addIRPasses(addPass);
745 derived().addCodeGenPrepare(addPass);
747 derived().addISelPrepare(addPass);
748}
749
750/// Add common target configurable passes that perform LLVM IR to IR transforms
751/// following machine independent optimization.
752template <typename Derived, typename TargetMachineT>
754 AddIRPass &addPass) const {
755 // Before running any passes, run the verifier to determine if the input
756 // coming from the front-end and/or optimizer is valid.
757 if (!Opt.DisableVerify)
758 addPass(VerifierPass(), /*Force=*/true);
759
760 // Run loop strength reduction before anything else.
761 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
762 LoopPassManager LPM;
763 LPM.addPass(CanonicalizeFreezeInLoopsPass());
764 LPM.addPass(LoopStrengthReducePass());
765 if (Opt.EnableLoopTermFold)
766 LPM.addPass(LoopTermFoldPass());
767 addPass(createFunctionToLoopPassAdaptor(std::move(LPM),
768 /*UseMemorySSA=*/true));
769 }
770
772 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
773 // loads and compares. ExpandMemCmpPass then tries to expand those calls
774 // into optimally-sized loads and compares. The transforms are enabled by a
775 // target lowering hook.
776 if (!Opt.DisableMergeICmps)
777 addPass(MergeICmpsPass());
778 addPass(ExpandMemCmpPass(TM));
779 }
780
781 // Run GC lowering passes for builtin collectors
782 // TODO: add a pass insertion point here
783 addPass(GCLoweringPass());
784 addPass(ShadowStackGCLoweringPass());
786
787 // Make sure that no unreachable blocks are instruction selected.
788 addPass(UnreachableBlockElimPass());
789
790 // Prepare expensive constants for SelectionDAG.
791 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
792 addPass(ConstantHoistingPass());
793
794 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
795 // operands with calls to the corresponding functions in a vector library.
797 addPass(ReplaceWithVeclib());
798
800 !Opt.DisablePartialLibcallInlining)
802
803 // Instrument function entry and exit, e.g. with calls to mcount().
804 addPass(EntryExitInstrumenterPass(/*PostInlining=*/true));
805
806 // Add scalarization of target's unsupported masked memory intrinsics pass.
807 // the unsupported intrinsic will be replaced with a chain of basic blocks,
808 // that stores/loads element one-by-one if the appropriate mask bit is set.
810
811 // Expand reduction intrinsics into shuffle sequences if the target wants to.
812 if (!Opt.DisableExpandReductions)
813 addPass(ExpandReductionsPass());
814
815 // Convert conditional moves to conditional jumps when profitable.
816 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
817 addPass(SelectOptimizePass(TM));
818
819 if (Opt.EnableGlobalMergeFunc)
820 addPass(GlobalMergeFuncPass());
821}
822
823/// Turn exception handling constructs into something the code generators can
824/// handle.
825template <typename Derived, typename TargetMachineT>
827 AddIRPass &addPass) const {
828 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
829 assert(MCAI && "No MCAsmInfo");
830 switch (MCAI->getExceptionHandlingType()) {
832 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
833 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
834 // catch info can get misplaced when a selector ends up more than one block
835 // removed from the parent invoke(s). This could happen when a landing
836 // pad is shared by multiple invokes and is also a target of a normal
837 // edge from elsewhere.
838 addPass(SjLjEHPreparePass(&TM));
839 [[fallthrough]];
844 addPass(DwarfEHPreparePass(TM));
845 break;
847 // We support using both GCC-style and MSVC-style exceptions on Windows, so
848 // add both preparation passes. Each pass will only actually run if it
849 // recognizes the personality function.
850 addPass(WinEHPreparePass());
851 addPass(DwarfEHPreparePass(TM));
852 break;
854 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
855 // on catchpads and cleanuppads because it does not outline them into
856 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
857 // should remove PHIs there.
858 addPass(WinEHPreparePass(/*DemoteCatchSwitchPHIOnly=*/false));
859 addPass(WasmEHPreparePass());
860 break;
862 addPass(LowerInvokePass());
863
864 // The lower invoke pass may create unreachable code. Remove it.
865 addPass(UnreachableBlockElimPass());
866 break;
867 }
868}
869
870/// Add pass to prepare the LLVM IR for code generation. This should be done
871/// before exception handling preparation passes.
872template <typename Derived, typename TargetMachineT>
874 AddIRPass &addPass) const {
875 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
876 addPass(CodeGenPreparePass(TM));
877 // TODO: Default ctor'd RewriteSymbolPass is no-op.
878 // addPass(RewriteSymbolPass());
879}
880
881/// Add common passes that perform LLVM IR to IR transforms in preparation for
882/// instruction selection.
883template <typename Derived, typename TargetMachineT>
885 AddIRPass &addPass) const {
886 derived().addPreISel(addPass);
887
888 if (Opt.RequiresCodeGenSCCOrder)
889 addPass.requireCGSCCOrder();
890
892 addPass(ObjCARCContractPass());
893
894 addPass(CallBrPreparePass());
895 // Add both the safe stack and the stack protection passes: each of them will
896 // only protect functions that have corresponding attributes.
897 addPass(SafeStackPass(TM));
898 addPass(StackProtectorPass(TM));
899
900 if (Opt.PrintISelInput)
901 addPass(PrintFunctionPass(dbgs(),
902 "\n\n*** Final LLVM Code input to ISel ***\n"));
903
904 // All passes which modify the LLVM IR are now complete; run the verifier
905 // to ensure that the IR is valid.
906 if (!Opt.DisableVerify)
907 addPass(VerifierPass(), /*Force=*/true);
908}
909
910template <typename Derived, typename TargetMachineT>
912 AddMachinePass &addPass) const {
913 // Enable FastISel with -fast-isel, but allow that to be overridden.
914 TM.setO0WantsFastISel(Opt.EnableFastISelOption.value_or(true));
915
916 // Determine an instruction selector.
917 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
918 SelectorType Selector;
919
920 if (Opt.EnableFastISelOption && *Opt.EnableFastISelOption == true)
921 Selector = SelectorType::FastISel;
922 else if ((Opt.EnableGlobalISelOption &&
923 *Opt.EnableGlobalISelOption == true) ||
924 (TM.Options.EnableGlobalISel &&
925 (!Opt.EnableGlobalISelOption ||
926 *Opt.EnableGlobalISelOption == false)))
927 Selector = SelectorType::GlobalISel;
928 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
929 Selector = SelectorType::FastISel;
930 else
931 Selector = SelectorType::SelectionDAG;
932
933 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
934 if (Selector == SelectorType::FastISel) {
935 TM.setFastISel(true);
936 TM.setGlobalISel(false);
937 } else if (Selector == SelectorType::GlobalISel) {
938 TM.setFastISel(false);
939 TM.setGlobalISel(true);
940 }
941
942 // Add instruction selector passes.
943 if (Selector == SelectorType::GlobalISel) {
944 if (auto Err = derived().addIRTranslator(addPass))
945 return std::move(Err);
946
947 derived().addPreLegalizeMachineIR(addPass);
948
949 if (auto Err = derived().addLegalizeMachineIR(addPass))
950 return std::move(Err);
951
952 // Before running the register bank selector, ask the target if it
953 // wants to run some passes.
954 derived().addPreRegBankSelect(addPass);
955
956 if (auto Err = derived().addRegBankSelect(addPass))
957 return std::move(Err);
958
959 derived().addPreGlobalInstructionSelect(addPass);
960
961 if (auto Err = derived().addGlobalInstructionSelect(addPass))
962 return std::move(Err);
963
964 // Pass to reset the MachineFunction if the ISel failed.
965 addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
967
968 // Provide a fallback path when we do not want to abort on
969 // not-yet-supported input.
971 if (auto Err = derived().addInstSelector(addPass))
972 return std::move(Err);
973
974 } else if (auto Err = derived().addInstSelector(addPass))
975 return std::move(Err);
976
977 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
978 // FinalizeISel.
979 addPass(FinalizeISelPass());
980
981 // // Print the instruction selected machine code...
982 // printAndVerify("After Instruction Selection");
983
984 return Error::success();
985}
986
987/// Add the complete set of target-independent postISel code generator passes.
988///
989/// This can be read as the standard order of major LLVM CodeGen stages. Stages
990/// with nontrivial configuration or multiple passes are broken out below in
991/// add%Stage routines.
992///
993/// Any CodeGenPassBuilder<Derived, TargetMachine>::addXX routine may be
994/// overriden by the Target. The addPre/Post methods with empty header
995/// implementations allow injecting target-specific fixups just before or after
996/// major stages. Additionally, targets have the flexibility to change pass
997/// order within a stage by overriding default implementation of add%Stage
998/// routines below. Each technique has maintainability tradeoffs because
999/// alternate pass orders are not well supported. addPre/Post works better if
1000/// the target pass is easily tied to a common pass. But if it has subtle
1001/// dependencies on multiple passes, the target should override the stage
1002/// instead.
1003template <typename Derived, typename TargetMachineT>
1005 AddMachinePass &addPass) const {
1006 // Add passes that optimize machine instructions in SSA form.
1008 derived().addMachineSSAOptimization(addPass);
1009 } else {
1010 // If the target requests it, assign local variables to stack slots relative
1011 // to one another and simplify frame index references where possible.
1013 }
1014
1015 if (TM.Options.EnableIPRA) {
1017 addPass(RegUsageInfoPropagationPass());
1018 }
1019 // Run pre-ra passes.
1020 derived().addPreRegAlloc(addPass);
1021
1022 // Run register allocation and passes that are tightly coupled with it,
1023 // including phi elimination and scheduling.
1024 if (*Opt.OptimizeRegAlloc) {
1025 derived().addOptimizedRegAlloc(addPass);
1026 } else {
1027 if (auto Err = derived().addFastRegAlloc(addPass))
1028 return Err;
1029 }
1030
1031 // Run post-ra passes.
1032 derived().addPostRegAlloc(addPass);
1033
1036
1037 // Insert prolog/epilog code. Eliminate abstract frame index references...
1039 addPass(PostRAMachineSinkingPass());
1040 addPass(ShrinkWrapPass());
1041 }
1042
1043 addPass(PrologEpilogInserterPass());
1044
1045 /// Add passes that optimize machine instructions after register allocation.
1047 derived().addMachineLateOptimization(addPass);
1048
1049 // Expand pseudo instructions before second scheduling pass.
1050 addPass(ExpandPostRAPseudosPass());
1051
1052 // Run pre-sched2 passes.
1053 derived().addPreSched2(addPass);
1054
1055 if (Opt.EnableImplicitNullChecks)
1056 addPass(ImplicitNullChecksPass());
1057
1058 // Second pass scheduler.
1059 // Let Target optionally insert this pass by itself at some other
1060 // point.
1062 !TM.targetSchedulesPostRAScheduling()) {
1063 if (Opt.MISchedPostRA)
1064 addPass(PostMachineSchedulerPass(&TM));
1065 else
1066 addPass(PostRASchedulerPass(&TM));
1067 }
1068
1069 // GC
1070 derived().addGCPasses(addPass);
1071
1072 // Basic block placement.
1074 derived().addBlockPlacement(addPass);
1075
1076 // Insert before XRay Instrumentation.
1077 addPass(FEntryInserterPass());
1078
1079 addPass(XRayInstrumentationPass());
1080 addPass(PatchableFunctionPass());
1081
1082 derived().addPreEmitPass(addPass);
1083
1084 if (TM.Options.EnableIPRA)
1085 // Collect register usage information and produce a register mask of
1086 // clobbered registers, to be used to optimize call sites.
1087 addPass(RegUsageInfoCollectorPass());
1088
1089 addPass(FuncletLayoutPass());
1090
1091 addPass(RemoveLoadsIntoFakeUsesPass());
1092 addPass(StackMapLivenessPass());
1093 addPass(LiveDebugValuesPass(
1094 getTM<TargetMachine>().Options.ShouldEmitDebugEntryValues()));
1096
1097 if (TM.Options.EnableMachineOutliner &&
1099 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
1100 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
1101 TM.Options.SupportsDefaultOutlining)
1102 addPass(MachineOutlinerPass(Opt.EnableMachineOutliner));
1103 }
1104
1106
1107 // Add passes that directly emit MI after all other MI passes.
1108 derived().addPreEmitPass2(addPass);
1109
1110 return Error::success();
1111}
1112
1113/// Add passes that optimize machine instructions in SSA form.
1114template <typename Derived, typename TargetMachineT>
1116 AddMachinePass &addPass) const {
1117 // Pre-ra tail duplication.
1118 addPass(EarlyTailDuplicatePass());
1119
1120 // Optimize PHIs before DCE: removing dead PHI cycles may make more
1121 // instructions dead.
1122 addPass(OptimizePHIsPass());
1123
1124 // This pass merges large allocas. StackSlotColoring is a different pass
1125 // which merges spill slots.
1126 addPass(StackColoringPass());
1127
1128 // If the target requests it, assign local variables to stack slots relative
1129 // to one another and simplify frame index references where possible.
1131
1132 // With optimization, dead code should already be eliminated. However
1133 // there is one known exception: lowered code for arguments that are only
1134 // used by tail calls, where the tail calls reuse the incoming stack
1135 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
1137
1138 // Allow targets to insert passes that improve instruction level parallelism,
1139 // like if-conversion. Such passes will typically need dominator trees and
1140 // loop info, just like LICM and CSE below.
1141 derived().addILPOpts(addPass);
1142
1143 addPass(EarlyMachineLICMPass());
1144 addPass(MachineCSEPass());
1145
1146 addPass(MachineSinkingPass(Opt.EnableSinkAndFold));
1147
1148 addPass(PeepholeOptimizerPass());
1149 // Clean-up the dead code that may have been generated by peephole
1150 // rewriting.
1152}
1153
1154//===---------------------------------------------------------------------===//
1155/// Register Allocation Pass Configuration
1156//===---------------------------------------------------------------------===//
1157
1158/// Instantiate the default register allocator pass for this target for either
1159/// the optimized or unoptimized allocation path. This will be added to the pass
1160/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1161/// in the optimized case.
1162///
1163/// A target that uses the standard regalloc pass order for fast or optimized
1164/// allocation may still override this for per-target regalloc
1165/// selection. But -regalloc-npm=... always takes precedence.
1166/// If a target does not want to allow users to set -regalloc-npm=... at all,
1167/// check if Opt.RegAlloc == RegAllocType::Unset.
1168template <typename Derived, typename TargetMachineT>
1170 AddMachinePass &addPass, bool Optimized) const {
1171 if (Optimized)
1172 addPass(RAGreedyPass());
1173 else
1174 addPass(RegAllocFastPass());
1175}
1176
1177/// Find and instantiate the register allocation pass requested by this target
1178/// at the current optimization level. Different register allocators are
1179/// defined as separate passes because they may require different analysis.
1180///
1181/// This helper ensures that the -regalloc-npm= option is always available,
1182/// even for targets that override the default allocator.
1183template <typename Derived, typename TargetMachineT>
1185 AddMachinePass &addPass, bool Optimized) const {
1186 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
1187 if (Opt.RegAlloc > RegAllocType::Default) {
1188 switch (Opt.RegAlloc) {
1189 case RegAllocType::Fast:
1190 addPass(RegAllocFastPass());
1191 break;
1193 addPass(RAGreedyPass());
1194 break;
1195 default:
1196 reportFatalUsageError("register allocator not supported yet");
1197 }
1198 return;
1199 }
1200 // -regalloc=default or unspecified, so pick based on the optimization level
1201 // or ask the target for the regalloc pass.
1202 derived().addTargetRegisterAllocator(addPass, Optimized);
1203}
1204
1205template <typename Derived, typename TargetMachineT>
1207 AddMachinePass &addPass) const {
1208 // TODO: Ensure allocator is default or fast.
1209 addRegAllocPass(addPass, false);
1210 return Error::success();
1211}
1212
1213template <typename Derived, typename TargetMachineT>
1215 AddMachinePass &addPass) const {
1216 // Add the selected register allocation pass.
1217 addRegAllocPass(addPass, true);
1218
1219 // Allow targets to change the register assignments before rewriting.
1220 derived().addPreRewrite(addPass);
1221
1222 // Finally rewrite virtual registers.
1223 addPass(VirtRegRewriterPass());
1224 // Perform stack slot coloring and post-ra machine LICM.
1225 //
1226 // FIXME: Re-enable coloring with register when it's capable of adding
1227 // kill markers.
1228 addPass(StackSlotColoringPass());
1229
1230 return Error::success();
1231}
1232
1233/// Add the minimum set of target-independent passes that are required for
1234/// register allocation. No coalescing or scheduling.
1235template <typename Derived, typename TargetMachineT>
1237 AddMachinePass &addPass) const {
1238 addPass(PHIEliminationPass());
1239 addPass(TwoAddressInstructionPass());
1240 return derived().addRegAssignmentFast(addPass);
1241}
1242
1243/// Add standard target-independent passes that are tightly coupled with
1244/// optimized register allocation, including coalescing, machine instruction
1245/// scheduling, and register allocation itself.
1246template <typename Derived, typename TargetMachineT>
1248 AddMachinePass &addPass) const {
1249 addPass(DetectDeadLanesPass());
1250
1251 addPass(InitUndefPass());
1252
1253 addPass(ProcessImplicitDefsPass());
1254
1255 // LiveVariables currently requires pure SSA form.
1256 //
1257 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1258 // LiveVariables can be removed completely, and LiveIntervals can be directly
1259 // computed. (We still either need to regenerate kill flags after regalloc, or
1260 // preferably fix the scavenger to not depend on them).
1261 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
1262 // When LiveVariables is removed this has to be removed/moved either.
1263 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
1264 // after it with -stop-before/-stop-after.
1267
1268 // Edge splitting is smarter with machine loop info.
1270 addPass(PHIEliminationPass());
1271
1272 // Eventually, we want to run LiveIntervals before PHI elimination.
1273 if (Opt.EarlyLiveIntervals)
1275
1276 addPass(TwoAddressInstructionPass());
1277 addPass(RegisterCoalescerPass());
1278
1279 // The machine scheduler may accidentally create disconnected components
1280 // when moving subregister definitions around, avoid this by splitting them to
1281 // separate vregs before. Splitting can also improve reg. allocation quality.
1283
1284 // PreRA instruction scheduling.
1285 addPass(MachineSchedulerPass(&TM));
1286
1287 if (auto E = derived().addRegAssignmentOptimized(addPass)) {
1288 // addRegAssignmentOptimized did not add a reg alloc pass, so do nothing.
1289 return;
1290 }
1291 // Allow targets to expand pseudo instructions depending on the choice of
1292 // registers before MachineCopyPropagation.
1293 derived().addPostRewrite(addPass);
1294
1295 // Copy propagate to forward register uses and try to eliminate COPYs that
1296 // were not coalesced.
1297 addPass(MachineCopyPropagationPass());
1298
1299 // Run post-ra machine LICM to hoist reloads / remats.
1300 //
1301 // FIXME: can this move into MachineLateOptimization?
1302 addPass(MachineLICMPass());
1303}
1304
1305//===---------------------------------------------------------------------===//
1306/// Post RegAlloc Pass Configuration
1307//===---------------------------------------------------------------------===//
1308
1309/// Add passes that optimize machine instructions after register allocation.
1310template <typename Derived, typename TargetMachineT>
1312 AddMachinePass &addPass) const {
1313 // Branch folding must be run after regalloc and prolog/epilog insertion.
1314 addPass(BranchFolderPass(Opt.EnableTailMerge));
1315
1316 // Tail duplication.
1317 // Note that duplicating tail just increases code size and degrades
1318 // performance for targets that require Structured Control Flow.
1319 // In addition it can also make CFG irreducible. Thus we disable it.
1320 if (!TM.requiresStructuredCFG())
1321 addPass(TailDuplicatePass());
1322
1323 // Cleanup of redundant (identical) address/immediate loads.
1325
1326 // Copy propagation.
1327 addPass(MachineCopyPropagationPass());
1328}
1329
1330/// Add standard basic block placement passes.
1331template <typename Derived, typename TargetMachineT>
1333 AddMachinePass &addPass) const {
1334 addPass(MachineBlockPlacementPass(Opt.EnableTailMerge));
1335 // Run a separate pass to collect block placement statistics.
1336 if (Opt.EnableBlockPlacementStats)
1338}
1339
1340} // namespace llvm
1341
1342#endif // LLVM_PASSES_CODEGENPASSBUILDER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
This header provides classes for managing passes over SCCs of the call graph.
Analysis containing CSE Info
Definition CSEInfo.cpp:27
Defines an IR pass for CodeGen Prepare.
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
This file defines passes to print out IR in various granularities.
This header defines various interfaces for pass management in LLVM.
This file contains the declaration of the InterleavedAccessPass class, its corresponding pass name is...
static LVOptions Options
Definition LVOptions.cpp:25
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This is the interface for a metadata-based scoped no-alias analysis.
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file defines the SmallVector class.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
This is the interface for a metadata-based TBAA.
static const char PassName[]
A pass that canonicalizes freeze instructions in a loop.
AddIRPass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, bool Force=false, StringRef Name=PassT::name())
void requireCGSCCOrder()
Setting this will add passes to the CGSCC pass manager.
void stopAddingInCGSCCOrder()
Stop adding passes to the CGSCC pass manager.
void stopAddingInCGSCCOrder()
Stop adding passes to the CGSCC pass manager.
AddMachinePass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, bool Force=false, StringRef Name=PassT::name())
void requireCGSCCOrder()
Setting this will add passes to the CGSCC pass manager.
void addPreRewrite(AddMachinePass &) const
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
void addPostRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes after register allocation pass pipe...
void addPreGlobalInstructionSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the (global) ins...
Error addRegAssignmentFast(AddMachinePass &) const
Add core register alloator passes which do the actual register assignment and rewriting.
decltype(std::declval< PassT & >().run( std::declval< Function & >(), std::declval< FunctionAnalysisManager & >())) is_function_pass_t
Error addFastRegAlloc(AddMachinePass &) const
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
Error addIRTranslator(AddMachinePass &) const
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
void addILPOpts(AddMachinePass &) const
Add passes that optimize instruction level parallelism for out-of-order targets.
void addRegAllocPass(AddMachinePass &, bool Optimized) const
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addPreSched2(AddMachinePass &) const
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
Error addRegBankSelect(AddMachinePass &) const
This method should install a register bank selector pass, which assigns register banks to virtual reg...
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
void addPreRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before register allocat...
void insertPass(InsertedPassT &&Pass) const
Insert InsertedPass pass after TargetPass pass.
void addGCPasses(AddMachinePass &) const
addGCPasses - Add late codegen passes that analyze code for garbage collection.
Error buildPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType) const
void addGlobalMergePass(AddIRPass &) const
Target can override this to add GlobalMergePass before all IR passes.
Error addLegalizeMachineIR(AddMachinePass &) const
This method should install a legalize pass, which converts the instruction sequence into one that can...
Error addCoreISelPasses(AddMachinePass &) const
Add the actual instruction selection passes.
std::function< Expected< std::unique_ptr< MCStreamer > >(MCContext &)> CreateMCStreamer
void addOptimizedRegAlloc(AddMachinePass &) const
addOptimizedRegAlloc - Add passes related to register allocation.
void addISelPasses(AddIRPass &) const
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
decltype(std::declval< PassT & >().run( std::declval< MachineFunction & >(), std::declval< MachineFunctionAnalysisManager & >())) is_machine_function_pass_t
void addMachineSSAOptimization(AddMachinePass &) const
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
CodeGenPassBuilder(TargetMachineT &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
Error addRegAssignmentOptimized(AddMachinePass &) const
void addCodeGenPrepare(AddIRPass &) const
Add pass to prepare the LLVM IR for code generation.
Error addMachinePasses(AddMachinePass &) const
Add the complete, standard set of LLVM CodeGen passes.
void addISelPrepare(AddIRPass &) const
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
void disablePass()
Allow the target to disable a specific pass by default.
void addBlockPlacement(AddMachinePass &) const
Add standard basic block placement passes.
Error addInstSelector(AddMachinePass &) const
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const
Utilities for targets to add passes to the pass manager.
void addPreEmitPass2(AddMachinePass &) const
Targets may add passes immediately before machine code is emitted in this callback.
void addPostRewrite(AddMachinePass &) const
Add passes to be run immediately after virtual registers are rewritten to physical registers.
void addPreRegBankSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the register ban...
void addPreEmitPass(AddMachinePass &) const
This pass may be implemented by targets that want to run passes immediately before machine code is em...
Error addGlobalInstructionSelect(AddMachinePass &) const
This method should install a (global) instruction selector pass, which converts possibly generic inst...
void addMachineLateOptimization(AddMachinePass &) const
Add passes that optimize machine instructions after register allocation.
void addIRPasses(AddIRPass &) const
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
decltype(std::declval< PassT & >().run( std::declval< Module & >(), std::declval< ModuleAnalysisManager & >())) is_module_pass_t
void addPreLegalizeMachineIR(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before legalization.
void addPassesToHandleExceptions(AddIRPass &) const
Add passes to lower exception handling for the code generator.
PassInstrumentationCallbacks * getPassInstrumentationCallbacks() const
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
void addPreISel(AddIRPass &) const
{{@ For GlobalISel
void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:66
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
Performs Loop Strength Reduce Pass.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:64
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:633
Context object for machine code objects.
Definition MCContext.h:83
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ABI StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name. Empty if no match found.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
Pass (for the new pass manager) for printing a Function as LLVM's text IR assembly.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
static Expected< StartStopInfo > getStartStopInfo(PassInstrumentationCallbacks &PIC)
Returns pass name in -stop-before or -stop-after NOTE: New pass manager migration only.
static bool willCompleteCodeGenPipeline()
Returns true if none of the -stop-before and -stop-after options is set.
Create a verifier pass.
Definition Verifier.h:134
An abstract base class for streams implementations that also support a pwrite operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:98
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:56
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:61
@ None
No exception support.
Definition CodeGen.h:54
@ AIX
AIX Exception Handling.
Definition CodeGen.h:60
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:55
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:58
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:59
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:111
FunctionToMachineFunctionPassAdaptor createFunctionToMachineFunctionPassAdaptor(MachineFunctionPassT &&Pass)
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:180
Global function merging pass for new pass manager.
A utility pass template to force an analysis result to be available.