LLVM 24.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"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/DebugInfo.h"
70#include "llvm/IR/DebugLoc.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
76#include "llvm/IR/Instruction.h"
79#include "llvm/IR/Intrinsics.h"
80#include "llvm/IR/IntrinsicsWebAssembly.h"
81#include "llvm/IR/Metadata.h"
82#include "llvm/IR/Module.h"
84#include "llvm/IR/PrintPasses.h"
85#include "llvm/IR/Statepoint.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
90#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/Pass.h"
97#include "llvm/Support/Debug.h"
100#include "llvm/Support/Timer.h"
105#include <cassert>
106#include <cstdint>
107#include <iterator>
108#include <limits>
109#include <list>
110#include <memory>
111#include <optional>
112#include <string>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE "isel"
119#define ISEL_DUMP_DEBUG_TYPE DEBUG_TYPE "-dump"
120
121STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
122STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
123STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
124STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
125STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
126STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
127STATISTIC(NumFastIselFailLowerArguments,
128 "Number of entry blocks where fast isel failed to lower arguments");
129
131 "fast-isel-abort", cl::Hidden,
132 cl::desc("Enable abort calls when \"fast\" instruction selection "
133 "fails to lower an instruction: 0 disable the abort, 1 will "
134 "abort but for args, calls and terminators, 2 will also "
135 "abort for argument lowering, and 3 will never fallback "
136 "to SelectionDAG."));
137
139 "fast-isel-report-on-fallback", cl::Hidden,
140 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
141 "falls back to SelectionDAG."));
142
143static cl::opt<bool>
144UseMBPI("use-mbpi",
145 cl::desc("use Machine Branch Probability Info"),
146 cl::init(true), cl::Hidden);
147
148#ifndef NDEBUG
149static cl::opt<bool>
150 DumpSortedDAG("dump-sorted-dags", cl::Hidden,
151 cl::desc("Print DAGs with sorted nodes in debug dump"),
152 cl::init(false));
153
156 cl::desc("Only display the basic block whose name "
157 "matches this for all view-*-dags options"));
158static cl::opt<bool>
159ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
160 cl::desc("Pop up a window to show dags before the first "
161 "dag combine pass"));
162static cl::opt<bool>
163ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
164 cl::desc("Pop up a window to show dags before legalize types"));
165static cl::opt<bool>
166 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
167 cl::desc("Pop up a window to show dags before the post "
168 "legalize types dag combine pass"));
169static cl::opt<bool>
170 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
171 cl::desc("Pop up a window to show dags before legalize"));
172static cl::opt<bool>
173ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
174 cl::desc("Pop up a window to show dags before the second "
175 "dag combine pass"));
176static cl::opt<bool>
177ViewISelDAGs("view-isel-dags", cl::Hidden,
178 cl::desc("Pop up a window to show isel dags as they are selected"));
179static cl::opt<bool>
180ViewSchedDAGs("view-sched-dags", cl::Hidden,
181 cl::desc("Pop up a window to show sched dags as they are processed"));
182static cl::opt<bool>
183ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
184 cl::desc("Pop up a window to show SUnit dags after they are processed"));
185#else
186static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
187 ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
188 ViewDAGCombine2 = false, ViewISelDAGs = false,
189 ViewSchedDAGs = false, ViewSUnitDAGs = false;
190#endif
191
192#ifndef NDEBUG
193#define ISEL_DUMP(X) \
194 do { \
195 if (llvm::DebugFlag && \
196 (isCurrentDebugType(DEBUG_TYPE) || \
197 (isCurrentDebugType(ISEL_DUMP_DEBUG_TYPE) && MatchFilterFuncName))) { \
198 X; \
199 } \
200 } while (false)
201#else
202#define ISEL_DUMP(X) do { } while (false)
203#endif
204
205//===---------------------------------------------------------------------===//
206///
207/// RegisterScheduler class - Track the registration of instruction schedulers.
208///
209//===---------------------------------------------------------------------===//
212
213//===---------------------------------------------------------------------===//
214///
215/// ISHeuristic command line option for instruction schedulers.
216///
217//===---------------------------------------------------------------------===//
220ISHeuristic("pre-RA-sched",
222 cl::desc("Instruction schedulers available (before register"
223 " allocation):"));
224
226defaultListDAGScheduler("default", "Best scheduler for the target",
228
229static bool dontUseFastISelFor(const Function &Fn) {
230 // Don't enable FastISel for functions with swiftasync Arguments.
231 // Debug info on those is reliant on good Argument lowering, and FastISel is
232 // not capable of lowering the entire function. Mixing the two selectors tend
233 // to result in poor lowering of Arguments.
234 return any_of(Fn.args(), [](const Argument &Arg) {
235 return Arg.hasAttribute(Attribute::AttrKind::SwiftAsync);
236 });
237}
238
239static bool maintainPGOProfile(const TargetMachine &TM,
240 CodeGenOptLevel OptLevel) {
241 if (OptLevel != CodeGenOptLevel::None)
242 return true;
243 if (TM.getPGOOption()) {
244 const PGOOptions &Options = *TM.getPGOOption();
245 return Options.Action == PGOOptions::PGOAction::IRUse ||
248 }
249 return false;
250}
251
252namespace llvm {
253
254 //===--------------------------------------------------------------------===//
255 /// This class is used by SelectionDAGISel to temporarily override
256 /// the optimization level on a per-function basis.
259 CodeGenOptLevel SavedOptLevel;
260 bool SavedFastISel;
261
262 public:
264 : IS(ISel) {
265 SavedOptLevel = IS.OptLevel;
266 SavedFastISel = IS.TM.Options.EnableFastISel;
267 if (NewOptLevel != SavedOptLevel) {
268 IS.OptLevel = NewOptLevel;
269 IS.TM.setOptLevel(NewOptLevel);
270 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
271 << IS.MF->getFunction().getName() << "\n");
272 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel)
273 << " ; After: -O" << static_cast<int>(NewOptLevel)
274 << "\n");
275 if (NewOptLevel == CodeGenOptLevel::None)
276 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
277 }
278 if (dontUseFastISelFor(IS.MF->getFunction()))
279 IS.TM.setFastISel(false);
281 dbgs() << "\tFastISel is "
282 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
283 << "\n");
284 }
285
287 if (IS.OptLevel == SavedOptLevel)
288 return;
289 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
290 << IS.MF->getFunction().getName() << "\n");
291 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
292 << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
293 IS.OptLevel = SavedOptLevel;
294 IS.TM.setOptLevel(SavedOptLevel);
295 IS.TM.setFastISel(SavedFastISel);
296 }
297 };
298
299 //===--------------------------------------------------------------------===//
300 /// createDefaultScheduler - This creates an instruction scheduler appropriate
301 /// for the target.
303 CodeGenOptLevel OptLevel) {
304 const TargetLowering *TLI = IS->TLI;
305 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
306
307 // Try first to see if the Target has its own way of selecting a scheduler
308 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
309 return SchedulerCtor(IS, OptLevel);
310 }
311
312 if (OptLevel == CodeGenOptLevel::None ||
313 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
315 return createSourceListDAGScheduler(IS, OptLevel);
317 return createBURRListDAGScheduler(IS, OptLevel);
319 return createHybridListDAGScheduler(IS, OptLevel);
321 return createVLIWDAGScheduler(IS, OptLevel);
323 return createFastDAGScheduler(IS, OptLevel);
325 return createDAGLinearizer(IS, OptLevel);
327 "Unknown sched type!");
328 return createILPListDAGScheduler(IS, OptLevel);
329 }
330
331} // end namespace llvm
332
335 MachineBasicBlock *MBB) const {
336 switch (MI.getOpcode()) {
337 case TargetOpcode::STATEPOINT:
338 // As an implementation detail, STATEPOINT shares the STACKMAP format at
339 // this point in the process. We diverge later.
340 case TargetOpcode::STACKMAP:
341 case TargetOpcode::PATCHPOINT:
342 return emitPatchPoint(MI, MBB);
343 default:
344 break;
345 }
346
347#ifndef NDEBUG
348 dbgs() << "If a target marks an instruction with "
349 "'usesCustomInserter', it must implement "
350 "TargetLowering::EmitInstrWithCustomInserter!\n";
351#endif
352 llvm_unreachable(nullptr);
353}
354
356 SDNode *Node) const {
357 assert(!MI.hasPostISelHook() &&
358 "If a target marks an instruction with 'hasPostISelHook', "
359 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
360}
361
362//===----------------------------------------------------------------------===//
363// SelectionDAGISel code
364//===----------------------------------------------------------------------===//
365
374
376 // If we already selected that function, we do not need to run SDISel.
377 if (MF.getProperties().hasSelected())
378 return false;
379
380 // Do some sanity-checking on the command-line options.
381 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
382 reportFatalUsageError("-fast-isel-abort > 0 requires -fast-isel");
383
384 // Decide what flavour of variable location debug-info will be used, before
385 // we change the optimisation level.
387
388 // Reset OptLevel to None for optnone functions.
389 CodeGenOptLevel NewOptLevel = skipFunction(MF.getFunction())
391 : Selector->OptLevel;
392
393 Selector->MF = &MF;
394 OptLevelChanger OLC(*Selector, NewOptLevel);
395 Selector->initializeAnalysisResults(*this);
396 return Selector->runOnMachineFunction(MF);
397}
398
411
413
415 CodeGenOptLevel OptLevel = Selector->OptLevel;
416 bool RegisterPGOPasses = maintainPGOProfile(Selector->TM, Selector->OptLevel);
417 if (OptLevel != CodeGenOptLevel::None)
425 if (UseMBPI && RegisterPGOPasses)
428 // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
429 // the module.
432 if (RegisterPGOPasses)
434
436
438}
439
443 // If we already selected that function, we do not need to run SDISel.
444 if (MF.getProperties().hasSelected())
445 return PreservedAnalyses::all();
446
447 // Do some sanity-checking on the command-line options.
448 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
449 reportFatalUsageError("-fast-isel-abort > 0 requires -fast-isel");
450
451 // Decide what flavour of variable location debug-info will be used, before
452 // we change the optimisation level.
454
455 // Reset OptLevel to None for optnone functions or when opt-bisect skips.
456 // TODO: Add a function analysis to handle this.
457 Selector->MF = &MF;
458 CodeGenOptLevel NewOptLevel =
459 (MF.getFunction().hasOptNone() ||
462 : Selector->OptLevel;
463
464 OptLevelChanger OLC(*Selector, NewOptLevel);
465 Selector->initializeAnalysisResults(MFAM);
466 Selector->runOnMachineFunction(MF);
467
469}
470
474 .getManager();
476 Function &Fn = MF->getFunction();
477#ifndef NDEBUG
478 FuncName = Fn.getName();
480#else
482#endif
483
484 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
485 bool RegisterPGOPasses = maintainPGOProfile(TM, OptLevel);
486 TII = Subtarget.getInstrInfo();
487 TLI = Subtarget.getTargetLowering();
488 RegInfo = &MF->getRegInfo();
489 LibInfo = &FAM.getResult<TargetLibraryAnalysis>(Fn);
490
491 GFI = Fn.hasGC() ? &FAM.getResult<GCFunctionAnalysis>(Fn) : nullptr;
492 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
493 AC = &FAM.getResult<AssumptionAnalysis>(Fn);
494 auto *PSI = MAMP.getCachedResult<ProfileSummaryAnalysis>(*Fn.getParent());
495 BlockFrequencyInfo *BFI = nullptr;
496 if (PSI && PSI->hasProfileSummary() && RegisterPGOPasses)
497 BFI = &FAM.getResult<BlockFrequencyAnalysis>(Fn);
498
499 FunctionVarLocs const *FnVarLocs = nullptr;
501 FnVarLocs = &FAM.getResult<DebugAssignmentTrackingAnalysis>(Fn);
502
503 auto *UA = FAM.getCachedResult<UniformityInfoAnalysis>(Fn);
504
505 const ModuleLibcallLoweringInfo *LibcallResult =
506 MAMP.getCachedResult<LibcallLoweringModuleAnalysis>(*Fn.getParent());
507 if (!LibcallResult) {
509 "' analysis required");
510 }
511
512 LibcallLowering = &getLibcallLowering(*LibcallResult, Subtarget);
513 CurDAG->init(*MF, MFAM, LibInfo, LibcallLowering, UA, PSI, BFI, FnVarLocs);
514
515 // Now get the optional analyzes if we want to.
516 // This is based on the possibly changed OptLevel (after optnone is taken
517 // into account). That's unfortunate but OK because it just means we won't
518 // ask for passes that have been required anyway.
519
520 if (UseMBPI && RegisterPGOPasses)
521 FuncInfo->BPI = &FAM.getResult<BranchProbabilityAnalysis>(Fn);
522 else
523 FuncInfo->BPI = nullptr;
524
526 BatchAA.emplace(FAM.getResult<AAManager>(Fn));
527 else
528 BatchAA = std::nullopt;
529
530 SP = &FAM.getResult<SSPLayoutAnalysis>(Fn);
531
532 TTI = &FAM.getResult<TargetIRAnalysis>(Fn);
533
534 HwMode = Subtarget.getHwMode();
535}
536
538 Function &Fn = MF->getFunction();
539#ifndef NDEBUG
540 FuncName = Fn.getName();
542#else
544#endif
545
546 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
547
548 bool RegisterPGOPasses = maintainPGOProfile(TM, OptLevel);
549 TII = Subtarget.getInstrInfo();
550 TLI = Subtarget.getTargetLowering();
551 RegInfo = &MF->getRegInfo();
553
554 GFI = Fn.hasGC() ? &MFP.getAnalysis<GCModuleInfo>().getFunctionInfo(Fn)
555 : nullptr;
556 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
557 AC = &MFP.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(Fn);
558 auto *PSI = &MFP.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
559 BlockFrequencyInfo *BFI = nullptr;
560 if (PSI && PSI->hasProfileSummary() && RegisterPGOPasses)
561 BFI = &MFP.getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
562
563 FunctionVarLocs const *FnVarLocs = nullptr;
565 FnVarLocs = MFP.getAnalysis<AssignmentTrackingAnalysis>().getResults();
566
567 UniformityInfo *UA = nullptr;
568 if (auto *UAPass = MFP.getAnalysisIfAvailable<UniformityInfoWrapperPass>())
569 UA = &UAPass->getUniformityInfo();
570
573 *Fn.getParent(), Subtarget);
574
575 CurDAG->init(*MF, LibInfo, LibcallLowering, UA, PSI, BFI, FnVarLocs);
576
577 // Now get the optional analyzes if we want to.
578 // This is based on the possibly changed OptLevel (after optnone is taken
579 // into account). That's unfortunate but OK because it just means we won't
580 // ask for passes that have been required anyway.
581
582 if (UseMBPI && RegisterPGOPasses)
583 FuncInfo->BPI =
585 else
586 FuncInfo->BPI = nullptr;
587
590 else
591 BatchAA = std::nullopt;
592
593 SP = &MFP.getAnalysis<StackProtector>().getLayoutInfo();
594
596
597 HwMode = Subtarget.getHwMode();
598}
599
601 SwiftError->setFunction(mf);
602 const Function &Fn = mf.getFunction();
603
604 bool InstrRef = mf.useDebugInstrRef();
605
606 FuncInfo->set(MF->getFunction(), *MF, CurDAG);
607
608 ISEL_DUMP(dbgs() << "\n\n\n=== " << FuncName << '\n');
609
610 SDB->init(GFI, getBatchAA(), AC, LibInfo, *TTI);
611
612 MF->setHasInlineAsm(false);
613
614 FuncInfo->SplitCSR = false;
615
616 // We split CSR if the target supports it for the given function
617 // and the function has only return exits.
618 if (OptLevel != CodeGenOptLevel::None && TLI->supportSplitCSR(MF)) {
619 FuncInfo->SplitCSR = true;
620
621 // Collect all the return blocks.
622 for (const BasicBlock &BB : Fn) {
623 if (!succ_empty(&BB))
624 continue;
625
626 const Instruction *Term = BB.getTerminator();
627 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
628 continue;
629
630 // Bail out if the exit block is not Return nor Unreachable.
631 FuncInfo->SplitCSR = false;
632 break;
633 }
634 }
635
636 MachineBasicBlock *EntryMBB = &MF->front();
637 if (FuncInfo->SplitCSR)
638 // This performs initialization so lowering for SplitCSR will be correct.
639 TLI->initializeSplitCSR(EntryMBB);
640
641 SelectAllBasicBlocks(Fn);
643 DiagnosticInfoISelFallback DiagFallback(Fn);
644 Fn.getContext().diagnose(DiagFallback);
645 }
646
647 // Replace forward-declared registers with the registers containing
648 // the desired value.
649 // Note: it is important that this happens **before** the call to
650 // EmitLiveInCopies, since implementations can skip copies of unused
651 // registers. If we don't apply the reg fixups before, some registers may
652 // appear as unused and will be skipped, resulting in bad MI.
653 MachineRegisterInfo &MRI = MF->getRegInfo();
654 for (auto I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
655 I != E; ++I) {
656 Register From = I->first;
657 Register To = I->second;
658 // If To is also scheduled to be replaced, find what its ultimate
659 // replacement is.
660 while (true) {
661 auto J = FuncInfo->RegFixups.find(To);
662 if (J == E)
663 break;
664 To = J->second;
665 }
666 // Make sure the new register has a sufficiently constrained register class.
667 if (From.isVirtual() && To.isVirtual())
668 MRI.constrainRegClass(To, MRI.getRegClass(From));
669 // Replace it.
670
671 // Replacing one register with another won't touch the kill flags.
672 // We need to conservatively clear the kill flags as a kill on the old
673 // register might dominate existing uses of the new register.
674 if (!MRI.use_empty(To))
675 MRI.clearKillFlags(From);
676 MRI.replaceRegWith(From, To);
677 }
678
679 // If the first basic block in the function has live ins that need to be
680 // copied into vregs, emit the copies into the top of the block before
681 // emitting the code for the block.
682 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
683 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
684
685 // Insert copies in the entry block and the return blocks.
686 if (FuncInfo->SplitCSR) {
688 // Collect all the return blocks.
689 for (MachineBasicBlock &MBB : mf) {
690 if (!MBB.succ_empty())
691 continue;
692
693 MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
694 if (Term != MBB.end() && Term->isReturn()) {
695 Returns.push_back(&MBB);
696 continue;
697 }
698 }
699 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
700 }
701
703 if (!FuncInfo->ArgDbgValues.empty())
704 for (std::pair<MCRegister, Register> LI : RegInfo->liveins())
705 if (LI.second)
706 LiveInMap.insert(LI);
707
708 // Insert DBG_VALUE instructions for function arguments to the entry block.
709 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
710 MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
711 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
712 "Function parameters should not be described by DBG_VALUE_LIST.");
713 bool hasFI = MI->getDebugOperand(0).isFI();
714 Register Reg =
715 hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
716 if (Reg.isPhysical())
717 EntryMBB->insert(EntryMBB->begin(), MI);
718 else {
719 MachineInstr *Def = RegInfo->getVRegDef(Reg);
720 if (Def) {
721 MachineBasicBlock::iterator InsertPos = Def;
722 // FIXME: VR def may not be in entry block.
723 Def->getParent()->insert(std::next(InsertPos), MI);
724 } else
725 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
726 << printReg(Reg) << '\n');
727 }
728
729 // Don't try and extend through copies in instruction referencing mode.
730 if (InstrRef)
731 continue;
732
733 // If Reg is live-in then update debug info to track its copy in a vreg.
734 if (!Reg.isPhysical())
735 continue;
736 auto LDI = LiveInMap.find(Reg);
737 if (LDI != LiveInMap.end()) {
738 assert(!hasFI && "There's no handling of frame pointer updating here yet "
739 "- add if needed");
740 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
741 MachineBasicBlock::iterator InsertPos = Def;
742 const MDNode *Variable = MI->getDebugVariable();
743 const MDNode *Expr = MI->getDebugExpression();
744 DebugLoc DL = MI->getDebugLoc();
745 bool IsIndirect = MI->isIndirectDebugValue();
746 if (IsIndirect)
747 assert(MI->getDebugOffset().getImm() == 0 &&
748 "DBG_VALUE with nonzero offset");
749 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
750 "Expected inlined-at fields to agree");
751 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
752 "Didn't expect to see a DBG_VALUE_LIST here");
753 // Def is never a terminator here, so it is ok to increment InsertPos.
754 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
755 IsIndirect, LDI->second, Variable, Expr);
756
757 // If this vreg is directly copied into an exported register then
758 // that COPY instructions also need DBG_VALUE, if it is the only
759 // user of LDI->second.
760 MachineInstr *CopyUseMI = nullptr;
761 for (MachineInstr &UseMI : RegInfo->use_instructions(LDI->second)) {
762 if (UseMI.isDebugValue())
763 continue;
764 if (UseMI.isCopy() && !CopyUseMI && UseMI.getParent() == EntryMBB) {
765 CopyUseMI = &UseMI;
766 continue;
767 }
768 // Otherwise this is another use or second copy use.
769 CopyUseMI = nullptr;
770 break;
771 }
772 if (CopyUseMI &&
773 TRI.getRegSizeInBits(LDI->second, MRI) ==
774 TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
775 // Use MI's debug location, which describes where Variable was
776 // declared, rather than whatever is attached to CopyUseMI.
777 MachineInstr *NewMI =
778 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
779 CopyUseMI->getOperand(0).getReg(), Variable, Expr);
780 MachineBasicBlock::iterator Pos = CopyUseMI;
781 EntryMBB->insertAfter(Pos, NewMI);
782 }
783 }
784 }
785
786 // For debug-info, in instruction referencing mode, we need to perform some
787 // post-isel maintenence.
788 if (MF->useDebugInstrRef())
789 MF->finalizeDebugInstrRefs();
790
791 // Determine if there are any calls in this machine function.
792 MachineFrameInfo &MFI = MF->getFrameInfo();
793 for (const auto &MBB : *MF) {
794 if (MFI.hasCalls() && MF->hasInlineAsm())
795 break;
796
797 for (const auto &MI : MBB) {
798 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
799 if ((MCID.isCall() && !MCID.isReturn()) ||
800 MI.isStackAligningInlineAsm()) {
801 MFI.setHasCalls(true);
802 }
803 if (MI.isInlineAsm()) {
804 MF->setHasInlineAsm(true);
805 }
806 }
807 }
808
809 // Release function-specific state. SDB and CurDAG are already cleared
810 // at this point.
811 FuncInfo->clear();
812
813 ISEL_DUMP(dbgs() << "*** MachineFunction at end of ISel ***\n");
814 ISEL_DUMP(MF->print(dbgs()));
815
816 return true;
817}
818
822 bool ShouldAbort) {
823 // Print the function name explicitly if we don't have a debug location (which
824 // makes the diagnostic less useful) or if we're going to emit a raw error.
825 if (!R.getLocation().isValid() || ShouldAbort)
826 R << (" (in function: " + MF.getName() + ")").str();
827
828 if (ShouldAbort)
829 reportFatalUsageError(Twine(R.getMsg()));
830
831 ORE.emit(R);
832 LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
833}
834
835// Detect any fake uses that follow a tail call and move them before the tail
836// call. Ignore fake uses that use values that are def'd by or after the tail
837// call.
841 if (--I == Begin || !isa<ReturnInst>(*I))
842 return;
843 // Detect whether there are any fake uses trailing a (potential) tail call.
844 bool HaveFakeUse = false;
845 bool HaveTailCall = false;
846 do {
847 if (const CallInst *CI = dyn_cast<CallInst>(--I))
848 if (CI->isTailCall()) {
849 HaveTailCall = true;
850 break;
851 }
853 if (II->getIntrinsicID() == Intrinsic::fake_use)
854 HaveFakeUse = true;
855 } while (I != Begin);
856
857 // If we didn't find any tail calls followed by fake uses, we are done.
858 if (!HaveTailCall || !HaveFakeUse)
859 return;
860
862 // Record the fake uses we found so we can move them to the front of the
863 // tail call. Ignore them if they use a value that is def'd by or after
864 // the tail call.
865 for (BasicBlock::iterator Inst = I; Inst != End; Inst++) {
866 if (IntrinsicInst *FakeUse = dyn_cast<IntrinsicInst>(Inst);
867 FakeUse && FakeUse->getIntrinsicID() == Intrinsic::fake_use) {
868 if (auto UsedDef = dyn_cast<Instruction>(FakeUse->getOperand(0));
869 !UsedDef || UsedDef->getParent() != I->getParent() ||
870 UsedDef->comesBefore(&*I))
871 FakeUses.push_back(FakeUse);
872 }
873 }
874
875 for (auto *Inst : FakeUses)
876 Inst->moveBefore(*Inst->getParent(), I);
877}
878
879void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
881 bool &HadTailCall) {
882 // Allow creating illegal types during DAG building for the basic block.
883 CurDAG->NewNodesMustHaveLegalTypes = false;
884
885 // Lower the instructions. If a call is emitted as a tail call, cease emitting
886 // nodes for this block. If an instruction is elided, don't emit it, but do
887 // handle any debug-info attached to it.
888 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
889 if (!ElidedArgCopyInstrs.count(&*I))
890 SDB->visit(*I);
891 else
892 SDB->visitDbgInfo(*I);
893 }
894
895 // Make sure the root of the DAG is up-to-date.
896 CurDAG->setRoot(SDB->getControlRoot());
897 HadTailCall = SDB->HasTailCall;
898 SDB->resolveOrClearDbgInfo();
899 SDB->clear();
900
901 // Final step, emit the lowered DAG as machine code.
902 CodeGenAndEmitDAG();
903}
904
905void SelectionDAGISel::ComputeLiveOutVRegInfo() {
906 SmallPtrSet<SDNode *, 16> Added;
908
909 Worklist.push_back(CurDAG->getRoot().getNode());
910 Added.insert(CurDAG->getRoot().getNode());
911
912 KnownBits Known;
913
914 do {
915 SDNode *N = Worklist.pop_back_val();
916
917 // Otherwise, add all chain operands to the worklist.
918 for (const SDValue &Op : N->op_values())
919 if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
920 Worklist.push_back(Op.getNode());
921
922 // If this is a CopyToReg with a vreg dest, process it.
923 if (N->getOpcode() != ISD::CopyToReg)
924 continue;
925
926 Register DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
927 if (!DestReg.isVirtual())
928 continue;
929
930 // Ignore non-integer values.
931 SDValue Src = N->getOperand(2);
932 EVT SrcVT = Src.getValueType();
933 if (!SrcVT.isInteger())
934 continue;
935
936 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
937 Known = CurDAG->computeKnownBits(Src);
938 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
939 } while (!Worklist.empty());
940}
941
942void SelectionDAGISel::CodeGenAndEmitDAG() {
943 StringRef GroupName = "sdag";
944 StringRef GroupDescription = "Instruction Selection and Scheduling";
945 std::string BlockName;
946 bool MatchFilterBB = false;
947 (void)MatchFilterBB;
948
949 // Pre-type legalization allow creation of any node types.
950 CurDAG->NewNodesMustHaveLegalTypes = false;
951
952#ifndef NDEBUG
953 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
955 FuncInfo->MBB->getBasicBlock()->getName());
956#endif
957#ifdef NDEBUG
961#endif
962 {
963 BlockName =
964 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
965 }
966 ISEL_DUMP(dbgs() << "\nInitial selection DAG: "
967 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
968 << "'\n";
969 CurDAG->dump(DumpSortedDAG));
970
971#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
972 if (TTI->hasBranchDivergence())
973 CurDAG->VerifyDAGDivergence();
974#endif
975
976 if (ViewDAGCombine1 && MatchFilterBB)
977 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
978
979 // Run the DAG combiner in pre-legalize mode.
980 {
981 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
982 GroupDescription, TimePassesIsEnabled);
984 }
985
986 ISEL_DUMP(dbgs() << "\nOptimized lowered selection DAG: "
987 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
988 << "'\n";
989 CurDAG->dump(DumpSortedDAG));
990
991#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
992 if (TTI->hasBranchDivergence())
993 CurDAG->VerifyDAGDivergence();
994#endif
995
996 // Second step, hack on the DAG until it only uses operations and types that
997 // the target supports.
998 if (ViewLegalizeTypesDAGs && MatchFilterBB)
999 CurDAG->viewGraph("legalize-types input for " + BlockName);
1000
1001 bool Changed;
1002 {
1003 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
1004 GroupDescription, TimePassesIsEnabled);
1005 Changed = CurDAG->LegalizeTypes();
1006 }
1007
1008 ISEL_DUMP(dbgs() << "\nType-legalized selection DAG: "
1009 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1010 << "'\n";
1011 CurDAG->dump(DumpSortedDAG));
1012
1013#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1014 if (TTI->hasBranchDivergence())
1015 CurDAG->VerifyDAGDivergence();
1016#endif
1017
1018 // Only allow creation of legal node types.
1019 CurDAG->NewNodesMustHaveLegalTypes = true;
1020
1021 if (Changed) {
1022 if (ViewDAGCombineLT && MatchFilterBB)
1023 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
1024
1025 // Run the DAG combiner in post-type-legalize mode.
1026 {
1027 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
1028 GroupName, GroupDescription, TimePassesIsEnabled);
1030 }
1031
1032 ISEL_DUMP(dbgs() << "\nOptimized type-legalized selection DAG: "
1033 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1034 << "'\n";
1035 CurDAG->dump(DumpSortedDAG));
1036
1037#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1038 if (TTI->hasBranchDivergence())
1039 CurDAG->VerifyDAGDivergence();
1040#endif
1041 }
1042
1043 {
1044 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
1045 GroupDescription, TimePassesIsEnabled);
1046 Changed = CurDAG->LegalizeVectors();
1047 }
1048
1049 if (Changed) {
1050 ISEL_DUMP(dbgs() << "\nVector-legalized selection DAG: "
1051 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1052 << "'\n";
1053 CurDAG->dump(DumpSortedDAG));
1054
1055#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1056 if (TTI->hasBranchDivergence())
1057 CurDAG->VerifyDAGDivergence();
1058#endif
1059
1060 {
1061 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
1062 GroupDescription, TimePassesIsEnabled);
1063 CurDAG->LegalizeTypes();
1064 }
1065
1066 ISEL_DUMP(dbgs() << "\nVector/type-legalized selection DAG: "
1067 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1068 << "'\n";
1069 CurDAG->dump(DumpSortedDAG));
1070
1071#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1072 if (TTI->hasBranchDivergence())
1073 CurDAG->VerifyDAGDivergence();
1074#endif
1075
1076 if (ViewDAGCombineLT && MatchFilterBB)
1077 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
1078
1079 // Run the DAG combiner in post-type-legalize mode.
1080 {
1081 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
1082 GroupName, GroupDescription, TimePassesIsEnabled);
1084 }
1085
1086 ISEL_DUMP(dbgs() << "\nOptimized vector-legalized selection DAG: "
1087 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1088 << "'\n";
1089 CurDAG->dump(DumpSortedDAG));
1090
1091#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1092 if (TTI->hasBranchDivergence())
1093 CurDAG->VerifyDAGDivergence();
1094#endif
1095 }
1096
1097 if (ViewLegalizeDAGs && MatchFilterBB)
1098 CurDAG->viewGraph("legalize input for " + BlockName);
1099
1100 {
1101 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
1102 GroupDescription, TimePassesIsEnabled);
1103 CurDAG->Legalize();
1104 }
1105
1106 ISEL_DUMP(dbgs() << "\nLegalized selection DAG: "
1107 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1108 << "'\n";
1109 CurDAG->dump(DumpSortedDAG));
1110
1111#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1112 if (TTI->hasBranchDivergence())
1113 CurDAG->VerifyDAGDivergence();
1114#endif
1115
1116 if (ViewDAGCombine2 && MatchFilterBB)
1117 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
1118
1119 // Run the DAG combiner in post-legalize mode.
1120 {
1121 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
1122 GroupDescription, TimePassesIsEnabled);
1124 }
1125
1126 ISEL_DUMP(dbgs() << "\nOptimized legalized selection DAG: "
1127 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1128 << "'\n";
1129 CurDAG->dump(DumpSortedDAG));
1130
1131#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1132 if (TTI->hasBranchDivergence())
1133 CurDAG->VerifyDAGDivergence();
1134#endif
1135
1137 ComputeLiveOutVRegInfo();
1138
1139 if (ViewISelDAGs && MatchFilterBB)
1140 CurDAG->viewGraph("isel input for " + BlockName);
1141
1142 // Third, instruction select all of the operations to machine code, adding the
1143 // code to the MachineBasicBlock.
1144 {
1145 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
1146 GroupDescription, TimePassesIsEnabled);
1147 DoInstructionSelection();
1148 }
1149
1150 ISEL_DUMP(dbgs() << "\nSelected selection DAG: "
1151 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1152 << "'\n";
1153 CurDAG->dump(DumpSortedDAG));
1154
1155 if (ViewSchedDAGs && MatchFilterBB)
1156 CurDAG->viewGraph("scheduler input for " + BlockName);
1157
1158 // Schedule machine code.
1159 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
1160 {
1161 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
1162 GroupDescription, TimePassesIsEnabled);
1163 Scheduler->Run(CurDAG, FuncInfo->MBB);
1164 }
1165
1166 if (ViewSUnitDAGs && MatchFilterBB)
1167 Scheduler->viewGraph();
1168
1169 // Emit machine code to BB. This can change 'BB' to the last block being
1170 // inserted into.
1171 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
1172 {
1173 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
1174 GroupDescription, TimePassesIsEnabled);
1175
1176 // FuncInfo->InsertPt is passed by reference and set to the end of the
1177 // scheduled instructions.
1178 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
1179 }
1180
1181 // If the block was split, make sure we update any references that are used to
1182 // update PHI nodes later on.
1183 if (FirstMBB != LastMBB)
1184 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
1185
1186 // Free the scheduler state.
1187 {
1188 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
1189 GroupDescription, TimePassesIsEnabled);
1190 delete Scheduler;
1191 }
1192
1193 // Free the SelectionDAG state, now that we're finished with it.
1194 CurDAG->clear();
1195}
1196
1197namespace {
1198
1199/// ISelUpdater - helper class to handle updates of the instruction selection
1200/// graph.
1201class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1202 SelectionDAG::allnodes_iterator &ISelPosition;
1203
1204public:
1205 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1206 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1207
1208 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1209 /// deleted is the current ISelPosition node, update ISelPosition.
1210 ///
1211 void NodeDeleted(SDNode *N, SDNode *E) override {
1212 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1213 ++ISelPosition;
1214 }
1215
1216 /// NodeInserted - Handle new nodes inserted into the graph: propagate
1217 /// metadata from root nodes that also applies to new nodes, in case the root
1218 /// is later deleted.
1219 void NodeInserted(SDNode *N) override {
1220 SDNode *CurNode = &*ISelPosition;
1221 if (MDNode *MD = DAG.getPCSections(CurNode))
1222 DAG.addPCSections(N, MD);
1223 if (MDNode *MMRA = DAG.getMMRAMetadata(CurNode))
1224 DAG.addMMRAMetadata(N, MMRA);
1225 }
1226};
1227
1228} // end anonymous namespace
1229
1230// This function is used to enforce the topological node id property
1231// leveraged during instruction selection. Before the selection process all
1232// nodes are given a non-negative id such that all nodes have a greater id than
1233// their operands. As this holds transitively we can prune checks that a node N
1234// is a predecessor of M another by not recursively checking through M's
1235// operands if N's ID is larger than M's ID. This significantly improves
1236// performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
1237
1238// However, when we fuse multiple nodes into a single node during the
1239// selection we may induce a predecessor relationship between inputs and
1240// outputs of distinct nodes being merged, violating the topological property.
1241// Should a fused node have a successor which has yet to be selected,
1242// our legality checks would be incorrect. To avoid this we mark all unselected
1243// successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
1244// (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1245// We use bit-negation to more clearly enforce that node id -1 can only be
1246// achieved by selected nodes. As the conversion is reversable to the original
1247// Id, topological pruning can still be leveraged when looking for unselected
1248// nodes. This method is called internally in all ISel replacement related
1249// functions.
1252 Nodes.push_back(Node);
1253
1254 while (!Nodes.empty()) {
1255 SDNode *N = Nodes.pop_back_val();
1256 for (auto *U : N->users()) {
1257 auto UId = U->getNodeId();
1258 if (UId > 0) {
1260 Nodes.push_back(U);
1261 }
1262 }
1263 }
1264}
1265
1266// InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
1267// NodeId with the equivalent node id which is invalid for topological
1268// pruning.
1270 int InvalidId = -(N->getNodeId() + 1);
1271 N->setNodeId(InvalidId);
1272}
1273
1274// getUninvalidatedNodeId - get original uninvalidated node id.
1276 int Id = N->getNodeId();
1277 if (Id < -1)
1278 return -(Id + 1);
1279 return Id;
1280}
1281
1282void SelectionDAGISel::DoInstructionSelection() {
1283 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1284 << printMBBReference(*FuncInfo->MBB) << " '"
1285 << FuncInfo->MBB->getName() << "'\n");
1286
1288
1289 // Select target instructions for the DAG.
1290 {
1291 // Number all nodes with a topological order and set DAGSize.
1293
1294 // Create a dummy node (which is not added to allnodes), that adds
1295 // a reference to the root node, preventing it from being deleted,
1296 // and tracking any changes of the root.
1297 HandleSDNode Dummy(CurDAG->getRoot());
1299 ++ISelPosition;
1300
1301 // Make sure that ISelPosition gets properly updated when nodes are deleted
1302 // in calls made from this function. New nodes inherit relevant metadata.
1303 ISelUpdater ISU(*CurDAG, ISelPosition);
1304
1305 // The AllNodes list is now topological-sorted. Visit the
1306 // nodes by starting at the end of the list (the root of the
1307 // graph) and preceding back toward the beginning (the entry
1308 // node).
1309 while (ISelPosition != CurDAG->allnodes_begin()) {
1310 SDNode *Node = &*--ISelPosition;
1311 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1312 // but there are currently some corner cases that it misses. Also, this
1313 // makes it theoretically possible to disable the DAGCombiner.
1314 if (Node->use_empty())
1315 continue;
1316
1317#ifndef NDEBUG
1319 Nodes.push_back(Node);
1320
1321 while (!Nodes.empty()) {
1322 auto N = Nodes.pop_back_val();
1323 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1324 continue;
1325 for (const SDValue &Op : N->op_values()) {
1326 if (Op->getOpcode() == ISD::TokenFactor)
1327 Nodes.push_back(Op.getNode());
1328 else {
1329 // We rely on topological ordering of node ids for checking for
1330 // cycles when fusing nodes during selection. All unselected nodes
1331 // successors of an already selected node should have a negative id.
1332 // This assertion will catch such cases. If this assertion triggers
1333 // it is likely you using DAG-level Value/Node replacement functions
1334 // (versus equivalent ISEL replacement) in backend-specific
1335 // selections. See comment in EnforceNodeIdInvariant for more
1336 // details.
1337 assert(Op->getNodeId() != -1 &&
1338 "Node has already selected predecessor node");
1339 }
1340 }
1341 }
1342#endif
1343
1344 // When we are using non-default rounding modes or FP exception behavior
1345 // FP operations are represented by StrictFP pseudo-operations. For
1346 // targets that do not (yet) understand strict FP operations directly,
1347 // we convert them to normal FP opcodes instead at this point. This
1348 // will allow them to be handled by existing target-specific instruction
1349 // selectors.
1350 if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1351 // For some opcodes, we need to call TLI->getOperationAction using
1352 // the first operand type instead of the result type. Note that this
1353 // must match what SelectionDAGLegalize::LegalizeOp is doing.
1354 EVT ActionVT;
1355 switch (Node->getOpcode()) {
1358 case ISD::STRICT_LRINT:
1359 case ISD::STRICT_LLRINT:
1360 case ISD::STRICT_LROUND:
1362 case ISD::STRICT_FSETCC:
1364 ActionVT = Node->getOperand(1).getValueType();
1365 break;
1366 default:
1367 ActionVT = Node->getValueType(0);
1368 break;
1369 }
1370 if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1372 Node = CurDAG->mutateStrictFPToFP(Node);
1373 }
1374
1375 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1376 Node->dump(CurDAG));
1377
1378 Select(Node);
1379 }
1380
1381 CurDAG->setRoot(Dummy.getValue());
1382 }
1383
1384 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1385
1387}
1388
1390 for (const User *U : CPI->users()) {
1391 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1392 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1393 if (IID == Intrinsic::eh_exceptionpointer ||
1394 IID == Intrinsic::eh_exceptioncode)
1395 return true;
1396 }
1397 }
1398 return false;
1399}
1400
1401// wasm.landingpad.index intrinsic is for associating a landing pad index number
1402// with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1403// and store the mapping in the function.
1405 const CatchPadInst *CPI) {
1406 MachineFunction *MF = MBB->getParent();
1407 // In case of single catch (...), we don't emit LSDA, so we don't need
1408 // this information.
1409 bool IsSingleCatchAllClause =
1410 CPI->arg_size() == 1 &&
1411 cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1412 // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1413 // and they don't need LSDA info
1414 bool IsCatchLongjmp = CPI->arg_size() == 0;
1415 if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
1416 // Create a mapping from landing pad label to landing pad index.
1417 bool IntrFound = false;
1418 for (const User *U : CPI->users()) {
1419 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1420 Intrinsic::ID IID = Call->getIntrinsicID();
1421 if (IID == Intrinsic::wasm_landingpad_index) {
1422 Value *IndexArg = Call->getArgOperand(1);
1423 int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1424 MF->setWasmLandingPadIndex(MBB, Index);
1425 IntrFound = true;
1426 break;
1427 }
1428 }
1429 }
1430 assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1431 (void)IntrFound;
1432 }
1433}
1434
1435/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1436/// do other setup for EH landing-pad blocks.
1437bool SelectionDAGISel::PrepareEHLandingPad() {
1438 MachineBasicBlock *MBB = FuncInfo->MBB;
1439 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1440 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1441 const TargetRegisterClass *PtrRC =
1442 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
1443
1444 auto Pers = classifyEHPersonality(PersonalityFn);
1445
1446 // Catchpads have one live-in register, which typically holds the exception
1447 // pointer or code.
1448 if (isFuncletEHPersonality(Pers)) {
1449 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHIIt())) {
1451 // Get or create the virtual register to hold the pointer or code. Mark
1452 // the live in physreg and copy into the vreg.
1453 MCRegister EHPhysReg = TLI->getExceptionPointerRegister(
1454 FuncInfo->ExceptionModel, PersonalityFn);
1455 assert(EHPhysReg && "target lacks exception pointer register");
1456 MBB->addLiveIn(EHPhysReg);
1457 Register VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1458 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1459 TII->get(TargetOpcode::COPY), VReg)
1460 .addReg(EHPhysReg, RegState::Kill);
1461 }
1462 }
1463 return true;
1464 }
1465
1466 // Add a label to mark the beginning of the landing pad. Deletion of the
1467 // landing pad can thus be detected via the MachineModuleInfo.
1468 MCSymbol *Label = MF->addLandingPad(MBB);
1469
1470 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1471 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1472 .addSym(Label);
1473
1474 // If the unwinder does not preserve all registers, ensure that the
1475 // function marks the clobbered registers as used.
1476 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
1477 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1478 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
1479
1480 if (Pers == EHPersonality::Wasm_CXX || Pers == EHPersonality::Wasm_D) {
1481 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHIIt()))
1483 } else {
1484 // Assign the call site to the landing pad's begin label.
1485 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1486 // Mark exception register as live in.
1487 if (MCRegister Reg = TLI->getExceptionPointerRegister(
1488 FuncInfo->ExceptionModel, PersonalityFn))
1489 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1490 // Mark exception selector register as live in.
1491 if (MCRegister Reg = TLI->getExceptionSelectorRegister(
1492 FuncInfo->ExceptionModel, PersonalityFn))
1493 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1494 }
1495
1496 return true;
1497}
1498
1499// Mark and Report IPToState for each Block under IsEHa
1500void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
1501 llvm::WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
1502 if (!EHInfo)
1503 return;
1504 for (MachineBasicBlock &MBB : *MF) {
1505 const BasicBlock *BB = MBB.getBasicBlock();
1506 int State = EHInfo->BlockToStateMap[BB];
1507 if (BB->getFirstMayFaultInst()) {
1508 // Report IP range only for blocks with Faulty inst
1509 auto MBBb = MBB.getFirstNonPHI();
1510
1511 if (MBBb == MBB.end())
1512 continue;
1513
1514 MachineInstr *MIb = &*MBBb;
1515 if (MIb->isTerminator())
1516 continue;
1517
1518 // Insert EH Labels
1519 MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
1520 MCSymbol *EndLabel = MF->getContext().createTempSymbol();
1521 EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
1522 BuildMI(MBB, MBBb, SDB->getCurDebugLoc(),
1523 TII->get(TargetOpcode::EH_LABEL))
1524 .addSym(BeginLabel);
1525 auto MBBe = MBB.instr_end();
1526 MachineInstr *MIe = &*(--MBBe);
1527 // insert before (possible multiple) terminators
1528 while (MIe->isTerminator())
1529 MIe = &*(--MBBe);
1530 ++MBBe;
1531 BuildMI(MBB, MBBe, SDB->getCurDebugLoc(),
1532 TII->get(TargetOpcode::EH_LABEL))
1533 .addSym(EndLabel);
1534 }
1535 }
1536}
1537
1538/// isFoldedOrDeadInstruction - Return true if the specified instruction is
1539/// side-effect free and is either dead or folded into a generated instruction.
1540/// Return false if it needs to be emitted.
1542 const FunctionLoweringInfo &FuncInfo) {
1543 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1544 !I->isTerminator() && // Terminators aren't folded.
1545 !I->isEHPad() && // EH pad instructions aren't folded.
1546 !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1547}
1548
1550 const Value *Arg, DIExpression *Expr,
1551 DILocalVariable *Var,
1552 DebugLoc DbgLoc) {
1553 if (!Expr->isEntryValue() || !isa<Argument>(Arg))
1554 return false;
1555
1556 auto ArgIt = FuncInfo.ValueMap.find(Arg);
1557 if (ArgIt == FuncInfo.ValueMap.end())
1558 return false;
1559 Register ArgVReg = ArgIt->getSecond();
1560
1561 // Find the corresponding livein physical register to this argument.
1562 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1563 if (VirtReg == ArgVReg) {
1564 // Append an op deref to account for the fact that this is a dbg_declare.
1565 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
1566 FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
1567 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1568 << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
1569 << ", DbgLoc=" << DbgLoc << "\n");
1570 return true;
1571 }
1572 return false;
1573}
1574
1576 const Value *Address, DIExpression *Expr,
1577 DILocalVariable *Var, DebugLoc DbgLoc) {
1578 if (!Address) {
1579 LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
1580 << " (bad address)\n");
1581 return false;
1582 }
1583
1584 if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
1585 return true;
1586
1587 if (!Address->getType()->isPointerTy())
1588 return false;
1589
1590 MachineFunction *MF = FuncInfo.MF;
1591 const DataLayout &DL = MF->getDataLayout();
1592
1593 assert(Var && "Missing variable");
1594 assert(DbgLoc && "Missing location");
1595
1596 // Look through casts and constant offset GEPs. These mostly come from
1597 // inalloca.
1598 APInt Offset(DL.getIndexTypeSizeInBits(Address->getType()), 0);
1599 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1600
1601 // Check if the variable is a static alloca or a byval or inalloca
1602 // argument passed in memory. If it is not, then we will ignore this
1603 // intrinsic and handle this during isel like dbg.value.
1604 int FI = std::numeric_limits<int>::max();
1605 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1606 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1607 if (SI != FuncInfo.StaticAllocaMap.end())
1608 FI = SI->second;
1609 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1610 FI = FuncInfo.getArgumentFrameIndex(Arg);
1611
1612 if (FI == std::numeric_limits<int>::max())
1613 return false;
1614
1615 if (Offset.getBoolValue())
1617 Offset.getZExtValue());
1618
1619 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1620 << ", Expr=" << *Expr << ", FI=" << FI
1621 << ", DbgLoc=" << DbgLoc << "\n");
1622 MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
1623 return true;
1624}
1625
1626/// Collect llvm.dbg.declare information. This is done after argument lowering
1627/// in case the declarations refer to arguments.
1629 for (const auto &I : instructions(*FuncInfo.Fn)) {
1630 for (const DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1632 processDbgDeclare(FuncInfo, DVR.getVariableLocationOp(0),
1633 DVR.getExpression(), DVR.getVariable(),
1634 DVR.getDebugLoc()))
1635 FuncInfo.PreprocessedDVRDeclares.insert(&DVR);
1636 }
1637 }
1638}
1639
1640/// Collect single location variable information generated with assignment
1641/// tracking. This is done after argument lowering in case the declarations
1642/// refer to arguments.
1644 FunctionVarLocs const *FnVarLocs) {
1645 for (auto It = FnVarLocs->single_locs_begin(),
1646 End = FnVarLocs->single_locs_end();
1647 It != End; ++It) {
1648 assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
1649 processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1650 FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1651 }
1652}
1653
1654void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1655 FastISelFailed = false;
1656 // Initialize the Fast-ISel state, if needed.
1657 FastISel *FastIS = nullptr;
1658 if (TM.Options.EnableFastISel) {
1659 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1660 FastIS = TLI->createFastISel(*FuncInfo, LibInfo, LibcallLowering);
1661 }
1662
1663 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1664
1665 // Lower arguments up front. An RPO iteration always visits the entry block
1666 // first.
1667 assert(*RPOT.begin() == &Fn.getEntryBlock());
1668 ++NumEntryBlocks;
1669
1670 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1671 FuncInfo->MBB = FuncInfo->getMBB(&Fn.getEntryBlock());
1672 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1673
1674 CurDAG->setFunctionLoweringInfo(FuncInfo.get());
1675
1676 if (!FastIS) {
1677 LowerArguments(Fn, /*FastISel=*/false);
1678 } else {
1679 // See if fast isel can lower the arguments.
1680 FastIS->startNewBlock();
1681 if (!FastIS->lowerArguments()) {
1682 FastISelFailed = true;
1683 // Fast isel failed to lower these arguments
1684 ++NumFastIselFailLowerArguments;
1685
1686 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1687 Fn.getSubprogram(),
1688 &Fn.getEntryBlock());
1689 R << "FastISel didn't lower all arguments: "
1690 << ore::NV("Prototype", Fn.getFunctionType());
1692
1693 // Use SelectionDAG argument lowering
1694 LowerArguments(Fn, /*FastISel=*/true);
1695 CurDAG->setRoot(SDB->getControlRoot());
1696 SDB->clear();
1697 CodeGenAndEmitDAG();
1698 }
1699
1700 // If we inserted any instructions at the beginning, make a note of
1701 // where they are, so we can be sure to emit subsequent instructions
1702 // after them.
1703 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1704 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1705 else
1706 FastIS->setLastLocalValue(nullptr);
1707 }
1708
1709 bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1710
1711 if (FastIS && Inserted)
1712 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1713
1715 assert(CurDAG->getFunctionVarLocs() &&
1716 "expected AssignmentTrackingAnalysis pass results");
1717 processSingleLocVars(*FuncInfo, CurDAG->getFunctionVarLocs());
1718 } else {
1720 }
1721
1722 // Iterate over all basic blocks in the function.
1723 FuncInfo->VisitedBBs.assign(Fn.getMaxBlockNumber(), false);
1724 for (const BasicBlock *LLVMBB : RPOT) {
1726 bool AllPredsVisited = true;
1727 for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1728 if (!FuncInfo->VisitedBBs[Pred->getNumber()]) {
1729 AllPredsVisited = false;
1730 break;
1731 }
1732 }
1733
1734 if (AllPredsVisited) {
1735 for (const PHINode &PN : LLVMBB->phis())
1736 FuncInfo->ComputePHILiveOutRegInfo(&PN);
1737 } else {
1738 for (const PHINode &PN : LLVMBB->phis())
1739 FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1740 }
1741
1742 FuncInfo->VisitedBBs[LLVMBB->getNumber()] = true;
1743 }
1744
1745 // Fake uses that follow tail calls are dropped. To avoid this, move
1746 // such fake uses in front of the tail call, provided they don't
1747 // use anything def'd by or after the tail call.
1748 {
1749 BasicBlock::iterator BBStart =
1750 const_cast<BasicBlock *>(LLVMBB)->getFirstNonPHIIt();
1751 BasicBlock::iterator BBEnd = const_cast<BasicBlock *>(LLVMBB)->end();
1752 preserveFakeUses(BBStart, BBEnd);
1753 }
1754
1755 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHIIt();
1756 BasicBlock::const_iterator const End = LLVMBB->end();
1758
1759 FuncInfo->MBB = FuncInfo->getMBB(LLVMBB);
1760 if (!FuncInfo->MBB)
1761 continue; // Some blocks like catchpads have no code or MBB.
1762
1763 // Insert new instructions after any phi or argument setup code.
1764 FuncInfo->InsertPt = FuncInfo->MBB->end();
1765
1766 // Setup an EH landing-pad block.
1767 FuncInfo->ExceptionPointerVirtReg = Register();
1768 FuncInfo->ExceptionSelectorVirtReg = Register();
1769 if (LLVMBB->isEHPad()) {
1770 if (!PrepareEHLandingPad())
1771 continue;
1772
1773 if (!FastIS) {
1774 SDValue NewRoot = TLI->lowerEHPadEntry(CurDAG->getRoot(),
1775 SDB->getCurSDLoc(), *CurDAG);
1776 if (NewRoot && NewRoot != CurDAG->getRoot())
1777 CurDAG->setRoot(NewRoot);
1778 }
1779 }
1780
1781 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1782 if (FastIS) {
1783 if (LLVMBB != &Fn.getEntryBlock())
1784 FastIS->startNewBlock();
1785
1786 unsigned NumFastIselRemaining = std::distance(Begin, End);
1787
1788 // Pre-assign swifterror vregs.
1789 SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1790
1791 // Do FastISel on as many instructions as possible.
1792 for (; BI != Begin; --BI) {
1793 const Instruction *Inst = &*std::prev(BI);
1794
1795 // If we no longer require this instruction, skip it.
1796 if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1797 ElidedArgCopyInstrs.count(Inst)) {
1798 --NumFastIselRemaining;
1799 FastIS->handleDbgInfo(Inst);
1800 continue;
1801 }
1802
1803 // Bottom-up: reset the insert pos at the top, after any local-value
1804 // instructions.
1805 FastIS->recomputeInsertPt();
1806
1807 // Try to select the instruction with FastISel.
1808 if (FastIS->selectInstruction(Inst)) {
1809 --NumFastIselRemaining;
1810 ++NumFastIselSuccess;
1811
1812 FastIS->handleDbgInfo(Inst);
1813 // If fast isel succeeded, skip over all the folded instructions, and
1814 // then see if there is a load right before the selected instructions.
1815 // Try to fold the load if so.
1816 const Instruction *BeforeInst = Inst;
1817 while (BeforeInst != &*Begin) {
1818 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1819 if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1820 break;
1821 }
1822 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1823 BeforeInst->hasOneUse() &&
1824 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1825 // If we succeeded, don't re-select the load.
1827 << "FastISel folded load: " << *BeforeInst << "\n");
1828 FastIS->handleDbgInfo(BeforeInst);
1829 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1830 --NumFastIselRemaining;
1831 ++NumFastIselSuccess;
1832 }
1833 continue;
1834 }
1835
1836 FastISelFailed = true;
1837
1838 // Then handle certain instructions as single-LLVM-Instruction blocks.
1839 // We cannot separate out GCrelocates to their own blocks since we need
1840 // to keep track of gc-relocates for a particular gc-statepoint. This is
1841 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1842 // visitGCRelocate.
1843 if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1844 !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1845 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1846 Inst->getDebugLoc(), LLVMBB);
1847
1848 R << "FastISel missed call";
1849
1850 if (R.isEnabled() || EnableFastISelAbort) {
1851 std::string InstStrStorage;
1852 raw_string_ostream InstStr(InstStrStorage);
1853 InstStr << *Inst;
1854
1855 R << ": " << InstStrStorage;
1856 }
1857
1859
1860 // If the call has operand bundles, then it's best if they are handled
1861 // together with the call instead of selecting the call as its own
1862 // block.
1863 if (cast<CallInst>(Inst)->hasOperandBundles()) {
1864 NumFastIselFailures += NumFastIselRemaining;
1865 break;
1866 }
1867
1868 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1869 !Inst->use_empty()) {
1870 Register &R = FuncInfo->ValueMap[Inst];
1871 if (!R)
1872 R = FuncInfo->CreateRegs(Inst);
1873 }
1874
1875 bool HadTailCall = false;
1876 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1877 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1878
1879 // If the call was emitted as a tail call, we're done with the block.
1880 // We also need to delete any previously emitted instructions.
1881 if (HadTailCall) {
1882 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1883 --BI;
1884 break;
1885 }
1886
1887 // Recompute NumFastIselRemaining as Selection DAG instruction
1888 // selection may have handled the call, input args, etc.
1889 unsigned RemainingNow = std::distance(Begin, BI);
1890 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1891 NumFastIselRemaining = RemainingNow;
1892 continue;
1893 }
1894
1895 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1896 Inst->getDebugLoc(), LLVMBB);
1897
1898 bool ShouldAbort = EnableFastISelAbort;
1899 if (Inst->isTerminator()) {
1900 // Use a different message for terminator misses.
1901 R << "FastISel missed terminator";
1902 // Don't abort for terminator unless the level is really high
1903 ShouldAbort = (EnableFastISelAbort > 2);
1904 } else {
1905 R << "FastISel missed";
1906 }
1907
1908 if (R.isEnabled() || EnableFastISelAbort) {
1909 std::string InstStrStorage;
1910 raw_string_ostream InstStr(InstStrStorage);
1911 InstStr << *Inst;
1912 R << ": " << InstStrStorage;
1913 }
1914
1915 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1916
1917 NumFastIselFailures += NumFastIselRemaining;
1918 break;
1919 }
1920
1921 FastIS->recomputeInsertPt();
1922 }
1923
1924 if (SP->shouldEmitSDCheck(*LLVMBB)) {
1925 bool FunctionBasedInstrumentation =
1926 TLI->getSSPStackGuardCheck(*Fn.getParent(), *LibcallLowering) &&
1927 Fn.hasMinSize();
1928 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->getMBB(LLVMBB),
1929 FunctionBasedInstrumentation);
1930 }
1931
1932 if (Begin != BI)
1933 ++NumDAGBlocks;
1934 else
1935 ++NumFastIselBlocks;
1936
1937 if (Begin != BI) {
1938 // Run SelectionDAG instruction selection on the remainder of the block
1939 // not handled by FastISel. If FastISel is not run, this is the entire
1940 // block.
1941 bool HadTailCall;
1942 SelectBasicBlock(Begin, BI, HadTailCall);
1943
1944 // But if FastISel was run, we already selected some of the block.
1945 // If we emitted a tail-call, we need to delete any previously emitted
1946 // instruction that follows it.
1947 if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1948 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1949 }
1950
1951 if (FastIS)
1952 FastIS->finishBasicBlock();
1953 FinishBasicBlock();
1954 FuncInfo->PHINodesToUpdate.clear();
1955 ElidedArgCopyInstrs.clear();
1956 }
1957
1958 // AsynchEH: Report Block State under -AsynchEH
1959 if (Fn.getParent()->getModuleFlag("eh-asynch"))
1960 reportIPToStateForBlocks(MF);
1961
1962 SP->copyToMachineFrameInfo(MF->getFrameInfo());
1963
1964 SwiftError->propagateVRegs();
1965
1966 delete FastIS;
1967 SDB->clearDanglingDebugInfo();
1968 SDB->SPDescriptor.resetPerFunctionState();
1969}
1970
1971void
1972SelectionDAGISel::FinishBasicBlock() {
1973 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1974 << FuncInfo->PHINodesToUpdate.size() << "\n";
1975 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1976 ++i) dbgs()
1977 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1978 << ", " << printReg(FuncInfo->PHINodesToUpdate[i].second)
1979 << ")\n");
1980
1981 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1982 // PHI nodes in successors.
1983 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1984 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1985 assert(PHI->isPHI() &&
1986 "This is not a machine PHI node that we are updating!");
1987 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1988 continue;
1989 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1990 }
1991
1992 // Handle stack protector.
1993 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1994 // The target provides a guard check function. There is no need to
1995 // generate error handling code or to split current basic block.
1996 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1997
1998 // Add load and check to the basicblock.
1999 FuncInfo->MBB = ParentMBB;
2000 FuncInfo->InsertPt = findSplitPointForStackProtector(ParentMBB, *TII);
2001 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
2002 CurDAG->setRoot(SDB->getRoot());
2003 SDB->clear();
2004 CodeGenAndEmitDAG();
2005
2006 // Clear the Per-BB State.
2007 SDB->SPDescriptor.resetPerBBState();
2008 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
2009 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
2010 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
2011
2012 // Find the split point to split the parent mbb. At the same time copy all
2013 // physical registers used in the tail of parent mbb into virtual registers
2014 // before the split point and back into physical registers after the split
2015 // point. This prevents us needing to deal with Live-ins and many other
2016 // register allocation issues caused by us splitting the parent mbb. The
2017 // register allocator will clean up said virtual copies later on.
2018 MachineBasicBlock::iterator SplitPoint =
2020
2021 // Splice the terminator of ParentMBB into SuccessMBB.
2022 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
2023 ParentMBB->end());
2024
2025 // Add compare/jump on neq/jump to the parent BB.
2026 FuncInfo->MBB = ParentMBB;
2027 FuncInfo->InsertPt = ParentMBB->end();
2028 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
2029 CurDAG->setRoot(SDB->getRoot());
2030 SDB->clear();
2031 CodeGenAndEmitDAG();
2032
2033 // CodeGen Failure MBB if we have not codegened it yet.
2034 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
2035 if (FailureMBB->empty()) {
2036 FuncInfo->MBB = FailureMBB;
2037 FuncInfo->InsertPt = FailureMBB->end();
2038 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
2039 CurDAG->setRoot(SDB->getRoot());
2040 SDB->clear();
2041 CodeGenAndEmitDAG();
2042 }
2043
2044 // Clear the Per-BB State.
2045 SDB->SPDescriptor.resetPerBBState();
2046 }
2047
2048 // Lower each BitTestBlock.
2049 for (auto &BTB : SDB->SL->BitTestCases) {
2050 // Lower header first, if it wasn't already lowered
2051 if (!BTB.Emitted) {
2052 // Set the current basic block to the mbb we wish to insert the code into
2053 FuncInfo->MBB = BTB.Parent;
2054 FuncInfo->InsertPt = FuncInfo->MBB->end();
2055 // Emit the code
2056 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
2057 CurDAG->setRoot(SDB->getRoot());
2058 SDB->clear();
2059 CodeGenAndEmitDAG();
2060 }
2061
2062 BranchProbability UnhandledProb = BTB.Prob;
2063 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
2064 UnhandledProb -= BTB.Cases[j].ExtraProb;
2065 // Set the current basic block to the mbb we wish to insert the code into
2066 FuncInfo->MBB = BTB.Cases[j].ThisBB;
2067 FuncInfo->InsertPt = FuncInfo->MBB->end();
2068 // Emit the code
2069
2070 // If all cases cover a contiguous range, it is not necessary to jump to
2071 // the default block after the last bit test fails. This is because the
2072 // range check during bit test header creation has guaranteed that every
2073 // case here doesn't go outside the range. In this case, there is no need
2074 // to perform the last bit test, as it will always be true. Instead, make
2075 // the second-to-last bit-test fall through to the target of the last bit
2076 // test, and delete the last bit test.
2077
2078 MachineBasicBlock *NextMBB;
2079 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2080 // Second-to-last bit-test with contiguous range or omitted range
2081 // check: fall through to the target of the final bit test.
2082 NextMBB = BTB.Cases[j + 1].TargetBB;
2083 } else if (j + 1 == ej) {
2084 // For the last bit test, fall through to Default.
2085 NextMBB = BTB.Default;
2086 } else {
2087 // Otherwise, fall through to the next bit test.
2088 NextMBB = BTB.Cases[j + 1].ThisBB;
2089 }
2090
2091 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
2092 FuncInfo->MBB);
2093
2094 CurDAG->setRoot(SDB->getRoot());
2095 SDB->clear();
2096 CodeGenAndEmitDAG();
2097
2098 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2099 // Since we're not going to use the final bit test, remove it.
2100 BTB.Cases.pop_back();
2101 break;
2102 }
2103 }
2104
2105 // Update PHI Nodes
2106 for (const std::pair<MachineInstr *, Register> &P :
2107 FuncInfo->PHINodesToUpdate) {
2108 MachineInstrBuilder PHI(*MF, P.first);
2109 MachineBasicBlock *PHIBB = PHI->getParent();
2110 assert(PHI->isPHI() &&
2111 "This is not a machine PHI node that we are updating!");
2112 // This is "default" BB. We have two jumps to it. From "header" BB and
2113 // from last "case" BB, unless the latter was skipped.
2114 if (PHIBB == BTB.Default) {
2115 PHI.addReg(P.second).addMBB(BTB.Parent);
2116 if (!BTB.ContiguousRange) {
2117 PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
2118 }
2119 }
2120 // One of "cases" BB.
2121 for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
2122 MachineBasicBlock* cBB = BT.ThisBB;
2123 if (cBB->isSuccessor(PHIBB))
2124 PHI.addReg(P.second).addMBB(cBB);
2125 }
2126 }
2127 }
2128 SDB->SL->BitTestCases.clear();
2129
2130 // If the JumpTable record is filled in, then we need to emit a jump table.
2131 // Updating the PHI nodes is tricky in this case, since we need to determine
2132 // whether the PHI is a successor of the range check MBB or the jump table MBB
2133 for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
2134 // Lower header first, if it wasn't already lowered
2135 if (!SDB->SL->JTCases[i].first.Emitted) {
2136 // Set the current basic block to the mbb we wish to insert the code into
2137 FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
2138 FuncInfo->InsertPt = FuncInfo->MBB->end();
2139 // Emit the code
2140 SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
2141 SDB->SL->JTCases[i].first, FuncInfo->MBB);
2142 CurDAG->setRoot(SDB->getRoot());
2143 SDB->clear();
2144 CodeGenAndEmitDAG();
2145 }
2146
2147 // Set the current basic block to the mbb we wish to insert the code into
2148 FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
2149 FuncInfo->InsertPt = FuncInfo->MBB->end();
2150 // Emit the code
2151 SDB->visitJumpTable(SDB->SL->JTCases[i].second);
2152 CurDAG->setRoot(SDB->getRoot());
2153 SDB->clear();
2154 CodeGenAndEmitDAG();
2155
2156 // Update PHI Nodes
2157 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
2158 pi != pe; ++pi) {
2159 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
2160 MachineBasicBlock *PHIBB = PHI->getParent();
2161 assert(PHI->isPHI() &&
2162 "This is not a machine PHI node that we are updating!");
2163 // "default" BB. We can go there only from header BB.
2164 if (PHIBB == SDB->SL->JTCases[i].second.Default)
2165 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
2166 .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
2167 // JT BB. Just iterate over successors here
2168 if (FuncInfo->MBB->isSuccessor(PHIBB))
2169 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
2170 }
2171 }
2172 SDB->SL->JTCases.clear();
2173
2174 // If we generated any switch lowering information, build and codegen any
2175 // additional DAGs necessary.
2176 for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
2177 // Set the current basic block to the mbb we wish to insert the code into
2178 FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
2179 FuncInfo->InsertPt = FuncInfo->MBB->end();
2180
2181 // Determine the unique successors.
2183 Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
2184 if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
2185 Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
2186
2187 // Emit the code. Note that this could result in FuncInfo->MBB being split.
2188 SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
2189 CurDAG->setRoot(SDB->getRoot());
2190 SDB->clear();
2191 CodeGenAndEmitDAG();
2192
2193 // Remember the last block, now that any splitting is done, for use in
2194 // populating PHI nodes in successors.
2195 MachineBasicBlock *ThisBB = FuncInfo->MBB;
2196
2197 // Handle any PHI nodes in successors of this chunk, as if we were coming
2198 // from the original BB before switch expansion. Note that PHI nodes can
2199 // occur multiple times in PHINodesToUpdate. We have to be very careful to
2200 // handle them the right number of times.
2201 for (MachineBasicBlock *Succ : Succs) {
2202 FuncInfo->MBB = Succ;
2203 FuncInfo->InsertPt = FuncInfo->MBB->end();
2204 // FuncInfo->MBB may have been removed from the CFG if a branch was
2205 // constant folded.
2206 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
2208 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
2209 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
2210 MachineInstrBuilder PHI(*MF, MBBI);
2211 // This value for this PHI node is recorded in PHINodesToUpdate.
2212 for (unsigned pn = 0; ; ++pn) {
2213 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
2214 "Didn't find PHI entry!");
2215 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
2216 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
2217 break;
2218 }
2219 }
2220 }
2221 }
2222 }
2223 }
2224 SDB->SL->SwitchCases.clear();
2225}
2226
2227/// Create the scheduler. If a specific scheduler was specified
2228/// via the SchedulerRegistry, use it, otherwise select the
2229/// one preferred by the target.
2230///
2231ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
2232 return ISHeuristic(this, OptLevel);
2233}
2234
2235//===----------------------------------------------------------------------===//
2236// Helper functions used by the generated instruction selector.
2237//===----------------------------------------------------------------------===//
2238// Calls to these methods are generated by tblgen.
2239
2240/// CheckAndMask - The isel is trying to match something like (and X, 255). If
2241/// the dag combiner simplified the 255, we still want to match. RHS is the
2242/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2243/// specified in the .td file (e.g. 255).
2245 int64_t DesiredMaskS) const {
2246 const APInt &ActualMask = RHS->getAPIntValue();
2247 // TODO: Avoid implicit trunc?
2248 // See https://github.com/llvm/llvm-project/issues/112510.
2249 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2250 /*isSigned=*/false, /*implicitTrunc=*/true);
2251
2252 // If the actual mask exactly matches, success!
2253 if (ActualMask == DesiredMask)
2254 return true;
2255
2256 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2257 if (!ActualMask.isSubsetOf(DesiredMask))
2258 return false;
2259
2260 // Otherwise, the DAG Combiner may have proven that the value coming in is
2261 // either already zero or is not demanded. Check for known zero input bits.
2262 APInt NeededMask = DesiredMask & ~ActualMask;
2263 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2264 return true;
2265
2266 // TODO: check to see if missing bits are just not demanded.
2267
2268 // Otherwise, this pattern doesn't match.
2269 return false;
2270}
2271
2272/// CheckOrMask - The isel is trying to match something like (or X, 255). If
2273/// the dag combiner simplified the 255, we still want to match. RHS is the
2274/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2275/// specified in the .td file (e.g. 255).
2277 int64_t DesiredMaskS) const {
2278 const APInt &ActualMask = RHS->getAPIntValue();
2279 // TODO: Avoid implicit trunc?
2280 // See https://github.com/llvm/llvm-project/issues/112510.
2281 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2282 /*isSigned=*/false, /*implicitTrunc=*/true);
2283
2284 // If the actual mask exactly matches, success!
2285 if (ActualMask == DesiredMask)
2286 return true;
2287
2288 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2289 if (!ActualMask.isSubsetOf(DesiredMask))
2290 return false;
2291
2292 // Otherwise, the DAG Combiner may have proven that the value coming in is
2293 // either already zero or is not demanded. Check for known zero input bits.
2294 APInt NeededMask = DesiredMask & ~ActualMask;
2295 KnownBits Known = CurDAG->computeKnownBits(LHS);
2296
2297 // If all the missing bits in the or are already known to be set, match!
2298 if (NeededMask.isSubsetOf(Known.One))
2299 return true;
2300
2301 // TODO: check to see if missing bits are just not demanded.
2302
2303 // Otherwise, this pattern doesn't match.
2304 return false;
2305}
2306
2307/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2308/// by tblgen. Others should not call it.
2310 const SDLoc &DL) {
2311 // Change the vector of SDValue into a list of SDNodeHandle for x86 might call
2312 // replaceAllUses when matching address.
2313
2314 std::list<HandleSDNode> Handles;
2315
2316 Handles.emplace_back(Ops[InlineAsm::Op_InputChain]); // 0
2317 Handles.emplace_back(Ops[InlineAsm::Op_AsmString]); // 1
2318 Handles.emplace_back(Ops[InlineAsm::Op_MDNode]); // 2, !srcloc
2319 Handles.emplace_back(
2320 Ops[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2321
2322 unsigned i = InlineAsm::Op_FirstOperand, e = Ops.size();
2323 if (Ops[e - 1].getValueType() == MVT::Glue)
2324 --e; // Don't process a glue operand if it is here.
2325
2326 while (i != e) {
2327 InlineAsm::Flag Flags(Ops[i]->getAsZExtVal());
2328 if (!Flags.isMemKind() && !Flags.isFuncKind()) {
2329 // Just skip over this operand, copying the operands verbatim.
2330 Handles.insert(Handles.end(), Ops.begin() + i,
2331 Ops.begin() + i + Flags.getNumOperandRegisters() + 1);
2332 i += Flags.getNumOperandRegisters() + 1;
2333 } else {
2334 assert(Flags.getNumOperandRegisters() == 1 &&
2335 "Memory operand with multiple values?");
2336
2337 unsigned TiedToOperand;
2338 if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
2339 // We need the constraint ID from the operand this is tied to.
2340 unsigned CurOp = InlineAsm::Op_FirstOperand;
2341 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2342 for (; TiedToOperand; --TiedToOperand) {
2343 CurOp += Flags.getNumOperandRegisters() + 1;
2344 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2345 }
2346 }
2347
2348 // Otherwise, this is a memory operand. Ask the target to select it.
2349 std::vector<SDValue> SelOps;
2350 const InlineAsm::ConstraintCode ConstraintID =
2351 Flags.getMemoryConstraintID();
2352 if (SelectInlineAsmMemoryOperand(Ops[i + 1], ConstraintID, SelOps))
2353 report_fatal_error("Could not match memory address. Inline asm"
2354 " failure!");
2355
2356 // Add this to the output node.
2357 Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
2359 SelOps.size());
2360 Flags.setMemConstraint(ConstraintID);
2361 Handles.emplace_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
2362 llvm::append_range(Handles, SelOps);
2363 i += 2;
2364 }
2365 }
2366
2367 // Add the glue input back if present.
2368 if (e != Ops.size())
2369 Handles.emplace_back(Ops.back());
2370
2371 Ops.clear();
2372 for (auto &handle : Handles)
2373 Ops.push_back(handle.getValue());
2374}
2375
2376/// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2377/// beyond "ImmedUse". We may ignore chains as they are checked separately.
2378static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2379 bool IgnoreChains) {
2382 // Only check if we have non-immediate uses of Def.
2383 if (ImmedUse->isOnlyUserOf(Def))
2384 return false;
2385
2386 // We don't care about paths to Def that go through ImmedUse so mark it
2387 // visited and mark non-def operands as used.
2388 Visited.insert(ImmedUse);
2389 for (const SDValue &Op : ImmedUse->op_values()) {
2390 SDNode *N = Op.getNode();
2391 // Ignore chain deps (they are validated by
2392 // HandleMergeInputChains) and immediate uses
2393 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2394 continue;
2395 if (!Visited.insert(N).second)
2396 continue;
2397 WorkList.push_back(N);
2398 }
2399
2400 // Initialize worklist to operands of Root.
2401 if (Root != ImmedUse) {
2402 for (const SDValue &Op : Root->op_values()) {
2403 SDNode *N = Op.getNode();
2404 // Ignore chains (they are validated by HandleMergeInputChains)
2405 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2406 continue;
2407 if (!Visited.insert(N).second)
2408 continue;
2409 WorkList.push_back(N);
2410 }
2411 }
2412
2413 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2414}
2415
2416/// IsProfitableToFold - Returns true if it's profitable to fold the specific
2417/// operand node N of U during instruction selection that starts at Root.
2419 SDNode *Root) const {
2421 return false;
2422 return N.hasOneUse();
2423}
2424
2425/// IsLegalToFold - Returns true if the specific operand node N of
2426/// U can be folded during instruction selection that starts at Root.
2429 bool IgnoreChains) {
2431 return false;
2432
2433 // If Root use can somehow reach N through a path that doesn't contain
2434 // U then folding N would create a cycle. e.g. In the following
2435 // diagram, Root can reach N through X. If N is folded into Root, then
2436 // X is both a predecessor and a successor of U.
2437 //
2438 // [N*] //
2439 // ^ ^ //
2440 // / \ //
2441 // [U*] [X]? //
2442 // ^ ^ //
2443 // \ / //
2444 // \ / //
2445 // [Root*] //
2446 //
2447 // * indicates nodes to be folded together.
2448 //
2449 // If Root produces glue, then it gets (even more) interesting. Since it
2450 // will be "glued" together with its glue use in the scheduler, we need to
2451 // check if it might reach N.
2452 //
2453 // [N*] //
2454 // ^ ^ //
2455 // / \ //
2456 // [U*] [X]? //
2457 // ^ ^ //
2458 // \ \ //
2459 // \ | //
2460 // [Root*] | //
2461 // ^ | //
2462 // f | //
2463 // | / //
2464 // [Y] / //
2465 // ^ / //
2466 // f / //
2467 // | / //
2468 // [GU] //
2469 //
2470 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2471 // (call it Fold), then X is a predecessor of GU and a successor of
2472 // Fold. But since Fold and GU are glued together, this will create
2473 // a cycle in the scheduling graph.
2474
2475 // If the node has glue, walk down the graph to the "lowest" node in the
2476 // glued set.
2477 EVT VT = Root->getValueType(Root->getNumValues()-1);
2478 while (VT == MVT::Glue) {
2479 SDNode *GU = Root->getGluedUser();
2480 if (!GU)
2481 break;
2482 Root = GU;
2483 VT = Root->getValueType(Root->getNumValues()-1);
2484
2485 // If our query node has a glue result with a use, we've walked up it. If
2486 // the user (which has already been selected) has a chain or indirectly uses
2487 // the chain, HandleMergeInputChains will not consider it. Because of
2488 // this, we cannot ignore chains in this predicate.
2489 IgnoreChains = false;
2490 }
2491
2492 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2493}
2494
2495void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2496 SDLoc DL(N);
2497
2498 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2500
2501 const EVT VTs[] = {MVT::Other, MVT::Glue};
2502 SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2503 New->setNodeId(-1);
2504 ReplaceUses(N, New.getNode());
2506}
2507
2508void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2509 SDLoc dl(Op);
2510 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2511 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2512
2513 EVT VT = Op->getValueType(0);
2514 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2515
2516 const MachineFunction &MF = CurDAG->getMachineFunction();
2517 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, MF);
2518
2519 SDValue New;
2520 if (!Reg) {
2521 const Function &Fn = MF.getFunction();
2522 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
2523 "invalid register \"" + Twine(RegStr->getString().data()) +
2524 "\" for llvm.read_register",
2525 Fn, Op->getDebugLoc()));
2526 New =
2527 SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0);
2528 ReplaceUses(SDValue(Op, 1), Op->getOperand(0));
2529 } else {
2530 New =
2531 CurDAG->getCopyFromReg(Op->getOperand(0), dl, Reg, Op->getValueType(0));
2532 }
2533
2534 New->setNodeId(-1);
2535 ReplaceUses(Op, New.getNode());
2536 CurDAG->RemoveDeadNode(Op);
2537}
2538
2539void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2540 SDLoc dl(Op);
2541 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2542 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2543
2544 EVT VT = Op->getOperand(2).getValueType();
2545 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2546
2547 const MachineFunction &MF = CurDAG->getMachineFunction();
2548 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, MF);
2549
2550 if (!Reg) {
2551 const Function &Fn = MF.getFunction();
2552 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
2553 "invalid register \"" + Twine(RegStr->getString().data()) +
2554 "\" for llvm.write_register",
2555 Fn, Op->getDebugLoc()));
2556 ReplaceUses(SDValue(Op, 0), Op->getOperand(0));
2557 } else {
2558 SDValue New =
2559 CurDAG->getCopyToReg(Op->getOperand(0), dl, Reg, Op->getOperand(2));
2560 New->setNodeId(-1);
2561 ReplaceUses(Op, New.getNode());
2562 }
2563
2564 CurDAG->RemoveDeadNode(Op);
2565}
2566
2567void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2568 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2569}
2570
2571// Use the generic target FAKE_USE target opcode. The chain operand
2572// must come last, because InstrEmitter::AddOperand() requires it.
2573void SelectionDAGISel::Select_FAKE_USE(SDNode *N) {
2574 CurDAG->SelectNodeTo(N, TargetOpcode::FAKE_USE, N->getValueType(0),
2575 N->getOperand(1), N->getOperand(0));
2576}
2577
2578void SelectionDAGISel::Select_RELOC_NONE(SDNode *N) {
2579 CurDAG->SelectNodeTo(N, TargetOpcode::RELOC_NONE, N->getValueType(0),
2580 N->getOperand(1), N->getOperand(0));
2581}
2582
2583void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2584 // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2585 // If FREEZE instruction is added later, the code below must be changed as
2586 // well.
2587 CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2588 N->getOperand(0));
2589}
2590
2591void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2592 CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2593 N->getOperand(0));
2594}
2595
2596void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2597 CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2598 N->getOperand(0));
2599}
2600
2601void SelectionDAGISel::Select_CONVERGENCECTRL_ANCHOR(SDNode *N) {
2602 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ANCHOR,
2603 N->getValueType(0));
2604}
2605
2606void SelectionDAGISel::Select_CONVERGENCECTRL_ENTRY(SDNode *N) {
2607 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ENTRY,
2608 N->getValueType(0));
2609}
2610
2611void SelectionDAGISel::Select_CONVERGENCECTRL_LOOP(SDNode *N) {
2612 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_LOOP,
2613 N->getValueType(0), N->getOperand(0));
2614}
2615
2616void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2617 SDValue OpVal, SDLoc DL) {
2618 SDNode *OpNode = OpVal.getNode();
2619
2620 // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2621 // nodes at DAG-construction time.
2622 assert(OpNode->getOpcode() != ISD::FrameIndex);
2623
2624 if (OpNode->getOpcode() == ISD::Constant) {
2625 Ops.push_back(
2626 CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
2627 Ops.push_back(CurDAG->getTargetConstant(OpNode->getAsZExtVal(), DL,
2628 OpVal.getValueType()));
2629 } else {
2630 Ops.push_back(OpVal);
2631 }
2632}
2633
2634void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2636 auto *It = N->op_begin();
2637 SDLoc DL(N);
2638
2639 // Stash the chain and glue operands so we can move them to the end.
2640 SDValue Chain = *It++;
2641 SDValue InGlue = *It++;
2642
2643 // <id> operand.
2644 SDValue ID = *It++;
2645 assert(ID.getValueType() == MVT::i64);
2646 Ops.push_back(ID);
2647
2648 // <numShadowBytes> operand.
2649 SDValue Shad = *It++;
2650 assert(Shad.getValueType() == MVT::i32);
2651 Ops.push_back(Shad);
2652
2653 // Live variable operands.
2654 for (; It != N->op_end(); It++)
2655 pushStackMapLiveVariable(Ops, *It, DL);
2656
2657 Ops.push_back(Chain);
2658 Ops.push_back(InGlue);
2659
2660 SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2661 CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2662}
2663
2664void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2666 auto *It = N->op_begin();
2667 SDLoc DL(N);
2668
2669 // Cache arguments that will be moved to the end in the target node.
2670 SDValue Chain = *It++;
2671 std::optional<SDValue> Glue;
2672 if (It->getValueType() == MVT::Glue)
2673 Glue = *It++;
2674 SDValue RegMask = *It++;
2675
2676 // <id> operand.
2677 SDValue ID = *It++;
2678 assert(ID.getValueType() == MVT::i64);
2679 Ops.push_back(ID);
2680
2681 // <numShadowBytes> operand.
2682 SDValue Shad = *It++;
2683 assert(Shad.getValueType() == MVT::i32);
2684 Ops.push_back(Shad);
2685
2686 // Add the callee.
2687 Ops.push_back(*It++);
2688
2689 // Add <numArgs>.
2690 SDValue NumArgs = *It++;
2691 assert(NumArgs.getValueType() == MVT::i32);
2692 Ops.push_back(NumArgs);
2693
2694 // Calling convention.
2695 Ops.push_back(*It++);
2696
2697 // Push the args for the call.
2698 for (uint64_t I = NumArgs->getAsZExtVal(); I != 0; I--)
2699 Ops.push_back(*It++);
2700
2701 // Now push the live variables.
2702 for (; It != N->op_end(); It++)
2703 pushStackMapLiveVariable(Ops, *It, DL);
2704
2705 // Finally, the regmask, chain and (if present) glue are moved to the end.
2706 Ops.push_back(RegMask);
2707 Ops.push_back(Chain);
2708 if (Glue.has_value())
2709 Ops.push_back(*Glue);
2710
2711 SDVTList NodeTys = N->getVTList();
2712 CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2713}
2714
2715/// GetVBR - decode a vbr encoding whose top bit is set.
2717GetVBR(uint64_t Val, const uint8_t *MatcherTable, size_t &Idx) {
2718 assert(Val >= 128 && "Not a VBR");
2719 Val &= 127; // Remove first vbr bit.
2720
2721 unsigned Shift = 7;
2722 uint64_t NextBits;
2723 do {
2724 NextBits = MatcherTable[Idx++];
2725 Val |= (NextBits&127) << Shift;
2726 Shift += 7;
2727 } while (NextBits & 128);
2728
2729 return Val;
2730}
2731
2732LLVM_ATTRIBUTE_ALWAYS_INLINE static int64_t
2733GetSignedVBR(const unsigned char *MatcherTable, size_t &Idx) {
2734 int64_t Val = 0;
2735 unsigned Shift = 0;
2736 uint64_t NextBits;
2737 do {
2738 NextBits = MatcherTable[Idx++];
2739 Val |= (NextBits & 127) << Shift;
2740 Shift += 7;
2741 } while (NextBits & 128);
2742
2743 if (Shift < 64 && (NextBits & 0x40))
2744 Val |= UINT64_MAX << Shift;
2745
2746 return Val;
2747}
2748
2749/// getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value,
2750/// use GetVBR to decode it.
2752getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex) {
2753 unsigned SimpleVT = MatcherTable[MatcherIndex++];
2754 if (SimpleVT & 128)
2755 SimpleVT = GetVBR(SimpleVT, MatcherTable, MatcherIndex);
2756
2757 return static_cast<MVT::SimpleValueType>(SimpleVT);
2758}
2759
2760/// Decode a HwMode VT in MatcherTable by calling getValueTypeForHwMode.
2762getHwModeVT(const uint8_t *MatcherTable, size_t &MatcherIndex,
2763 const SelectionDAGISel &SDISel) {
2764 unsigned Index = MatcherTable[MatcherIndex++];
2765 return SDISel.getValueTypeForHwMode(Index);
2766}
2767
2768void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
2769 SDLoc dl(N);
2770 CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
2771 CurDAG->getTargetConstant(N->getConstantOperandVal(1),
2772 dl, MVT::i64, true));
2773}
2774
2775/// When a match is complete, this method updates uses of interior chain results
2776/// to use the new results.
2777void SelectionDAGISel::UpdateChains(
2778 SDNode *NodeToMatch, SDValue InputChain,
2779 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2780 SmallVector<SDNode*, 4> NowDeadNodes;
2781
2782 // Now that all the normal results are replaced, we replace the chain and
2783 // glue results if present.
2784 if (!ChainNodesMatched.empty()) {
2785 assert(InputChain.getNode() &&
2786 "Matched input chains but didn't produce a chain");
2787 // Loop over all of the nodes we matched that produced a chain result.
2788 // Replace all the chain results with the final chain we ended up with.
2789 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2790 SDNode *ChainNode = ChainNodesMatched[i];
2791 // If ChainNode is null, it's because we replaced it on a previous
2792 // iteration and we cleared it out of the map. Just skip it.
2793 if (!ChainNode)
2794 continue;
2795
2796 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2797 "Deleted node left in chain");
2798
2799 // Don't replace the results of the root node if we're doing a
2800 // MorphNodeTo.
2801 if (ChainNode == NodeToMatch && isMorphNodeTo)
2802 continue;
2803
2804 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2805 if (ChainVal.getValueType() == MVT::Glue)
2806 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2807 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2808 SelectionDAG::DAGNodeDeletedListener NDL(
2809 *CurDAG, [&](SDNode *N, SDNode *E) {
2810 llvm::replace(ChainNodesMatched, N, static_cast<SDNode *>(nullptr));
2811 });
2812 if (ChainNode->getOpcode() != ISD::TokenFactor)
2813 ReplaceUses(ChainVal, InputChain);
2814
2815 // If the node became dead and we haven't already seen it, delete it.
2816 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2817 !llvm::is_contained(NowDeadNodes, ChainNode))
2818 NowDeadNodes.push_back(ChainNode);
2819 }
2820 }
2821
2822 if (!NowDeadNodes.empty())
2823 CurDAG->RemoveDeadNodes(NowDeadNodes);
2824
2825 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2826}
2827
2828/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2829/// operation for when the pattern matched at least one node with a chains. The
2830/// input vector contains a list of all of the chained nodes that we match. We
2831/// must determine if this is a valid thing to cover (i.e. matching it won't
2832/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2833/// be used as the input node chain for the generated nodes.
2834static SDValue
2836 SDValue InputGlue, SelectionDAG *CurDAG) {
2837
2840 SmallVector<SDValue, 3> InputChains;
2841 unsigned int Max = 8192;
2842
2843 // Quick exit on trivial merge.
2844 if (ChainNodesMatched.size() == 1)
2845 return ChainNodesMatched[0]->getOperand(0);
2846
2847 // Add chains that aren't already added (internal). Peek through
2848 // token factors.
2849 std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2850 if (V.getValueType() != MVT::Other)
2851 return;
2852 if (V->getOpcode() == ISD::EntryToken)
2853 return;
2854 if (!Visited.insert(V.getNode()).second)
2855 return;
2856 if (V->getOpcode() == ISD::TokenFactor) {
2857 for (const SDValue &Op : V->op_values())
2858 AddChains(Op);
2859 } else
2860 InputChains.push_back(V);
2861 };
2862
2863 for (auto *N : ChainNodesMatched) {
2864 Worklist.push_back(N);
2865 Visited.insert(N);
2866 }
2867
2868 while (!Worklist.empty())
2869 AddChains(Worklist.pop_back_val()->getOperand(0));
2870
2871 // Skip the search if there are no chain dependencies.
2872 if (InputChains.size() == 0)
2873 return CurDAG->getEntryNode();
2874
2875 // If one of these chains is a successor of input, we must have a
2876 // node that is both the predecessor and successor of the
2877 // to-be-merged nodes. Fail.
2878 Visited.clear();
2879 for (SDValue V : InputChains) {
2880 // If we need to create a TokenFactor, and any of the input chain nodes will
2881 // also be glued to the output, we cannot merge the chains. The TokenFactor
2882 // would prevent the glue from being honored.
2883 if (InputChains.size() != 1 &&
2884 V->getValueType(V->getNumValues() - 1) == MVT::Glue &&
2885 InputGlue.getNode() == V.getNode())
2886 return SDValue();
2887 Worklist.push_back(V.getNode());
2888 }
2889
2890 for (auto *N : ChainNodesMatched)
2891 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2892 return SDValue();
2893
2894 // Return merged chain.
2895 if (InputChains.size() == 1)
2896 return InputChains[0];
2897 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2898 MVT::Other, InputChains);
2899}
2900
2901/// MorphNode - Handle morphing a node in place for the selector.
2902SDNode *SelectionDAGISel::
2903MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2904 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2905 // It is possible we're using MorphNodeTo to replace a node with no
2906 // normal results with one that has a normal result (or we could be
2907 // adding a chain) and the input could have glue and chains as well.
2908 // In this case we need to shift the operands down.
2909 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2910 // than the old isel though.
2911 int OldGlueResultNo = -1, OldChainResultNo = -1;
2912
2913 unsigned NTMNumResults = Node->getNumValues();
2914 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2915 OldGlueResultNo = NTMNumResults-1;
2916 if (NTMNumResults != 1 &&
2917 Node->getValueType(NTMNumResults-2) == MVT::Other)
2918 OldChainResultNo = NTMNumResults-2;
2919 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2920 OldChainResultNo = NTMNumResults-1;
2921
2922 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2923 // that this deletes operands of the old node that become dead.
2924 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2925
2926 // MorphNodeTo can operate in two ways: if an existing node with the
2927 // specified operands exists, it can just return it. Otherwise, it
2928 // updates the node in place to have the requested operands.
2929 if (Res == Node) {
2930 // If we updated the node in place, reset the node ID. To the isel,
2931 // this should be just like a newly allocated machine node.
2932 Res->setNodeId(-1);
2933 }
2934
2935 unsigned ResNumResults = Res->getNumValues();
2936 // Move the glue if needed.
2937 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2938 static_cast<unsigned>(OldGlueResultNo) != ResNumResults - 1)
2939 ReplaceUses(SDValue(Node, OldGlueResultNo),
2940 SDValue(Res, ResNumResults - 1));
2941
2942 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2943 --ResNumResults;
2944
2945 // Move the chain reference if needed.
2946 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2947 static_cast<unsigned>(OldChainResultNo) != ResNumResults - 1)
2948 ReplaceUses(SDValue(Node, OldChainResultNo),
2949 SDValue(Res, ResNumResults - 1));
2950
2951 // Otherwise, no replacement happened because the node already exists. Replace
2952 // Uses of the old node with the new one.
2953 if (Res != Node) {
2954 ReplaceNode(Node, Res);
2955 } else {
2957 }
2958
2959 return Res;
2960}
2961
2962/// CheckSame - Implements OP_CheckSame.
2964CheckSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
2965 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2966 // Accept if it is exactly the same as a previously recorded node.
2967 unsigned RecNo = MatcherTable[MatcherIndex++];
2968 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2969 return N == RecordedNodes[RecNo].first;
2970}
2971
2972/// CheckChildSame - Implements OP_CheckChildXSame.
2974 const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
2975 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2976 unsigned ChildNo) {
2977 if (ChildNo >= N.getNumOperands())
2978 return false; // Match fails if out of range child #.
2979 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2980 RecordedNodes);
2981}
2982
2983/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2985CheckPatternPredicate(unsigned Opcode, const uint8_t *MatcherTable,
2986 size_t &MatcherIndex, const SelectionDAGISel &SDISel) {
2987 bool TwoBytePredNo =
2989 unsigned PredNo =
2990 TwoBytePredNo || Opcode == SelectionDAGISel::OPC_CheckPatternPredicate
2991 ? MatcherTable[MatcherIndex++]
2993 if (TwoBytePredNo)
2994 PredNo |= MatcherTable[MatcherIndex++] << 8;
2995 return SDISel.CheckPatternPredicate(PredNo);
2996}
2997
2998/// CheckNodePredicate - Implements OP_CheckNodePredicate.
3000CheckNodePredicate(unsigned Opcode, const uint8_t *MatcherTable,
3001 size_t &MatcherIndex, const SelectionDAGISel &SDISel,
3002 SDValue Op) {
3003 unsigned PredNo = Opcode == SelectionDAGISel::OPC_CheckPredicate
3004 ? MatcherTable[MatcherIndex++]
3006 return SDISel.CheckNodePredicate(Op, PredNo);
3007}
3008
3010CheckOpcode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDNode *N) {
3011 uint16_t Opc = MatcherTable[MatcherIndex++];
3012 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3013 return N->getOpcode() == Opc;
3014}
3015
3017 SDValue N,
3018 const TargetLowering *TLI,
3019 const DataLayout &DL) {
3020 if (N.getValueType() == VT)
3021 return true;
3022
3023 // Handle the case when VT is iPTR.
3024 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
3025}
3026
3029 const DataLayout &DL, unsigned ChildNo) {
3030 if (ChildNo >= N.getNumOperands())
3031 return false; // Match fails if out of range child #.
3032 return ::CheckType(VT, N.getOperand(ChildNo), TLI, DL);
3033}
3034
3036CheckCondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N) {
3037 return cast<CondCodeSDNode>(N)->get() ==
3038 static_cast<ISD::CondCode>(MatcherTable[MatcherIndex++]);
3039}
3040
3042CheckChild2CondCode(const uint8_t *MatcherTable, size_t &MatcherIndex,
3043 SDValue N) {
3044 if (2 >= N.getNumOperands())
3045 return false;
3046 return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
3047}
3048
3050CheckValueType(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3051 const TargetLowering *TLI, const DataLayout &DL) {
3052 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
3053 if (cast<VTSDNode>(N)->getVT() == VT)
3054 return true;
3055
3056 // Handle the case when VT is iPTR.
3057 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
3058}
3059
3061CheckInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N) {
3062 int64_t Val = GetSignedVBR(MatcherTable, MatcherIndex);
3063
3065 return C && C->getAPIntValue().trySExtValue() == Val;
3066}
3067
3069CheckChildInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3070 unsigned ChildNo) {
3071 if (ChildNo >= N.getNumOperands())
3072 return false; // Match fails if out of range child #.
3073 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
3074}
3075
3077CheckAndImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3078 const SelectionDAGISel &SDISel) {
3079 int64_t Val = MatcherTable[MatcherIndex++];
3080 if (Val & 128)
3081 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3082
3083 if (N->getOpcode() != ISD::AND) return false;
3084
3085 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3086 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
3087}
3088
3090CheckOrImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3091 const SelectionDAGISel &SDISel) {
3092 int64_t Val = MatcherTable[MatcherIndex++];
3093 if (Val & 128)
3094 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3095
3096 if (N->getOpcode() != ISD::OR) return false;
3097
3098 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3099 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
3100}
3101
3102/// IsPredicateKnownToFail - If we know how and can do so without pushing a
3103/// scope, evaluate the current node. Returns true if the current predicate is
3104/// known to fail; Index is unspecified in that case. If the current predicate
3105/// is known to pass, returns false and advances Index past it. If the current
3106/// predicate is unknown, returns false and leaves Index at the predicate.
3108 const uint8_t *Table, size_t &Index, SDValue N,
3109 const SelectionDAGISel &SDISel,
3110 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
3111 size_t StartIndex = Index;
3112 unsigned Opcode = Table[Index++];
3113 switch (Opcode) {
3114 default:
3115 Index = StartIndex; // Could not evaluate this predicate.
3116 return false;
3118 return !::CheckSame(Table, Index, N, RecordedNodes);
3123 return !::CheckChildSame(Table, Index, N, RecordedNodes,
3135 return !::CheckPatternPredicate(Opcode, Table, Index, SDISel);
3145 return !::CheckNodePredicate(Opcode, Table, Index, SDISel, N);
3147 return !::CheckOpcode(Table, Index, N.getNode());
3153 MVT VT;
3154 switch (Opcode) {
3156 VT = MVT::i32;
3157 break;
3159 VT = MVT::i64;
3160 break;
3162 VT = getHwModeVT(Table, Index, SDISel);
3163 break;
3165 VT = SDISel.getValueTypeForHwMode(0);
3166 break;
3167 default:
3168 VT = getSimpleVT(Table, Index);
3169 break;
3170 }
3171 return !::CheckType(VT.SimpleTy, N, SDISel.TLI,
3172 SDISel.CurDAG->getDataLayout());
3173 }
3176 unsigned Res = Table[Index++];
3178 ? getHwModeVT(Table, Index, SDISel)
3179 : getSimpleVT(Table, Index);
3180 return !::CheckType(VT.SimpleTy, N.getValue(Res), SDISel.TLI,
3181 SDISel.CurDAG->getDataLayout());
3182 }
3223 MVT VT;
3224 unsigned ChildNo;
3227 VT = MVT::i32;
3229 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3231 VT = MVT::i64;
3233 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeByHwMode &&
3235 VT = getHwModeVT(Table, Index, SDISel);
3239 VT = SDISel.getValueTypeForHwMode(0);
3241 } else {
3242 VT = getSimpleVT(Table, Index);
3243 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3244 }
3245 return !::CheckChildType(VT.SimpleTy, N, SDISel.TLI,
3246 SDISel.CurDAG->getDataLayout(), ChildNo);
3247 }
3249 return !::CheckCondCode(Table, Index, N);
3251 return !::CheckChild2CondCode(Table, Index, N);
3253 return !::CheckValueType(Table, Index, N, SDISel.TLI,
3254 SDISel.CurDAG->getDataLayout());
3256 return !::CheckInteger(Table, Index, N);
3262 return !::CheckChildInteger(
3265 return !::CheckAndImm(Table, Index, N, SDISel);
3267 return !::CheckOrImm(Table, Index, N, SDISel);
3268 }
3269}
3270
3271namespace {
3272
3273struct MatchScope {
3274 /// FailIndex - If this match fails, this is the index to continue with.
3275 unsigned FailIndex;
3276
3277 /// NodeStack - The node stack when the scope was formed.
3278 SmallVector<SDValue, 4> NodeStack;
3279
3280 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
3281 unsigned NumRecordedNodes;
3282
3283 /// NumMatchedMemRefs - The number of matched memref entries.
3284 unsigned NumMatchedMemRefs;
3285
3286 /// InputChain/InputGlue - The current chain/glue
3287 SDValue InputChain, InputGlue;
3288
3289 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
3290 bool HasChainNodesMatched;
3291};
3292
3293/// \A DAG update listener to keep the matching state
3294/// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
3295/// change the DAG while matching. X86 addressing mode matcher is an example
3296/// for this.
3297class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
3298{
3299 SDNode **NodeToMatch;
3300 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
3301 SmallVectorImpl<MatchScope> &MatchScopes;
3302
3303public:
3304 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
3305 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
3306 SmallVectorImpl<MatchScope> &MS)
3307 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
3308 RecordedNodes(RN), MatchScopes(MS) {}
3309
3310 void NodeDeleted(SDNode *N, SDNode *E) override {
3311 // Some early-returns here to avoid the search if we deleted the node or
3312 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
3313 // do, so it's unnecessary to update matching state at that point).
3314 // Neither of these can occur currently because we only install this
3315 // update listener during matching a complex patterns.
3316 if (!E || E->isMachineOpcode())
3317 return;
3318 // Check if NodeToMatch was updated.
3319 if (N == *NodeToMatch)
3320 *NodeToMatch = E;
3321 // Performing linear search here does not matter because we almost never
3322 // run this code. You'd have to have a CSE during complex pattern
3323 // matching.
3324 for (auto &I : RecordedNodes)
3325 if (I.first.getNode() == N)
3326 I.first.setNode(E);
3327
3328 for (auto &I : MatchScopes)
3329 for (auto &J : I.NodeStack)
3330 if (J.getNode() == N)
3331 J.setNode(E);
3332 }
3333};
3334
3335} // end anonymous namespace
3336
3338 const uint8_t *MatcherTable,
3339 unsigned TableSize,
3340 const uint8_t *OperandLists) {
3341 // FIXME: Should these even be selected? Handle these cases in the caller?
3342 switch (NodeToMatch->getOpcode()) {
3343 default:
3344 break;
3345 case ISD::EntryToken: // These nodes remain the same.
3346 case ISD::BasicBlock:
3347 case ISD::Register:
3348 case ISD::RegisterMask:
3349 case ISD::HANDLENODE:
3350 case ISD::MDNODE_SDNODE:
3356 case ISD::MCSymbol:
3361 case ISD::TokenFactor:
3362 case ISD::CopyFromReg:
3363 case ISD::CopyToReg:
3364 case ISD::EH_LABEL:
3367 case ISD::LIFETIME_END:
3368 case ISD::PSEUDO_PROBE:
3370 NodeToMatch->setNodeId(-1); // Mark selected.
3371 return;
3372 case ISD::AssertSext:
3373 case ISD::AssertZext:
3375 case ISD::AssertAlign:
3376 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
3377 CurDAG->RemoveDeadNode(NodeToMatch);
3378 return;
3379 case ISD::INLINEASM:
3380 case ISD::INLINEASM_BR:
3381 Select_INLINEASM(NodeToMatch);
3382 return;
3383 case ISD::READ_REGISTER:
3384 Select_READ_REGISTER(NodeToMatch);
3385 return;
3387 Select_WRITE_REGISTER(NodeToMatch);
3388 return;
3389 case ISD::POISON:
3390 case ISD::UNDEF:
3391 Select_UNDEF(NodeToMatch);
3392 return;
3393 case ISD::FAKE_USE:
3394 Select_FAKE_USE(NodeToMatch);
3395 return;
3396 case ISD::RELOC_NONE:
3397 Select_RELOC_NONE(NodeToMatch);
3398 return;
3399 case ISD::FREEZE:
3400 Select_FREEZE(NodeToMatch);
3401 return;
3402 case ISD::ARITH_FENCE:
3403 Select_ARITH_FENCE(NodeToMatch);
3404 return;
3405 case ISD::MEMBARRIER:
3406 Select_MEMBARRIER(NodeToMatch);
3407 return;
3408 case ISD::STACKMAP:
3409 Select_STACKMAP(NodeToMatch);
3410 return;
3411 case ISD::PATCHPOINT:
3412 Select_PATCHPOINT(NodeToMatch);
3413 return;
3415 Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
3416 return;
3418 Select_CONVERGENCECTRL_ANCHOR(NodeToMatch);
3419 return;
3421 Select_CONVERGENCECTRL_ENTRY(NodeToMatch);
3422 return;
3424 Select_CONVERGENCECTRL_LOOP(NodeToMatch);
3425 return;
3426 }
3427
3428 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
3429
3430 // Set up the node stack with NodeToMatch as the only node on the stack.
3431 SmallVector<SDValue, 8> NodeStack;
3432 SDValue N = SDValue(NodeToMatch, 0);
3433 NodeStack.push_back(N);
3434
3435 // MatchScopes - Scopes used when matching, if a match failure happens, this
3436 // indicates where to continue checking.
3437 SmallVector<MatchScope, 8> MatchScopes;
3438
3439 // RecordedNodes - This is the set of nodes that have been recorded by the
3440 // state machine. The second value is the parent of the node, or null if the
3441 // root is recorded.
3443
3444 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3445 // pattern.
3447
3448 // These are the current input chain and glue for use when generating nodes.
3449 // Various Emit operations change these. For example, emitting a copytoreg
3450 // uses and updates these.
3451 SDValue InputChain, InputGlue, DeactivationSymbol;
3452
3453 // ChainNodesMatched - If a pattern matches nodes that have input/output
3454 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3455 // which ones they are. The result is captured into this list so that we can
3456 // update the chain results when the pattern is complete.
3457 SmallVector<SDNode*, 3> ChainNodesMatched;
3458
3459 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3460
3461 // Determine where to start the interpreter. Normally we start at opcode #0,
3462 // but if the state machine starts with an OPC_SwitchOpcode, then we
3463 // accelerate the first lookup (which is guaranteed to be hot) with the
3464 // OpcodeOffset table.
3465 size_t MatcherIndex = 0;
3466
3467 if (!OpcodeOffset.empty()) {
3468 // Already computed the OpcodeOffset table, just index into it.
3469 if (N.getOpcode() < OpcodeOffset.size())
3470 MatcherIndex = OpcodeOffset[N.getOpcode()];
3471 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
3472
3473 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
3474 // Otherwise, the table isn't computed, but the state machine does start
3475 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3476 // is the first time we're selecting an instruction.
3477 size_t Idx = 1;
3478 while (true) {
3479 // Get the size of this case.
3480 unsigned CaseSize = MatcherTable[Idx++];
3481 if (CaseSize & 128)
3482 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
3483 if (CaseSize == 0) break;
3484
3485 // Get the opcode, add the index to the table.
3486 uint16_t Opc = MatcherTable[Idx++];
3487 Opc |= static_cast<uint16_t>(MatcherTable[Idx++]) << 8;
3488 if (Opc >= OpcodeOffset.size())
3489 OpcodeOffset.resize((Opc+1)*2);
3490 OpcodeOffset[Opc] = Idx;
3491 Idx += CaseSize;
3492 }
3493
3494 // Okay, do the lookup for the first opcode.
3495 if (N.getOpcode() < OpcodeOffset.size())
3496 MatcherIndex = OpcodeOffset[N.getOpcode()];
3497 }
3498
3499 while (true) {
3500 assert(MatcherIndex < TableSize && "Invalid index");
3501#ifndef NDEBUG
3502 size_t CurrentOpcodeIndex = MatcherIndex;
3503#endif
3504 BuiltinOpcodes Opcode =
3505 static_cast<BuiltinOpcodes>(MatcherTable[MatcherIndex++]);
3506 switch (Opcode) {
3507 case OPC_Scope: {
3508 // Okay, the semantics of this operation are that we should push a scope
3509 // then evaluate the first child. However, pushing a scope only to have
3510 // the first check fail (which then pops it) is inefficient. If we can
3511 // determine immediately that the first check (or first several) will
3512 // immediately fail, don't even bother pushing a scope for them.
3513 size_t FailIndex;
3514
3515 while (true) {
3516 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3517 if (NumToSkip & 128)
3518 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3519 // Found the end of the scope with no match.
3520 if (NumToSkip == 0) {
3521 FailIndex = 0;
3522 break;
3523 }
3524
3525 FailIndex = MatcherIndex+NumToSkip;
3526
3527 size_t MatcherIndexOfPredicate = MatcherIndex;
3528 (void)MatcherIndexOfPredicate; // silence warning.
3529
3530 // If we can't evaluate this predicate without pushing a scope (e.g. if
3531 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3532 // push the scope and evaluate the full predicate chain.
3533 if (!IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, *this,
3534 RecordedNodes))
3535 break;
3536
3537 LLVM_DEBUG(
3538 dbgs() << " Skipped scope entry (due to false predicate) at "
3539 << "index " << MatcherIndexOfPredicate << ", continuing at "
3540 << FailIndex << "\n");
3541 ++NumDAGIselRetries;
3542
3543 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3544 // move to the next case.
3545 MatcherIndex = FailIndex;
3546 }
3547
3548 // If the whole scope failed to match, bail.
3549 if (FailIndex == 0) break;
3550
3551 // Push a MatchScope which indicates where to go if the first child fails
3552 // to match.
3553 MatchScope &NewEntry = MatchScopes.emplace_back();
3554 NewEntry.FailIndex = FailIndex;
3555 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3556 NewEntry.NumRecordedNodes = RecordedNodes.size();
3557 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3558 NewEntry.InputChain = InputChain;
3559 NewEntry.InputGlue = InputGlue;
3560 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3561 continue;
3562 }
3563 case OPC_RecordNode: {
3564 // Remember this node, it may end up being an operand in the pattern.
3565 SDNode *Parent = nullptr;
3566 if (NodeStack.size() > 1)
3567 Parent = NodeStack[NodeStack.size()-2].getNode();
3568 RecordedNodes.emplace_back(N, Parent);
3569 continue;
3570 }
3571
3576 unsigned ChildNo = Opcode-OPC_RecordChild0;
3577 if (ChildNo >= N.getNumOperands())
3578 break; // Match fails if out of range child #.
3579
3580 RecordedNodes.emplace_back(N->getOperand(ChildNo), N.getNode());
3581 continue;
3582 }
3583 case OPC_RecordMemRef:
3584 if (auto *MN = dyn_cast<MemSDNode>(N))
3585 llvm::append_range(MatchedMemRefs, MN->memoperands());
3586 else {
3587 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3588 dbgs() << '\n');
3589 }
3590
3591 continue;
3592
3594 // If the current node has an input glue, capture it in InputGlue.
3595 if (N->getNumOperands() != 0 &&
3596 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3597 InputGlue = N->getOperand(N->getNumOperands()-1);
3598 continue;
3599
3601 // If the current node has a deactivation symbol, capture it in
3602 // DeactivationSymbol.
3603 if (N->getNumOperands() != 0 &&
3604 N->getOperand(N->getNumOperands() - 1).getOpcode() ==
3606 DeactivationSymbol = N->getOperand(N->getNumOperands() - 1);
3607 continue;
3608
3609 case OPC_MoveChild: {
3610 unsigned ChildNo = MatcherTable[MatcherIndex++];
3611 if (ChildNo >= N.getNumOperands())
3612 break; // Match fails if out of range child #.
3613 N = N.getOperand(ChildNo);
3614 NodeStack.push_back(N);
3615 continue;
3616 }
3617
3618 case OPC_MoveChild0: case OPC_MoveChild1:
3619 case OPC_MoveChild2: case OPC_MoveChild3:
3620 case OPC_MoveChild4: case OPC_MoveChild5:
3621 case OPC_MoveChild6: case OPC_MoveChild7: {
3622 unsigned ChildNo = Opcode-OPC_MoveChild0;
3623 if (ChildNo >= N.getNumOperands())
3624 break; // Match fails if out of range child #.
3625 N = N.getOperand(ChildNo);
3626 NodeStack.push_back(N);
3627 continue;
3628 }
3629
3630 case OPC_MoveSibling:
3631 case OPC_MoveSibling0:
3632 case OPC_MoveSibling1:
3633 case OPC_MoveSibling2:
3634 case OPC_MoveSibling3:
3635 case OPC_MoveSibling4:
3636 case OPC_MoveSibling5:
3637 case OPC_MoveSibling6:
3638 case OPC_MoveSibling7: {
3639 // Pop the current node off the NodeStack.
3640 NodeStack.pop_back();
3641 assert(!NodeStack.empty() && "Node stack imbalance!");
3642 N = NodeStack.back();
3643
3644 unsigned SiblingNo = Opcode == OPC_MoveSibling
3645 ? MatcherTable[MatcherIndex++]
3646 : Opcode - OPC_MoveSibling0;
3647 if (SiblingNo >= N.getNumOperands())
3648 break; // Match fails if out of range sibling #.
3649 N = N.getOperand(SiblingNo);
3650 NodeStack.push_back(N);
3651 continue;
3652 }
3653 case OPC_MoveParent:
3654 // Pop the current node off the NodeStack.
3655 NodeStack.pop_back();
3656 assert(!NodeStack.empty() && "Node stack imbalance!");
3657 N = NodeStack.back();
3658 continue;
3659
3660 case OPC_CheckSame:
3661 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3662 continue;
3663
3666 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3667 Opcode-OPC_CheckChild0Same))
3668 break;
3669 continue;
3670
3681 if (!::CheckPatternPredicate(Opcode, MatcherTable, MatcherIndex, *this))
3682 break;
3683 continue;
3692 case OPC_CheckPredicate:
3693 if (!::CheckNodePredicate(Opcode, MatcherTable, MatcherIndex, *this, N))
3694 break;
3695 continue;
3697 unsigned OpNum = MatcherTable[MatcherIndex++];
3699
3700 for (unsigned i = 0; i < OpNum; ++i)
3701 Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3702
3703 unsigned PredNo = MatcherTable[MatcherIndex++];
3705 break;
3706 continue;
3707 }
3716 case OPC_CheckComplexPat7: {
3717 unsigned CPNum = Opcode == OPC_CheckComplexPat
3718 ? MatcherTable[MatcherIndex++]
3719 : Opcode - OPC_CheckComplexPat0;
3720 unsigned RecNo = MatcherTable[MatcherIndex++];
3721 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3722
3723 // If target can modify DAG during matching, keep the matching state
3724 // consistent.
3725 std::unique_ptr<MatchStateUpdater> MSU;
3727 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3728 MatchScopes));
3729
3730 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3731 RecordedNodes[RecNo].first, CPNum,
3732 RecordedNodes))
3733 break;
3734 continue;
3735 }
3736 case OPC_CheckOpcode:
3737 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3738 continue;
3739
3740 case OPC_CheckType:
3741 case OPC_CheckTypeI32:
3742 case OPC_CheckTypeI64:
3745 MVT VT;
3746 switch (Opcode) {
3747 case OPC_CheckTypeI32:
3748 VT = MVT::i32;
3749 break;
3750 case OPC_CheckTypeI64:
3751 VT = MVT::i64;
3752 break;
3754 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
3755 break;
3757 VT = getValueTypeForHwMode(0);
3758 break;
3759 default:
3760 VT = getSimpleVT(MatcherTable, MatcherIndex);
3761 break;
3762 }
3763 if (!::CheckType(VT.SimpleTy, N, TLI, CurDAG->getDataLayout()))
3764 break;
3765 continue;
3766 }
3767
3768 case OPC_CheckTypeRes:
3770 unsigned Res = MatcherTable[MatcherIndex++];
3771 MVT VT = Opcode == OPC_CheckTypeResByHwMode
3772 ? getHwModeVT(MatcherTable, MatcherIndex, *this)
3773 : getSimpleVT(MatcherTable, MatcherIndex);
3774 if (!::CheckType(VT.SimpleTy, N.getValue(Res), TLI,
3775 CurDAG->getDataLayout()))
3776 break;
3777 continue;
3778 }
3779
3780 case OPC_SwitchOpcode: {
3781 unsigned CurNodeOpcode = N.getOpcode();
3782 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3783 unsigned CaseSize;
3784 while (true) {
3785 // Get the size of this case.
3786 CaseSize = MatcherTable[MatcherIndex++];
3787 if (CaseSize & 128)
3788 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3789 if (CaseSize == 0) break;
3790
3791 uint16_t Opc = MatcherTable[MatcherIndex++];
3792 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3793
3794 // If the opcode matches, then we will execute this case.
3795 if (CurNodeOpcode == Opc)
3796 break;
3797
3798 // Otherwise, skip over this case.
3799 MatcherIndex += CaseSize;
3800 }
3801
3802 // If no cases matched, bail out.
3803 if (CaseSize == 0) break;
3804
3805 // Otherwise, execute the case we found.
3806 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3807 << MatcherIndex << "\n");
3808 continue;
3809 }
3810
3811 case OPC_SwitchType: {
3812 MVT CurNodeVT = N.getSimpleValueType();
3813 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3814 unsigned CaseSize;
3815 while (true) {
3816 // Get the size of this case.
3817 CaseSize = MatcherTable[MatcherIndex++];
3818 if (CaseSize & 128)
3819 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3820 if (CaseSize == 0) break;
3821
3822 MVT CaseVT = getSimpleVT(MatcherTable, MatcherIndex);
3823 if (CaseVT == MVT::iPTR)
3824 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3825
3826 // If the VT matches, then we will execute this case.
3827 if (CurNodeVT == CaseVT)
3828 break;
3829
3830 // Otherwise, skip over this case.
3831 MatcherIndex += CaseSize;
3832 }
3833
3834 // If no cases matched, bail out.
3835 if (CaseSize == 0) break;
3836
3837 // Otherwise, execute the case we found.
3838 LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
3839 << "] from " << SwitchStart << " to " << MatcherIndex
3840 << '\n');
3841 continue;
3842 }
3868 unsigned ChildNo;
3871 VT = MVT::i32;
3873 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3875 VT = MVT::i64;
3877 } else {
3878 VT = getSimpleVT(MatcherTable, MatcherIndex);
3879 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3880 }
3881 if (!::CheckChildType(VT, N, TLI, CurDAG->getDataLayout(), ChildNo))
3882 break;
3883 continue;
3884 }
3901 MVT VT;
3902 unsigned ChildNo;
3903 if (Opcode >= OPC_CheckChild0TypeByHwMode0 &&
3904 Opcode <= OPC_CheckChild7TypeByHwMode0) {
3905 VT = getValueTypeForHwMode(0);
3906 ChildNo = Opcode - OPC_CheckChild0TypeByHwMode0;
3907 } else {
3908 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
3909 ChildNo = Opcode - OPC_CheckChild0TypeByHwMode;
3910 }
3911 if (!::CheckChildType(VT.SimpleTy, N, TLI, CurDAG->getDataLayout(),
3912 ChildNo))
3913 break;
3914 continue;
3915 }
3916 case OPC_CheckCondCode:
3917 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3918 continue;
3920 if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3921 continue;
3922 case OPC_CheckValueType:
3923 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3924 CurDAG->getDataLayout()))
3925 break;
3926 continue;
3927 case OPC_CheckInteger:
3928 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3929 continue;
3933 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3934 Opcode-OPC_CheckChild0Integer)) break;
3935 continue;
3936 case OPC_CheckAndImm:
3937 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3938 continue;
3939 case OPC_CheckOrImm:
3940 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3941 continue;
3943 if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3944 break;
3945 continue;
3947 if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3948 break;
3949 continue;
3950 case OPC_CheckUndef:
3951 if (!N.isUndef())
3952 break;
3953 continue;
3954
3956 assert(NodeStack.size() != 1 && "No parent node");
3957 // Verify that all intermediate nodes between the root and this one have
3958 // a single use (ignoring chains, which are handled in UpdateChains).
3959 bool HasMultipleUses = false;
3960 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3961 unsigned NNonChainUses = 0;
3962 SDNode *NS = NodeStack[i].getNode();
3963 for (const SDUse &U : NS->uses())
3964 if (U.getValueType() != MVT::Other)
3965 if (++NNonChainUses > 1) {
3966 HasMultipleUses = true;
3967 break;
3968 }
3969 if (HasMultipleUses) break;
3970 }
3971 if (HasMultipleUses) break;
3972
3973 // Check to see that the target thinks this is profitable to fold and that
3974 // we can fold it without inducing cycles in the graph.
3975 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3976 NodeToMatch) ||
3977 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3978 NodeToMatch, OptLevel,
3979 true/*We validate our own chains*/))
3980 break;
3981
3982 continue;
3983 }
3984 case OPC_EmitInteger:
3985 case OPC_EmitIntegerI8:
3986 case OPC_EmitIntegerI16:
3987 case OPC_EmitIntegerI32:
3988 case OPC_EmitIntegerI64:
3991 MVT VT;
3992 switch (Opcode) {
3993 case OPC_EmitIntegerI8:
3994 VT = MVT::i8;
3995 break;
3996 case OPC_EmitIntegerI16:
3997 VT = MVT::i16;
3998 break;
3999 case OPC_EmitIntegerI32:
4000 VT = MVT::i32;
4001 break;
4002 case OPC_EmitIntegerI64:
4003 VT = MVT::i64;
4004 break;
4006 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4007 break;
4009 VT = getValueTypeForHwMode(0);
4010 break;
4011 default:
4012 VT = getSimpleVT(MatcherTable, MatcherIndex);
4013 break;
4014 }
4015 int64_t Val = GetSignedVBR(MatcherTable, MatcherIndex);
4016 Val = SignExtend64(Val, MVT(VT).getFixedSizeInBits());
4017 RecordedNodes.emplace_back(
4018 CurDAG->getSignedConstant(Val, SDLoc(NodeToMatch), VT.SimpleTy,
4019 /*isTarget=*/true),
4020 nullptr);
4021 continue;
4022 }
4023
4024 case OPC_EmitRegister:
4028 MVT VT;
4029 switch (Opcode) {
4031 VT = MVT::i32;
4032 break;
4034 VT = MVT::i64;
4035 break;
4037 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4038 break;
4039 default:
4040 VT = getSimpleVT(MatcherTable, MatcherIndex);
4041 break;
4042 }
4043 unsigned RegNo = MatcherTable[MatcherIndex++];
4044 RecordedNodes.emplace_back(CurDAG->getRegister(RegNo, VT), nullptr);
4045 continue;
4046 }
4047 case OPC_EmitRegister2:
4049 // For targets w/ more than 256 register names, the register enum
4050 // values are stored in two bytes in the matcher table (just like
4051 // opcodes).
4052 MVT VT = Opcode == OPC_EmitRegisterByHwMode2
4053 ? getHwModeVT(MatcherTable, MatcherIndex, *this)
4054 : getSimpleVT(MatcherTable, MatcherIndex);
4055 unsigned RegNo = MatcherTable[MatcherIndex++];
4056 RegNo |= MatcherTable[MatcherIndex++] << 8;
4057 RecordedNodes.emplace_back(CurDAG->getRegister(RegNo, VT), nullptr);
4058 continue;
4059 }
4060
4070 // Convert from IMM/FPIMM to target version.
4071 unsigned RecNo = Opcode == OPC_EmitConvertToTarget
4072 ? MatcherTable[MatcherIndex++]
4073 : Opcode - OPC_EmitConvertToTarget0;
4074 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
4075 SDValue Imm = RecordedNodes[RecNo].first;
4076
4077 if (Imm->getOpcode() == ISD::Constant) {
4078 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
4079 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
4080 Imm.getValueType());
4081 } else if (Imm->getOpcode() == ISD::ConstantFP) {
4082 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
4083 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
4084 Imm.getValueType());
4085 }
4086
4087 RecordedNodes.emplace_back(Imm, RecordedNodes[RecNo].second);
4088 continue;
4089 }
4090
4091 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
4092 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
4093 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
4094 // These are space-optimized forms of OPC_EmitMergeInputChains.
4095 assert(!InputChain.getNode() &&
4096 "EmitMergeInputChains should be the first chain producing node");
4097 assert(ChainNodesMatched.empty() &&
4098 "Should only have one EmitMergeInputChains per match");
4099
4100 // Read all of the chained nodes.
4101 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
4102 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
4103 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
4104
4105 // If the chained node is not the root, we can't fold it if it has
4106 // multiple uses.
4107 // FIXME: What if other value results of the node have uses not matched
4108 // by this pattern?
4109 if (ChainNodesMatched.back() != NodeToMatch &&
4110 !RecordedNodes[RecNo].first.hasOneUse()) {
4111 ChainNodesMatched.clear();
4112 break;
4113 }
4114
4115 // Merge the input chains if they are not intra-pattern references.
4116 InputChain = HandleMergeInputChains(ChainNodesMatched, InputGlue, CurDAG);
4117
4118 if (!InputChain.getNode())
4119 break; // Failed to merge.
4120 continue;
4121 }
4122
4124 assert(!InputChain.getNode() &&
4125 "EmitMergeInputChains should be the first chain producing node");
4126 // This node gets a list of nodes we matched in the input that have
4127 // chains. We want to token factor all of the input chains to these nodes
4128 // together. However, if any of the input chains is actually one of the
4129 // nodes matched in this pattern, then we have an intra-match reference.
4130 // Ignore these because the newly token factored chain should not refer to
4131 // the old nodes.
4132 unsigned NumChains = MatcherTable[MatcherIndex++];
4133 assert(NumChains != 0 && "Can't TF zero chains");
4134
4135 assert(ChainNodesMatched.empty() &&
4136 "Should only have one EmitMergeInputChains per match");
4137
4138 // Read all of the chained nodes.
4139 for (unsigned i = 0; i != NumChains; ++i) {
4140 unsigned RecNo = MatcherTable[MatcherIndex++];
4141 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
4142 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
4143
4144 // If the chained node is not the root, we can't fold it if it has
4145 // multiple uses.
4146 // FIXME: What if other value results of the node have uses not matched
4147 // by this pattern?
4148 if (ChainNodesMatched.back() != NodeToMatch &&
4149 !RecordedNodes[RecNo].first.hasOneUse()) {
4150 ChainNodesMatched.clear();
4151 break;
4152 }
4153 }
4154
4155 // If the inner loop broke out, the match fails.
4156 if (ChainNodesMatched.empty())
4157 break;
4158
4159 // Merge the input chains if they are not intra-pattern references.
4160 InputChain = HandleMergeInputChains(ChainNodesMatched, InputGlue, CurDAG);
4161
4162 if (!InputChain.getNode())
4163 break; // Failed to merge.
4164
4165 continue;
4166 }
4167
4168 case OPC_EmitCopyToReg:
4169 case OPC_EmitCopyToReg0:
4170 case OPC_EmitCopyToReg1:
4171 case OPC_EmitCopyToReg2:
4172 case OPC_EmitCopyToReg3:
4173 case OPC_EmitCopyToReg4:
4174 case OPC_EmitCopyToReg5:
4175 case OPC_EmitCopyToReg6:
4176 case OPC_EmitCopyToReg7:
4178 unsigned RecNo =
4179 Opcode >= OPC_EmitCopyToReg0 && Opcode <= OPC_EmitCopyToReg7
4180 ? Opcode - OPC_EmitCopyToReg0
4181 : MatcherTable[MatcherIndex++];
4182 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
4183 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
4184 if (Opcode == OPC_EmitCopyToRegTwoByte)
4185 DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
4186
4187 if (!InputChain.getNode())
4188 InputChain = CurDAG->getEntryNode();
4189
4190 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
4191 DestPhysReg, RecordedNodes[RecNo].first,
4192 InputGlue);
4193
4194 InputGlue = InputChain.getValue(1);
4195 continue;
4196 }
4197
4198 case OPC_EmitNodeXForm: {
4199 unsigned XFormNo = MatcherTable[MatcherIndex++];
4200 unsigned RecNo = MatcherTable[MatcherIndex++];
4201 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
4202 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
4203 RecordedNodes.emplace_back(Res, nullptr);
4204 continue;
4205 }
4206 case OPC_Coverage: {
4207 // This is emitted right before MorphNode/EmitNode.
4208 // So it should be safe to assume that this node has been selected
4209 unsigned index = MatcherTable[MatcherIndex++];
4210 index |= (MatcherTable[MatcherIndex++] << 8);
4211 index |= (MatcherTable[MatcherIndex++] << 16);
4212 index |= (MatcherTable[MatcherIndex++] << 24);
4213 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
4214 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
4215 continue;
4216 }
4217
4218 case OPC_EmitNode:
4220 case OPC_EmitNode0:
4221 case OPC_EmitNode1:
4222 case OPC_EmitNode2:
4223 case OPC_EmitNode1None:
4224 case OPC_EmitNode2None:
4225 case OPC_EmitNode0Chain:
4226 case OPC_EmitNode1Chain:
4227 case OPC_EmitNode2Chain:
4228 case OPC_MorphNodeTo:
4230 case OPC_MorphNodeTo0:
4231 case OPC_MorphNodeTo1:
4232 case OPC_MorphNodeTo2:
4242 uint32_t TargetOpc = MatcherTable[MatcherIndex++];
4243 TargetOpc |= (MatcherTable[MatcherIndex++] << 8);
4244 unsigned EmitNodeInfo;
4245 if (Opcode >= OPC_EmitNode1None && Opcode <= OPC_EmitNode2Chain) {
4246 if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4247 EmitNodeInfo = OPFL_Chain;
4248 else
4249 EmitNodeInfo = OPFL_None;
4250 } else if (Opcode >= OPC_MorphNodeTo1None &&
4251 Opcode <= OPC_MorphNodeTo2GlueOutput) {
4252 if (Opcode >= OPC_MorphNodeTo0Chain && Opcode <= OPC_MorphNodeTo2Chain)
4253 EmitNodeInfo = OPFL_Chain;
4254 else if (Opcode >= OPC_MorphNodeTo1GlueInput &&
4255 Opcode <= OPC_MorphNodeTo2GlueInput)
4256 EmitNodeInfo = OPFL_GlueInput;
4257 else if (Opcode >= OPC_MorphNodeTo1GlueOutput &&
4259 EmitNodeInfo = OPFL_GlueOutput;
4260 else
4261 EmitNodeInfo = OPFL_None;
4262 } else
4263 EmitNodeInfo = MatcherTable[MatcherIndex++];
4264 // Get the result VT list.
4265 unsigned NumVTs;
4266 // If this is one of the compressed forms, get the number of VTs based
4267 // on the Opcode. Otherwise read the next byte from the table.
4268 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
4269 NumVTs = Opcode - OPC_MorphNodeTo0;
4270 else if (Opcode >= OPC_MorphNodeTo1None && Opcode <= OPC_MorphNodeTo2None)
4271 NumVTs = Opcode - OPC_MorphNodeTo1None + 1;
4272 else if (Opcode >= OPC_MorphNodeTo0Chain &&
4273 Opcode <= OPC_MorphNodeTo2Chain)
4274 NumVTs = Opcode - OPC_MorphNodeTo0Chain;
4275 else if (Opcode >= OPC_MorphNodeTo1GlueInput &&
4276 Opcode <= OPC_MorphNodeTo2GlueInput)
4277 NumVTs = Opcode - OPC_MorphNodeTo1GlueInput + 1;
4278 else if (Opcode >= OPC_MorphNodeTo1GlueOutput &&
4280 NumVTs = Opcode - OPC_MorphNodeTo1GlueOutput + 1;
4281 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
4282 NumVTs = Opcode - OPC_EmitNode0;
4283 else if (Opcode >= OPC_EmitNode1None && Opcode <= OPC_EmitNode2None)
4284 NumVTs = Opcode - OPC_EmitNode1None + 1;
4285 else if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4286 NumVTs = Opcode - OPC_EmitNode0Chain;
4287 else
4288 NumVTs = MatcherTable[MatcherIndex++];
4290 if (Opcode == OPC_EmitNodeByHwMode || Opcode == OPC_MorphNodeToByHwMode) {
4291 for (unsigned i = 0; i != NumVTs; ++i) {
4292 MVT VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4293 if (VT == MVT::iPTR)
4294 VT = TLI->getPointerTy(CurDAG->getDataLayout());
4295 VTs.push_back(VT);
4296 }
4297 } else {
4298 for (unsigned i = 0; i != NumVTs; ++i) {
4299 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
4300 if (VT == MVT::iPTR)
4301 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
4302 VTs.push_back(VT);
4303 }
4304 }
4305
4306 if (EmitNodeInfo & OPFL_Chain)
4307 VTs.push_back(MVT::Other);
4308 if (EmitNodeInfo & OPFL_GlueOutput)
4309 VTs.push_back(MVT::Glue);
4310
4311 // This is hot code, so optimize the two most common cases of 1 and 2
4312 // results.
4313 SDVTList VTList;
4314 if (VTs.size() == 1)
4315 VTList = CurDAG->getVTList(VTs[0]);
4316 else if (VTs.size() == 2)
4317 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
4318 else
4319 VTList = CurDAG->getVTList(VTs);
4320
4321 // Get the operand list.
4322 unsigned NumOps = MatcherTable[MatcherIndex++];
4323
4325 if (NumOps != 0) {
4326 // Get the index into the OperandLists.
4327 size_t OperandIndex = MatcherTable[MatcherIndex++];
4328 if (OperandIndex & 128)
4329 OperandIndex = GetVBR(OperandIndex, MatcherTable, MatcherIndex);
4330
4331 for (unsigned i = 0; i != NumOps; ++i) {
4332 unsigned RecNo = OperandLists[OperandIndex++];
4333 if (RecNo & 128)
4334 RecNo = GetVBR(RecNo, OperandLists, OperandIndex);
4335
4336 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
4337 Ops.push_back(RecordedNodes[RecNo].first);
4338 }
4339 }
4340
4341 // If there are variadic operands to add, handle them now.
4342 if (EmitNodeInfo & OPFL_VariadicInfo) {
4343 // Determine the start index to copy from.
4344 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
4345 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
4346 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
4347 "Invalid variadic node");
4348 // Copy all of the variadic operands, not including a potential glue
4349 // input.
4350 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
4351 i != e; ++i) {
4352 SDValue V = NodeToMatch->getOperand(i);
4353 if (V.getValueType() == MVT::Glue) break;
4354 Ops.push_back(V);
4355 }
4356 }
4357
4358 // If this has chain/glue inputs, add them.
4359 if (EmitNodeInfo & OPFL_Chain)
4360 Ops.push_back(InputChain);
4361 if (DeactivationSymbol.getNode() != nullptr)
4362 Ops.push_back(DeactivationSymbol);
4363 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
4364 Ops.push_back(InputGlue);
4365
4366 // Check whether any matched node could raise an FP exception. Since all
4367 // such nodes must have a chain, it suffices to check ChainNodesMatched.
4368 // We need to perform this check before potentially modifying one of the
4369 // nodes via MorphNode.
4370 bool MayRaiseFPException =
4371 llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
4372 return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
4373 });
4374
4375 // Create the node.
4376 MachineSDNode *Res = nullptr;
4377 bool IsMorphNodeTo =
4378 Opcode == OPC_MorphNodeTo || Opcode == OPC_MorphNodeToByHwMode ||
4379 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2GlueOutput);
4380 if (!IsMorphNodeTo) {
4381 // If this is a normal EmitNode command, just create the new node and
4382 // add the results to the RecordedNodes list.
4383 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
4384 VTList, Ops);
4385
4386 // Add all the non-glue/non-chain results to the RecordedNodes list.
4387 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
4388 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
4389 RecordedNodes.emplace_back(SDValue(Res, i), nullptr);
4390 }
4391 } else {
4392 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
4393 "NodeToMatch was removed partway through selection");
4395 SDNode *E) {
4396 CurDAG->salvageDebugInfo(*N);
4397 auto &Chain = ChainNodesMatched;
4398 assert((!E || !is_contained(Chain, N)) &&
4399 "Chain node replaced during MorphNode");
4400 llvm::erase(Chain, N);
4401 });
4402 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
4403 Ops, EmitNodeInfo));
4404 }
4405
4406 // Set the NoFPExcept flag when no original matched node could
4407 // raise an FP exception, but the new node potentially might.
4408 if (!MayRaiseFPException && mayRaiseFPException(Res))
4409 Res->setFlags(Res->getFlags() | SDNodeFlags::NoFPExcept);
4410
4411 // If the node had chain/glue results, update our notion of the current
4412 // chain and glue.
4413 if (EmitNodeInfo & OPFL_GlueOutput) {
4414 InputGlue = SDValue(Res, VTs.size()-1);
4415 if (EmitNodeInfo & OPFL_Chain)
4416 InputChain = SDValue(Res, VTs.size()-2);
4417 } else if (EmitNodeInfo & OPFL_Chain)
4418 InputChain = SDValue(Res, VTs.size()-1);
4419
4420 // If the OPFL_MemRefs glue is set on this node, slap all of the
4421 // accumulated memrefs onto it.
4422 //
4423 // FIXME: This is vastly incorrect for patterns with multiple outputs
4424 // instructions that access memory and for ComplexPatterns that match
4425 // loads.
4426 if (EmitNodeInfo & OPFL_MemRefs) {
4427 // Only attach load or store memory operands if the generated
4428 // instruction may load or store.
4429 const MCInstrDesc &MCID = TII->get(TargetOpc);
4430 bool mayLoad = MCID.mayLoad();
4431 bool mayStore = MCID.mayStore();
4432
4433 // We expect to have relatively few of these so just filter them into a
4434 // temporary buffer so that we can easily add them to the instruction.
4436 for (MachineMemOperand *MMO : MatchedMemRefs) {
4437 if (MMO->isLoad()) {
4438 if (mayLoad)
4439 FilteredMemRefs.push_back(MMO);
4440 } else if (MMO->isStore()) {
4441 if (mayStore)
4442 FilteredMemRefs.push_back(MMO);
4443 } else {
4444 FilteredMemRefs.push_back(MMO);
4445 }
4446 }
4447
4448 CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
4449 }
4450
4451 LLVM_DEBUG({
4452 if (!MatchedMemRefs.empty() && Res->memoperands_empty())
4453 dbgs() << " Dropping mem operands\n";
4454 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") << " node: ";
4455 Res->dump(CurDAG);
4456 });
4457
4458 // If this was a MorphNodeTo then we're completely done!
4459 if (IsMorphNodeTo) {
4460 // Update chain uses.
4461 UpdateChains(Res, InputChain, ChainNodesMatched, true);
4462 return;
4463 }
4464 continue;
4465 }
4466
4467 case OPC_CompleteMatch: {
4468 // The match has been completed, and any new nodes (if any) have been
4469 // created. Patch up references to the matched dag to use the newly
4470 // created nodes.
4471 unsigned NumResults = MatcherTable[MatcherIndex++];
4472
4473 for (unsigned i = 0; i != NumResults; ++i) {
4474 unsigned ResSlot = MatcherTable[MatcherIndex++];
4475 if (ResSlot & 128)
4476 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
4477
4478 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
4479 SDValue Res = RecordedNodes[ResSlot].first;
4480
4481 assert(i < NodeToMatch->getNumValues() &&
4482 NodeToMatch->getValueType(i) != MVT::Other &&
4483 NodeToMatch->getValueType(i) != MVT::Glue &&
4484 "Invalid number of results to complete!");
4485 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
4486 NodeToMatch->getValueType(i) == MVT::iPTR ||
4487 Res.getValueType() == MVT::iPTR ||
4488 NodeToMatch->getValueType(i).getSizeInBits() ==
4489 Res.getValueSizeInBits()) &&
4490 "invalid replacement");
4491 ReplaceUses(SDValue(NodeToMatch, i), Res);
4492 }
4493
4494 // Update chain uses.
4495 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
4496
4497 // If the root node defines glue, we need to update it to the glue result.
4498 // TODO: This never happens in our tests and I think it can be removed /
4499 // replaced with an assert, but if we do it this the way the change is
4500 // NFC.
4501 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
4502 MVT::Glue &&
4503 InputGlue.getNode())
4504 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
4505 InputGlue);
4506
4507 assert(NodeToMatch->use_empty() &&
4508 "Didn't replace all uses of the node?");
4509 CurDAG->RemoveDeadNode(NodeToMatch);
4510
4511 return;
4512 }
4513 }
4514
4515 // If the code reached this point, then the match failed. See if there is
4516 // another child to try in the current 'Scope', otherwise pop it until we
4517 // find a case to check.
4518 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
4519 << "\n");
4520 ++NumDAGIselRetries;
4521 while (true) {
4522 if (MatchScopes.empty()) {
4523 CannotYetSelect(NodeToMatch);
4524 return;
4525 }
4526
4527 // Restore the interpreter state back to the point where the scope was
4528 // formed.
4529 MatchScope &LastScope = MatchScopes.back();
4530 RecordedNodes.resize(LastScope.NumRecordedNodes);
4531 NodeStack.assign(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
4532 N = NodeStack.back();
4533
4534 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
4535 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
4536 MatcherIndex = LastScope.FailIndex;
4537
4538 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
4539
4540 InputChain = LastScope.InputChain;
4541 InputGlue = LastScope.InputGlue;
4542 if (!LastScope.HasChainNodesMatched)
4543 ChainNodesMatched.clear();
4544
4545 // Check to see what the offset is at the new MatcherIndex. If it is zero
4546 // we have reached the end of this scope, otherwise we have another child
4547 // in the current scope to try.
4548 unsigned NumToSkip = MatcherTable[MatcherIndex++];
4549 if (NumToSkip & 128)
4550 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
4551
4552 // If we have another child in this scope to match, update FailIndex and
4553 // try it.
4554 if (NumToSkip != 0) {
4555 LastScope.FailIndex = MatcherIndex+NumToSkip;
4556 break;
4557 }
4558
4559 // End of this scope, pop it and try the next child in the containing
4560 // scope.
4561 MatchScopes.pop_back();
4562 }
4563 }
4564}
4565
4566/// Return whether the node may raise an FP exception.
4568 // For machine opcodes, consult the MCID flag.
4569 if (N->isMachineOpcode()) {
4570 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
4571 return MCID.mayRaiseFPException();
4572 }
4573
4574 // For ISD opcodes, only StrictFP opcodes may raise an FP
4575 // exception.
4576 if (N->isTargetOpcode()) {
4577 const SelectionDAGTargetInfo &TSI = CurDAG->getSelectionDAGInfo();
4578 return TSI.mayRaiseFPException(N->getOpcode());
4579 }
4580 return N->isStrictFPOpcode();
4581}
4582
4584 assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
4585 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
4586 if (!C)
4587 return false;
4588
4589 // Detect when "or" is used to add an offset to a stack object.
4590 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
4591 MachineFrameInfo &MFI = MF->getFrameInfo();
4592 Align A = MFI.getObjectAlign(FN->getIndex());
4593 int32_t Off = C->getSExtValue();
4594 // If the alleged offset fits in the zero bits guaranteed by
4595 // the alignment, then this or is really an add.
4596 return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
4597 }
4598 return false;
4599}
4600
4601void SelectionDAGISel::CannotYetSelect(SDNode *N) {
4602 std::string msg;
4604 Msg << "Cannot select: ";
4605
4606 Msg.enable_colors(errs().has_colors());
4607
4608 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
4609 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
4610 N->getOpcode() != ISD::INTRINSIC_VOID) {
4611 N->printrFull(Msg, CurDAG);
4612 Msg << "\nIn function: " << MF->getName();
4613 } else {
4614 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
4615 unsigned iid = N->getConstantOperandVal(HasInputChain);
4616 if (iid < Intrinsic::num_intrinsics)
4617 Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
4618 else
4619 Msg << "unknown intrinsic #" << iid;
4620 }
4621 report_fatal_error(Twine(msg));
4622}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
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
BitTracker BT
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:376
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the FastISel class.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
PostRA Machine Instruction Scheduler
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
This header defines classes/functions to handle pass execution timing information with interfaces for...
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
SI Fold Operands
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckNodePredicate(unsigned Opcode, const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel, SDValue Op)
CheckNodePredicate - Implements OP_CheckNodePredicate.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
CheckSame - Implements OP_CheckSame.
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 CheckOrImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckCondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, unsigned ChildNo)
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 uint8_t *MatcherTable, size_t &Idx)
GetVBR - decode a vbr encoding whose top bit is set.
static cl::opt< bool > DumpSortedDAG("dump-sorted-dags", cl::Hidden, cl::desc("Print DAGs with sorted nodes in debug dump"), cl::init(false))
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
static bool IsPredicateKnownToFail(const uint8_t *Table, size_t &Index, SDValue N, const SelectionDAGISel &SDISel, const 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< 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 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 LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
static void processSingleLocVars(FunctionLoweringInfo &FuncInfo, FunctionVarLocs const *FnVarLocs)
Collect single location variable information generated with assignment tracking.
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 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 LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckPatternPredicate(unsigned Opcode, const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
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 void preserveFakeUses(BasicBlock::iterator Begin, BasicBlock::iterator End)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOpcode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDNode *N)
static SDValue HandleMergeInputChains(const SmallVectorImpl< SDNode * > &ChainNodesMatched, SDValue InputGlue, SelectionDAG *CurDAG)
HandleMergeInputChains - This implements the OPC_EmitMergeInputChains operation for when the pattern ...
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
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 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 LLVM_ATTRIBUTE_ALWAYS_INLINE int64_t GetSignedVBR(const unsigned char *MatcherTable, size_t &Idx)
static bool maintainPGOProfile(const TargetMachine &TM, CodeGenOptLevel OptLevel)
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 MVT::SimpleValueType getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex)
getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value, use GetVBR to decode it.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChild2CondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
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 LLVM_ATTRIBUTE_ALWAYS_INLINE MVT getHwModeVT(const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel)
Decode a HwMode VT in MatcherTable by calling getValueTypeForHwMode.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
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.
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:1261
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
unsigned getNumber() const
Definition BasicBlock.h:95
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:683
LLVM_ABI const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
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.
This class represents a function call, abstracting a target machine's calling convention.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
static LLVM_ABI 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 ...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for ISel fallback path.
void setLastLocalValue(MachineInstr *I)
Update the position of the last instruction emitted for materializing constants for use in the curren...
Definition FastISel.h:239
void handleDbgInfo(const Instruction *II)
Target-independent lowering of non-instruction debug info associated with this instruction.
bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst)
We're checking to see if we can fold LI into FoldInst.
void removeDeadCode(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
Remove all dead instructions between the I and E.
Definition FastISel.cpp:415
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...
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:406
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.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
SmallPtrSet< const DbgVariableRecord *, 8 > PreprocessedDVRDeclares
Collection of dbg_declare instructions handled after argument lowering and before ISel proper.
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
LLVM_ABI 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.
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:197
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:794
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:813
iterator_range< arg_iterator > args()
Definition Function.h:877
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition Function.h:321
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
An analysis pass which caches information about the Function.
Definition GCMetadata.h:214
An analysis pass which caches information about the entire Module.
Definition GCMetadata.h:237
Module * getParent()
Get the module that this global value is contained inside of...
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.
bool isTerminator() const
iterator_range< user_iterator > users()
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI 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.
Describe properties that are true of each instruction in the target description file.
virtual unsigned getHwMode(enum HwModeType type=HwMode_Default) const
HwMode ID corresponding to the 'type' parameter is retrieved from the HwMode bit set of the current s...
const MDNode * getMD() const
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
Machine Value Type.
SimpleValueType SimpleTy
LLVM_ABI 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.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
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.
LLVM_ABI 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 '...
MachineInstrBundleIterator< MachineInstr > iterator
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 useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index)
Map the landing pad to its index. Used for Wasm exception handling.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void setUseDebugInstrRef(bool UseInstrRef)
Set whether this function will use instruction referencing or not.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
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 MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
Representation of each machine instruction.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
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,...
ArrayRef< std::pair< MCRegister, Register > > liveins() const
An SDNode that represents everything that will be needed to construct a MachineInstr.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
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.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
static LLVM_ABI 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:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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 LLVM_ABI MachinePassRegistry< FunctionPassCtor > Registry
RegisterScheduler class - Track the registration of instruction schedulers.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
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.
SDNode * getGluedUser() const
If this node has a glue value with a user, return the user (there is at most one).
LLVM_ABI 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
iterator_range< use_iterator > uses()
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
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
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.
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)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::optional< BatchAAResults > BatchAA
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).
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
const TargetTransformInfo * TTI
virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
virtual bool CheckNodePredicateWithOperands(SDValue Op, unsigned PredNo, ArrayRef< SDValue > Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
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
std::unique_ptr< SwiftErrorValueTracking > SwiftError
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)
virtual MVT getValueTypeForHwMode(unsigned Index) const
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...
BatchAAResults * getBatchAA() const
Returns a (possibly null) pointer to the current BatchAAResults.
bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckAndMask - The isel is trying to match something like (and X, 255).
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.
void SelectCodeCommon(SDNode *NodeToMatch, const uint8_t *MatcherTable, unsigned TableSize, const uint8_t *OperandLists)
const LibcallLoweringInfo * LibcallLowering
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
Targets can subclass this to parameterize the SelectionDAG lowering and instruction selection process...
virtual bool mayRaiseFPException(unsigned Opcode) const
Returns true if a node with the given target-specific opcode may raise a floating-point exception.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
allnodes_const_iterator allnodes_begin() const
const DataLayout & getDataLayout() const
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
ilist< SDNode >::iterator allnodes_iterator
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
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...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
Primary interface to the complete machine description for the target machine.
const std::optional< PGOOptions > & getPGOOption() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Wrapper pass for TargetTransformInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI 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:191
@ CONVERGENCECTRL_ANCHOR
The llvm.experimental.convergence.* intrinsics.
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ TargetBlockAddress
Definition ISDOpcodes.h:193
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ FAKE_USE
FAKE_USE represents a use of the operand but does not do anything.
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ CONVERGENCECTRL_ENTRY
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:71
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ RELOC_NONE
Issue a no-op relocation against a given symbol at the current location.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ STACKMAP
The llvm.experimental.stackmap intrinsic.
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ CONVERGENCECTRL_LOOP
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
LLVM_ABI 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,...
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
LLVM_ABI ScheduleDAGSDNodes * createDefaultScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDefaultScheduler - This creates an instruction scheduler appropriate for the target.
@ Offset
Definition DWP.cpp:577
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI 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.
@ Known
Known to have no common set bits.
@ Kill
The last use of a register.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI 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 ...
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI ScheduleDAGSDNodes * createFastDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createFastDAGScheduler - This creates a "fast" scheduler.
LLVM_ABI 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:2216
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:1762
LLVM_ABI ScheduleDAGSDNodes * createDAGLinearizer(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDAGLinearizer - This creates a "no-scheduling" scheduler which linearize the DAG using topologi...
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool isFunctionInPrintList(StringRef FunctionName)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI 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:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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
LLVM_ABI ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createSourceListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source...
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
DWARFExpression::Operation Op
LLVM_ABI void initializeAAResultsWrapperPassPass(PassRegistry &)
LLVM_ABI void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &)
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:1933
LLVM_ABI ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
LLVM_ABI ScheduleDAGSDNodes * createVLIWDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createVLIWDAGScheduler - Scheduler for VLIW targets.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#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:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
A struct capturing PGO tunables.
Definition PGOOptions.h:22
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.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)
DenseMap< const BasicBlock *, int > BlockToStateMap