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