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