LLVM 24.0.0git
CodeGenPassBuilder.cpp
Go to the documentation of this file.
1//===--- CodeGenPassBuilder.cpp --------------------------------------- ---===//
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//
9// This file defines interfaces to access the target independent code
10// generation passes provided by the LLVM backend.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/StringRef.h"
62#include "llvm/CodeGen/PEI.h"
99#include "llvm/IR/PassManager.h"
100#include "llvm/IR/Verifier.h"
102#include "llvm/MC/MCAsmInfo.h"
103#include "llvm/MC/MCStreamer.h"
107#include "llvm/Support/CodeGen.h"
108#include "llvm/Support/Debug.h"
109#include "llvm/Support/Error.h"
123#include <cassert>
124#include <utility>
125
126using namespace llvm;
127
128namespace llvm {
129#define DUMMY_MACHINE_FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
130 AnalysisKey PASS_NAME::Key;
131#include "llvm/Passes/MachinePassRegistry.def"
132} // namespace llvm
133
135 const CGPassBuilderOption &Opts,
137 : TM(TM), Opt(Opts), PIC(PIC) {
138 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
139 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
140
141 // Target should override TM.Options.EnableIPRA in their target-specific
142 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
143 if (Opt.EnableIPRA) {
144 TM.Options.EnableIPRA = *Opt.EnableIPRA;
145 } else {
146 // If not explicitly specified, use target default.
147 TM.Options.EnableIPRA |= TM.useIPRA();
148 }
149
150 if (Opt.EnableGlobalISelAbort)
151 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
152
153 if (Opt.EnableRegAllocFastTied != cl::boolOrDefault::BOU_UNSET)
154 TM.setEnableTiedFastRegAlloc(Opt.EnableRegAllocFastTied ==
156
157 // An explicit RegAlloc choice implies its pipeline: only the fast
158 // allocator uses the unoptimized one.
159 if (Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_UNSET) {
160 bool Optimized = Opt.RegAlloc > RegAllocType::Default
161 ? Opt.RegAlloc != RegAllocType::Fast
162 : getOptLevel() != CodeGenOptLevel::None;
163 Opt.OptimizeRegAlloc =
164 Optimized ? cl::boolOrDefault::BOU_TRUE : cl::boolOrDefault::BOU_FALSE;
165 }
166}
167
168// Out-of-line to anchor the vtable in this translation unit.
170
172 return make_error<StringError>("addInstSelector is not overridden",
174}
175
177 return make_error<StringError>("addIRTranslator is not overridden",
179}
180
182 return make_error<StringError>("addLegalizeMachineIR is not overridden",
184}
185
187 return make_error<StringError>("addRegBankSelect is not overridden",
189}
190
192 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
194}
195
197 llvm_unreachable("addAsmPrinterBegin is not overriden");
198}
199
201 llvm_unreachable("addAsmPrinter is not overridden");
202}
203
205 llvm_unreachable("addAsmPrinterEnd is not overriden");
206}
207
209 bool FreeMachineFunctions) {
210 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
211 return;
212 if (!PMW.MFPM.isEmpty()) {
213 PMW.FPM.addPass(
214 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
215 PMW.MFPM = MachineFunctionPassManager();
216 }
217 if (FreeMachineFunctions)
219 if (AddInCGSCCOrder) {
221 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
222 } else {
223 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
224 }
225 PMW.FPM = FunctionPassManager();
226}
227
230 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
231 auto StartStopInfo = TargetPassConfig::getStartStopInfo(*PIC);
232 if (!StartStopInfo)
233 return StartStopInfo.takeError();
234 setStartStopPasses(*StartStopInfo);
235
237 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
238
239 PassManagerWrapper PMW(MPM);
240
242 /*Force=*/true);
244 /*Force=*/true);
246 /*Force=*/true);
248 /*Force=*/true);
250 PMW,
251 /*Force=*/true);
252 addISelPasses(PMW);
253 flushFPMsToMPM(PMW);
254
255 if (PrintAsm) {
256 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
257 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
258 if (!MCStreamerOrErr)
259 return MCStreamerOrErr.takeError();
260 std::unique_ptr<AsmPrinter> Printer(
261 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
262 if (!Printer)
263 return createStringError("failed to create AsmPrinter");
264 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
266 }
267
268 if (PrintMIR)
269 addModulePass(PrintMIRPreparePass(Out), PMW, /*Force=*/true);
270
271 if (auto Err = addCoreISelPasses(PMW))
272 return Err;
273
274 if (auto Err = addMachinePasses(PMW))
275 return Err;
276
277 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
278 : Opt.VerifyMachineCode == MachineVerifierMode::End)
279 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
280
281 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
282 // final output so that -stop-before=<target>-asm-printer works. When printing
283 // MIR as the final output, we never end up running AsmPrinter.
284 addAsmPrinter(PMW);
285
286 if (PrintAsm) {
287 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
288 addAsmPrinterEnd(PMW);
289 } else {
290 if (PrintMIR)
291 addMachineFunctionPass(PrintMIRPass(Out), PMW, /*Force=*/true);
292 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
293 }
294
295 return verifyStartStop(*StartStopInfo);
296}
297
298void CodeGenPassBuilder::setStartStopPasses(
300 if (!Info.StartPass.empty()) {
301 Started = false;
302 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
303 Count = 0u](StringRef ClassName) mutable {
304 if (Count == Info.StartInstanceNum) {
305 if (AfterFlag) {
306 AfterFlag = false;
307 Started = true;
308 }
309 return Started;
310 }
311
312 auto PassName = PIC->getPassNameForClassName(ClassName);
313 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
314 Started = !Info.StartAfter;
315
316 return Started;
317 });
318 }
319
320 if (!Info.StopPass.empty()) {
321 Stopped = false;
322 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
323 Count = 0u](StringRef ClassName) mutable {
324 if (Count == Info.StopInstanceNum) {
325 if (AfterFlag) {
326 AfterFlag = false;
327 Stopped = true;
328 }
329 return !Stopped;
330 }
331
332 auto PassName = PIC->getPassNameForClassName(ClassName);
333 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
334 Stopped = !Info.StopAfter;
335 return !Stopped;
336 });
337 }
338}
339
340Error CodeGenPassBuilder::verifyStartStop(
341 const TargetPassConfig::StartStopInfo &Info) const {
342 if (Started && Stopped)
343 return Error::success();
344
345 if (!Started)
347 "Can't find start pass \"" + Info.StartPass + "\".",
348 std::make_error_code(std::errc::invalid_argument));
349 if (!Stopped)
351 "Can't find stop pass \"" + Info.StopPass + "\".",
352 std::make_error_code(std::errc::invalid_argument));
353 return Error::success();
354}
355
358 if (TM.useEmulatedTLS())
360
361 // ObjCARCContract operates on ObjC intrinsics and must run before
362 // PreISelIntrinsicLowering.
365 flushFPMsToMPM(PMW);
366 }
369
370 addIRPasses(PMW);
373 addISelPrepare(PMW);
374}
375
376/// Add common target configurable passes that perform LLVM IR to IR transforms
377/// following machine independent optimization.
379 // Before running any passes, run the verifier to determine if the input
380 // coming from the front-end and/or optimizer is valid.
381 if (!Opt.DisableVerify)
382 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
383
384 // Run loop strength reduction before anything else.
385 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
386 // These passes do not use MSSA.
387 LoopPassManager LPM;
388 LPM.addPass(CanonicalizeFreezeInLoopsPass());
389 LPM.addPass(LoopStrengthReducePass());
390 if (Opt.EnableLoopTermFold)
391 LPM.addPass(LoopTermFoldPass());
393 /*UseMemorySSA=*/false),
394 PMW);
395 }
396
397 // Run GC lowering passes for builtin collectors
398 // TODO: add a pass insertion point here
400 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
401 // splitting the function pipeline if we do not have to.
402 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
403 flushFPMsToMPM(PMW);
405 }
406
407 // Make sure that no unreachable blocks are instruction selected.
409
410 // Prepare expensive constants for SelectionDAG.
411 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
413
414 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
415 // operands with calls to the corresponding functions in a vector library.
418
420 !Opt.DisablePartialLibcallInlining)
422
423 // Instrument function entry and exit, e.g. with calls to mcount().
424 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
425
426 // Add scalarization of target's unsupported masked memory intrinsics pass.
427 // the unsupported intrinsic will be replaced with a chain of basic blocks,
428 // that stores/loads element one-by-one if the appropriate mask bit is set.
430
431 // Expand reduction intrinsics into shuffle sequences if the target wants to.
432 if (!Opt.DisableExpandReductions)
434
435 // Convert conditional moves to conditional jumps when profitable.
436 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
438
439 if (Opt.EnableGlobalMergeFunc) {
440 flushFPMsToMPM(PMW);
442 }
443}
444
445/// Turn exception handling constructs into something the code generators can
446/// handle.
448 const MCAsmInfo &MCAI = TM.getMCAsmInfo();
449 switch (MCAI.getExceptionHandlingType()) {
451 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
452 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
453 // catch info can get misplaced when a selector ends up more than one block
454 // removed from the parent invoke(s). This could happen when a landing
455 // pad is shared by multiple invokes and is also a target of a normal
456 // edge from elsewhere.
458 [[fallthrough]];
464 break;
466 // We support using both GCC-style and MSVC-style exceptions on Windows, so
467 // add both preparation passes. Each pass will only actually run if it
468 // recognizes the personality function.
471 break;
473 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
474 // on catchpads and cleanuppads because it does not outline them into
475 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
476 // should remove PHIs there.
478 break;
482 // Emscripten EH is lowered earlier by WebAssemblyLowerEmscriptenEHSjLj, so
483 // by this point it needs no generic EH preparation, like the None case.
485
486 // The lower invoke pass may create unreachable code. Remove it.
488 break;
489 }
490}
491
492/// Add pass to prepare the LLVM IR for code generation. This should be done
493/// before exception handling preparation passes.
495 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
497 // TODO: Default ctor'd RewriteSymbolPass is no-op.
498 // addPass(RewriteSymbolPass());
499}
500
501/// Add common passes that perform LLVM IR to IR transforms in preparation for
502/// instruction selection.
504 addPreISel(PMW);
505
506 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
508
510 // Add both the safe stack and the stack protection passes: each of them will
511 // only protect functions that have corresponding attributes.
514
515 if (Opt.PrintISelInput)
517 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
518 PMW);
519
520 // All passes which modify the LLVM IR are now complete; run the verifier
521 // to ensure that the IR is valid.
522 if (!Opt.DisableVerify)
523 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
524}
525
527 // Enable FastISel with -fast-isel, but allow that to be overridden.
528 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
530
531 // Determine an instruction selector.
532 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
533 SelectorType Selector;
534
535 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
536 Selector = SelectorType::FastISel;
537 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
538 (TM.Options.EnableGlobalISel &&
539 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
540 Selector = SelectorType::GlobalISel;
541 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
542 Selector = SelectorType::FastISel;
543 else
544 Selector = SelectorType::SelectionDAG;
545
546 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
547 if (Selector == SelectorType::FastISel) {
548 TM.setFastISel(true);
549 TM.setGlobalISel(false);
550 } else if (Selector == SelectorType::GlobalISel) {
551 TM.setFastISel(false);
552 TM.setGlobalISel(true);
553 }
554
555 // Add instruction selector passes.
556 if (Selector == SelectorType::GlobalISel) {
557 if (auto Err = addIRTranslator(PMW))
558 return Err;
559
561
562 if (auto Err = addLegalizeMachineIR(PMW))
563 return Err;
564
565 // Before running the register bank selector, ask the target if it
566 // wants to run some passes.
568
569 if (auto Err = addRegBankSelect(PMW))
570 return Err;
571
573
574 if (auto Err = addGlobalInstructionSelect(PMW))
575 return Err;
576
577 // Pass to reset the MachineFunction if the ISel failed.
581 PMW);
582
583 // Provide a fallback path when we do not want to abort on
584 // not-yet-supported input.
586 if (auto Err = addInstSelector(PMW))
587 return Err;
588
589 } else if (auto Err = addInstSelector(PMW))
590 return Err;
591
592 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
593 // FinalizeISel.
595
596 // // Print the instruction selected machine code...
597 // printAndVerify("After Instruction Selection");
598
599 return Error::success();
600}
601
602/// Add the complete set of target-independent postISel code generator passes.
603///
604/// This can be read as the standard order of major LLVM CodeGen stages. Stages
605/// with nontrivial configuration or multiple passes are broken out below in
606/// add%Stage routines.
607///
608/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
609/// addPre/Post methods with empty header implementations allow injecting
610/// target-specific fixups just before or after major stages. Additionally,
611/// targets have the flexibility to change pass order within a stage by
612/// overriding default implementation of add%Stage routines below. Each
613/// technique has maintainability tradeoffs because alternate pass orders are
614/// not well supported. addPre/Post works better if the target pass is easily
615/// tied to a common pass. But if it has subtle dependencies on multiple passes,
616/// the target should override the stage instead.
618 // Add passes that optimize machine instructions in SSA form.
621 } else {
622 // If the target requests it, assign local variables to stack slots relative
623 // to one another and simplify frame index references where possible.
625 }
626
627 if (TM.Options.EnableIPRA) {
628 flushFPMsToMPM(PMW);
630 PMW, /*Force=*/true);
632 }
633 // Run pre-ra passes.
634 addPreRegAlloc(PMW);
635
636 // Run register allocation and passes that are tightly coupled with it,
637 // including phi elimination and scheduling.
638 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
640 : addFastRegAlloc(PMW))
641 return Err;
642
643 // Run post-ra passes.
644 addPostRegAlloc(PMW);
645
648
649 // Insert prolog/epilog code. Eliminate abstract frame index references...
653 }
654
656
657 /// Add passes that optimize machine instructions after register allocation.
660
661 // Expand pseudo instructions before second scheduling pass.
663
664 // Run pre-sched2 passes.
665 addPreSched2(PMW);
666
667 if (Opt.EnableImplicitNullChecks)
669
670 // Second pass scheduler.
671 // Let Target optionally insert this pass by itself at some other
672 // point.
674 !TM.targetSchedulesPostRAScheduling()) {
675 if (Opt.MISchedPostRA)
677 else
679 }
680
681 // GC
682 addGCPasses(PMW);
683
684 // Basic block placement.
687
688 // Insert before XRay Instrumentation.
690
693
694 addPreEmitPass(PMW);
695
696 if (TM.Options.EnableIPRA) {
697 // Collect register usage information and produce a register mask of
698 // clobbered registers, to be used to optimize call sites.
700 // If -print-regusage is specified, print the collected register usage info.
701 if (Opt.PrintRegUsage) {
702 flushFPMsToMPM(PMW);
704 }
705 }
706
708
710 addMachineFunctionPass(StackMapLivenessPass(), PMW);
711 addMachineFunctionPass(LiveDebugValuesPass(TM.shouldEmitDebugEntryValues()),
712 PMW);
714
715 if (TM.Options.EnableMachineOutliner &&
717 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
718 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
719 TM.supportsDefaultOutlining()) {
720 flushFPMsToMPM(PMW);
721 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
722 }
723 }
724
725 if (Opt.EnableGCEmptyBlocks)
727
729
731
732 // Add passes that directly emit MI after all other MI passes.
733 addPreEmitPass2(PMW);
734
735 return Error::success();
736}
737
738/// Add passes that optimize machine instructions in SSA form.
740 // Pre-ra tail duplication.
742
743 // Optimize PHIs before DCE: removing dead PHI cycles may make more
744 // instructions dead.
746
747 // This pass merges large allocas. StackSlotColoring is a different pass
748 // which merges spill slots.
750
751 // If the target requests it, assign local variables to stack slots relative
752 // to one another and simplify frame index references where possible.
754
755 // With optimization, dead code should already be eliminated. However
756 // there is one known exception: lowered code for arguments that are only
757 // used by tail calls, where the tail calls reuse the incoming stack
758 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
760
761 // Allow targets to insert passes that improve instruction level parallelism,
762 // like if-conversion. Such passes will typically need dominator trees and
763 // loop info, just like LICM and CSE below.
764 addILPOpts(PMW);
765
768
769 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
770
772 // Clean-up the dead code that may have been generated by peephole
773 // rewriting.
775}
776
777//===---------------------------------------------------------------------===//
778/// Register Allocation Pass Configuration
779//===---------------------------------------------------------------------===//
780
781/// Instantiate the default register allocator pass for this target for either
782/// the optimized or unoptimized allocation path. This will be added to the pass
783/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
784/// in the optimized case.
785///
786/// A target that uses the standard regalloc pass order for fast or optimized
787/// allocation may still override this for per-target regalloc
788/// selection. But -regalloc-npm=... always takes precedence.
789/// If a target does not want to allow users to set -regalloc-npm=... at all,
790/// check if Opt.RegAlloc == RegAllocType::Unset.
792 bool Optimized) {
793 if (Optimized)
795 else
797}
798
799/// Find and instantiate the register allocation pass requested by this target
800/// at the current optimization level. Different register allocators are
801/// defined as separate passes because they may require different analysis.
802///
803/// This helper ensures that the -regalloc-npm= option is always available,
804/// even for targets that override the default allocator.
806 bool Optimized) {
807 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
808 if (Opt.RegAlloc > RegAllocType::Default) {
809 switch (Opt.RegAlloc) {
812 break;
815 break;
816 default:
817 reportFatalUsageError("register allocator not supported yet");
818 }
819 return;
820 }
821 // -regalloc=default or unspecified, so pick based on the optimization level
822 // or ask the target for the regalloc pass.
823 addTargetRegisterAllocator(PMW, Optimized);
824}
825
827 // TODO: Ensure allocator is default or fast.
828 addRegAllocPass(PMW, false);
829 return Error::success();
830}
831
834 // Add the selected register allocation pass.
835 addRegAllocPass(PMW, true);
836
837 // Allow targets to change the register assignments before rewriting.
838 addPreRewrite(PMW);
839
840 // Finally rewrite virtual registers.
842
843 return true;
844}
845
846/// Add the minimum set of target-independent passes that are required for
847/// register allocation. No coalescing or scheduling.
854
855/// Add standard target-independent passes that are tightly coupled with
856/// optimized register allocation, including coalescing, machine instruction
857/// scheduling, and register allocation itself.
860
862
864
865 // LiveVariables currently requires pure SSA form.
866 //
867 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
868 // LiveVariables can be removed completely, and LiveIntervals can be directly
869 // computed. (We still either need to regenerate kill flags after regalloc, or
870 // preferably fix the scavenger to not depend on them).
871 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
872 // When LiveVariables is removed this has to be removed/moved either.
873 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
874 // after it with -stop-before/-stop-after.
878
879 // LiveIntervals is computed unconditionally before TwoAddressInstruction so
880 // that pass can rely on it instead of LiveVariables. This is a step toward
881 // removing LiveVariables entirely.
884
885 // Edge splitting is smarter with machine loop info.
889
892
893 // The machine scheduler may accidentally create disconnected components
894 // when moving subregister definitions around, avoid this by splitting them to
895 // separate vregs before. Splitting can also improve reg. allocation quality.
897
898 // PreRA instruction scheduling.
900
902 if (!AddedPasses)
903 return AddedPasses.takeError();
904 if (!AddedPasses.get())
905 return Error::success();
906
908
909 // Allow targets to expand pseudo instructions depending on the choice of
910 // registers before MachineCopyPropagation.
911 addPostRewrite(PMW);
912
913 // Copy propagate to forward register uses and try to eliminate COPYs that
914 // were not coalesced.
916
917 // Run post-ra machine LICM to hoist reloads / remats.
918 //
919 // FIXME: can this move into MachineLateOptimization?
921
922 return Error::success();
923}
924
925//===---------------------------------------------------------------------===//
926/// Post RegAlloc Pass Configuration
927//===---------------------------------------------------------------------===//
928
929/// Add passes that optimize machine instructions after register allocation.
931 // Cleanup of redundant (identical) address/immediate loads.
933
934 // Branch folding must be run after regalloc and prolog/epilog insertion.
935 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
936
937 // Tail duplication.
938 // Note that duplicating tail just increases code size and degrades
939 // performance for targets that require Structured Control Flow.
940 // In addition it can also make CFG irreducible. Thus we disable it.
941 if (!TM.requiresStructuredCFG())
943
944 // Copy propagation.
946}
947
948/// Add standard basic block placement passes.
951 // Run a separate pass to collect block placement statistics.
952 if (Opt.EnableBlockPlacementStats)
954}
amdgpu next use AMDGPU Next Use Analysis Printer
This header provides classes for managing passes over SCCs of the call graph.
Interfaces for producing common pass manager configurations.
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...
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This file contains the declaration of the ResetMachineFunctionPass class.
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.
static const char PassName[]
A pass that canonicalizes freeze instructions in a loop.
virtual void addPreEmitPass(PassManagerWrapper &PMW)
This pass may be implemented by targets that want to run passes immediately before machine code is em...
virtual void addMachineSSAOptimization(PassManagerWrapper &PMW)
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
void addRegAllocPass(PassManagerWrapper &PMW, bool Optimized)
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addMachineFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
CodeGenPassBuilder(TargetMachine &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
virtual Error addLegalizeMachineIR(PassManagerWrapper &PMW)
This method should install a legalize pass, which converts the instruction sequence into one that can...
virtual void addPreRewrite(PassManagerWrapper &PMW)
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
virtual Error addMachinePasses(PassManagerWrapper &PMW)
Add the complete, standard set of LLVM CodeGen passes.
void flushFPMsToMPM(PassManagerWrapper &PMW, bool FreeMachineFunctions=false)
virtual void addAsmPrinter(PassManagerWrapper &PMW)
virtual Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW)
Add core register allocator passes which do the actual register assignment and rewriting.
void addFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual void addIRPasses(PassManagerWrapper &PMW)
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addMachineLateOptimization(PassManagerWrapper &PMW)
Add passes that optimize machine instructions after register allocation.
Error buildPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
virtual void addPreRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before register allocat...
virtual void addPostRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after register allocation pass pipe...
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
virtual void addPreSched2(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
void addISelPasses(PassManagerWrapper &PMW)
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
virtual void addCodeGenPrepare(PassManagerWrapper &PMW)
Add pass to prepare the LLVM IR for code generation.
Error addCoreISelPasses(PassManagerWrapper &PMW)
Add the actual instruction selection passes.
virtual void addPreEmitPass2(PassManagerWrapper &PMW)
Targets may add passes immediately before machine code is emitted in this callback.
virtual void addPreRegBankSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the register ban...
virtual void addGlobalMergePass(PassManagerWrapper &PMW)
Target can override this to add GlobalMergePass before all IR passes.
CodeGenOptLevel getOptLevel() const
virtual void addTargetRegisterAllocator(PassManagerWrapper &PMW, bool Optimized)
Utilities for targets to add passes to the pass manager.
virtual Error addGlobalInstructionSelect(PassManagerWrapper &PMW)
This method should install a (global) instruction selector pass, which converts possibly generic inst...
virtual void addAsmPrinterBegin(PassManagerWrapper &PMW)
virtual Error addIRTranslator(PassManagerWrapper &PMW)
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
virtual void addPreLegalizeMachineIR(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before legalization.
virtual Expected< bool > addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW)
virtual void addISelPrepare(PassManagerWrapper &PMW)
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
virtual void addPreISel(PassManagerWrapper &PMW)
{{@ For GlobalISel
virtual Error addOptimizedRegAlloc(PassManagerWrapper &PMW)
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addPostBBSections(PassManagerWrapper &PMW)
void addModulePass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual Error addFastRegAlloc(PassManagerWrapper &PMW)
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addPreGlobalInstructionSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the (global) ins...
void addPassesToHandleExceptions(PassManagerWrapper &PMW)
Add passes to lower exception handling for the code generator.
virtual void addILPOpts(PassManagerWrapper &PMW)
Add passes that optimize instruction level parallelism for out-of-order targets.
PassInstrumentationCallbacks * PIC
virtual void addAsmPrinterEnd(PassManagerWrapper &PMW)
virtual Error addInstSelector(PassManagerWrapper &PMW)
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
virtual void addBlockPlacement(PassManagerWrapper &PMW)
Add standard basic block placement passes.
virtual void addPostRewrite(PassManagerWrapper &PMW)
Add passes to be run immediately after virtual registers are rewritten to physical registers.
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
virtual void addGCPasses(PassManagerWrapper &PMW)
addGCPasses - Add late codegen passes that analyze code for garbage collection.
void requireCGSCCOrder(PassManagerWrapper &PMW)
virtual Error addRegBankSelect(PassManagerWrapper &PMW)
This method should install a register bank selector pass, which assigns register banks to virtual reg...
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
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:67
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:656
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 (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...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
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.
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:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
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:256
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:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:64
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Global function merging pass for new pass manager.
A utility pass template to force an analysis result to be available.