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