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