LLVM 20.0.0git
SelectionDAGISel.cpp
Go to the documentation of this file.
1//===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
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 implements the SelectionDAGISel class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ScheduleDAGSDNodes.h"
15#include "SelectionDAGBuilder.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringRef.h"
27#include "llvm/Analysis/CFG.h"
64#include "llvm/IR/BasicBlock.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
69#include "llvm/IR/DebugLoc.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsWebAssembly.h"
80#include "llvm/IR/Metadata.h"
81#include "llvm/IR/Module.h"
82#include "llvm/IR/PrintPasses.h"
83#include "llvm/IR/Statepoint.h"
84#include "llvm/IR/Type.h"
85#include "llvm/IR/User.h"
86#include "llvm/IR/Value.h"
88#include "llvm/MC/MCInstrDesc.h"
89#include "llvm/Pass.h"
95#include "llvm/Support/Debug.h"
98#include "llvm/Support/Timer.h"
104#include <algorithm>
105#include <cassert>
106#include <cstdint>
107#include <iterator>
108#include <limits>
109#include <memory>
110#include <optional>
111#include <string>
112#include <utility>
113#include <vector>
114
115using namespace llvm;
116
117#define DEBUG_TYPE "isel"
118#define ISEL_DUMP_DEBUG_TYPE DEBUG_TYPE "-dump"
119
120STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
121STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
122STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
123STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
124STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
125STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
126STATISTIC(NumFastIselFailLowerArguments,
127 "Number of entry blocks where fast isel failed to lower arguments");
128
130 "fast-isel-abort", cl::Hidden,
131 cl::desc("Enable abort calls when \"fast\" instruction selection "
132 "fails to lower an instruction: 0 disable the abort, 1 will "
133 "abort but for args, calls and terminators, 2 will also "
134 "abort for argument lowering, and 3 will never fallback "
135 "to SelectionDAG."));
136
138 "fast-isel-report-on-fallback", cl::Hidden,
139 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
140 "falls back to SelectionDAG."));
141
142static cl::opt<bool>
143UseMBPI("use-mbpi",
144 cl::desc("use Machine Branch Probability Info"),
145 cl::init(true), cl::Hidden);
146
147#ifndef NDEBUG
150 cl::desc("Only display the basic block whose name "
151 "matches this for all view-*-dags options"));
152static cl::opt<bool>
153ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
154 cl::desc("Pop up a window to show dags before the first "
155 "dag combine pass"));
156static cl::opt<bool>
157ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
158 cl::desc("Pop up a window to show dags before legalize types"));
159static cl::opt<bool>
160 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
161 cl::desc("Pop up a window to show dags before the post "
162 "legalize types dag combine pass"));
163static cl::opt<bool>
164 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
165 cl::desc("Pop up a window to show dags before legalize"));
166static cl::opt<bool>
167ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
168 cl::desc("Pop up a window to show dags before the second "
169 "dag combine pass"));
170static cl::opt<bool>
171ViewISelDAGs("view-isel-dags", cl::Hidden,
172 cl::desc("Pop up a window to show isel dags as they are selected"));
173static cl::opt<bool>
174ViewSchedDAGs("view-sched-dags", cl::Hidden,
175 cl::desc("Pop up a window to show sched dags as they are processed"));
176static cl::opt<bool>
177ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
178 cl::desc("Pop up a window to show SUnit dags after they are processed"));
179#else
180static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
181 ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
182 ViewDAGCombine2 = false, ViewISelDAGs = false,
183 ViewSchedDAGs = false, ViewSUnitDAGs = false;
184#endif
185
186#ifndef NDEBUG
187#define ISEL_DUMP(X) \
188 do { \
189 if (llvm::DebugFlag && \
190 (isCurrentDebugType(DEBUG_TYPE) || \
191 (isCurrentDebugType(ISEL_DUMP_DEBUG_TYPE) && MatchFilterFuncName))) { \
192 X; \
193 } \
194 } while (false)
195#else
196#define ISEL_DUMP(X) do { } while (false)
197#endif
198
199//===---------------------------------------------------------------------===//
200///
201/// RegisterScheduler class - Track the registration of instruction schedulers.
202///
203//===---------------------------------------------------------------------===//
206
207//===---------------------------------------------------------------------===//
208///
209/// ISHeuristic command line option for instruction schedulers.
210///
211//===---------------------------------------------------------------------===//
214ISHeuristic("pre-RA-sched",
216 cl::desc("Instruction schedulers available (before register"
217 " allocation):"));
218
220defaultListDAGScheduler("default", "Best scheduler for the target",
222
223static bool dontUseFastISelFor(const Function &Fn) {
224 // Don't enable FastISel for functions with swiftasync Arguments.
225 // Debug info on those is reliant on good Argument lowering, and FastISel is
226 // not capable of lowering the entire function. Mixing the two selectors tend
227 // to result in poor lowering of Arguments.
228 return any_of(Fn.args(), [](const Argument &Arg) {
229 return Arg.hasAttribute(Attribute::AttrKind::SwiftAsync);
230 });
231}
232
233namespace llvm {
234
235 //===--------------------------------------------------------------------===//
236 /// This class is used by SelectionDAGISel to temporarily override
237 /// the optimization level on a per-function basis.
240 CodeGenOptLevel SavedOptLevel;
241 bool SavedFastISel;
242
243 public:
245 : IS(ISel) {
246 SavedOptLevel = IS.OptLevel;
247 SavedFastISel = IS.TM.Options.EnableFastISel;
248 if (NewOptLevel != SavedOptLevel) {
249 IS.OptLevel = NewOptLevel;
250 IS.TM.setOptLevel(NewOptLevel);
251 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
252 << IS.MF->getFunction().getName() << "\n");
253 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel)
254 << " ; After: -O" << static_cast<int>(NewOptLevel)
255 << "\n");
256 if (NewOptLevel == CodeGenOptLevel::None)
258 }
260 IS.TM.setFastISel(false);
262 dbgs() << "\tFastISel is "
263 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
264 << "\n");
265 }
266
268 if (IS.OptLevel == SavedOptLevel)
269 return;
270 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
271 << IS.MF->getFunction().getName() << "\n");
272 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
273 << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
274 IS.OptLevel = SavedOptLevel;
275 IS.TM.setOptLevel(SavedOptLevel);
276 IS.TM.setFastISel(SavedFastISel);
277 }
278 };
279
280 //===--------------------------------------------------------------------===//
281 /// createDefaultScheduler - This creates an instruction scheduler appropriate
282 /// for the target.
284 CodeGenOptLevel OptLevel) {
285 const TargetLowering *TLI = IS->TLI;
286 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
287
288 // Try first to see if the Target has its own way of selecting a scheduler
289 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
290 return SchedulerCtor(IS, OptLevel);
291 }
292
293 if (OptLevel == CodeGenOptLevel::None ||
294 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
296 return createSourceListDAGScheduler(IS, OptLevel);
298 return createBURRListDAGScheduler(IS, OptLevel);
300 return createHybridListDAGScheduler(IS, OptLevel);
302 return createVLIWDAGScheduler(IS, OptLevel);
304 return createFastDAGScheduler(IS, OptLevel);
306 return createDAGLinearizer(IS, OptLevel);
308 "Unknown sched type!");
309 return createILPListDAGScheduler(IS, OptLevel);
310 }
311
312} // end namespace llvm
313
316 MachineBasicBlock *MBB) const {
317#ifndef NDEBUG
318 dbgs() << "If a target marks an instruction with "
319 "'usesCustomInserter', it must implement "
320 "TargetLowering::EmitInstrWithCustomInserter!\n";
321#endif
322 llvm_unreachable(nullptr);
323}
324
326 SDNode *Node) const {
327 assert(!MI.hasPostISelHook() &&
328 "If a target marks an instruction with 'hasPostISelHook', "
329 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
330}
331
332//===----------------------------------------------------------------------===//
333// SelectionDAGISel code
334//===----------------------------------------------------------------------===//
335
337 char &ID, std::unique_ptr<SelectionDAGISel> S)
338 : MachineFunctionPass(ID), Selector(std::move(S)) {
344}
345
347 // If we already selected that function, we do not need to run SDISel.
348 if (MF.getProperties().hasProperty(
350 return false;
351
352 // Do some sanity-checking on the command-line options.
353 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
354 report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
355
356 // Decide what flavour of variable location debug-info will be used, before
357 // we change the optimisation level.
359
360 // Reset the target options before resetting the optimization
361 // level below.
362 // FIXME: This is a horrible hack and should be processed via
363 // codegen looking at the optimization level explicitly when
364 // it wants to look at it.
365 Selector->TM.resetTargetOptions(MF.getFunction());
366 // Reset OptLevel to None for optnone functions.
367 CodeGenOptLevel NewOptLevel = skipFunction(MF.getFunction())
369 : Selector->OptLevel;
370
371 Selector->MF = &MF;
372 OptLevelChanger OLC(*Selector, NewOptLevel);
373 Selector->initializeAnalysisResults(*this);
374 return Selector->runOnMachineFunction(MF);
375}
376
378 : TM(tm), FuncInfo(new FunctionLoweringInfo()),
379 SwiftError(new SwiftErrorValueTracking()),
380 CurDAG(new SelectionDAG(tm, OL)),
381 SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
382 OL)),
383 OptLevel(OL) {
389}
390
392 delete CurDAG;
393 delete SwiftError;
394}
395
397 CodeGenOptLevel OptLevel = Selector->OptLevel;
398 if (OptLevel != CodeGenOptLevel::None)
404#ifndef NDEBUG
406#endif
408 if (UseMBPI && OptLevel != CodeGenOptLevel::None)
411 // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
412 // the module.
415 if (OptLevel != CodeGenOptLevel::None)
418}
419
420static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
421 MachineModuleInfo &MMI) {
422 // Only needed for MSVC
423 if (!TT.isWindowsMSVCEnvironment())
424 return;
425
426 // If it's already set, nothing to do.
427 if (MMI.usesMSVCFloatingPoint())
428 return;
429
430 for (const Instruction &I : instructions(F)) {
431 if (I.getType()->isFPOrFPVectorTy()) {
432 MMI.setUsesMSVCFloatingPoint(true);
433 return;
434 }
435 for (const auto &Op : I.operands()) {
436 if (Op->getType()->isFPOrFPVectorTy()) {
437 MMI.setUsesMSVCFloatingPoint(true);
438 return;
439 }
440 }
441 }
442}
443
447 // If we already selected that function, we do not need to run SDISel.
448 if (MF.getProperties().hasProperty(
450 return PreservedAnalyses::all();
451
452 // Do some sanity-checking on the command-line options.
453 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
454 report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
455
456 // Decide what flavour of variable location debug-info will be used, before
457 // we change the optimisation level.
459
460 // Reset the target options before resetting the optimization
461 // level below.
462 // FIXME: This is a horrible hack and should be processed via
463 // codegen looking at the optimization level explicitly when
464 // it wants to look at it.
465 Selector->TM.resetTargetOptions(MF.getFunction());
466 // Reset OptLevel to None for optnone functions.
467 // TODO: Add a function analysis to handle this.
468 Selector->MF = &MF;
469 // Reset OptLevel to None for optnone functions.
470 CodeGenOptLevel NewOptLevel = MF.getFunction().hasOptNone()
472 : Selector->OptLevel;
473
474 OptLevelChanger OLC(*Selector, NewOptLevel);
475 Selector->initializeAnalysisResults(MFAM);
476 Selector->runOnMachineFunction(MF);
477
479}
480
484 .getManager();
486 Function &Fn = MF->getFunction();
487#ifndef NDEBUG
488 FuncName = Fn.getName();
490#else
492#endif
493
496 RegInfo = &MF->getRegInfo();
498 GFI = Fn.hasGC() ? &FAM.getResult<GCFunctionAnalysis>(Fn) : nullptr;
499 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
501 auto *PSI = MAMP.getCachedResult<ProfileSummaryAnalysis>(*Fn.getParent());
502 BlockFrequencyInfo *BFI = nullptr;
504 if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
506
507 FunctionVarLocs const *FnVarLocs = nullptr;
510
513 MAMP.getCachedResult<MachineModuleAnalysis>(*Fn.getParent())->getMMI();
514
515 CurDAG->init(*MF, *ORE, MFAM, LibInfo, UA, PSI, BFI, MMI, FnVarLocs);
516
517 // Now get the optional analyzes if we want to.
518 // This is based on the possibly changed OptLevel (after optnone is taken
519 // into account). That's unfortunate but OK because it just means we won't
520 // ask for passes that have been required anyway.
521
524 else
525 FuncInfo->BPI = nullptr;
526
528 AA = &FAM.getResult<AAManager>(Fn);
529 else
530 AA = nullptr;
531
533
534#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
536#endif
537}
538
540 Function &Fn = MF->getFunction();
541#ifndef NDEBUG
542 FuncName = Fn.getName();
544#else
546#endif
547
550 RegInfo = &MF->getRegInfo();
552 GFI = Fn.hasGC() ? &MFP.getAnalysis<GCModuleInfo>().getFunctionInfo(Fn)
553 : nullptr;
554 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
555 AC = &MFP.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(Fn);
556 auto *PSI = &MFP.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
557 BlockFrequencyInfo *BFI = nullptr;
558 if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
559 BFI = &MFP.getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
560
561 FunctionVarLocs const *FnVarLocs = nullptr;
563 FnVarLocs = MFP.getAnalysis<AssignmentTrackingAnalysis>().getResults();
564
565 UniformityInfo *UA = nullptr;
566 if (auto *UAPass = MFP.getAnalysisIfAvailable<UniformityInfoWrapperPass>())
567 UA = &UAPass->getUniformityInfo();
568
571
572 CurDAG->init(*MF, *ORE, &MFP, LibInfo, UA, PSI, BFI, MMI, FnVarLocs);
573
574 // Now get the optional analyzes if we want to.
575 // This is based on the possibly changed OptLevel (after optnone is taken
576 // into account). That's unfortunate but OK because it just means we won't
577 // ask for passes that have been required anyway.
578
580 FuncInfo->BPI =
582 else
583 FuncInfo->BPI = nullptr;
584
586 AA = &MFP.getAnalysis<AAResultsWrapperPass>().getAAResults();
587 else
588 AA = nullptr;
589
590 SP = &MFP.getAnalysis<StackProtector>().getLayoutInfo();
591
592#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
594#endif
595}
596
599 const Function &Fn = mf.getFunction();
600
601 bool InstrRef = mf.shouldUseDebugInstrRef();
602
603 FuncInfo->set(MF->getFunction(), *MF, CurDAG);
604
605 ISEL_DUMP(dbgs() << "\n\n\n=== " << FuncName << '\n');
606
607 SDB->init(GFI, AA, AC, LibInfo);
608
609 MF->setHasInlineAsm(false);
610
611 FuncInfo->SplitCSR = false;
612
613 // We split CSR if the target supports it for the given function
614 // and the function has only return exits.
616 FuncInfo->SplitCSR = true;
617
618 // Collect all the return blocks.
619 for (const BasicBlock &BB : Fn) {
620 if (!succ_empty(&BB))
621 continue;
622
623 const Instruction *Term = BB.getTerminator();
624 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
625 continue;
626
627 // Bail out if the exit block is not Return nor Unreachable.
628 FuncInfo->SplitCSR = false;
629 break;
630 }
631 }
632
633 MachineBasicBlock *EntryMBB = &MF->front();
634 if (FuncInfo->SplitCSR)
635 // This performs initialization so lowering for SplitCSR will be correct.
636 TLI->initializeSplitCSR(EntryMBB);
637
638 SelectAllBasicBlocks(Fn);
640 DiagnosticInfoISelFallback DiagFallback(Fn);
641 Fn.getContext().diagnose(DiagFallback);
642 }
643
644 // Replace forward-declared registers with the registers containing
645 // the desired value.
646 // Note: it is important that this happens **before** the call to
647 // EmitLiveInCopies, since implementations can skip copies of unused
648 // registers. If we don't apply the reg fixups before, some registers may
649 // appear as unused and will be skipped, resulting in bad MI.
651 for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
652 E = FuncInfo->RegFixups.end();
653 I != E; ++I) {
654 Register From = I->first;
655 Register To = I->second;
656 // If To is also scheduled to be replaced, find what its ultimate
657 // replacement is.
658 while (true) {
659 DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
660 if (J == E)
661 break;
662 To = J->second;
663 }
664 // Make sure the new register has a sufficiently constrained register class.
665 if (From.isVirtual() && To.isVirtual())
666 MRI.constrainRegClass(To, MRI.getRegClass(From));
667 // Replace it.
668
669 // Replacing one register with another won't touch the kill flags.
670 // We need to conservatively clear the kill flags as a kill on the old
671 // register might dominate existing uses of the new register.
672 if (!MRI.use_empty(To))
673 MRI.clearKillFlags(From);
674 MRI.replaceRegWith(From, To);
675 }
676
677 // If the first basic block in the function has live ins that need to be
678 // copied into vregs, emit the copies into the top of the block before
679 // emitting the code for the block.
681 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
682
683 // Insert copies in the entry block and the return blocks.
684 if (FuncInfo->SplitCSR) {
686 // Collect all the return blocks.
687 for (MachineBasicBlock &MBB : mf) {
688 if (!MBB.succ_empty())
689 continue;
690
692 if (Term != MBB.end() && Term->isReturn()) {
693 Returns.push_back(&MBB);
694 continue;
695 }
696 }
697 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
698 }
699
701 if (!FuncInfo->ArgDbgValues.empty())
702 for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
703 if (LI.second)
704 LiveInMap.insert(LI);
705
706 // Insert DBG_VALUE instructions for function arguments to the entry block.
707 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
708 MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
709 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
710 "Function parameters should not be described by DBG_VALUE_LIST.");
711 bool hasFI = MI->getDebugOperand(0).isFI();
712 Register Reg =
713 hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
714 if (Reg.isPhysical())
715 EntryMBB->insert(EntryMBB->begin(), MI);
716 else {
717 MachineInstr *Def = RegInfo->getVRegDef(Reg);
718 if (Def) {
719 MachineBasicBlock::iterator InsertPos = Def;
720 // FIXME: VR def may not be in entry block.
721 Def->getParent()->insert(std::next(InsertPos), MI);
722 } else
723 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
724 << Register::virtReg2Index(Reg) << "\n");
725 }
726
727 // Don't try and extend through copies in instruction referencing mode.
728 if (InstrRef)
729 continue;
730
731 // If Reg is live-in then update debug info to track its copy in a vreg.
732 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
733 if (LDI != LiveInMap.end()) {
734 assert(!hasFI && "There's no handling of frame pointer updating here yet "
735 "- add if needed");
736 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
737 MachineBasicBlock::iterator InsertPos = Def;
738 const MDNode *Variable = MI->getDebugVariable();
739 const MDNode *Expr = MI->getDebugExpression();
740 DebugLoc DL = MI->getDebugLoc();
741 bool IsIndirect = MI->isIndirectDebugValue();
742 if (IsIndirect)
743 assert(MI->getDebugOffset().getImm() == 0 &&
744 "DBG_VALUE with nonzero offset");
745 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
746 "Expected inlined-at fields to agree");
747 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
748 "Didn't expect to see a DBG_VALUE_LIST here");
749 // Def is never a terminator here, so it is ok to increment InsertPos.
750 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
751 IsIndirect, LDI->second, Variable, Expr);
752
753 // If this vreg is directly copied into an exported register then
754 // that COPY instructions also need DBG_VALUE, if it is the only
755 // user of LDI->second.
756 MachineInstr *CopyUseMI = nullptr;
757 for (MachineInstr &UseMI : RegInfo->use_instructions(LDI->second)) {
758 if (UseMI.isDebugValue())
759 continue;
760 if (UseMI.isCopy() && !CopyUseMI && UseMI.getParent() == EntryMBB) {
761 CopyUseMI = &UseMI;
762 continue;
763 }
764 // Otherwise this is another use or second copy use.
765 CopyUseMI = nullptr;
766 break;
767 }
768 if (CopyUseMI &&
769 TRI.getRegSizeInBits(LDI->second, MRI) ==
770 TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
771 // Use MI's debug location, which describes where Variable was
772 // declared, rather than whatever is attached to CopyUseMI.
773 MachineInstr *NewMI =
774 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
775 CopyUseMI->getOperand(0).getReg(), Variable, Expr);
776 MachineBasicBlock::iterator Pos = CopyUseMI;
777 EntryMBB->insertAfter(Pos, NewMI);
778 }
779 }
780 }
781
782 // For debug-info, in instruction referencing mode, we need to perform some
783 // post-isel maintenence.
784 if (MF->useDebugInstrRef())
786
787 // Determine if there are any calls in this machine function.
789 for (const auto &MBB : *MF) {
790 if (MFI.hasCalls() && MF->hasInlineAsm())
791 break;
792
793 for (const auto &MI : MBB) {
794 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
795 if ((MCID.isCall() && !MCID.isReturn()) ||
796 MI.isStackAligningInlineAsm()) {
797 MFI.setHasCalls(true);
798 }
799 if (MI.isInlineAsm()) {
800 MF->setHasInlineAsm(true);
801 }
802 }
803 }
804
805 // Determine if floating point is used for msvc
807
808 // Release function-specific state. SDB and CurDAG are already cleared
809 // at this point.
810 FuncInfo->clear();
811
812 ISEL_DUMP(dbgs() << "*** MachineFunction at end of ISel ***\n");
813 ISEL_DUMP(MF->print(dbgs()));
814
815 return true;
816}
817
821 bool ShouldAbort) {
822 // Print the function name explicitly if we don't have a debug location (which
823 // makes the diagnostic less useful) or if we're going to emit a raw error.
824 if (!R.getLocation().isValid() || ShouldAbort)
825 R << (" (in function: " + MF.getName() + ")").str();
826
827 if (ShouldAbort)
828 report_fatal_error(Twine(R.getMsg()));
829
830 ORE.emit(R);
831 LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
832}
833
834void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
836 bool &HadTailCall) {
837 // Allow creating illegal types during DAG building for the basic block.
839
840 // Lower the instructions. If a call is emitted as a tail call, cease emitting
841 // nodes for this block. If an instruction is elided, don't emit it, but do
842 // handle any debug-info attached to it.
843 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
844 if (!ElidedArgCopyInstrs.count(&*I))
845 SDB->visit(*I);
846 else
847 SDB->visitDbgInfo(*I);
848 }
849
850 // Make sure the root of the DAG is up-to-date.
851 CurDAG->setRoot(SDB->getControlRoot());
852 HadTailCall = SDB->HasTailCall;
853 SDB->resolveOrClearDbgInfo();
854 SDB->clear();
855
856 // Final step, emit the lowered DAG as machine code.
857 CodeGenAndEmitDAG();
858}
859
860void SelectionDAGISel::ComputeLiveOutVRegInfo() {
863
864 Worklist.push_back(CurDAG->getRoot().getNode());
865 Added.insert(CurDAG->getRoot().getNode());
866
867 KnownBits Known;
868
869 do {
870 SDNode *N = Worklist.pop_back_val();
871
872 // Otherwise, add all chain operands to the worklist.
873 for (const SDValue &Op : N->op_values())
874 if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
875 Worklist.push_back(Op.getNode());
876
877 // If this is a CopyToReg with a vreg dest, process it.
878 if (N->getOpcode() != ISD::CopyToReg)
879 continue;
880
881 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
882 if (!Register::isVirtualRegister(DestReg))
883 continue;
884
885 // Ignore non-integer values.
886 SDValue Src = N->getOperand(2);
887 EVT SrcVT = Src.getValueType();
888 if (!SrcVT.isInteger())
889 continue;
890
891 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
892 Known = CurDAG->computeKnownBits(Src);
893 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
894 } while (!Worklist.empty());
895}
896
897void SelectionDAGISel::CodeGenAndEmitDAG() {
898 StringRef GroupName = "sdag";
899 StringRef GroupDescription = "Instruction Selection and Scheduling";
900 std::string BlockName;
901 bool MatchFilterBB = false;
902 (void)MatchFilterBB;
903
904 // Pre-type legalization allow creation of any node types.
906
907#ifndef NDEBUG
908 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
910 FuncInfo->MBB->getBasicBlock()->getName());
911#endif
912#ifdef NDEBUG
916#endif
917 {
918 BlockName =
919 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
920 }
921 ISEL_DUMP(dbgs() << "\nInitial selection DAG: "
922 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
923 << "'\n";
924 CurDAG->dump());
925
926#if LLVM_ENABLE_ABI_BREAKING_CHECKS
929#endif
930
931 if (ViewDAGCombine1 && MatchFilterBB)
932 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
933
934 // Run the DAG combiner in pre-legalize mode.
935 {
936 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
937 GroupDescription, TimePassesIsEnabled);
939 }
940
941 ISEL_DUMP(dbgs() << "\nOptimized lowered selection DAG: "
942 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
943 << "'\n";
944 CurDAG->dump());
945
946#if LLVM_ENABLE_ABI_BREAKING_CHECKS
949#endif
950
951 // Second step, hack on the DAG until it only uses operations and types that
952 // the target supports.
953 if (ViewLegalizeTypesDAGs && MatchFilterBB)
954 CurDAG->viewGraph("legalize-types input for " + BlockName);
955
956 bool Changed;
957 {
958 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
959 GroupDescription, TimePassesIsEnabled);
960 Changed = CurDAG->LegalizeTypes();
961 }
962
963 ISEL_DUMP(dbgs() << "\nType-legalized selection DAG: "
964 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
965 << "'\n";
966 CurDAG->dump());
967
968#if LLVM_ENABLE_ABI_BREAKING_CHECKS
971#endif
972
973 // Only allow creation of legal node types.
975
976 if (Changed) {
977 if (ViewDAGCombineLT && MatchFilterBB)
978 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
979
980 // Run the DAG combiner in post-type-legalize mode.
981 {
982 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
983 GroupName, GroupDescription, TimePassesIsEnabled);
985 }
986
987 ISEL_DUMP(dbgs() << "\nOptimized type-legalized selection DAG: "
988 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
989 << "'\n";
990 CurDAG->dump());
991
992#if LLVM_ENABLE_ABI_BREAKING_CHECKS
995#endif
996 }
997
998 {
999 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
1000 GroupDescription, TimePassesIsEnabled);
1001 Changed = CurDAG->LegalizeVectors();
1002 }
1003
1004 if (Changed) {
1005 ISEL_DUMP(dbgs() << "\nVector-legalized selection DAG: "
1006 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1007 << "'\n";
1008 CurDAG->dump());
1009
1010#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1011 if (TTI->hasBranchDivergence())
1013#endif
1014
1015 {
1016 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
1017 GroupDescription, TimePassesIsEnabled);
1019 }
1020
1021 ISEL_DUMP(dbgs() << "\nVector/type-legalized selection DAG: "
1022 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1023 << "'\n";
1024 CurDAG->dump());
1025
1026#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1027 if (TTI->hasBranchDivergence())
1029#endif
1030
1031 if (ViewDAGCombineLT && MatchFilterBB)
1032 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
1033
1034 // Run the DAG combiner in post-type-legalize mode.
1035 {
1036 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
1037 GroupName, GroupDescription, TimePassesIsEnabled);
1039 }
1040
1041 ISEL_DUMP(dbgs() << "\nOptimized vector-legalized selection DAG: "
1042 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1043 << "'\n";
1044 CurDAG->dump());
1045
1046#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1047 if (TTI->hasBranchDivergence())
1049#endif
1050 }
1051
1052 if (ViewLegalizeDAGs && MatchFilterBB)
1053 CurDAG->viewGraph("legalize input for " + BlockName);
1054
1055 {
1056 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
1057 GroupDescription, TimePassesIsEnabled);
1058 CurDAG->Legalize();
1059 }
1060
1061 ISEL_DUMP(dbgs() << "\nLegalized selection DAG: "
1062 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1063 << "'\n";
1064 CurDAG->dump());
1065
1066#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1067 if (TTI->hasBranchDivergence())
1069#endif
1070
1071 if (ViewDAGCombine2 && MatchFilterBB)
1072 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
1073
1074 // Run the DAG combiner in post-legalize mode.
1075 {
1076 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
1077 GroupDescription, TimePassesIsEnabled);
1079 }
1080
1081 ISEL_DUMP(dbgs() << "\nOptimized legalized selection DAG: "
1082 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1083 << "'\n";
1084 CurDAG->dump());
1085
1086#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1087 if (TTI->hasBranchDivergence())
1089#endif
1090
1092 ComputeLiveOutVRegInfo();
1093
1094 if (ViewISelDAGs && MatchFilterBB)
1095 CurDAG->viewGraph("isel input for " + BlockName);
1096
1097 // Third, instruction select all of the operations to machine code, adding the
1098 // code to the MachineBasicBlock.
1099 {
1100 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
1101 GroupDescription, TimePassesIsEnabled);
1102 DoInstructionSelection();
1103 }
1104
1105 ISEL_DUMP(dbgs() << "\nSelected selection DAG: "
1106 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1107 << "'\n";
1108 CurDAG->dump());
1109
1110 if (ViewSchedDAGs && MatchFilterBB)
1111 CurDAG->viewGraph("scheduler input for " + BlockName);
1112
1113 // Schedule machine code.
1114 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
1115 {
1116 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
1117 GroupDescription, TimePassesIsEnabled);
1118 Scheduler->Run(CurDAG, FuncInfo->MBB);
1119 }
1120
1121 if (ViewSUnitDAGs && MatchFilterBB)
1122 Scheduler->viewGraph();
1123
1124 // Emit machine code to BB. This can change 'BB' to the last block being
1125 // inserted into.
1126 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
1127 {
1128 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
1129 GroupDescription, TimePassesIsEnabled);
1130
1131 // FuncInfo->InsertPt is passed by reference and set to the end of the
1132 // scheduled instructions.
1133 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
1134 }
1135
1136 // If the block was split, make sure we update any references that are used to
1137 // update PHI nodes later on.
1138 if (FirstMBB != LastMBB)
1139 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
1140
1141 // Free the scheduler state.
1142 {
1143 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
1144 GroupDescription, TimePassesIsEnabled);
1145 delete Scheduler;
1146 }
1147
1148 // Free the SelectionDAG state, now that we're finished with it.
1149 CurDAG->clear();
1150}
1151
1152namespace {
1153
1154/// ISelUpdater - helper class to handle updates of the instruction selection
1155/// graph.
1156class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1157 SelectionDAG::allnodes_iterator &ISelPosition;
1158
1159public:
1160 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1161 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1162
1163 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1164 /// deleted is the current ISelPosition node, update ISelPosition.
1165 ///
1166 void NodeDeleted(SDNode *N, SDNode *E) override {
1167 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1168 ++ISelPosition;
1169 }
1170
1171 /// NodeInserted - Handle new nodes inserted into the graph: propagate
1172 /// metadata from root nodes that also applies to new nodes, in case the root
1173 /// is later deleted.
1174 void NodeInserted(SDNode *N) override {
1175 SDNode *CurNode = &*ISelPosition;
1176 if (MDNode *MD = DAG.getPCSections(CurNode))
1177 DAG.addPCSections(N, MD);
1178 if (MDNode *MMRA = DAG.getMMRAMetadata(CurNode))
1179 DAG.addMMRAMetadata(N, MMRA);
1180 }
1181};
1182
1183} // end anonymous namespace
1184
1185// This function is used to enforce the topological node id property
1186// leveraged during instruction selection. Before the selection process all
1187// nodes are given a non-negative id such that all nodes have a greater id than
1188// their operands. As this holds transitively we can prune checks that a node N
1189// is a predecessor of M another by not recursively checking through M's
1190// operands if N's ID is larger than M's ID. This significantly improves
1191// performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
1192
1193// However, when we fuse multiple nodes into a single node during the
1194// selection we may induce a predecessor relationship between inputs and
1195// outputs of distinct nodes being merged, violating the topological property.
1196// Should a fused node have a successor which has yet to be selected,
1197// our legality checks would be incorrect. To avoid this we mark all unselected
1198// successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
1199// (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1200// We use bit-negation to more clearly enforce that node id -1 can only be
1201// achieved by selected nodes. As the conversion is reversable to the original
1202// Id, topological pruning can still be leveraged when looking for unselected
1203// nodes. This method is called internally in all ISel replacement related
1204// functions.
1207 Nodes.push_back(Node);
1208
1209 while (!Nodes.empty()) {
1210 SDNode *N = Nodes.pop_back_val();
1211 for (auto *U : N->uses()) {
1212 auto UId = U->getNodeId();
1213 if (UId > 0) {
1215 Nodes.push_back(U);
1216 }
1217 }
1218 }
1219}
1220
1221// InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
1222// NodeId with the equivalent node id which is invalid for topological
1223// pruning.
1225 int InvalidId = -(N->getNodeId() + 1);
1226 N->setNodeId(InvalidId);
1227}
1228
1229// getUninvalidatedNodeId - get original uninvalidated node id.
1231 int Id = N->getNodeId();
1232 if (Id < -1)
1233 return -(Id + 1);
1234 return Id;
1235}
1236
1237void SelectionDAGISel::DoInstructionSelection() {
1238 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1239 << printMBBReference(*FuncInfo->MBB) << " '"
1240 << FuncInfo->MBB->getName() << "'\n");
1241
1243
1244 // Select target instructions for the DAG.
1245 {
1246 // Number all nodes with a topological order and set DAGSize.
1248
1249 // Create a dummy node (which is not added to allnodes), that adds
1250 // a reference to the root node, preventing it from being deleted,
1251 // and tracking any changes of the root.
1252 HandleSDNode Dummy(CurDAG->getRoot());
1254 ++ISelPosition;
1255
1256 // Make sure that ISelPosition gets properly updated when nodes are deleted
1257 // in calls made from this function. New nodes inherit relevant metadata.
1258 ISelUpdater ISU(*CurDAG, ISelPosition);
1259
1260 // The AllNodes list is now topological-sorted. Visit the
1261 // nodes by starting at the end of the list (the root of the
1262 // graph) and preceding back toward the beginning (the entry
1263 // node).
1264 while (ISelPosition != CurDAG->allnodes_begin()) {
1265 SDNode *Node = &*--ISelPosition;
1266 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1267 // but there are currently some corner cases that it misses. Also, this
1268 // makes it theoretically possible to disable the DAGCombiner.
1269 if (Node->use_empty())
1270 continue;
1271
1272#ifndef NDEBUG
1274 Nodes.push_back(Node);
1275
1276 while (!Nodes.empty()) {
1277 auto N = Nodes.pop_back_val();
1278 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1279 continue;
1280 for (const SDValue &Op : N->op_values()) {
1281 if (Op->getOpcode() == ISD::TokenFactor)
1282 Nodes.push_back(Op.getNode());
1283 else {
1284 // We rely on topological ordering of node ids for checking for
1285 // cycles when fusing nodes during selection. All unselected nodes
1286 // successors of an already selected node should have a negative id.
1287 // This assertion will catch such cases. If this assertion triggers
1288 // it is likely you using DAG-level Value/Node replacement functions
1289 // (versus equivalent ISEL replacement) in backend-specific
1290 // selections. See comment in EnforceNodeIdInvariant for more
1291 // details.
1292 assert(Op->getNodeId() != -1 &&
1293 "Node has already selected predecessor node");
1294 }
1295 }
1296 }
1297#endif
1298
1299 // When we are using non-default rounding modes or FP exception behavior
1300 // FP operations are represented by StrictFP pseudo-operations. For
1301 // targets that do not (yet) understand strict FP operations directly,
1302 // we convert them to normal FP opcodes instead at this point. This
1303 // will allow them to be handled by existing target-specific instruction
1304 // selectors.
1305 if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1306 // For some opcodes, we need to call TLI->getOperationAction using
1307 // the first operand type instead of the result type. Note that this
1308 // must match what SelectionDAGLegalize::LegalizeOp is doing.
1309 EVT ActionVT;
1310 switch (Node->getOpcode()) {
1313 case ISD::STRICT_LRINT:
1314 case ISD::STRICT_LLRINT:
1315 case ISD::STRICT_LROUND:
1317 case ISD::STRICT_FSETCC:
1319 ActionVT = Node->getOperand(1).getValueType();
1320 break;
1321 default:
1322 ActionVT = Node->getValueType(0);
1323 break;
1324 }
1325 if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1328 }
1329
1330 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1331 Node->dump(CurDAG));
1332
1333 Select(Node);
1334 }
1335
1336 CurDAG->setRoot(Dummy.getValue());
1337 }
1338
1339 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1340
1342}
1343
1345 for (const User *U : CPI->users()) {
1346 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1347 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1348 if (IID == Intrinsic::eh_exceptionpointer ||
1349 IID == Intrinsic::eh_exceptioncode)
1350 return true;
1351 }
1352 }
1353 return false;
1354}
1355
1356// wasm.landingpad.index intrinsic is for associating a landing pad index number
1357// with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1358// and store the mapping in the function.
1360 const CatchPadInst *CPI) {
1361 MachineFunction *MF = MBB->getParent();
1362 // In case of single catch (...), we don't emit LSDA, so we don't need
1363 // this information.
1364 bool IsSingleCatchAllClause =
1365 CPI->arg_size() == 1 &&
1366 cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1367 // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1368 // and they don't need LSDA info
1369 bool IsCatchLongjmp = CPI->arg_size() == 0;
1370 if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
1371 // Create a mapping from landing pad label to landing pad index.
1372 bool IntrFound = false;
1373 for (const User *U : CPI->users()) {
1374 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1375 Intrinsic::ID IID = Call->getIntrinsicID();
1376 if (IID == Intrinsic::wasm_landingpad_index) {
1377 Value *IndexArg = Call->getArgOperand(1);
1378 int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1380 IntrFound = true;
1381 break;
1382 }
1383 }
1384 }
1385 assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1386 (void)IntrFound;
1387 }
1388}
1389
1390/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1391/// do other setup for EH landing-pad blocks.
1392bool SelectionDAGISel::PrepareEHLandingPad() {
1394 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1395 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1396 const TargetRegisterClass *PtrRC =
1398
1399 auto Pers = classifyEHPersonality(PersonalityFn);
1400
1401 // Catchpads have one live-in register, which typically holds the exception
1402 // pointer or code.
1403 if (isFuncletEHPersonality(Pers)) {
1404 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1406 // Get or create the virtual register to hold the pointer or code. Mark
1407 // the live in physreg and copy into the vreg.
1408 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1409 assert(EHPhysReg && "target lacks exception pointer register");
1410 MBB->addLiveIn(EHPhysReg);
1411 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1412 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1413 TII->get(TargetOpcode::COPY), VReg)
1414 .addReg(EHPhysReg, RegState::Kill);
1415 }
1416 }
1417 return true;
1418 }
1419
1420 // Add a label to mark the beginning of the landing pad. Deletion of the
1421 // landing pad can thus be detected via the MachineModuleInfo.
1423
1424 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1425 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1426 .addSym(Label);
1427
1428 // If the unwinder does not preserve all registers, ensure that the
1429 // function marks the clobbered registers as used.
1431 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1433
1434 if (Pers == EHPersonality::Wasm_CXX) {
1435 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
1437 } else {
1438 // Assign the call site to the landing pad's begin label.
1439 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1440 // Mark exception register as live in.
1441 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1442 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1443 // Mark exception selector register as live in.
1444 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1445 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1446 }
1447
1448 return true;
1449}
1450
1451// Mark and Report IPToState for each Block under IsEHa
1452void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
1454 if (!EHInfo)
1455 return;
1456 for (MachineBasicBlock &MBB : *MF) {
1457 const BasicBlock *BB = MBB.getBasicBlock();
1458 int State = EHInfo->BlockToStateMap[BB];
1459 if (BB->getFirstMayFaultInst()) {
1460 // Report IP range only for blocks with Faulty inst
1461 auto MBBb = MBB.getFirstNonPHI();
1462 MachineInstr *MIb = &*MBBb;
1463 if (MIb->isTerminator())
1464 continue;
1465
1466 // Insert EH Labels
1467 MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
1468 MCSymbol *EndLabel = MF->getContext().createTempSymbol();
1469 EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
1470 BuildMI(MBB, MBBb, SDB->getCurDebugLoc(),
1471 TII->get(TargetOpcode::EH_LABEL))
1472 .addSym(BeginLabel);
1473 auto MBBe = MBB.instr_end();
1474 MachineInstr *MIe = &*(--MBBe);
1475 // insert before (possible multiple) terminators
1476 while (MIe->isTerminator())
1477 MIe = &*(--MBBe);
1478 ++MBBe;
1479 BuildMI(MBB, MBBe, SDB->getCurDebugLoc(),
1480 TII->get(TargetOpcode::EH_LABEL))
1481 .addSym(EndLabel);
1482 }
1483 }
1484}
1485
1486/// isFoldedOrDeadInstruction - Return true if the specified instruction is
1487/// side-effect free and is either dead or folded into a generated instruction.
1488/// Return false if it needs to be emitted.
1490 const FunctionLoweringInfo &FuncInfo) {
1491 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1492 !I->isTerminator() && // Terminators aren't folded.
1493 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1494 !I->isEHPad() && // EH pad instructions aren't folded.
1495 !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1496}
1497
1499 const Value *Arg, DIExpression *Expr,
1500 DILocalVariable *Var,
1501 DebugLoc DbgLoc) {
1502 if (!Expr->isEntryValue() || !isa<Argument>(Arg))
1503 return false;
1504
1505 auto ArgIt = FuncInfo.ValueMap.find(Arg);
1506 if (ArgIt == FuncInfo.ValueMap.end())
1507 return false;
1508 Register ArgVReg = ArgIt->getSecond();
1509
1510 // Find the corresponding livein physical register to this argument.
1511 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1512 if (VirtReg == ArgVReg) {
1513 // Append an op deref to account for the fact that this is a dbg_declare.
1514 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
1515 FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
1516 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1517 << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
1518 << ", DbgLoc=" << DbgLoc << "\n");
1519 return true;
1520 }
1521 return false;
1522}
1523
1525 const Value *Address, DIExpression *Expr,
1526 DILocalVariable *Var, DebugLoc DbgLoc) {
1527 if (!Address) {
1528 LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
1529 << " (bad address)\n");
1530 return false;
1531 }
1532
1533 if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
1534 return true;
1535
1536 MachineFunction *MF = FuncInfo.MF;
1537 const DataLayout &DL = MF->getDataLayout();
1538
1539 assert(Var && "Missing variable");
1540 assert(DbgLoc && "Missing location");
1541
1542 // Look through casts and constant offset GEPs. These mostly come from
1543 // inalloca.
1544 APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
1545 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1546
1547 // Check if the variable is a static alloca or a byval or inalloca
1548 // argument passed in memory. If it is not, then we will ignore this
1549 // intrinsic and handle this during isel like dbg.value.
1550 int FI = std::numeric_limits<int>::max();
1551 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1552 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1553 if (SI != FuncInfo.StaticAllocaMap.end())
1554 FI = SI->second;
1555 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1556 FI = FuncInfo.getArgumentFrameIndex(Arg);
1557
1558 if (FI == std::numeric_limits<int>::max())
1559 return false;
1560
1561 if (Offset.getBoolValue())
1563 Offset.getZExtValue());
1564
1565 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1566 << ", Expr=" << *Expr << ", FI=" << FI
1567 << ", DbgLoc=" << DbgLoc << "\n");
1568 MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
1569 return true;
1570}
1571
1572/// Collect llvm.dbg.declare information. This is done after argument lowering
1573/// in case the declarations refer to arguments.
1575 for (const auto &I : instructions(*FuncInfo.Fn)) {
1576 const auto *DI = dyn_cast<DbgDeclareInst>(&I);
1577 if (DI && processDbgDeclare(FuncInfo, DI->getAddress(), DI->getExpression(),
1578 DI->getVariable(), DI->getDebugLoc()))
1579 FuncInfo.PreprocessedDbgDeclares.insert(DI);
1580 for (const DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1582 processDbgDeclare(FuncInfo, DVR.getVariableLocationOp(0),
1583 DVR.getExpression(), DVR.getVariable(),
1584 DVR.getDebugLoc()))
1585 FuncInfo.PreprocessedDVRDeclares.insert(&DVR);
1586 }
1587 }
1588}
1589
1590/// Collect single location variable information generated with assignment
1591/// tracking. This is done after argument lowering in case the declarations
1592/// refer to arguments.
1594 FunctionVarLocs const *FnVarLocs) {
1595 for (auto It = FnVarLocs->single_locs_begin(),
1596 End = FnVarLocs->single_locs_end();
1597 It != End; ++It) {
1598 assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
1599 processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1600 FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1601 }
1602}
1603
1604void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1605 FastISelFailed = false;
1606 // Initialize the Fast-ISel state, if needed.
1607 FastISel *FastIS = nullptr;
1609 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1610 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1611 }
1612
1614
1615 // Lower arguments up front. An RPO iteration always visits the entry block
1616 // first.
1617 assert(*RPOT.begin() == &Fn.getEntryBlock());
1618 ++NumEntryBlocks;
1619
1620 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1621 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1622 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1623
1625
1626 if (!FastIS) {
1627 LowerArguments(Fn);
1628 } else {
1629 // See if fast isel can lower the arguments.
1630 FastIS->startNewBlock();
1631 if (!FastIS->lowerArguments()) {
1632 FastISelFailed = true;
1633 // Fast isel failed to lower these arguments
1634 ++NumFastIselFailLowerArguments;
1635
1636 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1637 Fn.getSubprogram(),
1638 &Fn.getEntryBlock());
1639 R << "FastISel didn't lower all arguments: "
1640 << ore::NV("Prototype", Fn.getFunctionType());
1642
1643 // Use SelectionDAG argument lowering
1644 LowerArguments(Fn);
1645 CurDAG->setRoot(SDB->getControlRoot());
1646 SDB->clear();
1647 CodeGenAndEmitDAG();
1648 }
1649
1650 // If we inserted any instructions at the beginning, make a note of
1651 // where they are, so we can be sure to emit subsequent instructions
1652 // after them.
1653 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1654 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1655 else
1656 FastIS->setLastLocalValue(nullptr);
1657 }
1658
1659 bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1660
1661 if (FastIS && Inserted)
1662 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1663
1666 "expected AssignmentTrackingAnalysis pass results");
1668 } else {
1670 }
1671
1672 // Iterate over all basic blocks in the function.
1673 for (const BasicBlock *LLVMBB : RPOT) {
1675 bool AllPredsVisited = true;
1676 for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1677 if (!FuncInfo->VisitedBBs.count(Pred)) {
1678 AllPredsVisited = false;
1679 break;
1680 }
1681 }
1682
1683 if (AllPredsVisited) {
1684 for (const PHINode &PN : LLVMBB->phis())
1685 FuncInfo->ComputePHILiveOutRegInfo(&PN);
1686 } else {
1687 for (const PHINode &PN : LLVMBB->phis())
1688 FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1689 }
1690
1691 FuncInfo->VisitedBBs.insert(LLVMBB);
1692 }
1693
1694 BasicBlock::const_iterator const Begin =
1695 LLVMBB->getFirstNonPHI()->getIterator();
1696 BasicBlock::const_iterator const End = LLVMBB->end();
1698
1699 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1700 if (!FuncInfo->MBB)
1701 continue; // Some blocks like catchpads have no code or MBB.
1702
1703 // Insert new instructions after any phi or argument setup code.
1704 FuncInfo->InsertPt = FuncInfo->MBB->end();
1705
1706 // Setup an EH landing-pad block.
1707 FuncInfo->ExceptionPointerVirtReg = 0;
1708 FuncInfo->ExceptionSelectorVirtReg = 0;
1709 if (LLVMBB->isEHPad())
1710 if (!PrepareEHLandingPad())
1711 continue;
1712
1713 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1714 if (FastIS) {
1715 if (LLVMBB != &Fn.getEntryBlock())
1716 FastIS->startNewBlock();
1717
1718 unsigned NumFastIselRemaining = std::distance(Begin, End);
1719
1720 // Pre-assign swifterror vregs.
1721 SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1722
1723 // Do FastISel on as many instructions as possible.
1724 for (; BI != Begin; --BI) {
1725 const Instruction *Inst = &*std::prev(BI);
1726
1727 // If we no longer require this instruction, skip it.
1728 if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1729 ElidedArgCopyInstrs.count(Inst)) {
1730 --NumFastIselRemaining;
1731 FastIS->handleDbgInfo(Inst);
1732 continue;
1733 }
1734
1735 // Bottom-up: reset the insert pos at the top, after any local-value
1736 // instructions.
1737 FastIS->recomputeInsertPt();
1738
1739 // Try to select the instruction with FastISel.
1740 if (FastIS->selectInstruction(Inst)) {
1741 --NumFastIselRemaining;
1742 ++NumFastIselSuccess;
1743
1744 FastIS->handleDbgInfo(Inst);
1745 // If fast isel succeeded, skip over all the folded instructions, and
1746 // then see if there is a load right before the selected instructions.
1747 // Try to fold the load if so.
1748 const Instruction *BeforeInst = Inst;
1749 while (BeforeInst != &*Begin) {
1750 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1751 if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1752 break;
1753 }
1754 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1755 BeforeInst->hasOneUse() &&
1756 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1757 // If we succeeded, don't re-select the load.
1759 << "FastISel folded load: " << *BeforeInst << "\n");
1760 FastIS->handleDbgInfo(BeforeInst);
1761 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1762 --NumFastIselRemaining;
1763 ++NumFastIselSuccess;
1764 }
1765 continue;
1766 }
1767
1768 FastISelFailed = true;
1769
1770 // Then handle certain instructions as single-LLVM-Instruction blocks.
1771 // We cannot separate out GCrelocates to their own blocks since we need
1772 // to keep track of gc-relocates for a particular gc-statepoint. This is
1773 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1774 // visitGCRelocate.
1775 if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1776 !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1777 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1778 Inst->getDebugLoc(), LLVMBB);
1779
1780 R << "FastISel missed call";
1781
1782 if (R.isEnabled() || EnableFastISelAbort) {
1783 std::string InstStrStorage;
1784 raw_string_ostream InstStr(InstStrStorage);
1785 InstStr << *Inst;
1786
1787 R << ": " << InstStrStorage;
1788 }
1789
1791
1792 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1793 !Inst->use_empty()) {
1794 Register &R = FuncInfo->ValueMap[Inst];
1795 if (!R)
1796 R = FuncInfo->CreateRegs(Inst);
1797 }
1798
1799 bool HadTailCall = false;
1800 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1801 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1802
1803 // If the call was emitted as a tail call, we're done with the block.
1804 // We also need to delete any previously emitted instructions.
1805 if (HadTailCall) {
1806 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1807 --BI;
1808 break;
1809 }
1810
1811 // Recompute NumFastIselRemaining as Selection DAG instruction
1812 // selection may have handled the call, input args, etc.
1813 unsigned RemainingNow = std::distance(Begin, BI);
1814 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1815 NumFastIselRemaining = RemainingNow;
1816 continue;
1817 }
1818
1819 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1820 Inst->getDebugLoc(), LLVMBB);
1821
1822 bool ShouldAbort = EnableFastISelAbort;
1823 if (Inst->isTerminator()) {
1824 // Use a different message for terminator misses.
1825 R << "FastISel missed terminator";
1826 // Don't abort for terminator unless the level is really high
1827 ShouldAbort = (EnableFastISelAbort > 2);
1828 } else {
1829 R << "FastISel missed";
1830 }
1831
1832 if (R.isEnabled() || EnableFastISelAbort) {
1833 std::string InstStrStorage;
1834 raw_string_ostream InstStr(InstStrStorage);
1835 InstStr << *Inst;
1836 R << ": " << InstStrStorage;
1837 }
1838
1839 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1840
1841 NumFastIselFailures += NumFastIselRemaining;
1842 break;
1843 }
1844
1845 FastIS->recomputeInsertPt();
1846 }
1847
1848 if (SP->shouldEmitSDCheck(*LLVMBB)) {
1849 bool FunctionBasedInstrumentation =
1851 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1852 FunctionBasedInstrumentation);
1853 }
1854
1855 if (Begin != BI)
1856 ++NumDAGBlocks;
1857 else
1858 ++NumFastIselBlocks;
1859
1860 if (Begin != BI) {
1861 // Run SelectionDAG instruction selection on the remainder of the block
1862 // not handled by FastISel. If FastISel is not run, this is the entire
1863 // block.
1864 bool HadTailCall;
1865 SelectBasicBlock(Begin, BI, HadTailCall);
1866
1867 // But if FastISel was run, we already selected some of the block.
1868 // If we emitted a tail-call, we need to delete any previously emitted
1869 // instruction that follows it.
1870 if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1871 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1872 }
1873
1874 if (FastIS)
1875 FastIS->finishBasicBlock();
1876 FinishBasicBlock();
1877 FuncInfo->PHINodesToUpdate.clear();
1878 ElidedArgCopyInstrs.clear();
1879 }
1880
1881 // AsynchEH: Report Block State under -AsynchEH
1882 if (Fn.getParent()->getModuleFlag("eh-asynch"))
1883 reportIPToStateForBlocks(MF);
1884
1886
1888
1889 delete FastIS;
1890 SDB->clearDanglingDebugInfo();
1891 SDB->SPDescriptor.resetPerFunctionState();
1892}
1893
1894void
1895SelectionDAGISel::FinishBasicBlock() {
1896 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1897 << FuncInfo->PHINodesToUpdate.size() << "\n";
1898 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1899 ++i) dbgs()
1900 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1901 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1902
1903 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1904 // PHI nodes in successors.
1905 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1906 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1907 assert(PHI->isPHI() &&
1908 "This is not a machine PHI node that we are updating!");
1909 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1910 continue;
1911 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1912 }
1913
1914 // Handle stack protector.
1915 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1916 // The target provides a guard check function. There is no need to
1917 // generate error handling code or to split current basic block.
1918 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1919
1920 // Add load and check to the basicblock.
1921 FuncInfo->MBB = ParentMBB;
1922 FuncInfo->InsertPt =
1924 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1925 CurDAG->setRoot(SDB->getRoot());
1926 SDB->clear();
1927 CodeGenAndEmitDAG();
1928
1929 // Clear the Per-BB State.
1930 SDB->SPDescriptor.resetPerBBState();
1931 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1932 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1933 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1934
1935 // Find the split point to split the parent mbb. At the same time copy all
1936 // physical registers used in the tail of parent mbb into virtual registers
1937 // before the split point and back into physical registers after the split
1938 // point. This prevents us needing to deal with Live-ins and many other
1939 // register allocation issues caused by us splitting the parent mbb. The
1940 // register allocator will clean up said virtual copies later on.
1941 MachineBasicBlock::iterator SplitPoint =
1943
1944 // Splice the terminator of ParentMBB into SuccessMBB.
1945 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1946 SplitPoint,
1947 ParentMBB->end());
1948
1949 // Add compare/jump on neq/jump to the parent BB.
1950 FuncInfo->MBB = ParentMBB;
1951 FuncInfo->InsertPt = ParentMBB->end();
1952 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1953 CurDAG->setRoot(SDB->getRoot());
1954 SDB->clear();
1955 CodeGenAndEmitDAG();
1956
1957 // CodeGen Failure MBB if we have not codegened it yet.
1958 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1959 if (FailureMBB->empty()) {
1960 FuncInfo->MBB = FailureMBB;
1961 FuncInfo->InsertPt = FailureMBB->end();
1962 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1963 CurDAG->setRoot(SDB->getRoot());
1964 SDB->clear();
1965 CodeGenAndEmitDAG();
1966 }
1967
1968 // Clear the Per-BB State.
1969 SDB->SPDescriptor.resetPerBBState();
1970 }
1971
1972 // Lower each BitTestBlock.
1973 for (auto &BTB : SDB->SL->BitTestCases) {
1974 // Lower header first, if it wasn't already lowered
1975 if (!BTB.Emitted) {
1976 // Set the current basic block to the mbb we wish to insert the code into
1977 FuncInfo->MBB = BTB.Parent;
1978 FuncInfo->InsertPt = FuncInfo->MBB->end();
1979 // Emit the code
1980 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1981 CurDAG->setRoot(SDB->getRoot());
1982 SDB->clear();
1983 CodeGenAndEmitDAG();
1984 }
1985
1986 BranchProbability UnhandledProb = BTB.Prob;
1987 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1988 UnhandledProb -= BTB.Cases[j].ExtraProb;
1989 // Set the current basic block to the mbb we wish to insert the code into
1990 FuncInfo->MBB = BTB.Cases[j].ThisBB;
1991 FuncInfo->InsertPt = FuncInfo->MBB->end();
1992 // Emit the code
1993
1994 // If all cases cover a contiguous range, it is not necessary to jump to
1995 // the default block after the last bit test fails. This is because the
1996 // range check during bit test header creation has guaranteed that every
1997 // case here doesn't go outside the range. In this case, there is no need
1998 // to perform the last bit test, as it will always be true. Instead, make
1999 // the second-to-last bit-test fall through to the target of the last bit
2000 // test, and delete the last bit test.
2001
2002 MachineBasicBlock *NextMBB;
2003 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2004 // Second-to-last bit-test with contiguous range or omitted range
2005 // check: fall through to the target of the final bit test.
2006 NextMBB = BTB.Cases[j + 1].TargetBB;
2007 } else if (j + 1 == ej) {
2008 // For the last bit test, fall through to Default.
2009 NextMBB = BTB.Default;
2010 } else {
2011 // Otherwise, fall through to the next bit test.
2012 NextMBB = BTB.Cases[j + 1].ThisBB;
2013 }
2014
2015 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
2016 FuncInfo->MBB);
2017
2018 CurDAG->setRoot(SDB->getRoot());
2019 SDB->clear();
2020 CodeGenAndEmitDAG();
2021
2022 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2023 // Since we're not going to use the final bit test, remove it.
2024 BTB.Cases.pop_back();
2025 break;
2026 }
2027 }
2028
2029 // Update PHI Nodes
2030 for (const std::pair<MachineInstr *, unsigned> &P :
2031 FuncInfo->PHINodesToUpdate) {
2032 MachineInstrBuilder PHI(*MF, P.first);
2033 MachineBasicBlock *PHIBB = PHI->getParent();
2034 assert(PHI->isPHI() &&
2035 "This is not a machine PHI node that we are updating!");
2036 // This is "default" BB. We have two jumps to it. From "header" BB and
2037 // from last "case" BB, unless the latter was skipped.
2038 if (PHIBB == BTB.Default) {
2039 PHI.addReg(P.second).addMBB(BTB.Parent);
2040 if (!BTB.ContiguousRange) {
2041 PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
2042 }
2043 }
2044 // One of "cases" BB.
2045 for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
2046 MachineBasicBlock* cBB = BT.ThisBB;
2047 if (cBB->isSuccessor(PHIBB))
2048 PHI.addReg(P.second).addMBB(cBB);
2049 }
2050 }
2051 }
2052 SDB->SL->BitTestCases.clear();
2053
2054 // If the JumpTable record is filled in, then we need to emit a jump table.
2055 // Updating the PHI nodes is tricky in this case, since we need to determine
2056 // whether the PHI is a successor of the range check MBB or the jump table MBB
2057 for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
2058 // Lower header first, if it wasn't already lowered
2059 if (!SDB->SL->JTCases[i].first.Emitted) {
2060 // Set the current basic block to the mbb we wish to insert the code into
2061 FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
2062 FuncInfo->InsertPt = FuncInfo->MBB->end();
2063 // Emit the code
2064 SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
2065 SDB->SL->JTCases[i].first, FuncInfo->MBB);
2066 CurDAG->setRoot(SDB->getRoot());
2067 SDB->clear();
2068 CodeGenAndEmitDAG();
2069 }
2070
2071 // Set the current basic block to the mbb we wish to insert the code into
2072 FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
2073 FuncInfo->InsertPt = FuncInfo->MBB->end();
2074 // Emit the code
2075 SDB->visitJumpTable(SDB->SL->JTCases[i].second);
2076 CurDAG->setRoot(SDB->getRoot());
2077 SDB->clear();
2078 CodeGenAndEmitDAG();
2079
2080 // Update PHI Nodes
2081 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
2082 pi != pe; ++pi) {
2083 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
2084 MachineBasicBlock *PHIBB = PHI->getParent();
2085 assert(PHI->isPHI() &&
2086 "This is not a machine PHI node that we are updating!");
2087 // "default" BB. We can go there only from header BB.
2088 if (PHIBB == SDB->SL->JTCases[i].second.Default)
2089 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
2090 .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
2091 // JT BB. Just iterate over successors here
2092 if (FuncInfo->MBB->isSuccessor(PHIBB))
2093 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
2094 }
2095 }
2096 SDB->SL->JTCases.clear();
2097
2098 // If we generated any switch lowering information, build and codegen any
2099 // additional DAGs necessary.
2100 for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
2101 // Set the current basic block to the mbb we wish to insert the code into
2102 FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
2103 FuncInfo->InsertPt = FuncInfo->MBB->end();
2104
2105 // Determine the unique successors.
2107 Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
2108 if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
2109 Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
2110
2111 // Emit the code. Note that this could result in FuncInfo->MBB being split.
2112 SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
2113 CurDAG->setRoot(SDB->getRoot());
2114 SDB->clear();
2115 CodeGenAndEmitDAG();
2116
2117 // Remember the last block, now that any splitting is done, for use in
2118 // populating PHI nodes in successors.
2119 MachineBasicBlock *ThisBB = FuncInfo->MBB;
2120
2121 // Handle any PHI nodes in successors of this chunk, as if we were coming
2122 // from the original BB before switch expansion. Note that PHI nodes can
2123 // occur multiple times in PHINodesToUpdate. We have to be very careful to
2124 // handle them the right number of times.
2125 for (MachineBasicBlock *Succ : Succs) {
2126 FuncInfo->MBB = Succ;
2127 FuncInfo->InsertPt = FuncInfo->MBB->end();
2128 // FuncInfo->MBB may have been removed from the CFG if a branch was
2129 // constant folded.
2130 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
2132 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
2133 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
2135 // This value for this PHI node is recorded in PHINodesToUpdate.
2136 for (unsigned pn = 0; ; ++pn) {
2137 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
2138 "Didn't find PHI entry!");
2139 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
2140 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
2141 break;
2142 }
2143 }
2144 }
2145 }
2146 }
2147 }
2148 SDB->SL->SwitchCases.clear();
2149}
2150
2151/// Create the scheduler. If a specific scheduler was specified
2152/// via the SchedulerRegistry, use it, otherwise select the
2153/// one preferred by the target.
2154///
2155ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
2156 return ISHeuristic(this, OptLevel);
2157}
2158
2159//===----------------------------------------------------------------------===//
2160// Helper functions used by the generated instruction selector.
2161//===----------------------------------------------------------------------===//
2162// Calls to these methods are generated by tblgen.
2163
2164/// CheckAndMask - The isel is trying to match something like (and X, 255). If
2165/// the dag combiner simplified the 255, we still want to match. RHS is the
2166/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2167/// specified in the .td file (e.g. 255).
2169 int64_t DesiredMaskS) const {
2170 const APInt &ActualMask = RHS->getAPIntValue();
2171 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2172
2173 // If the actual mask exactly matches, success!
2174 if (ActualMask == DesiredMask)
2175 return true;
2176
2177 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2178 if (!ActualMask.isSubsetOf(DesiredMask))
2179 return false;
2180
2181 // Otherwise, the DAG Combiner may have proven that the value coming in is
2182 // either already zero or is not demanded. Check for known zero input bits.
2183 APInt NeededMask = DesiredMask & ~ActualMask;
2184 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2185 return true;
2186
2187 // TODO: check to see if missing bits are just not demanded.
2188
2189 // Otherwise, this pattern doesn't match.
2190 return false;
2191}
2192
2193/// CheckOrMask - The isel is trying to match something like (or X, 255). If
2194/// the dag combiner simplified the 255, we still want to match. RHS is the
2195/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2196/// specified in the .td file (e.g. 255).
2198 int64_t DesiredMaskS) const {
2199 const APInt &ActualMask = RHS->getAPIntValue();
2200 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2201
2202 // If the actual mask exactly matches, success!
2203 if (ActualMask == DesiredMask)
2204 return true;
2205
2206 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2207 if (!ActualMask.isSubsetOf(DesiredMask))
2208 return false;
2209
2210 // Otherwise, the DAG Combiner may have proven that the value coming in is
2211 // either already zero or is not demanded. Check for known zero input bits.
2212 APInt NeededMask = DesiredMask & ~ActualMask;
2214
2215 // If all the missing bits in the or are already known to be set, match!
2216 if (NeededMask.isSubsetOf(Known.One))
2217 return true;
2218
2219 // TODO: check to see if missing bits are just not demanded.
2220
2221 // Otherwise, this pattern doesn't match.
2222 return false;
2223}
2224
2225/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2226/// by tblgen. Others should not call it.
2228 const SDLoc &DL) {
2229 // Change the vector of SDValue into a list of SDNodeHandle for x86 might call
2230 // replaceAllUses when matching address.
2231
2232 std::list<HandleSDNode> Handles;
2233
2234 Handles.emplace_back(Ops[InlineAsm::Op_InputChain]); // 0
2235 Handles.emplace_back(Ops[InlineAsm::Op_AsmString]); // 1
2236 Handles.emplace_back(Ops[InlineAsm::Op_MDNode]); // 2, !srcloc
2237 Handles.emplace_back(
2238 Ops[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2239
2240 unsigned i = InlineAsm::Op_FirstOperand, e = Ops.size();
2241 if (Ops[e - 1].getValueType() == MVT::Glue)
2242 --e; // Don't process a glue operand if it is here.
2243
2244 while (i != e) {
2245 InlineAsm::Flag Flags(Ops[i]->getAsZExtVal());
2246 if (!Flags.isMemKind() && !Flags.isFuncKind()) {
2247 // Just skip over this operand, copying the operands verbatim.
2248 Handles.insert(Handles.end(), Ops.begin() + i,
2249 Ops.begin() + i + Flags.getNumOperandRegisters() + 1);
2250 i += Flags.getNumOperandRegisters() + 1;
2251 } else {
2252 assert(Flags.getNumOperandRegisters() == 1 &&
2253 "Memory operand with multiple values?");
2254
2255 unsigned TiedToOperand;
2256 if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
2257 // We need the constraint ID from the operand this is tied to.
2258 unsigned CurOp = InlineAsm::Op_FirstOperand;
2259 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2260 for (; TiedToOperand; --TiedToOperand) {
2261 CurOp += Flags.getNumOperandRegisters() + 1;
2262 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2263 }
2264 }
2265
2266 // Otherwise, this is a memory operand. Ask the target to select it.
2267 std::vector<SDValue> SelOps;
2268 const InlineAsm::ConstraintCode ConstraintID =
2269 Flags.getMemoryConstraintID();
2270 if (SelectInlineAsmMemoryOperand(Ops[i + 1], ConstraintID, SelOps))
2271 report_fatal_error("Could not match memory address. Inline asm"
2272 " failure!");
2273
2274 // Add this to the output node.
2275 Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
2277 SelOps.size());
2278 Flags.setMemConstraint(ConstraintID);
2279 Handles.emplace_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
2280 Handles.insert(Handles.end(), SelOps.begin(), SelOps.end());
2281 i += 2;
2282 }
2283 }
2284
2285 // Add the glue input back if present.
2286 if (e != Ops.size())
2287 Handles.emplace_back(Ops.back());
2288
2289 Ops.clear();
2290 for (auto &handle : Handles)
2291 Ops.push_back(handle.getValue());
2292}
2293
2294/// findGlueUse - Return use of MVT::Glue value produced by the specified
2295/// SDNode.
2296///
2298 unsigned FlagResNo = N->getNumValues()-1;
2299 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2300 SDUse &Use = I.getUse();
2301 if (Use.getResNo() == FlagResNo)
2302 return Use.getUser();
2303 }
2304 return nullptr;
2305}
2306
2307/// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2308/// beyond "ImmedUse". We may ignore chains as they are checked separately.
2309static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2310 bool IgnoreChains) {
2313 // Only check if we have non-immediate uses of Def.
2314 if (ImmedUse->isOnlyUserOf(Def))
2315 return false;
2316
2317 // We don't care about paths to Def that go through ImmedUse so mark it
2318 // visited and mark non-def operands as used.
2319 Visited.insert(ImmedUse);
2320 for (const SDValue &Op : ImmedUse->op_values()) {
2321 SDNode *N = Op.getNode();
2322 // Ignore chain deps (they are validated by
2323 // HandleMergeInputChains) and immediate uses
2324 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2325 continue;
2326 if (!Visited.insert(N).second)
2327 continue;
2328 WorkList.push_back(N);
2329 }
2330
2331 // Initialize worklist to operands of Root.
2332 if (Root != ImmedUse) {
2333 for (const SDValue &Op : Root->op_values()) {
2334 SDNode *N = Op.getNode();
2335 // Ignore chains (they are validated by HandleMergeInputChains)
2336 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2337 continue;
2338 if (!Visited.insert(N).second)
2339 continue;
2340 WorkList.push_back(N);
2341 }
2342 }
2343
2344 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2345}
2346
2347/// IsProfitableToFold - Returns true if it's profitable to fold the specific
2348/// operand node N of U during instruction selection that starts at Root.
2350 SDNode *Root) const {
2352 return false;
2353 return N.hasOneUse();
2354}
2355
2356/// IsLegalToFold - Returns true if the specific operand node N of
2357/// U can be folded during instruction selection that starts at Root.
2359 CodeGenOptLevel OptLevel,
2360 bool IgnoreChains) {
2362 return false;
2363
2364 // If Root use can somehow reach N through a path that doesn't contain
2365 // U then folding N would create a cycle. e.g. In the following
2366 // diagram, Root can reach N through X. If N is folded into Root, then
2367 // X is both a predecessor and a successor of U.
2368 //
2369 // [N*] //
2370 // ^ ^ //
2371 // / \ //
2372 // [U*] [X]? //
2373 // ^ ^ //
2374 // \ / //
2375 // \ / //
2376 // [Root*] //
2377 //
2378 // * indicates nodes to be folded together.
2379 //
2380 // If Root produces glue, then it gets (even more) interesting. Since it
2381 // will be "glued" together with its glue use in the scheduler, we need to
2382 // check if it might reach N.
2383 //
2384 // [N*] //
2385 // ^ ^ //
2386 // / \ //
2387 // [U*] [X]? //
2388 // ^ ^ //
2389 // \ \ //
2390 // \ | //
2391 // [Root*] | //
2392 // ^ | //
2393 // f | //
2394 // | / //
2395 // [Y] / //
2396 // ^ / //
2397 // f / //
2398 // | / //
2399 // [GU] //
2400 //
2401 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2402 // (call it Fold), then X is a predecessor of GU and a successor of
2403 // Fold. But since Fold and GU are glued together, this will create
2404 // a cycle in the scheduling graph.
2405
2406 // If the node has glue, walk down the graph to the "lowest" node in the
2407 // glueged set.
2408 EVT VT = Root->getValueType(Root->getNumValues()-1);
2409 while (VT == MVT::Glue) {
2410 SDNode *GU = findGlueUse(Root);
2411 if (!GU)
2412 break;
2413 Root = GU;
2414 VT = Root->getValueType(Root->getNumValues()-1);
2415
2416 // If our query node has a glue result with a use, we've walked up it. If
2417 // the user (which has already been selected) has a chain or indirectly uses
2418 // the chain, HandleMergeInputChains will not consider it. Because of
2419 // this, we cannot ignore chains in this predicate.
2420 IgnoreChains = false;
2421 }
2422
2423 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2424}
2425
2426void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2427 SDLoc DL(N);
2428
2429 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2431
2432 const EVT VTs[] = {MVT::Other, MVT::Glue};
2433 SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2434 New->setNodeId(-1);
2435 ReplaceUses(N, New.getNode());
2437}
2438
2439void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2440 SDLoc dl(Op);
2441 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2442 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2443
2444 EVT VT = Op->getValueType(0);
2445 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2446 Register Reg =
2447 TLI->getRegisterByName(RegStr->getString().data(), Ty,
2450 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2451 New->setNodeId(-1);
2452 ReplaceUses(Op, New.getNode());
2454}
2455
2456void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2457 SDLoc dl(Op);
2458 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2459 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2460
2461 EVT VT = Op->getOperand(2).getValueType();
2462 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2463
2464 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
2467 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2468 New->setNodeId(-1);
2469 ReplaceUses(Op, New.getNode());
2471}
2472
2473void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2474 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2475}
2476
2477void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2478 // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2479 // If FREEZE instruction is added later, the code below must be changed as
2480 // well.
2481 CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2482 N->getOperand(0));
2483}
2484
2485void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2486 CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2487 N->getOperand(0));
2488}
2489
2490void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2491 CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2492 N->getOperand(0));
2493}
2494
2495void SelectionDAGISel::Select_CONVERGENCECTRL_ANCHOR(SDNode *N) {
2496 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ANCHOR,
2497 N->getValueType(0));
2498}
2499
2500void SelectionDAGISel::Select_CONVERGENCECTRL_ENTRY(SDNode *N) {
2501 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ENTRY,
2502 N->getValueType(0));
2503}
2504
2505void SelectionDAGISel::Select_CONVERGENCECTRL_LOOP(SDNode *N) {
2506 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_LOOP,
2507 N->getValueType(0), N->getOperand(0));
2508}
2509
2510void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2511 SDValue OpVal, SDLoc DL) {
2512 SDNode *OpNode = OpVal.getNode();
2513
2514 // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2515 // nodes at DAG-construction time.
2516 assert(OpNode->getOpcode() != ISD::FrameIndex);
2517
2518 if (OpNode->getOpcode() == ISD::Constant) {
2519 Ops.push_back(
2520 CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
2522 OpVal.getValueType()));
2523 } else {
2524 Ops.push_back(OpVal);
2525 }
2526}
2527
2528void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2530 auto *It = N->op_begin();
2531 SDLoc DL(N);
2532
2533 // Stash the chain and glue operands so we can move them to the end.
2534 SDValue Chain = *It++;
2535 SDValue InGlue = *It++;
2536
2537 // <id> operand.
2538 SDValue ID = *It++;
2539 assert(ID.getValueType() == MVT::i64);
2540 Ops.push_back(ID);
2541
2542 // <numShadowBytes> operand.
2543 SDValue Shad = *It++;
2544 assert(Shad.getValueType() == MVT::i32);
2545 Ops.push_back(Shad);
2546
2547 // Live variable operands.
2548 for (; It != N->op_end(); It++)
2549 pushStackMapLiveVariable(Ops, *It, DL);
2550
2551 Ops.push_back(Chain);
2552 Ops.push_back(InGlue);
2553
2554 SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2555 CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2556}
2557
2558void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2560 auto *It = N->op_begin();
2561 SDLoc DL(N);
2562
2563 // Cache arguments that will be moved to the end in the target node.
2564 SDValue Chain = *It++;
2565 std::optional<SDValue> Glue;
2566 if (It->getValueType() == MVT::Glue)
2567 Glue = *It++;
2568 SDValue RegMask = *It++;
2569
2570 // <id> operand.
2571 SDValue ID = *It++;
2572 assert(ID.getValueType() == MVT::i64);
2573 Ops.push_back(ID);
2574
2575 // <numShadowBytes> operand.
2576 SDValue Shad = *It++;
2577 assert(Shad.getValueType() == MVT::i32);
2578 Ops.push_back(Shad);
2579
2580 // Add the callee.
2581 Ops.push_back(*It++);
2582
2583 // Add <numArgs>.
2584 SDValue NumArgs = *It++;
2585 assert(NumArgs.getValueType() == MVT::i32);
2586 Ops.push_back(NumArgs);
2587
2588 // Calling convention.
2589 Ops.push_back(*It++);
2590
2591 // Push the args for the call.
2592 for (uint64_t I = NumArgs->getAsZExtVal(); I != 0; I--)
2593 Ops.push_back(*It++);
2594
2595 // Now push the live variables.
2596 for (; It != N->op_end(); It++)
2597 pushStackMapLiveVariable(Ops, *It, DL);
2598
2599 // Finally, the regmask, chain and (if present) glue are moved to the end.
2600 Ops.push_back(RegMask);
2601 Ops.push_back(Chain);
2602 if (Glue.has_value())
2603 Ops.push_back(*Glue);
2604
2605 SDVTList NodeTys = N->getVTList();
2606 CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2607}
2608
2609/// GetVBR - decode a vbr encoding whose top bit is set.
2611GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2612 assert(Val >= 128 && "Not a VBR");
2613 Val &= 127; // Remove first vbr bit.
2614
2615 unsigned Shift = 7;
2616 uint64_t NextBits;
2617 do {
2618 NextBits = MatcherTable[Idx++];
2619 Val |= (NextBits&127) << Shift;
2620 Shift += 7;
2621 } while (NextBits & 128);
2622
2623 return Val;
2624}
2625
2626void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
2627 SDLoc dl(N);
2628 CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
2629 CurDAG->getTargetConstant(N->getConstantOperandVal(1),
2630 dl, MVT::i64, true));
2631}
2632
2633/// When a match is complete, this method updates uses of interior chain results
2634/// to use the new results.
2635void SelectionDAGISel::UpdateChains(
2636 SDNode *NodeToMatch, SDValue InputChain,
2637 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2638 SmallVector<SDNode*, 4> NowDeadNodes;
2639
2640 // Now that all the normal results are replaced, we replace the chain and
2641 // glue results if present.
2642 if (!ChainNodesMatched.empty()) {
2643 assert(InputChain.getNode() &&
2644 "Matched input chains but didn't produce a chain");
2645 // Loop over all of the nodes we matched that produced a chain result.
2646 // Replace all the chain results with the final chain we ended up with.
2647 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2648 SDNode *ChainNode = ChainNodesMatched[i];
2649 // If ChainNode is null, it's because we replaced it on a previous
2650 // iteration and we cleared it out of the map. Just skip it.
2651 if (!ChainNode)
2652 continue;
2653
2654 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2655 "Deleted node left in chain");
2656
2657 // Don't replace the results of the root node if we're doing a
2658 // MorphNodeTo.
2659 if (ChainNode == NodeToMatch && isMorphNodeTo)
2660 continue;
2661
2662 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2663 if (ChainVal.getValueType() == MVT::Glue)
2664 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2665 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2667 *CurDAG, [&](SDNode *N, SDNode *E) {
2668 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2669 static_cast<SDNode *>(nullptr));
2670 });
2671 if (ChainNode->getOpcode() != ISD::TokenFactor)
2672 ReplaceUses(ChainVal, InputChain);
2673
2674 // If the node became dead and we haven't already seen it, delete it.
2675 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2676 !llvm::is_contained(NowDeadNodes, ChainNode))
2677 NowDeadNodes.push_back(ChainNode);
2678 }
2679 }
2680
2681 if (!NowDeadNodes.empty())
2682 CurDAG->RemoveDeadNodes(NowDeadNodes);
2683
2684 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2685}
2686
2687/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2688/// operation for when the pattern matched at least one node with a chains. The
2689/// input vector contains a list of all of the chained nodes that we match. We
2690/// must determine if this is a valid thing to cover (i.e. matching it won't
2691/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2692/// be used as the input node chain for the generated nodes.
2693static SDValue
2695 SelectionDAG *CurDAG) {
2696
2699 SmallVector<SDValue, 3> InputChains;
2700 unsigned int Max = 8192;
2701
2702 // Quick exit on trivial merge.
2703 if (ChainNodesMatched.size() == 1)
2704 return ChainNodesMatched[0]->getOperand(0);
2705
2706 // Add chains that aren't already added (internal). Peek through
2707 // token factors.
2708 std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2709 if (V.getValueType() != MVT::Other)
2710 return;
2711 if (V->getOpcode() == ISD::EntryToken)
2712 return;
2713 if (!Visited.insert(V.getNode()).second)
2714 return;
2715 if (V->getOpcode() == ISD::TokenFactor) {
2716 for (const SDValue &Op : V->op_values())
2717 AddChains(Op);
2718 } else
2719 InputChains.push_back(V);
2720 };
2721
2722 for (auto *N : ChainNodesMatched) {
2723 Worklist.push_back(N);
2724 Visited.insert(N);
2725 }
2726
2727 while (!Worklist.empty())
2728 AddChains(Worklist.pop_back_val()->getOperand(0));
2729
2730 // Skip the search if there are no chain dependencies.
2731 if (InputChains.size() == 0)
2732 return CurDAG->getEntryNode();
2733
2734 // If one of these chains is a successor of input, we must have a
2735 // node that is both the predecessor and successor of the
2736 // to-be-merged nodes. Fail.
2737 Visited.clear();
2738 for (SDValue V : InputChains)
2739 Worklist.push_back(V.getNode());
2740
2741 for (auto *N : ChainNodesMatched)
2742 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2743 return SDValue();
2744
2745 // Return merged chain.
2746 if (InputChains.size() == 1)
2747 return InputChains[0];
2748 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2749 MVT::Other, InputChains);
2750}
2751
2752/// MorphNode - Handle morphing a node in place for the selector.
2753SDNode *SelectionDAGISel::
2754MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2755 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2756 // It is possible we're using MorphNodeTo to replace a node with no
2757 // normal results with one that has a normal result (or we could be
2758 // adding a chain) and the input could have glue and chains as well.
2759 // In this case we need to shift the operands down.
2760 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2761 // than the old isel though.
2762 int OldGlueResultNo = -1, OldChainResultNo = -1;
2763
2764 unsigned NTMNumResults = Node->getNumValues();
2765 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2766 OldGlueResultNo = NTMNumResults-1;
2767 if (NTMNumResults != 1 &&
2768 Node->getValueType(NTMNumResults-2) == MVT::Other)
2769 OldChainResultNo = NTMNumResults-2;
2770 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2771 OldChainResultNo = NTMNumResults-1;
2772
2773 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2774 // that this deletes operands of the old node that become dead.
2775 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2776
2777 // MorphNodeTo can operate in two ways: if an existing node with the
2778 // specified operands exists, it can just return it. Otherwise, it
2779 // updates the node in place to have the requested operands.
2780 if (Res == Node) {
2781 // If we updated the node in place, reset the node ID. To the isel,
2782 // this should be just like a newly allocated machine node.
2783 Res->setNodeId(-1);
2784 }
2785
2786 unsigned ResNumResults = Res->getNumValues();
2787 // Move the glue if needed.
2788 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2789 static_cast<unsigned>(OldGlueResultNo) != ResNumResults - 1)
2790 ReplaceUses(SDValue(Node, OldGlueResultNo),
2791 SDValue(Res, ResNumResults - 1));
2792
2793 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2794 --ResNumResults;
2795
2796 // Move the chain reference if needed.
2797 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2798 static_cast<unsigned>(OldChainResultNo) != ResNumResults - 1)
2799 ReplaceUses(SDValue(Node, OldChainResultNo),
2800 SDValue(Res, ResNumResults - 1));
2801
2802 // Otherwise, no replacement happened because the node already exists. Replace
2803 // Uses of the old node with the new one.
2804 if (Res != Node) {
2805 ReplaceNode(Node, Res);
2806 } else {
2808 }
2809
2810 return Res;
2811}
2812
2813/// CheckSame - Implements OP_CheckSame.
2815CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2816 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2817 // Accept if it is exactly the same as a previously recorded node.
2818 unsigned RecNo = MatcherTable[MatcherIndex++];
2819 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2820 return N == RecordedNodes[RecNo].first;
2821}
2822
2823/// CheckChildSame - Implements OP_CheckChildXSame.
2825 const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2826 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2827 unsigned ChildNo) {
2828 if (ChildNo >= N.getNumOperands())
2829 return false; // Match fails if out of range child #.
2830 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2831 RecordedNodes);
2832}
2833
2834/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2836CheckPatternPredicate(unsigned Opcode, const unsigned char *MatcherTable,
2837 unsigned &MatcherIndex, const SelectionDAGISel &SDISel) {
2838 bool TwoBytePredNo =
2840 unsigned PredNo =
2841 TwoBytePredNo || Opcode == SelectionDAGISel::OPC_CheckPatternPredicate
2842 ? MatcherTable[MatcherIndex++]
2844 if (TwoBytePredNo)
2845 PredNo |= MatcherTable[MatcherIndex++] << 8;
2846 return SDISel.CheckPatternPredicate(PredNo);
2847}
2848
2849/// CheckNodePredicate - Implements OP_CheckNodePredicate.
2851CheckNodePredicate(unsigned Opcode, const unsigned char *MatcherTable,
2852 unsigned &MatcherIndex, const SelectionDAGISel &SDISel,
2853 SDNode *N) {
2854 unsigned PredNo = Opcode == SelectionDAGISel::OPC_CheckPredicate
2855 ? MatcherTable[MatcherIndex++]
2857 return SDISel.CheckNodePredicate(N, PredNo);
2858}
2859
2861CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2862 SDNode *N) {
2863 uint16_t Opc = MatcherTable[MatcherIndex++];
2864 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
2865 return N->getOpcode() == Opc;
2866}
2867
2869 SDValue N,
2870 const TargetLowering *TLI,
2871 const DataLayout &DL) {
2872 if (N.getValueType() == VT)
2873 return true;
2874
2875 // Handle the case when VT is iPTR.
2876 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2877}
2878
2881 const DataLayout &DL, unsigned ChildNo) {
2882 if (ChildNo >= N.getNumOperands())
2883 return false; // Match fails if out of range child #.
2884 return ::CheckType(VT, N.getOperand(ChildNo), TLI, DL);
2885}
2886
2888CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2889 SDValue N) {
2890 return cast<CondCodeSDNode>(N)->get() ==
2891 static_cast<ISD::CondCode>(MatcherTable[MatcherIndex++]);
2892}
2893
2895CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2896 SDValue N) {
2897 if (2 >= N.getNumOperands())
2898 return false;
2899 return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
2900}
2901
2903CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2904 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2906 static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
2907 if (cast<VTSDNode>(N)->getVT() == VT)
2908 return true;
2909
2910 // Handle the case when VT is iPTR.
2911 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2912}
2913
2914// Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
2915// shifted left by 1.
2917 if ((V & 1) == 0)
2918 return V >> 1;
2919 if (V != 1)
2920 return -(V >> 1);
2921 // There is no such thing as -0 with integers. "-0" really means MININT.
2922 return 1ULL << 63;
2923}
2924
2926CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2927 SDValue N) {
2928 int64_t Val = MatcherTable[MatcherIndex++];
2929 if (Val & 128)
2930 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2931
2932 Val = decodeSignRotatedValue(Val);
2933
2934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2935 return C && C->getAPIntValue().trySExtValue() == Val;
2936}
2937
2939CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2940 SDValue N, unsigned ChildNo) {
2941 if (ChildNo >= N.getNumOperands())
2942 return false; // Match fails if out of range child #.
2943 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2944}
2945
2947CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2948 SDValue N, const SelectionDAGISel &SDISel) {
2949 int64_t Val = MatcherTable[MatcherIndex++];
2950 if (Val & 128)
2951 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2952
2953 if (N->getOpcode() != ISD::AND) return false;
2954
2955 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2956 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2957}
2958
2960CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2961 const SelectionDAGISel &SDISel) {
2962 int64_t Val = MatcherTable[MatcherIndex++];
2963 if (Val & 128)
2964 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2965
2966 if (N->getOpcode() != ISD::OR) return false;
2967
2968 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2969 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2970}
2971
2972/// IsPredicateKnownToFail - If we know how and can do so without pushing a
2973/// scope, evaluate the current node. If the current predicate is known to
2974/// fail, set Result=true and return anything. If the current predicate is
2975/// known to pass, set Result=false and return the MatcherIndex to continue
2976/// with. If the current predicate is unknown, set Result=false and return the
2977/// MatcherIndex to continue with.
2978static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2979 unsigned Index, SDValue N,
2980 bool &Result,
2981 const SelectionDAGISel &SDISel,
2982 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2983 unsigned Opcode = Table[Index++];
2984 switch (Opcode) {
2985 default:
2986 Result = false;
2987 return Index-1; // Could not evaluate this predicate.
2989 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2990 return Index;
2995 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2997 return Index;
3008 Result = !::CheckPatternPredicate(Opcode, Table, Index, SDISel);
3009 return Index;
3019 Result = !::CheckNodePredicate(Opcode, Table, Index, SDISel, N.getNode());
3020 return Index;
3022 Result = !::CheckOpcode(Table, Index, N.getNode());
3023 return Index;
3028 switch (Opcode) {
3030 VT = MVT::i32;
3031 break;
3033 VT = MVT::i64;
3034 break;
3035 default:
3036 VT = static_cast<MVT::SimpleValueType>(Table[Index++]);
3037 break;
3038 }
3039 Result = !::CheckType(VT, N, SDISel.TLI, SDISel.CurDAG->getDataLayout());
3040 return Index;
3041 }
3043 unsigned Res = Table[Index++];
3044 Result = !::CheckType(static_cast<MVT::SimpleValueType>(Table[Index++]),
3045 N.getValue(Res), SDISel.TLI,
3046 SDISel.CurDAG->getDataLayout());
3047 return Index;
3048 }
3074 unsigned ChildNo;
3077 VT = MVT::i32;
3079 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3081 VT = MVT::i64;
3083 } else {
3084 VT = static_cast<MVT::SimpleValueType>(Table[Index++]);
3085 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3086 }
3087 Result = !::CheckChildType(VT, N, SDISel.TLI,
3088 SDISel.CurDAG->getDataLayout(), ChildNo);
3089 return Index;
3090 }
3092 Result = !::CheckCondCode(Table, Index, N);
3093 return Index;
3095 Result = !::CheckChild2CondCode(Table, Index, N);
3096 return Index;
3098 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
3099 SDISel.CurDAG->getDataLayout());
3100 return Index;
3102 Result = !::CheckInteger(Table, Index, N);
3103 return Index;
3109 Result = !::CheckChildInteger(Table, Index, N,
3111 return Index;
3113 Result = !::CheckAndImm(Table, Index, N, SDISel);
3114 return Index;
3116 Result = !::CheckOrImm(Table, Index, N, SDISel);
3117 return Index;
3118 }
3119}
3120
3121namespace {
3122
3123struct MatchScope {
3124 /// FailIndex - If this match fails, this is the index to continue with.
3125 unsigned FailIndex;
3126
3127 /// NodeStack - The node stack when the scope was formed.
3128 SmallVector<SDValue, 4> NodeStack;
3129
3130 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
3131 unsigned NumRecordedNodes;
3132
3133 /// NumMatchedMemRefs - The number of matched memref entries.
3134 unsigned NumMatchedMemRefs;
3135
3136 /// InputChain/InputGlue - The current chain/glue
3137 SDValue InputChain, InputGlue;
3138
3139 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
3140 bool HasChainNodesMatched;
3141};
3142
3143/// \A DAG update listener to keep the matching state
3144/// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
3145/// change the DAG while matching. X86 addressing mode matcher is an example
3146/// for this.
3147class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
3148{
3149 SDNode **NodeToMatch;
3151 SmallVectorImpl<MatchScope> &MatchScopes;
3152
3153public:
3154 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
3155 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
3157 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
3158 RecordedNodes(RN), MatchScopes(MS) {}
3159
3160 void NodeDeleted(SDNode *N, SDNode *E) override {
3161 // Some early-returns here to avoid the search if we deleted the node or
3162 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
3163 // do, so it's unnecessary to update matching state at that point).
3164 // Neither of these can occur currently because we only install this
3165 // update listener during matching a complex patterns.
3166 if (!E || E->isMachineOpcode())
3167 return;
3168 // Check if NodeToMatch was updated.
3169 if (N == *NodeToMatch)
3170 *NodeToMatch = E;
3171 // Performing linear search here does not matter because we almost never
3172 // run this code. You'd have to have a CSE during complex pattern
3173 // matching.
3174 for (auto &I : RecordedNodes)
3175 if (I.first.getNode() == N)
3176 I.first.setNode(E);
3177
3178 for (auto &I : MatchScopes)
3179 for (auto &J : I.NodeStack)
3180 if (J.getNode() == N)
3181 J.setNode(E);
3182 }
3183};
3184
3185} // end anonymous namespace
3186
3188 const unsigned char *MatcherTable,
3189 unsigned TableSize) {
3190 // FIXME: Should these even be selected? Handle these cases in the caller?
3191 switch (NodeToMatch->getOpcode()) {
3192 default:
3193 break;
3194 case ISD::EntryToken: // These nodes remain the same.
3195 case ISD::BasicBlock:
3196 case ISD::Register:
3197 case ISD::RegisterMask:
3198 case ISD::HANDLENODE:
3199 case ISD::MDNODE_SDNODE:
3205 case ISD::MCSymbol:
3210 case ISD::TokenFactor:
3211 case ISD::CopyFromReg:
3212 case ISD::CopyToReg:
3213 case ISD::EH_LABEL:
3216 case ISD::LIFETIME_END:
3217 case ISD::PSEUDO_PROBE:
3218 NodeToMatch->setNodeId(-1); // Mark selected.
3219 return;
3220 case ISD::AssertSext:
3221 case ISD::AssertZext:
3222 case ISD::AssertAlign:
3223 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
3224 CurDAG->RemoveDeadNode(NodeToMatch);
3225 return;
3226 case ISD::INLINEASM:
3227 case ISD::INLINEASM_BR:
3228 Select_INLINEASM(NodeToMatch);
3229 return;
3230 case ISD::READ_REGISTER:
3231 Select_READ_REGISTER(NodeToMatch);
3232 return;
3234 Select_WRITE_REGISTER(NodeToMatch);
3235 return;
3236 case ISD::UNDEF:
3237 Select_UNDEF(NodeToMatch);
3238 return;
3239 case ISD::FREEZE:
3240 Select_FREEZE(NodeToMatch);
3241 return;
3242 case ISD::ARITH_FENCE:
3243 Select_ARITH_FENCE(NodeToMatch);
3244 return;
3245 case ISD::MEMBARRIER:
3246 Select_MEMBARRIER(NodeToMatch);
3247 return;
3248 case ISD::STACKMAP:
3249 Select_STACKMAP(NodeToMatch);
3250 return;
3251 case ISD::PATCHPOINT:
3252 Select_PATCHPOINT(NodeToMatch);
3253 return;
3255 Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
3256 return;
3258 Select_CONVERGENCECTRL_ANCHOR(NodeToMatch);
3259 return;
3261 Select_CONVERGENCECTRL_ENTRY(NodeToMatch);
3262 return;
3264 Select_CONVERGENCECTRL_LOOP(NodeToMatch);
3265 return;
3266 }
3267
3268 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
3269
3270 // Set up the node stack with NodeToMatch as the only node on the stack.
3271 SmallVector<SDValue, 8> NodeStack;
3272 SDValue N = SDValue(NodeToMatch, 0);
3273 NodeStack.push_back(N);
3274
3275 // MatchScopes - Scopes used when matching, if a match failure happens, this
3276 // indicates where to continue checking.
3277 SmallVector<MatchScope, 8> MatchScopes;
3278
3279 // RecordedNodes - This is the set of nodes that have been recorded by the
3280 // state machine. The second value is the parent of the node, or null if the
3281 // root is recorded.
3283
3284 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3285 // pattern.
3287
3288 // These are the current input chain and glue for use when generating nodes.
3289 // Various Emit operations change these. For example, emitting a copytoreg
3290 // uses and updates these.
3291 SDValue InputChain, InputGlue;
3292
3293 // ChainNodesMatched - If a pattern matches nodes that have input/output
3294 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3295 // which ones they are. The result is captured into this list so that we can
3296 // update the chain results when the pattern is complete.
3297 SmallVector<SDNode*, 3> ChainNodesMatched;
3298
3299 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3300
3301 // Determine where to start the interpreter. Normally we start at opcode #0,
3302 // but if the state machine starts with an OPC_SwitchOpcode, then we
3303 // accelerate the first lookup (which is guaranteed to be hot) with the
3304 // OpcodeOffset table.
3305 unsigned MatcherIndex = 0;
3306
3307 if (!OpcodeOffset.empty()) {
3308 // Already computed the OpcodeOffset table, just index into it.
3309 if (N.getOpcode() < OpcodeOffset.size())
3310 MatcherIndex = OpcodeOffset[N.getOpcode()];
3311 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
3312
3313 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
3314 // Otherwise, the table isn't computed, but the state machine does start
3315 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3316 // is the first time we're selecting an instruction.
3317 unsigned Idx = 1;
3318 while (true) {
3319 // Get the size of this case.
3320 unsigned CaseSize = MatcherTable[Idx++];
3321 if (CaseSize & 128)
3322 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
3323 if (CaseSize == 0) break;
3324
3325 // Get the opcode, add the index to the table.
3326 uint16_t Opc = MatcherTable[Idx++];
3327 Opc |= static_cast<uint16_t>(MatcherTable[Idx++]) << 8;
3328 if (Opc >= OpcodeOffset.size())
3329 OpcodeOffset.resize((Opc+1)*2);
3330 OpcodeOffset[Opc] = Idx;
3331 Idx += CaseSize;
3332 }
3333
3334 // Okay, do the lookup for the first opcode.
3335 if (N.getOpcode() < OpcodeOffset.size())
3336 MatcherIndex = OpcodeOffset[N.getOpcode()];
3337 }
3338
3339 while (true) {
3340 assert(MatcherIndex < TableSize && "Invalid index");
3341#ifndef NDEBUG
3342 unsigned CurrentOpcodeIndex = MatcherIndex;
3343#endif
3344 BuiltinOpcodes Opcode =
3345 static_cast<BuiltinOpcodes>(MatcherTable[MatcherIndex++]);
3346 switch (Opcode) {
3347 case OPC_Scope: {
3348 // Okay, the semantics of this operation are that we should push a scope
3349 // then evaluate the first child. However, pushing a scope only to have
3350 // the first check fail (which then pops it) is inefficient. If we can
3351 // determine immediately that the first check (or first several) will
3352 // immediately fail, don't even bother pushing a scope for them.
3353 unsigned FailIndex;
3354
3355 while (true) {
3356 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3357 if (NumToSkip & 128)
3358 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3359 // Found the end of the scope with no match.
3360 if (NumToSkip == 0) {
3361 FailIndex = 0;
3362 break;
3363 }
3364
3365 FailIndex = MatcherIndex+NumToSkip;
3366
3367 unsigned MatcherIndexOfPredicate = MatcherIndex;
3368 (void)MatcherIndexOfPredicate; // silence warning.
3369
3370 // If we can't evaluate this predicate without pushing a scope (e.g. if
3371 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3372 // push the scope and evaluate the full predicate chain.
3373 bool Result;
3374 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
3375 Result, *this, RecordedNodes);
3376 if (!Result)
3377 break;
3378
3379 LLVM_DEBUG(
3380 dbgs() << " Skipped scope entry (due to false predicate) at "
3381 << "index " << MatcherIndexOfPredicate << ", continuing at "
3382 << FailIndex << "\n");
3383 ++NumDAGIselRetries;
3384
3385 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3386 // move to the next case.
3387 MatcherIndex = FailIndex;
3388 }
3389
3390 // If the whole scope failed to match, bail.
3391 if (FailIndex == 0) break;
3392
3393 // Push a MatchScope which indicates where to go if the first child fails
3394 // to match.
3395 MatchScope NewEntry;
3396 NewEntry.FailIndex = FailIndex;
3397 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3398 NewEntry.NumRecordedNodes = RecordedNodes.size();
3399 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3400 NewEntry.InputChain = InputChain;
3401 NewEntry.InputGlue = InputGlue;
3402 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3403 MatchScopes.push_back(NewEntry);
3404 continue;
3405 }
3406 case OPC_RecordNode: {
3407 // Remember this node, it may end up being an operand in the pattern.
3408 SDNode *Parent = nullptr;
3409 if (NodeStack.size() > 1)
3410 Parent = NodeStack[NodeStack.size()-2].getNode();
3411 RecordedNodes.push_back(std::make_pair(N, Parent));
3412 continue;
3413 }
3414
3419 unsigned ChildNo = Opcode-OPC_RecordChild0;
3420 if (ChildNo >= N.getNumOperands())
3421 break; // Match fails if out of range child #.
3422
3423 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
3424 N.getNode()));
3425 continue;
3426 }
3427 case OPC_RecordMemRef:
3428 if (auto *MN = dyn_cast<MemSDNode>(N))
3429 MatchedMemRefs.push_back(MN->getMemOperand());
3430 else {
3431 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3432 dbgs() << '\n');
3433 }
3434
3435 continue;
3436
3438 // If the current node has an input glue, capture it in InputGlue.
3439 if (N->getNumOperands() != 0 &&
3440 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3441 InputGlue = N->getOperand(N->getNumOperands()-1);
3442 continue;
3443
3444 case OPC_MoveChild: {
3445 unsigned ChildNo = MatcherTable[MatcherIndex++];
3446 if (ChildNo >= N.getNumOperands())
3447 break; // Match fails if out of range child #.
3448 N = N.getOperand(ChildNo);
3449 NodeStack.push_back(N);
3450 continue;
3451 }
3452
3453 case OPC_MoveChild0: case OPC_MoveChild1:
3454 case OPC_MoveChild2: case OPC_MoveChild3:
3455 case OPC_MoveChild4: case OPC_MoveChild5:
3456 case OPC_MoveChild6: case OPC_MoveChild7: {
3457 unsigned ChildNo = Opcode-OPC_MoveChild0;
3458 if (ChildNo >= N.getNumOperands())
3459 break; // Match fails if out of range child #.
3460 N = N.getOperand(ChildNo);
3461 NodeStack.push_back(N);
3462 continue;
3463 }
3464
3465 case OPC_MoveSibling:
3466 case OPC_MoveSibling0:
3467 case OPC_MoveSibling1:
3468 case OPC_MoveSibling2:
3469 case OPC_MoveSibling3:
3470 case OPC_MoveSibling4:
3471 case OPC_MoveSibling5:
3472 case OPC_MoveSibling6:
3473 case OPC_MoveSibling7: {
3474 // Pop the current node off the NodeStack.
3475 NodeStack.pop_back();
3476 assert(!NodeStack.empty() && "Node stack imbalance!");
3477 N = NodeStack.back();
3478
3479 unsigned SiblingNo = Opcode == OPC_MoveSibling
3480 ? MatcherTable[MatcherIndex++]
3481 : Opcode - OPC_MoveSibling0;
3482 if (SiblingNo >= N.getNumOperands())
3483 break; // Match fails if out of range sibling #.
3484 N = N.getOperand(SiblingNo);
3485 NodeStack.push_back(N);
3486 continue;
3487 }
3488 case OPC_MoveParent:
3489 // Pop the current node off the NodeStack.
3490 NodeStack.pop_back();
3491 assert(!NodeStack.empty() && "Node stack imbalance!");
3492 N = NodeStack.back();
3493 continue;
3494
3495 case OPC_CheckSame:
3496 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3497 continue;
3498
3501 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3502 Opcode-OPC_CheckChild0Same))
3503 break;
3504 continue;
3505
3516 if (!::CheckPatternPredicate(Opcode, MatcherTable, MatcherIndex, *this))
3517 break;
3518 continue;
3527 case OPC_CheckPredicate:
3528 if (!::CheckNodePredicate(Opcode, MatcherTable, MatcherIndex, *this,
3529 N.getNode()))
3530 break;
3531 continue;
3533 unsigned OpNum = MatcherTable[MatcherIndex++];
3535
3536 for (unsigned i = 0; i < OpNum; ++i)
3537 Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3538
3539 unsigned PredNo = MatcherTable[MatcherIndex++];
3540 if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
3541 break;
3542 continue;
3543 }
3552 case OPC_CheckComplexPat7: {
3553 unsigned CPNum = Opcode == OPC_CheckComplexPat
3554 ? MatcherTable[MatcherIndex++]
3555 : Opcode - OPC_CheckComplexPat0;
3556 unsigned RecNo = MatcherTable[MatcherIndex++];
3557 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3558
3559 // If target can modify DAG during matching, keep the matching state
3560 // consistent.
3561 std::unique_ptr<MatchStateUpdater> MSU;
3563 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3564 MatchScopes));
3565
3566 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3567 RecordedNodes[RecNo].first, CPNum,
3568 RecordedNodes))
3569 break;
3570 continue;
3571 }
3572 case OPC_CheckOpcode:
3573 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3574 continue;
3575
3576 case OPC_CheckType:
3577 case OPC_CheckTypeI32:
3578 case OPC_CheckTypeI64:
3580 switch (Opcode) {
3581 case OPC_CheckTypeI32:
3582 VT = MVT::i32;
3583 break;
3584 case OPC_CheckTypeI64:
3585 VT = MVT::i64;
3586 break;
3587 default:
3588 VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3589 break;
3590 }
3591 if (!::CheckType(VT, N, TLI, CurDAG->getDataLayout()))
3592 break;
3593 continue;
3594
3595 case OPC_CheckTypeRes: {
3596 unsigned Res = MatcherTable[MatcherIndex++];
3597 if (!::CheckType(
3598 static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]),
3599 N.getValue(Res), TLI, CurDAG->getDataLayout()))
3600 break;
3601 continue;
3602 }
3603
3604 case OPC_SwitchOpcode: {
3605 unsigned CurNodeOpcode = N.getOpcode();
3606 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3607 unsigned CaseSize;
3608 while (true) {
3609 // Get the size of this case.
3610 CaseSize = MatcherTable[MatcherIndex++];
3611 if (CaseSize & 128)
3612 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3613 if (CaseSize == 0) break;
3614
3615 uint16_t Opc = MatcherTable[MatcherIndex++];
3616 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3617
3618 // If the opcode matches, then we will execute this case.
3619 if (CurNodeOpcode == Opc)
3620 break;
3621
3622 // Otherwise, skip over this case.
3623 MatcherIndex += CaseSize;
3624 }
3625
3626 // If no cases matched, bail out.
3627 if (CaseSize == 0) break;
3628
3629 // Otherwise, execute the case we found.
3630 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3631 << MatcherIndex << "\n");
3632 continue;
3633 }
3634
3635 case OPC_SwitchType: {
3636 MVT CurNodeVT = N.getSimpleValueType();
3637 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3638 unsigned CaseSize;
3639 while (true) {
3640 // Get the size of this case.
3641 CaseSize = MatcherTable[MatcherIndex++];
3642 if (CaseSize & 128)
3643 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3644 if (CaseSize == 0) break;
3645
3646 MVT CaseVT =
3647 static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3648 if (CaseVT == MVT::iPTR)
3649 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3650
3651 // If the VT matches, then we will execute this case.
3652 if (CurNodeVT == CaseVT)
3653 break;
3654
3655 // Otherwise, skip over this case.
3656 MatcherIndex += CaseSize;
3657 }
3658
3659 // If no cases matched, bail out.
3660 if (CaseSize == 0) break;
3661
3662 // Otherwise, execute the case we found.
3663 LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
3664 << "] from " << SwitchStart << " to " << MatcherIndex
3665 << '\n');
3666 continue;
3667 }
3693 unsigned ChildNo;
3696 VT = MVT::i32;
3698 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3700 VT = MVT::i64;
3702 } else {
3703 VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3704 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3705 }
3706 if (!::CheckChildType(VT, N, TLI, CurDAG->getDataLayout(), ChildNo))
3707 break;
3708 continue;
3709 }
3710 case OPC_CheckCondCode:
3711 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3712 continue;
3714 if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3715 continue;
3716 case OPC_CheckValueType:
3717 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3719 break;
3720 continue;
3721 case OPC_CheckInteger:
3722 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3723 continue;
3727 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3728 Opcode-OPC_CheckChild0Integer)) break;
3729 continue;
3730 case OPC_CheckAndImm:
3731 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3732 continue;
3733 case OPC_CheckOrImm:
3734 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3735 continue;
3737 if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3738 break;
3739 continue;
3741 if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3742 break;
3743 continue;
3744
3746 assert(NodeStack.size() != 1 && "No parent node");
3747 // Verify that all intermediate nodes between the root and this one have
3748 // a single use (ignoring chains, which are handled in UpdateChains).
3749 bool HasMultipleUses = false;
3750 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3751 unsigned NNonChainUses = 0;
3752 SDNode *NS = NodeStack[i].getNode();
3753 for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3754 if (UI.getUse().getValueType() != MVT::Other)
3755 if (++NNonChainUses > 1) {
3756 HasMultipleUses = true;
3757 break;
3758 }
3759 if (HasMultipleUses) break;
3760 }
3761 if (HasMultipleUses) break;
3762
3763 // Check to see that the target thinks this is profitable to fold and that
3764 // we can fold it without inducing cycles in the graph.
3765 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3766 NodeToMatch) ||
3767 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3768 NodeToMatch, OptLevel,
3769 true/*We validate our own chains*/))
3770 break;
3771
3772 continue;
3773 }
3774 case OPC_EmitInteger:
3775 case OPC_EmitInteger8:
3776 case OPC_EmitInteger16:
3777 case OPC_EmitInteger32:
3778 case OPC_EmitInteger64:
3782 switch (Opcode) {
3783 case OPC_EmitInteger8:
3784 VT = MVT::i8;
3785 break;
3786 case OPC_EmitInteger16:
3787 VT = MVT::i16;
3788 break;
3789 case OPC_EmitInteger32:
3791 VT = MVT::i32;
3792 break;
3793 case OPC_EmitInteger64:
3794 VT = MVT::i64;
3795 break;
3796 default:
3797 VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3798 break;
3799 }
3800 int64_t Val = MatcherTable[MatcherIndex++];
3801 if (Val & 128)
3802 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3803 if (Opcode >= OPC_EmitInteger && Opcode <= OPC_EmitInteger64)
3804 Val = decodeSignRotatedValue(Val);
3805 RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
3806 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), VT), nullptr));
3807 continue;
3808 }
3809 case OPC_EmitRegister:
3811 case OPC_EmitRegisterI64: {
3813 switch (Opcode) {
3815 VT = MVT::i32;
3816 break;
3818 VT = MVT::i64;
3819 break;
3820 default:
3821 VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3822 break;
3823 }
3824 unsigned RegNo = MatcherTable[MatcherIndex++];
3825 RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
3826 CurDAG->getRegister(RegNo, VT), nullptr));
3827 continue;
3828 }
3829 case OPC_EmitRegister2: {
3830 // For targets w/ more than 256 register names, the register enum
3831 // values are stored in two bytes in the matcher table (just like
3832 // opcodes).
3834 static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3835 unsigned RegNo = MatcherTable[MatcherIndex++];
3836 RegNo |= MatcherTable[MatcherIndex++] << 8;
3837 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3838 CurDAG->getRegister(RegNo, VT), nullptr));
3839 continue;
3840 }
3841
3851 // Convert from IMM/FPIMM to target version.
3852 unsigned RecNo = Opcode == OPC_EmitConvertToTarget
3853 ? MatcherTable[MatcherIndex++]
3854 : Opcode - OPC_EmitConvertToTarget0;
3855 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3856 SDValue Imm = RecordedNodes[RecNo].first;
3857
3858 if (Imm->getOpcode() == ISD::Constant) {
3859 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3860 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3861 Imm.getValueType());
3862 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3863 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3864 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3865 Imm.getValueType());
3866 }
3867
3868 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3869 continue;
3870 }
3871
3872 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3873 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3874 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3875 // These are space-optimized forms of OPC_EmitMergeInputChains.
3876 assert(!InputChain.getNode() &&
3877 "EmitMergeInputChains should be the first chain producing node");
3878 assert(ChainNodesMatched.empty() &&
3879 "Should only have one EmitMergeInputChains per match");
3880
3881 // Read all of the chained nodes.
3882 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3883 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3884 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3885
3886 // If the chained node is not the root, we can't fold it if it has
3887 // multiple uses.
3888 // FIXME: What if other value results of the node have uses not matched
3889 // by this pattern?
3890 if (ChainNodesMatched.back() != NodeToMatch &&
3891 !RecordedNodes[RecNo].first.hasOneUse()) {
3892 ChainNodesMatched.clear();
3893 break;
3894 }
3895
3896 // Merge the input chains if they are not intra-pattern references.
3897 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3898
3899 if (!InputChain.getNode())
3900 break; // Failed to merge.
3901 continue;
3902 }
3903
3905 assert(!InputChain.getNode() &&
3906 "EmitMergeInputChains should be the first chain producing node");
3907 // This node gets a list of nodes we matched in the input that have
3908 // chains. We want to token factor all of the input chains to these nodes
3909 // together. However, if any of the input chains is actually one of the
3910 // nodes matched in this pattern, then we have an intra-match reference.
3911 // Ignore these because the newly token factored chain should not refer to
3912 // the old nodes.
3913 unsigned NumChains = MatcherTable[MatcherIndex++];
3914 assert(NumChains != 0 && "Can't TF zero chains");
3915
3916 assert(ChainNodesMatched.empty() &&
3917 "Should only have one EmitMergeInputChains per match");
3918
3919 // Read all of the chained nodes.
3920 for (unsigned i = 0; i != NumChains; ++i) {
3921 unsigned RecNo = MatcherTable[MatcherIndex++];
3922 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3923 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3924
3925 // If the chained node is not the root, we can't fold it if it has
3926 // multiple uses.
3927 // FIXME: What if other value results of the node have uses not matched
3928 // by this pattern?
3929 if (ChainNodesMatched.back() != NodeToMatch &&
3930 !RecordedNodes[RecNo].first.hasOneUse()) {
3931 ChainNodesMatched.clear();
3932 break;
3933 }
3934 }
3935
3936 // If the inner loop broke out, the match fails.
3937 if (ChainNodesMatched.empty())
3938 break;
3939
3940 // Merge the input chains if they are not intra-pattern references.
3941 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3942
3943 if (!InputChain.getNode())
3944 break; // Failed to merge.
3945
3946 continue;
3947 }
3948
3949 case OPC_EmitCopyToReg:
3950 case OPC_EmitCopyToReg0:
3951 case OPC_EmitCopyToReg1:
3952 case OPC_EmitCopyToReg2:
3953 case OPC_EmitCopyToReg3:
3954 case OPC_EmitCopyToReg4:
3955 case OPC_EmitCopyToReg5:
3956 case OPC_EmitCopyToReg6:
3957 case OPC_EmitCopyToReg7:
3959 unsigned RecNo =
3960 Opcode >= OPC_EmitCopyToReg0 && Opcode <= OPC_EmitCopyToReg7
3961 ? Opcode - OPC_EmitCopyToReg0
3962 : MatcherTable[MatcherIndex++];
3963 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3964 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3965 if (Opcode == OPC_EmitCopyToRegTwoByte)
3966 DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
3967
3968 if (!InputChain.getNode())
3969 InputChain = CurDAG->getEntryNode();
3970
3971 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3972 DestPhysReg, RecordedNodes[RecNo].first,
3973 InputGlue);
3974
3975 InputGlue = InputChain.getValue(1);
3976 continue;
3977 }
3978
3979 case OPC_EmitNodeXForm: {
3980 unsigned XFormNo = MatcherTable[MatcherIndex++];
3981 unsigned RecNo = MatcherTable[MatcherIndex++];
3982 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3983 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3984 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3985 continue;
3986 }
3987 case OPC_Coverage: {
3988 // This is emitted right before MorphNode/EmitNode.
3989 // So it should be safe to assume that this node has been selected
3990 unsigned index = MatcherTable[MatcherIndex++];
3991 index |= (MatcherTable[MatcherIndex++] << 8);
3992 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3993 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3994 continue;
3995 }
3996
3997 case OPC_EmitNode:
3998 case OPC_EmitNode0:
3999 case OPC_EmitNode1:
4000 case OPC_EmitNode2:
4001 case OPC_EmitNode0None:
4002 case OPC_EmitNode1None:
4003 case OPC_EmitNode2None:
4004 case OPC_EmitNode0Chain:
4005 case OPC_EmitNode1Chain:
4006 case OPC_EmitNode2Chain:
4007 case OPC_MorphNodeTo:
4008 case OPC_MorphNodeTo0:
4009 case OPC_MorphNodeTo1:
4010 case OPC_MorphNodeTo2:
4023 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
4024 TargetOpc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
4025 unsigned EmitNodeInfo;
4026 if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2Chain) {
4027 if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4028 EmitNodeInfo = OPFL_Chain;
4029 else
4030 EmitNodeInfo = OPFL_None;
4031 } else if (Opcode >= OPC_MorphNodeTo0None &&
4032 Opcode <= OPC_MorphNodeTo2GlueOutput) {
4033 if (Opcode >= OPC_MorphNodeTo0Chain && Opcode <= OPC_MorphNodeTo2Chain)
4034 EmitNodeInfo = OPFL_Chain;
4035 else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
4036 Opcode <= OPC_MorphNodeTo2GlueInput)
4037 EmitNodeInfo = OPFL_GlueInput;
4038 else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
4040 EmitNodeInfo = OPFL_GlueOutput;
4041 else
4042 EmitNodeInfo = OPFL_None;
4043 } else
4044 EmitNodeInfo = MatcherTable[MatcherIndex++];
4045 // Get the result VT list.
4046 unsigned NumVTs;
4047 // If this is one of the compressed forms, get the number of VTs based
4048 // on the Opcode. Otherwise read the next byte from the table.
4049 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
4050 NumVTs = Opcode - OPC_MorphNodeTo0;
4051 else if (Opcode >= OPC_MorphNodeTo0None && Opcode <= OPC_MorphNodeTo2None)
4052 NumVTs = Opcode - OPC_MorphNodeTo0None;
4053 else if (Opcode >= OPC_MorphNodeTo0Chain &&
4054 Opcode <= OPC_MorphNodeTo2Chain)
4055 NumVTs = Opcode - OPC_MorphNodeTo0Chain;
4056 else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
4057 Opcode <= OPC_MorphNodeTo2GlueInput)
4058 NumVTs = Opcode - OPC_MorphNodeTo0GlueInput;
4059 else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
4061 NumVTs = Opcode - OPC_MorphNodeTo0GlueOutput;
4062 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
4063 NumVTs = Opcode - OPC_EmitNode0;
4064 else if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2None)
4065 NumVTs = Opcode - OPC_EmitNode0None;
4066 else if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4067 NumVTs = Opcode - OPC_EmitNode0Chain;
4068 else
4069 NumVTs = MatcherTable[MatcherIndex++];
4071 for (unsigned i = 0; i != NumVTs; ++i) {
4073 static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
4074 if (VT == MVT::iPTR)
4075 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
4076 VTs.push_back(VT);
4077 }
4078
4079 if (EmitNodeInfo & OPFL_Chain)
4080 VTs.push_back(MVT::Other);
4081 if (EmitNodeInfo & OPFL_GlueOutput)
4082 VTs.push_back(MVT::Glue);
4083
4084 // This is hot code, so optimize the two most common cases of 1 and 2
4085 // results.
4086 SDVTList VTList;
4087 if (VTs.size() == 1)
4088 VTList = CurDAG->getVTList(VTs[0]);
4089 else if (VTs.size() == 2)
4090 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
4091 else
4092 VTList = CurDAG->getVTList(VTs);
4093
4094 // Get the operand list.
4095 unsigned NumOps = MatcherTable[MatcherIndex++];
4097 for (unsigned i = 0; i != NumOps; ++i) {
4098 unsigned RecNo = MatcherTable[MatcherIndex++];
4099 if (RecNo & 128)
4100 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
4101
4102 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
4103 Ops.push_back(RecordedNodes[RecNo].first);
4104 }
4105
4106 // If there are variadic operands to add, handle them now.
4107 if (EmitNodeInfo & OPFL_VariadicInfo) {
4108 // Determine the start index to copy from.
4109 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
4110 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
4111 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
4112 "Invalid variadic node");
4113 // Copy all of the variadic operands, not including a potential glue
4114 // input.
4115 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
4116 i != e; ++i) {
4117 SDValue V = NodeToMatch->getOperand(i);
4118 if (V.getValueType() == MVT::Glue) break;
4119 Ops.push_back(V);
4120 }
4121 }
4122
4123 // If this has chain/glue inputs, add them.
4124 if (EmitNodeInfo & OPFL_Chain)
4125 Ops.push_back(InputChain);
4126 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
4127 Ops.push_back(InputGlue);
4128
4129 // Check whether any matched node could raise an FP exception. Since all
4130 // such nodes must have a chain, it suffices to check ChainNodesMatched.
4131 // We need to perform this check before potentially modifying one of the
4132 // nodes via MorphNode.
4133 bool MayRaiseFPException =
4134 llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
4135 return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
4136 });
4137
4138 // Create the node.
4139 MachineSDNode *Res = nullptr;
4140 bool IsMorphNodeTo =
4141 Opcode == OPC_MorphNodeTo ||
4142 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2GlueOutput);
4143 if (!IsMorphNodeTo) {
4144 // If this is a normal EmitNode command, just create the new node and
4145 // add the results to the RecordedNodes list.
4146 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
4147 VTList, Ops);
4148
4149 // Add all the non-glue/non-chain results to the RecordedNodes list.
4150 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
4151 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
4152 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
4153 nullptr));
4154 }
4155 } else {
4156 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
4157 "NodeToMatch was removed partway through selection");
4159 SDNode *E) {
4161 auto &Chain = ChainNodesMatched;
4162 assert((!E || !is_contained(Chain, N)) &&
4163 "Chain node replaced during MorphNode");
4164 llvm::erase(Chain, N);
4165 });
4166 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
4167 Ops, EmitNodeInfo));
4168 }
4169
4170 // Set the NoFPExcept flag when no original matched node could
4171 // raise an FP exception, but the new node potentially might.
4172 if (!MayRaiseFPException && mayRaiseFPException(Res)) {
4173 SDNodeFlags Flags = Res->getFlags();
4174 Flags.setNoFPExcept(true);
4175 Res->setFlags(Flags);
4176 }
4177
4178 // If the node had chain/glue results, update our notion of the current
4179 // chain and glue.
4180 if (EmitNodeInfo & OPFL_GlueOutput) {
4181 InputGlue = SDValue(Res, VTs.size()-1);
4182 if (EmitNodeInfo & OPFL_Chain)
4183 InputChain = SDValue(Res, VTs.size()-2);
4184 } else if (EmitNodeInfo & OPFL_Chain)
4185 InputChain = SDValue(Res, VTs.size()-1);
4186
4187 // If the OPFL_MemRefs glue is set on this node, slap all of the
4188 // accumulated memrefs onto it.
4189 //
4190 // FIXME: This is vastly incorrect for patterns with multiple outputs
4191 // instructions that access memory and for ComplexPatterns that match
4192 // loads.
4193 if (EmitNodeInfo & OPFL_MemRefs) {
4194 // Only attach load or store memory operands if the generated
4195 // instruction may load or store.
4196 const MCInstrDesc &MCID = TII->get(TargetOpc);
4197 bool mayLoad = MCID.mayLoad();
4198 bool mayStore = MCID.mayStore();
4199
4200 // We expect to have relatively few of these so just filter them into a
4201 // temporary buffer so that we can easily add them to the instruction.
4203 for (MachineMemOperand *MMO : MatchedMemRefs) {
4204 if (MMO->isLoad()) {
4205 if (mayLoad)
4206 FilteredMemRefs.push_back(MMO);
4207 } else if (MMO->isStore()) {
4208 if (mayStore)
4209 FilteredMemRefs.push_back(MMO);
4210 } else {
4211 FilteredMemRefs.push_back(MMO);
4212 }
4213 }
4214
4215 CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
4216 }
4217
4218 LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
4219 << " Dropping mem operands\n";
4220 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created")
4221 << " node: ";
4222 Res->dump(CurDAG););
4223
4224 // If this was a MorphNodeTo then we're completely done!
4225 if (IsMorphNodeTo) {
4226 // Update chain uses.
4227 UpdateChains(Res, InputChain, ChainNodesMatched, true);
4228 return;
4229 }
4230 continue;
4231 }
4232
4233 case OPC_CompleteMatch: {
4234 // The match has been completed, and any new nodes (if any) have been
4235 // created. Patch up references to the matched dag to use the newly
4236 // created nodes.
4237 unsigned NumResults = MatcherTable[MatcherIndex++];
4238
4239 for (unsigned i = 0; i != NumResults; ++i) {
4240 unsigned ResSlot = MatcherTable[MatcherIndex++];
4241 if (ResSlot & 128)
4242 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
4243
4244 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
4245 SDValue Res = RecordedNodes[ResSlot].first;
4246
4247 assert(i < NodeToMatch->getNumValues() &&
4248 NodeToMatch->getValueType(i) != MVT::Other &&
4249 NodeToMatch->getValueType(i) != MVT::Glue &&
4250 "Invalid number of results to complete!");
4251 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
4252 NodeToMatch->getValueType(i) == MVT::iPTR ||
4253 Res.getValueType() == MVT::iPTR ||
4254 NodeToMatch->getValueType(i).getSizeInBits() ==
4255 Res.getValueSizeInBits()) &&
4256 "invalid replacement");
4257 ReplaceUses(SDValue(NodeToMatch, i), Res);
4258 }
4259
4260 // Update chain uses.
4261 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
4262
4263 // If the root node defines glue, we need to update it to the glue result.
4264 // TODO: This never happens in our tests and I think it can be removed /
4265 // replaced with an assert, but if we do it this the way the change is
4266 // NFC.
4267 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
4268 MVT::Glue &&
4269 InputGlue.getNode())
4270 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
4271 InputGlue);
4272
4273 assert(NodeToMatch->use_empty() &&
4274 "Didn't replace all uses of the node?");
4275 CurDAG->RemoveDeadNode(NodeToMatch);
4276
4277 return;
4278 }
4279 }
4280
4281 // If the code reached this point, then the match failed. See if there is
4282 // another child to try in the current 'Scope', otherwise pop it until we
4283 // find a case to check.
4284 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
4285 << "\n");
4286 ++NumDAGIselRetries;
4287 while (true) {
4288 if (MatchScopes.empty()) {
4289 CannotYetSelect(NodeToMatch);
4290 return;
4291 }
4292
4293 // Restore the interpreter state back to the point where the scope was
4294 // formed.
4295 MatchScope &LastScope = MatchScopes.back();
4296 RecordedNodes.resize(LastScope.NumRecordedNodes);
4297 NodeStack.clear();
4298 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
4299 N = NodeStack.back();
4300
4301 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
4302 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
4303 MatcherIndex = LastScope.FailIndex;
4304
4305 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
4306
4307 InputChain = LastScope.InputChain;
4308 InputGlue = LastScope.InputGlue;
4309 if (!LastScope.HasChainNodesMatched)
4310 ChainNodesMatched.clear();
4311
4312 // Check to see what the offset is at the new MatcherIndex. If it is zero
4313 // we have reached the end of this scope, otherwise we have another child
4314 // in the current scope to try.
4315 unsigned NumToSkip = MatcherTable[MatcherIndex++];
4316 if (NumToSkip & 128)
4317 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
4318
4319 // If we have another child in this scope to match, update FailIndex and
4320 // try it.
4321 if (NumToSkip != 0) {
4322 LastScope.FailIndex = MatcherIndex+NumToSkip;
4323 break;
4324 }
4325
4326 // End of this scope, pop it and try the next child in the containing
4327 // scope.
4328 MatchScopes.pop_back();
4329 }
4330 }
4331}
4332
4333/// Return whether the node may raise an FP exception.
4335 // For machine opcodes, consult the MCID flag.
4336 if (N->isMachineOpcode()) {
4337 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
4338 return MCID.mayRaiseFPException();
4339 }
4340
4341 // For ISD opcodes, only StrictFP opcodes may raise an FP
4342 // exception.
4343 if (N->isTargetOpcode())
4344 return N->isTargetStrictFPOpcode();
4345 return N->isStrictFPOpcode();
4346}
4347
4349 assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
4350 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
4351 if (!C)
4352 return false;
4353
4354 // Detect when "or" is used to add an offset to a stack object.
4355 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
4357 Align A = MFI.getObjectAlign(FN->getIndex());
4358 int32_t Off = C->getSExtValue();
4359 // If the alleged offset fits in the zero bits guaranteed by
4360 // the alignment, then this or is really an add.
4361 return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
4362 }
4363 return false;
4364}
4365
4366void SelectionDAGISel::CannotYetSelect(SDNode *N) {
4367 std::string msg;
4368 raw_string_ostream Msg(msg);
4369 Msg << "Cannot select: ";
4370
4371 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
4372 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
4373 N->getOpcode() != ISD::INTRINSIC_VOID) {
4374 N->printrFull(Msg, CurDAG);
4375 Msg << "\nIn function: " << MF->getName();
4376 } else {
4377 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
4378 unsigned iid = N->getConstantOperandVal(HasInputChain);
4379 if (iid < Intrinsic::num_intrinsics)
4380 Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
4381 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
4382 Msg << "target intrinsic %" << TII->getName(iid);
4383 else
4384 Msg << "unknown intrinsic #" << iid;
4385 }
4387}
unsigned const MachineRegisterInfo * MRI
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
amdgpu AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Expand Atomic instructions
BlockVerifier::State From
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ATTRIBUTE_ALWAYS_INLINE
LLVM_ATTRIBUTE_ALWAYS_INLINE - On compilers where we have a directive to do so, mark a method "always...
Definition: Compiler.h:261
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
bool End
Definition: ELF_riscv.cpp:480
This file defines the FastISel class.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine Instruction Scheduler
unsigned const TargetRegisterInfo * TRI
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
const char LLVMTargetMachineRef TM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static cl::opt< bool > ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed"))
static cl::opt< bool > ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post " "legalize types dag combine pass"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckPatternPredicate(unsigned Opcode, const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
static cl::opt< bool > ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE uint64_t GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx)
GetVBR - decode a vbr encoding whose top bit is set.
static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F, MachineModuleInfo &MMI)
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
static cl::opt< bool > ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass"))
static RegisterScheduler defaultListDAGScheduler("default", "Best scheduler for the target", createDefaultScheduler)
static unsigned IsPredicateKnownToFail(const unsigned char *Table, unsigned Index, SDValue N, bool &Result, const SelectionDAGISel &SDISel, SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
IsPredicateKnownToFail - If we know how and can do so without pushing a scope, evaluate the current n...
static cl::opt< int > EnableFastISelAbort("fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG."))
static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, const CatchPadInst *CPI)
#define ISEL_DUMP(X)
static void processSingleLocVars(FunctionLoweringInfo &FuncInfo, FunctionVarLocs const *FnVarLocs)
Collect single location variable information generated with assignment tracking.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static cl::opt< bool > UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL, unsigned ChildNo)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
CheckSame - Implements OP_CheckSame.
static bool dontUseFastISelFor(const Function &Fn)
static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, bool IgnoreChains)
findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path beyond "ImmedUse".
static cl::opt< bool > ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass"))
static bool processIfEntryValueDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Arg, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static cl::opt< bool > ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed"))
static void processDbgDeclares(FunctionLoweringInfo &FuncInfo)
Collect llvm.dbg.declare information.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static cl::opt< bool > ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize"))
static cl::opt< bool > ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types"))
static SDNode * findGlueUse(SDNode *N)
findGlueUse - Return use of MVT::Glue value produced by the specified SDNode.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckNodePredicate(unsigned Opcode, const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, SDNode *N)
CheckNodePredicate - Implements OP_CheckNodePredicate.
static cl::opt< RegisterScheduler::FunctionPassCtor, false, RegisterPassParser< RegisterScheduler > > ISHeuristic("pre-RA-sched", cl::init(&createDefaultScheduler), cl::Hidden, cl::desc("Instruction schedulers available (before register" " allocation):"))
ISHeuristic command line option for instruction schedulers.
static cl::opt< bool > EnableFastISelFallbackReport("fast-isel-report-on-fallback", cl::Hidden, cl::desc("Emit a diagnostic when \"fast\" instruction selection " "falls back to SelectionDAG."))
static bool processDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Address, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDNode *N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, unsigned ChildNo)
static cl::opt< std::string > FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options"))
static SDValue HandleMergeInputChains(SmallVectorImpl< SDNode * > &ChainNodesMatched, SelectionDAG *CurDAG)
HandleMergeInputChains - This implements the OPC_EmitMergeInputChains operation for when the pattern ...
static bool isFoldedOrDeadInstruction(const Instruction *I, const FunctionLoweringInfo &FuncInfo)
isFoldedOrDeadInstruction - Return true if the specified instruction is side-effect free and is eithe...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
DEMANGLE_DUMP_METHOD void dump() const
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition: APInt.h:78
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1237
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:451
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:507
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:168
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:365
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:665
const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
Definition: BasicBlock.cpp:356
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Legacy analysis pass which computes BranchProbabilityInfo.
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:269
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
This is an important base class in LLVM.
Definition: Constant.h:42
DWARF expression.
bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:33
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Diagnostic information for ISel fallback path.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition: FastISel.h:66
void setLastLocalValue(MachineInstr *I)
Update the position of the last instruction emitted for materializing constants for use in the curren...
Definition: FastISel.h:237
void handleDbgInfo(const Instruction *II)
Target-independent lowering of non-instruction debug info associated with this instruction.
Definition: FastISel.cpp:1192
bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst)
We're checking to see if we can fold LI into FoldInst.
Definition: FastISel.cpp:2315
void removeDeadCode(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
Remove all dead instructions between the I and E.
Definition: FastISel.cpp:410
void startNewBlock()
Set the current block to which generated machine instructions will be appended.
Definition: FastISel.cpp:123
bool selectInstruction(const Instruction *I)
Do "fast" instruction selection for the given LLVM IR instruction and append the generated machine in...
Definition: FastISel.cpp:1597
void finishBasicBlock()
Flush the local value map.
Definition: FastISel.cpp:136
void recomputeInsertPt()
Reset InsertPt to prepare for inserting instructions into the current block.
Definition: FastISel.cpp:401
bool lowerArguments()
Do "fast" instruction selection for function arguments and append the machine instructions to the cur...
Definition: FastISel.cpp:138
unsigned arg_size() const
arg_size - Return the number of funcletpad arguments.
Definition: InstrTypes.h:2441
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
Definition: InstrTypes.h:2457
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
SmallPtrSet< const DbgVariableRecord *, 8 > PreprocessedDVRDeclares
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
int getArgumentFrameIndex(const Argument *A)
getArgumentFrameIndex - Get frame index for the byval argument.
bool isExportedInst(const Value *V) const
isExportedInst - Return true if the specified value is an instruction exported from its block.
SmallPtrSet< const DbgDeclareInst *, 8 > PreprocessedDbgDeclares
Collection of dbg.declare instructions handled after argument lowering and before ISel proper.
DenseMap< const Value *, Register > ValueMap
ValueMap - Since we emit code for the function a basic block at a time, we must remember which virtua...
MachineRegisterInfo * RegInfo
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:178
Data structure describing the variable locations in a function.
const VarLocInfo * single_locs_begin() const
DILocalVariable * getDILocalVariable(const VarLocInfo *Loc) const
Return the DILocalVariable for the location definition represented by ID.
const VarLocInfo * single_locs_end() const
One past the last single-location variable location definition.
const BasicBlock & getEntryBlock() const
Definition: Function.h:800
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:207
iterator_range< arg_iterator > args()
Definition: Function.h:855
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1830
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition: Function.h:342
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:692
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:358
An analysis pass which caches information about the Function.
Definition: GCMetadata.h:180
An analysis pass which caches information about the entire Module.
Definition: GCMetadata.h:203
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
This class is used to form a handle around another node that is persistent and is updated across invo...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:466
bool isTerminator() const
Definition: Instruction.h:277
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Definition: MCContext.cpp:346
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
bool mayStore() const
Return true if this instruction could possibly modify memory.
Definition: MCInstrDesc.h:444
bool mayLoad() const
Return true if this instruction could possibly read memory.
Definition: MCInstrDesc.h:438
bool mayRaiseFPException() const
Return true if this instruction may raise a floating-point exception.
Definition: MCInstrDesc.h:447
bool isCall() const
Return true if the instruction is a call.
Definition: MCInstrDesc.h:288
bool isReturn() const
Return true if the instruction is a return.
Definition: MCInstrDesc.h:276
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:63
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition: MCInstrInfo.h:70
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
const MDNode * getMD() const
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
Machine Value Type.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
instr_iterator instr_end()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasCalls() const
Return true if the current function has any function calls.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool hasProperty(Property P) const
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setHasInlineAsm(bool B)
Set a flag that indicates that the function contains inline assembly.
void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index)
Map the landing pad to its index. Used for Wasm exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void finalizeDebugInstrRefs()
Finalise any partially emitted debug instructions.
void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef< unsigned > Sites)
Map the landing pad's EH symbol to the call site indexes.
void setUseDebugInstrRef(bool UseInstrRef)
Set whether this function will use instruction referencing or not.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
MCSymbol * addLandingPad(MachineBasicBlock *LandingPad)
Add a new panding pad, and extract the exception handling information from the landingpad instruction...
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldUseDebugInstrRef() const
Determine whether, in the current machine configuration, we should use instruction referencing or not...
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
const MachineBasicBlock & front() const
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:974
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
A description of a memory reference used in the backend.
An analysis that produces MachineModuleInfo for a module.
This class contains meta information specific to a module.
bool usesMSVCFloatingPoint() const
void setUsesMSVCFloatingPoint(bool b)
Register getReg() const
getReg - Returns the register number.
MachinePassRegistry - Track the registration of machine passes.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
void EmitLiveInCopies(MachineBasicBlock *EntryMBB, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII)
EmitLiveInCopies - Emit copies to initialize livein virtual registers into the given entry block.
ArrayRef< std::pair< MCRegister, Register > > liveins() const
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
An SDNode that represents everything that will be needed to construct a MachineInstr.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:333
This class is used by SelectionDAGISel to temporarily override the optimization level on a per-functi...
OptLevelChanger(SelectionDAGISel &ISel, CodeGenOptLevel NewOptLevel)
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:688
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RegisterPassParser class - Handle the addition of new machine passes.
ScheduleDAGSDNodes *(*)(SelectionDAGISel *, CodeGenOptLevel) FunctionPassCtor
static MachinePassRegistry< FunctionPassCtor > Registry
RegisterScheduler class - Track the registration of instruction schedulers.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static unsigned virtReg2Index(Register Reg)
Convert a virtual register number to a 0-based index.
Definition: Register.h:77
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:71
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
void setNodeId(int Id)
Set unique node id.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
static use_iterator use_end()
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
bool shouldEmitSDCheck(const BasicBlock &BB) const
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
SelectionDAGISelLegacy(char &ID, std::unique_ptr< SelectionDAGISel > S)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
AssumptionCache * AC
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
MachineModuleInfo * MMI
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
MachineFunction * MF
virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
MachineRegisterInfo * RegInfo
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
bool isOrEquivalentToAdd(const SDNode *N) const
virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N, unsigned PatternNo, SmallVectorImpl< std::pair< SDValue, SDNode * > > &Result)
virtual bool CheckPatternPredicate(unsigned PredNo) const
CheckPatternPredicate - This function is generated by tblgen in the target.
static int getNumFixedFromVariadicInfo(unsigned Flags)
getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the number of fixed arity values ...
const TargetLibraryInfo * LibInfo
static int getUninvalidatedNodeId(SDNode *N)
const TargetInstrInfo * TII
CodeGenOptLevel OptLevel
virtual bool CheckNodePredicateWithOperands(SDNode *N, unsigned PredNo, const SmallVectorImpl< SDValue > &Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
GCFunctionInfo * GFI
void SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable, unsigned TableSize)
static void EnforceNodeIdInvariant(SDNode *N)
void ReplaceUses(SDValue F, SDValue T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const
IsProfitableToFold - Returns true if it's profitable to fold the specific operand node N of U during ...
virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo)
bool MatchFilterFuncName
True if the function currently processing is in the function printing list (i.e.
void SelectInlineAsmMemoryOperands(std::vector< SDValue > &Ops, const SDLoc &DL)
SelectInlineAsmMemoryOperands - Calls to this are automatically generated by tblgen.
static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOptLevel OptLevel, bool IgnoreChains=false)
IsLegalToFold - Returns true if the specific operand node N of U can be folded during instruction sel...
virtual bool ComplexPatternFuncMutatesDAG() const
Return true if complex patterns for this target can mutate the DAG.
virtual void PreprocessISelDAG()
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckAndMask - The isel is trying to match something like (and X, 255).
SwiftErrorValueTracking * SwiftError
virtual StringRef getPatternForIndex(unsigned index)
getPatternForIndex - Patterns selected by tablegen during ISEL
bool mayRaiseFPException(SDNode *Node) const
Return whether the node may raise an FP exception.
std::unique_ptr< SelectionDAGBuilder > SDB
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL=CodeGenOptLevel::Default)
virtual bool runOnMachineFunction(MachineFunction &mf)
static void InvalidateNodeId(SDNode *N)
virtual StringRef getIncludePathForIndex(unsigned index)
getIncludePathForIndex - get the td source location of pattern instantiation
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:227
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
Definition: SelectionDAG.h:568
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
bool LegalizeVectors()
This transforms the SelectionDAG into a SelectionDAG that only uses vector math operations supported ...
SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
MachineModuleInfo * getMMI() const
Definition: SelectionDAG.h:505
void setFunctionLoweringInfo(FunctionLoweringInfo *FuncInfo)
Definition: SelectionDAG.h:475
SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
Definition: SelectionDAG.h:391
void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
allnodes_const_iterator allnodes_begin() const
Definition: SelectionDAG.h:548
void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:488
void viewGraph(const std::string &Title)
Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
void Legalize()
This transforms the SelectionDAG into a SelectionDAG that is compatible with the target instruction s...
void Combine(CombineLevel Level, AAResults *AA, CodeGenOptLevel OptLevel)
This iterates over the nodes in the SelectionDAG, folding certain types of nodes together,...
void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
SDValue getRegister(unsigned Reg, EVT VT)
void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N)
Definition: SelectionDAG.h:788
SDValue getTargetConstantFP(double Val, const SDLoc &DL, EVT VT)
Definition: SelectionDAG.h:723
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
Definition: SelectionDAG.h:691
unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:483
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT)
Definition: SelectionDAG.h:814
const FunctionVarLocs * getFunctionVarLocs() const
Returns the result of the AssignmentTrackingAnalysis pass if it's available, otherwise return nullptr...
Definition: SelectionDAG.h:500
KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
Definition: SelectionDAG.h:577
void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
Definition: SelectionDAG.h:571
ilist< SDNode >::iterator allnodes_iterator
Definition: SelectionDAG.h:551
bool LegalizeTypes()
This transforms the SelectionDAG into a SelectionDAG that only uses types natively supported by the t...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
bool createEntriesInEntryBlock(DebugLoc DbgLoc)
Create initial definitions of swifterror values in the entry block of the current function.
void setFunction(MachineFunction &MF)
Initialize data structures for specified new function.
void preassignVRegs(MachineBasicBlock *MBB, BasicBlock::const_iterator Begin, BasicBlock::const_iterator End)
void propagateVRegs()
Propagate assigned swifterror vregs through a function, synthesizing PHI nodes when needed to maintai...
Analysis pass providing the TargetTransformInfo.
TargetIntrinsicInfo - Interface to description of machine instruction set.
Analysis pass providing the TargetLibraryInfo.
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual Function * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
virtual Register getExceptionPointerRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
virtual Register getExceptionSelectorRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
virtual void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock * > &Exits) const
Insert explicit copies in entry and exit blocks.
virtual void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
virtual void initializeSplitCSR(MachineBasicBlock *Entry) const
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
virtual FastISel * createFastISel(FunctionLoweringInfo &, const TargetLibraryInfo *) const
This method returns a target specific FastISel object, or null if the target does not support "fast" ...
virtual bool supportSplitCSR(MachineFunction *MF) const
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
virtual const TargetIntrinsicInfo * getIntrinsicInfo() const
If intrinsic information is available, return it. If not, return null.
const Triple & getTargetTriple() const
void setFastISel(bool Enable)
TargetOptions Options
void setOptLevel(CodeGenOptLevel Level)
Overrides the optimization level.
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:72
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
iterator_range< user_iterator > users()
Definition: Value.h:421
bool use_empty() const
Definition: Value.h:344
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
self_iterator getIterator()
Definition: ilist_node.h:132
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#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
bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
@ TargetConstantPool
Definition: ISDOpcodes.h:174
@ CONVERGENCECTRL_ANCHOR
Definition: ISDOpcodes.h:1435
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
Definition: ISDOpcodes.h:1214
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition: ISDOpcodes.h:490
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition: ISDOpcodes.h:44
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
Definition: ISDOpcodes.h:1103
@ TargetBlockAddress
Definition: ISDOpcodes.h:176
@ ConstantFP
Definition: ISDOpcodes.h:77
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition: ISDOpcodes.h:205
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
Definition: ISDOpcodes.h:1271
@ STRICT_FSETCCS
Definition: ISDOpcodes.h:491
@ FrameIndex
Definition: ISDOpcodes.h:80
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:1145
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
Definition: ISDOpcodes.h:1151
@ STRICT_UINT_TO_FP
Definition: ISDOpcodes.h:464
@ TargetExternalSymbol
Definition: ISDOpcodes.h:175
@ CONVERGENCECTRL_ENTRY
Definition: ISDOpcodes.h:1436
@ TargetJumpTable
Definition: ISDOpcodes.h:173
@ WRITE_REGISTER
Definition: ISDOpcodes.h:125
@ STRICT_LROUND
Definition: ISDOpcodes.h:445
@ UNDEF
UNDEF - An undefined node.
Definition: ISDOpcodes.h:218
@ RegisterMask
Definition: ISDOpcodes.h:75
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition: ISDOpcodes.h:68
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition: ISDOpcodes.h:215
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition: ISDOpcodes.h:170
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
Definition: ISDOpcodes.h:1268
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition: ISDOpcodes.h:47
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition: ISDOpcodes.h:124
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition: ISDOpcodes.h:209
@ TargetConstantFP
Definition: ISDOpcodes.h:165
@ STRICT_LRINT
Definition: ISDOpcodes.h:447
@ TargetFrameIndex
Definition: ISDOpcodes.h:172
@ LIFETIME_START
This corresponds to the llvm.lifetime.
Definition: ISDOpcodes.h:1347
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition: ISDOpcodes.h:463
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
Definition: ISDOpcodes.h:1234
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
Definition: ISDOpcodes.h:1140
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition: ISDOpcodes.h:164
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:708
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition: ISDOpcodes.h:190
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
Definition: ISDOpcodes.h:1367
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition: ISDOpcodes.h:223
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition: ISDOpcodes.h:52
@ STRICT_LLRINT
Definition: ISDOpcodes.h:448
@ STRICT_LLROUND
Definition: ISDOpcodes.h:446
@ CONVERGENCECTRL_LOOP
Definition: ISDOpcodes.h:1437
@ INLINEASM
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:1137
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition: ISDOpcodes.h:61
@ AssertZext
Definition: ISDOpcodes.h:62
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:198
@ TargetGlobalTLSAddress
Definition: ISDOpcodes.h:171
bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
Definition: ISDOpcodes.h:1578
StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Definition: Function.cpp:1066
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ScheduleDAGSDNodes * createDefaultScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDefaultScheduler - This creates an instruction scheduler appropriate for the target.
@ Offset
Definition: DWP.cpp:480
bool succ_empty(const Instruction *I)
Definition: CFG.h:255
ScheduleDAGSDNodes * createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createBURRListDAGScheduler - This creates a bottom up register usage reduction list scheduler.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
ScheduleDAGSDNodes * createFastDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createFastDAGScheduler - This creates a "fast" scheduler.
PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2059
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
ScheduleDAGSDNodes * createDAGLinearizer(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDAGLinearizer - This creates a "no-scheduling" scheduler which linearize the DAG using topologi...
void initializeAAResultsWrapperPassPass(PassRegistry &)
void initializeGCModuleInfoPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isFunctionInPrintList(StringRef FunctionName)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
@ AfterLegalizeDAG
Definition: DAGCombine.h:19
@ AfterLegalizeVectorOps
Definition: DAGCombine.h:18
@ BeforeLegalizeTypes
Definition: DAGCombine.h:16
@ AfterLegalizeTypes
Definition: DAGCombine.h:17
ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createSourceListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source...
bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
Definition: DebugInfo.cpp:2242
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &)
ScheduleDAGSDNodes * createVLIWDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createVLIWDAGScheduler - Scheduler for VLIW targets.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Extended Value Type.
Definition: ValueTypes.h:34
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition: ValueTypes.h:136
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:358
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:306
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:151
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:163
These are IR-level optimization flags that may be propagated to SDNodes.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Clients of various APIs that cause global effects on the DAG can optionally implement this interface.
Definition: SelectionDAG.h:311
void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)
DenseMap< const BasicBlock *, int > BlockToStateMap
Definition: WinEHFuncInfo.h:95