1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #include "ScheduleDAGSDNodes.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineFunctionPass.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachinePassRegistry.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/MachineValueType.h"
45 #include "llvm/CodeGen/SchedulerRegistry.h"
46 #include "llvm/CodeGen/SelectionDAG.h"
47 #include "llvm/CodeGen/SelectionDAGISel.h"
48 #include "llvm/CodeGen/SelectionDAGNodes.h"
49 #include "llvm/CodeGen/StackProtector.h"
50 #include "llvm/CodeGen/ValueTypes.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DebugInfoMetadata.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DiagnosticInfo.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/InlineAsm.h"
58 #include "llvm/IR/InstrTypes.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/Intrinsics.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/IR/User.h"
66 #include "llvm/MC/MCInstrDesc.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/BranchProbability.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/Timer.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Target/TargetInstrInfo.h"
79 #include "llvm/Target/TargetIntrinsicInfo.h"
80 #include "llvm/Target/TargetLowering.h"
81 #include "llvm/Target/TargetMachine.h"
82 #include "llvm/Target/TargetOptions.h"
83 #include "llvm/Target/TargetRegisterInfo.h"
84 #include "llvm/Target/TargetSubtargetInfo.h"
85 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
97 #define DEBUG_TYPE "isel"
99 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
100 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
101 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
102 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
103 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
104 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
105 STATISTIC(NumFastIselFailLowerArguments,
106 "Number of entry blocks where fast isel failed to lower arguments");
108 static cl::opt<int> EnableFastISelAbort(
109 "fast-isel-abort", cl::Hidden,
110 cl::desc("Enable abort calls when \"fast\" instruction selection "
111 "fails to lower an instruction: 0 disable the abort, 1 will "
112 "abort but for args, calls and terminators, 2 will also "
113 "abort for argument lowering, and 3 will never fallback "
114 "to SelectionDAG."));
116 static cl::opt<bool> EnableFastISelFallbackReport(
117 "fast-isel-report-on-fallback", cl::Hidden,
118 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
119 "falls back to SelectionDAG."));
123 cl::desc("use Machine Branch Probability Info"),
124 cl::init(true), cl::Hidden);
127 static cl::opt<std::string>
128 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
129 cl::desc("Only display the basic block whose name "
130 "matches this for all view-*-dags options"));
132 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
133 cl::desc("Pop up a window to show dags before the first "
134 "dag combine pass"));
136 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
137 cl::desc("Pop up a window to show dags before legalize types"));
139 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
140 cl::desc("Pop up a window to show dags before legalize"));
142 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
143 cl::desc("Pop up a window to show dags before the second "
144 "dag combine pass"));
146 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
147 cl::desc("Pop up a window to show dags before the post legalize types"
148 " dag combine pass"));
150 ViewISelDAGs("view-isel-dags", cl::Hidden,
151 cl::desc("Pop up a window to show isel dags as they are selected"));
153 ViewSchedDAGs("view-sched-dags", cl::Hidden,
154 cl::desc("Pop up a window to show sched dags as they are processed"));
156 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
157 cl::desc("Pop up a window to show SUnit dags after they are processed"));
159 static const bool ViewDAGCombine1 = false,
160 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
161 ViewDAGCombine2 = false,
162 ViewDAGCombineLT = false,
163 ViewISelDAGs = false, ViewSchedDAGs = false,
164 ViewSUnitDAGs = false;
167 //===---------------------------------------------------------------------===//
169 /// RegisterScheduler class - Track the registration of instruction schedulers.
171 //===---------------------------------------------------------------------===//
172 MachinePassRegistry RegisterScheduler::Registry;
174 //===---------------------------------------------------------------------===//
176 /// ISHeuristic command line option for instruction schedulers.
178 //===---------------------------------------------------------------------===//
179 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
180 RegisterPassParser<RegisterScheduler>>
181 ISHeuristic("pre-RA-sched",
182 cl::init(&createDefaultScheduler), cl::Hidden,
183 cl::desc("Instruction schedulers available (before register"
186 static RegisterScheduler
187 defaultListDAGScheduler("default", "Best scheduler for the target",
188 createDefaultScheduler);
192 //===--------------------------------------------------------------------===//
193 /// \brief This class is used by SelectionDAGISel to temporarily override
194 /// the optimization level on a per-function basis.
195 class OptLevelChanger {
196 SelectionDAGISel &IS;
197 CodeGenOpt::Level SavedOptLevel;
201 OptLevelChanger(SelectionDAGISel &ISel,
202 CodeGenOpt::Level NewOptLevel) : IS(ISel) {
203 SavedOptLevel = IS.OptLevel;
204 if (NewOptLevel == SavedOptLevel)
206 IS.OptLevel = NewOptLevel;
207 IS.TM.setOptLevel(NewOptLevel);
208 DEBUG(dbgs() << "\nChanging optimization level for Function "
209 << IS.MF->getFunction()->getName() << "\n");
210 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
211 << " ; After: -O" << NewOptLevel << "\n");
212 SavedFastISel = IS.TM.Options.EnableFastISel;
213 if (NewOptLevel == CodeGenOpt::None) {
214 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
215 DEBUG(dbgs() << "\tFastISel is "
216 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
222 if (IS.OptLevel == SavedOptLevel)
224 DEBUG(dbgs() << "\nRestoring optimization level for Function "
225 << IS.MF->getFunction()->getName() << "\n");
226 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
227 << " ; After: -O" << SavedOptLevel << "\n");
228 IS.OptLevel = SavedOptLevel;
229 IS.TM.setOptLevel(SavedOptLevel);
230 IS.TM.setFastISel(SavedFastISel);
234 //===--------------------------------------------------------------------===//
235 /// createDefaultScheduler - This creates an instruction scheduler appropriate
237 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
238 CodeGenOpt::Level OptLevel) {
239 const TargetLowering *TLI = IS->TLI;
240 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
242 // Try first to see if the Target has its own way of selecting a scheduler
243 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
244 return SchedulerCtor(IS, OptLevel);
247 if (OptLevel == CodeGenOpt::None ||
248 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
249 TLI->getSchedulingPreference() == Sched::Source)
250 return createSourceListDAGScheduler(IS, OptLevel);
251 if (TLI->getSchedulingPreference() == Sched::RegPressure)
252 return createBURRListDAGScheduler(IS, OptLevel);
253 if (TLI->getSchedulingPreference() == Sched::Hybrid)
254 return createHybridListDAGScheduler(IS, OptLevel);
255 if (TLI->getSchedulingPreference() == Sched::VLIW)
256 return createVLIWDAGScheduler(IS, OptLevel);
257 assert(TLI->getSchedulingPreference() == Sched::ILP &&
258 "Unknown sched type!");
259 return createILPListDAGScheduler(IS, OptLevel);
262 } // end namespace llvm
264 // EmitInstrWithCustomInserter - This method should be implemented by targets
265 // that mark instructions with the 'usesCustomInserter' flag. These
266 // instructions are special in various ways, which require special support to
267 // insert. The specified MachineInstr is created but not inserted into any
268 // basic blocks, and this method is called to expand it into a sequence of
269 // instructions, potentially also creating new basic blocks and control flow.
270 // When new basic blocks are inserted and the edges from MBB to its successors
271 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
274 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
275 MachineBasicBlock *MBB) const {
277 dbgs() << "If a target marks an instruction with "
278 "'usesCustomInserter', it must implement "
279 "TargetLowering::EmitInstrWithCustomInserter!";
281 llvm_unreachable(nullptr);
284 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
285 SDNode *Node) const {
286 assert(!MI.hasPostISelHook() &&
287 "If a target marks an instruction with 'hasPostISelHook', "
288 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
291 //===----------------------------------------------------------------------===//
292 // SelectionDAGISel code
293 //===----------------------------------------------------------------------===//
295 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
296 CodeGenOpt::Level OL) :
297 MachineFunctionPass(ID), TM(tm),
298 FuncInfo(new FunctionLoweringInfo()),
299 CurDAG(new SelectionDAG(tm, OL)),
300 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
304 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
305 initializeBranchProbabilityInfoWrapperPassPass(
306 *PassRegistry::getPassRegistry());
307 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
308 initializeTargetLibraryInfoWrapperPassPass(
309 *PassRegistry::getPassRegistry());
312 SelectionDAGISel::~SelectionDAGISel() {
318 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
319 AU.addRequired<AAResultsWrapperPass>();
320 AU.addRequired<GCModuleInfo>();
321 AU.addRequired<StackProtector>();
322 AU.addPreserved<StackProtector>();
323 AU.addPreserved<GCModuleInfo>();
324 AU.addRequired<TargetLibraryInfoWrapperPass>();
325 if (UseMBPI && OptLevel != CodeGenOpt::None)
326 AU.addRequired<BranchProbabilityInfoWrapperPass>();
327 MachineFunctionPass::getAnalysisUsage(AU);
330 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
331 /// may trap on it. In this case we have to split the edge so that the path
332 /// through the predecessor block that doesn't go to the phi block doesn't
333 /// execute the possibly trapping instruction.
335 /// This is required for correctness, so it must be done at -O0.
337 static void SplitCriticalSideEffectEdges(Function &Fn) {
338 // Loop for blocks with phi nodes.
339 for (BasicBlock &BB : Fn) {
340 PHINode *PN = dyn_cast<PHINode>(BB.begin());
344 // For each block with a PHI node, check to see if any of the input values
345 // are potentially trapping constant expressions. Constant expressions are
346 // the only potentially trapping value that can occur as the argument to a
348 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
349 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
350 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
351 if (!CE || !CE->canTrap()) continue;
353 // The only case we have to worry about is when the edge is critical.
354 // Since this block has a PHI Node, we assume it has multiple input
355 // edges: check to see if the pred has multiple successors.
356 BasicBlock *Pred = PN->getIncomingBlock(i);
357 if (Pred->getTerminator()->getNumSuccessors() == 1)
360 // Okay, we have to split this edge.
362 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
363 CriticalEdgeSplittingOptions().setMergeIdenticalEdges());
369 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
370 // If we already selected that function, we do not need to run SDISel.
371 if (mf.getProperties().hasProperty(
372 MachineFunctionProperties::Property::Selected))
374 // Do some sanity-checking on the command-line options.
375 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
376 "-fast-isel-abort > 0 requires -fast-isel");
378 const Function &Fn = *mf.getFunction();
381 // Reset the target options before resetting the optimization
383 // FIXME: This is a horrible hack and should be processed via
384 // codegen looking at the optimization level explicitly when
385 // it wants to look at it.
386 TM.resetTargetOptions(Fn);
387 // Reset OptLevel to None for optnone functions.
388 CodeGenOpt::Level NewOptLevel = OptLevel;
389 if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
390 NewOptLevel = CodeGenOpt::None;
391 OptLevelChanger OLC(*this, NewOptLevel);
393 TII = MF->getSubtarget().getInstrInfo();
394 TLI = MF->getSubtarget().getTargetLowering();
395 RegInfo = &MF->getRegInfo();
396 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
397 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
398 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
399 ORE = make_unique<OptimizationRemarkEmitter>(&Fn);
401 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
403 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn));
405 CurDAG->init(*MF, *ORE);
406 FuncInfo->set(Fn, *MF, CurDAG);
408 if (UseMBPI && OptLevel != CodeGenOpt::None)
409 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
411 FuncInfo->BPI = nullptr;
413 SDB->init(GFI, *AA, LibInfo);
415 MF->setHasInlineAsm(false);
417 FuncInfo->SplitCSR = false;
419 // We split CSR if the target supports it for the given function
420 // and the function has only return exits.
421 if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
422 FuncInfo->SplitCSR = true;
424 // Collect all the return blocks.
425 for (const BasicBlock &BB : Fn) {
426 if (!succ_empty(&BB))
429 const TerminatorInst *Term = BB.getTerminator();
430 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
433 // Bail out if the exit block is not Return nor Unreachable.
434 FuncInfo->SplitCSR = false;
439 MachineBasicBlock *EntryMBB = &MF->front();
440 if (FuncInfo->SplitCSR)
441 // This performs initialization so lowering for SplitCSR will be correct.
442 TLI->initializeSplitCSR(EntryMBB);
444 SelectAllBasicBlocks(Fn);
445 if (FastISelFailed && EnableFastISelFallbackReport) {
446 DiagnosticInfoISelFallback DiagFallback(Fn);
447 Fn.getContext().diagnose(DiagFallback);
450 // If the first basic block in the function has live ins that need to be
451 // copied into vregs, emit the copies into the top of the block before
452 // emitting the code for the block.
453 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
454 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
456 // Insert copies in the entry block and the return blocks.
457 if (FuncInfo->SplitCSR) {
458 SmallVector<MachineBasicBlock*, 4> Returns;
459 // Collect all the return blocks.
460 for (MachineBasicBlock &MBB : mf) {
461 if (!MBB.succ_empty())
464 MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
465 if (Term != MBB.end() && Term->isReturn()) {
466 Returns.push_back(&MBB);
470 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
473 DenseMap<unsigned, unsigned> LiveInMap;
474 if (!FuncInfo->ArgDbgValues.empty())
475 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
476 E = RegInfo->livein_end(); LI != E; ++LI)
478 LiveInMap.insert(std::make_pair(LI->first, LI->second));
480 // Insert DBG_VALUE instructions for function arguments to the entry block.
481 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
482 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
483 bool hasFI = MI->getOperand(0).isFI();
485 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
486 if (TargetRegisterInfo::isPhysicalRegister(Reg))
487 EntryMBB->insert(EntryMBB->begin(), MI);
489 MachineInstr *Def = RegInfo->getVRegDef(Reg);
491 MachineBasicBlock::iterator InsertPos = Def;
492 // FIXME: VR def may not be in entry block.
493 Def->getParent()->insert(std::next(InsertPos), MI);
495 DEBUG(dbgs() << "Dropping debug info for dead vreg"
496 << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
499 // If Reg is live-in then update debug info to track its copy in a vreg.
500 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
501 if (LDI != LiveInMap.end()) {
502 assert(!hasFI && "There's no handling of frame pointer updating here yet "
504 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
505 MachineBasicBlock::iterator InsertPos = Def;
506 const MDNode *Variable = MI->getDebugVariable();
507 const MDNode *Expr = MI->getDebugExpression();
508 DebugLoc DL = MI->getDebugLoc();
509 bool IsIndirect = MI->isIndirectDebugValue();
510 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
511 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
512 "Expected inlined-at fields to agree");
513 // Def is never a terminator here, so it is ok to increment InsertPos.
514 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
515 IsIndirect, LDI->second, Offset, Variable, Expr);
517 // If this vreg is directly copied into an exported register then
518 // that COPY instructions also need DBG_VALUE, if it is the only
519 // user of LDI->second.
520 MachineInstr *CopyUseMI = nullptr;
521 for (MachineRegisterInfo::use_instr_iterator
522 UI = RegInfo->use_instr_begin(LDI->second),
523 E = RegInfo->use_instr_end(); UI != E; ) {
524 MachineInstr *UseMI = &*(UI++);
525 if (UseMI->isDebugValue()) continue;
526 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
527 CopyUseMI = UseMI; continue;
529 // Otherwise this is another use or second copy use.
530 CopyUseMI = nullptr; break;
533 // Use MI's debug location, which describes where Variable was
534 // declared, rather than whatever is attached to CopyUseMI.
535 MachineInstr *NewMI =
536 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
537 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
538 MachineBasicBlock::iterator Pos = CopyUseMI;
539 EntryMBB->insertAfter(Pos, NewMI);
544 // Determine if there are any calls in this machine function.
545 MachineFrameInfo &MFI = MF->getFrameInfo();
546 for (const auto &MBB : *MF) {
547 if (MFI.hasCalls() && MF->hasInlineAsm())
550 for (const auto &MI : MBB) {
551 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
552 if ((MCID.isCall() && !MCID.isReturn()) ||
553 MI.isStackAligningInlineAsm()) {
554 MFI.setHasCalls(true);
556 if (MI.isInlineAsm()) {
557 MF->setHasInlineAsm(true);
562 // Determine if there is a call to setjmp in the machine function.
563 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
565 // Replace forward-declared registers with the registers containing
566 // the desired value.
567 MachineRegisterInfo &MRI = MF->getRegInfo();
568 for (DenseMap<unsigned, unsigned>::iterator
569 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
571 unsigned From = I->first;
572 unsigned To = I->second;
573 // If To is also scheduled to be replaced, find what its ultimate
576 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
580 // Make sure the new register has a sufficiently constrained register class.
581 if (TargetRegisterInfo::isVirtualRegister(From) &&
582 TargetRegisterInfo::isVirtualRegister(To))
583 MRI.constrainRegClass(To, MRI.getRegClass(From));
587 // Replacing one register with another won't touch the kill flags.
588 // We need to conservatively clear the kill flags as a kill on the old
589 // register might dominate existing uses of the new register.
590 if (!MRI.use_empty(To))
591 MRI.clearKillFlags(From);
592 MRI.replaceRegWith(From, To);
595 if (TLI->hasCopyImplyingStackAdjustment(MF))
596 MFI.setHasCopyImplyingStackAdjustment(true);
598 // Freeze the set of reserved registers now that MachineFrameInfo has been
599 // set up. All the information required by getReservedRegs() should be
601 MRI.freezeReservedRegs(*MF);
603 // Release function-specific state. SDB and CurDAG are already cleared
607 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
608 DEBUG(MF->print(dbgs()));
613 static void reportFastISelFailure(MachineFunction &MF,
614 OptimizationRemarkEmitter &ORE,
615 OptimizationRemarkMissed &R,
617 // Print the function name explicitly if we don't have a debug location (which
618 // makes the diagnostic less useful) or if we're going to emit a raw error.
619 if (!R.getLocation().isValid() || ShouldAbort)
620 R << (" (in function: " + MF.getName() + ")").str();
623 report_fatal_error(R.getMsg());
628 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
629 BasicBlock::const_iterator End,
631 // Lower the instructions. If a call is emitted as a tail call, cease emitting
632 // nodes for this block.
633 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
634 if (!ElidedArgCopyInstrs.count(&*I))
638 // Make sure the root of the DAG is up-to-date.
639 CurDAG->setRoot(SDB->getControlRoot());
640 HadTailCall = SDB->HasTailCall;
643 // Final step, emit the lowered DAG as machine code.
647 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
648 SmallPtrSet<SDNode*, 16> VisitedNodes;
649 SmallVector<SDNode*, 128> Worklist;
651 Worklist.push_back(CurDAG->getRoot().getNode());
657 SDNode *N = Worklist.pop_back_val();
659 // If we've already seen this node, ignore it.
660 if (!VisitedNodes.insert(N).second)
663 // Otherwise, add all chain operands to the worklist.
664 for (const SDValue &Op : N->op_values())
665 if (Op.getValueType() == MVT::Other)
666 Worklist.push_back(Op.getNode());
668 // If this is a CopyToReg with a vreg dest, process it.
669 if (N->getOpcode() != ISD::CopyToReg)
672 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
673 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
676 // Ignore non-scalar or non-integer values.
677 SDValue Src = N->getOperand(2);
678 EVT SrcVT = Src.getValueType();
679 if (!SrcVT.isInteger() || SrcVT.isVector())
682 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
683 CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
684 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
685 } while (!Worklist.empty());
688 void SelectionDAGISel::CodeGenAndEmitDAG() {
689 StringRef GroupName = "sdag";
690 StringRef GroupDescription = "Instruction Selection and Scheduling";
691 std::string BlockName;
692 int BlockNumber = -1;
694 bool MatchFilterBB = false; (void)MatchFilterBB;
696 // Pre-type legalization allow creation of any node types.
697 CurDAG->NewNodesMustHaveLegalTypes = false;
700 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
701 FilterDAGBasicBlockName ==
702 FuncInfo->MBB->getBasicBlock()->getName().str());
705 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
706 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
710 BlockNumber = FuncInfo->MBB->getNumber();
712 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
714 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
715 << " '" << BlockName << "'\n"; CurDAG->dump());
717 if (ViewDAGCombine1 && MatchFilterBB)
718 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
720 // Run the DAG combiner in pre-legalize mode.
722 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
723 GroupDescription, TimePassesIsEnabled);
724 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
727 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
728 << " '" << BlockName << "'\n"; CurDAG->dump());
730 // Second step, hack on the DAG until it only uses operations and types that
731 // the target supports.
732 if (ViewLegalizeTypesDAGs && MatchFilterBB)
733 CurDAG->viewGraph("legalize-types input for " + BlockName);
737 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
738 GroupDescription, TimePassesIsEnabled);
739 Changed = CurDAG->LegalizeTypes();
742 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
743 << " '" << BlockName << "'\n"; CurDAG->dump());
745 // Only allow creation of legal node types.
746 CurDAG->NewNodesMustHaveLegalTypes = true;
749 if (ViewDAGCombineLT && MatchFilterBB)
750 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
752 // Run the DAG combiner in post-type-legalize mode.
754 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
755 GroupName, GroupDescription, TimePassesIsEnabled);
756 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
759 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
760 << " '" << BlockName << "'\n"; CurDAG->dump());
765 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
766 GroupDescription, TimePassesIsEnabled);
767 Changed = CurDAG->LegalizeVectors();
771 DEBUG(dbgs() << "Vector-legalized selection DAG: BB#" << BlockNumber
772 << " '" << BlockName << "'\n"; CurDAG->dump());
775 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
776 GroupDescription, TimePassesIsEnabled);
777 CurDAG->LegalizeTypes();
780 DEBUG(dbgs() << "Vector/type-legalized selection DAG: BB#" << BlockNumber
781 << " '" << BlockName << "'\n"; CurDAG->dump());
783 if (ViewDAGCombineLT && MatchFilterBB)
784 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
786 // Run the DAG combiner in post-type-legalize mode.
788 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
789 GroupName, GroupDescription, TimePassesIsEnabled);
790 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
793 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
794 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
797 if (ViewLegalizeDAGs && MatchFilterBB)
798 CurDAG->viewGraph("legalize input for " + BlockName);
801 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
802 GroupDescription, TimePassesIsEnabled);
806 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
807 << " '" << BlockName << "'\n"; CurDAG->dump());
809 if (ViewDAGCombine2 && MatchFilterBB)
810 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
812 // Run the DAG combiner in post-legalize mode.
814 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
815 GroupDescription, TimePassesIsEnabled);
816 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
819 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
820 << " '" << BlockName << "'\n"; CurDAG->dump());
822 if (OptLevel != CodeGenOpt::None)
823 ComputeLiveOutVRegInfo();
825 if (ViewISelDAGs && MatchFilterBB)
826 CurDAG->viewGraph("isel input for " + BlockName);
828 // Third, instruction select all of the operations to machine code, adding the
829 // code to the MachineBasicBlock.
831 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
832 GroupDescription, TimePassesIsEnabled);
833 DoInstructionSelection();
836 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
837 << " '" << BlockName << "'\n"; CurDAG->dump());
839 if (ViewSchedDAGs && MatchFilterBB)
840 CurDAG->viewGraph("scheduler input for " + BlockName);
842 // Schedule machine code.
843 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
845 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
846 GroupDescription, TimePassesIsEnabled);
847 Scheduler->Run(CurDAG, FuncInfo->MBB);
850 if (ViewSUnitDAGs && MatchFilterBB)
851 Scheduler->viewGraph();
853 // Emit machine code to BB. This can change 'BB' to the last block being
855 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
857 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
858 GroupDescription, TimePassesIsEnabled);
860 // FuncInfo->InsertPt is passed by reference and set to the end of the
861 // scheduled instructions.
862 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
865 // If the block was split, make sure we update any references that are used to
866 // update PHI nodes later on.
867 if (FirstMBB != LastMBB)
868 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
870 // Free the scheduler state.
872 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
873 GroupDescription, TimePassesIsEnabled);
877 // Free the SelectionDAG state, now that we're finished with it.
883 /// ISelUpdater - helper class to handle updates of the instruction selection
885 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
886 SelectionDAG::allnodes_iterator &ISelPosition;
889 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
890 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
892 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
893 /// deleted is the current ISelPosition node, update ISelPosition.
895 void NodeDeleted(SDNode *N, SDNode *E) override {
896 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
901 } // end anonymous namespace
903 static bool isStrictFPOp(SDNode *Node, unsigned &NewOpc) {
904 unsigned OrigOpc = Node->getOpcode();
906 case ISD::STRICT_FADD: NewOpc = ISD::FADD; return true;
907 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; return true;
908 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; return true;
909 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; return true;
910 case ISD::STRICT_FREM: NewOpc = ISD::FREM; return true;
911 default: return false;
915 SDNode* SelectionDAGISel::MutateStrictFPToFP(SDNode *Node, unsigned NewOpc) {
916 assert(((Node->getOpcode() == ISD::STRICT_FADD && NewOpc == ISD::FADD) ||
917 (Node->getOpcode() == ISD::STRICT_FSUB && NewOpc == ISD::FSUB) ||
918 (Node->getOpcode() == ISD::STRICT_FMUL && NewOpc == ISD::FMUL) ||
919 (Node->getOpcode() == ISD::STRICT_FDIV && NewOpc == ISD::FDIV) ||
920 (Node->getOpcode() == ISD::STRICT_FREM && NewOpc == ISD::FREM)) &&
921 "Unexpected StrictFP opcode!");
923 // We're taking this node out of the chain, so we need to re-link things.
924 SDValue InputChain = Node->getOperand(0);
925 SDValue OutputChain = SDValue(Node, 1);
926 CurDAG->ReplaceAllUsesOfValueWith(OutputChain, InputChain);
928 SDVTList VTs = CurDAG->getVTList(Node->getOperand(1).getValueType());
929 SDValue Ops[2] = { Node->getOperand(1), Node->getOperand(2) };
930 SDNode *Res = CurDAG->MorphNodeTo(Node, NewOpc, VTs, Ops);
932 // MorphNodeTo can operate in two ways: if an existing node with the
933 // specified operands exists, it can just return it. Otherwise, it
934 // updates the node in place to have the requested operands.
936 // If we updated the node in place, reset the node ID. To the isel,
937 // this should be just like a newly allocated machine node.
940 CurDAG->ReplaceAllUsesWith(Node, Res);
941 CurDAG->RemoveDeadNode(Node);
947 void SelectionDAGISel::DoInstructionSelection() {
948 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
949 << FuncInfo->MBB->getNumber()
950 << " '" << FuncInfo->MBB->getName() << "'\n");
954 // Select target instructions for the DAG.
956 // Number all nodes with a topological order and set DAGSize.
957 DAGSize = CurDAG->AssignTopologicalOrder();
959 // Create a dummy node (which is not added to allnodes), that adds
960 // a reference to the root node, preventing it from being deleted,
961 // and tracking any changes of the root.
962 HandleSDNode Dummy(CurDAG->getRoot());
963 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
966 // Make sure that ISelPosition gets properly updated when nodes are deleted
967 // in calls made from this function.
968 ISelUpdater ISU(*CurDAG, ISelPosition);
970 // The AllNodes list is now topological-sorted. Visit the
971 // nodes by starting at the end of the list (the root of the
972 // graph) and preceding back toward the beginning (the entry
974 while (ISelPosition != CurDAG->allnodes_begin()) {
975 SDNode *Node = &*--ISelPosition;
976 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
977 // but there are currently some corner cases that it misses. Also, this
978 // makes it theoretically possible to disable the DAGCombiner.
979 if (Node->use_empty())
982 // When we are using non-default rounding modes or FP exception behavior
983 // FP operations are represented by StrictFP pseudo-operations. They
984 // need to be simplified here so that the target-specific instruction
985 // selectors know how to handle them.
987 // If the current node is a strict FP pseudo-op, the isStrictFPOp()
988 // function will provide the corresponding normal FP opcode to which the
989 // node should be mutated.
990 unsigned NormalFPOpc = ISD::UNDEF;
991 bool IsStrictFPOp = isStrictFPOp(Node, NormalFPOpc);
993 Node = MutateStrictFPToFP(Node, NormalFPOpc);
997 // FIXME: Add code here to attach an implicit def and use of
998 // target-specific FP environment registers.
1001 CurDAG->setRoot(Dummy.getValue());
1004 DEBUG(dbgs() << "===== Instruction selection ends:\n");
1006 PostprocessISelDAG();
1009 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
1010 for (const User *U : CPI->users()) {
1011 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1012 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1013 if (IID == Intrinsic::eh_exceptionpointer ||
1014 IID == Intrinsic::eh_exceptioncode)
1021 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1022 /// do other setup for EH landing-pad blocks.
1023 bool SelectionDAGISel::PrepareEHLandingPad() {
1024 MachineBasicBlock *MBB = FuncInfo->MBB;
1025 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1026 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1027 const TargetRegisterClass *PtrRC =
1028 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
1030 // Catchpads have one live-in register, which typically holds the exception
1032 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1033 if (hasExceptionPointerOrCodeUser(CPI)) {
1034 // Get or create the virtual register to hold the pointer or code. Mark
1035 // the live in physreg and copy into the vreg.
1036 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1037 assert(EHPhysReg && "target lacks exception pointer register");
1038 MBB->addLiveIn(EHPhysReg);
1039 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1040 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1041 TII->get(TargetOpcode::COPY), VReg)
1042 .addReg(EHPhysReg, RegState::Kill);
1047 if (!LLVMBB->isLandingPad())
1050 // Add a label to mark the beginning of the landing pad. Deletion of the
1051 // landing pad can thus be detected via the MachineModuleInfo.
1052 MCSymbol *Label = MF->addLandingPad(MBB);
1054 // Assign the call site to the landing pad's begin label.
1055 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1057 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1058 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1061 // Mark exception register as live in.
1062 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1063 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1065 // Mark exception selector register as live in.
1066 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1067 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1072 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1073 /// side-effect free and is either dead or folded into a generated instruction.
1074 /// Return false if it needs to be emitted.
1075 static bool isFoldedOrDeadInstruction(const Instruction *I,
1076 FunctionLoweringInfo *FuncInfo) {
1077 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1078 !isa<TerminatorInst>(I) && // Terminators aren't folded.
1079 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1080 !I->isEHPad() && // EH pad instructions aren't folded.
1081 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
1084 /// Set up SwiftErrorVals by going through the function. If the function has
1085 /// swifterror argument, it will be the first entry.
1086 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI,
1087 FunctionLoweringInfo *FuncInfo) {
1088 if (!TLI->supportSwiftError())
1091 FuncInfo->SwiftErrorVals.clear();
1092 FuncInfo->SwiftErrorVRegDefMap.clear();
1093 FuncInfo->SwiftErrorVRegUpwardsUse.clear();
1094 FuncInfo->SwiftErrorArg = nullptr;
1096 // Check if function has a swifterror argument.
1097 bool HaveSeenSwiftErrorArg = false;
1098 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end();
1100 if (AI->hasSwiftErrorAttr()) {
1101 assert(!HaveSeenSwiftErrorArg &&
1102 "Must have only one swifterror parameter");
1103 (void)HaveSeenSwiftErrorArg; // silence warning.
1104 HaveSeenSwiftErrorArg = true;
1105 FuncInfo->SwiftErrorArg = &*AI;
1106 FuncInfo->SwiftErrorVals.push_back(&*AI);
1109 for (const auto &LLVMBB : Fn)
1110 for (const auto &Inst : LLVMBB) {
1111 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst))
1112 if (Alloca->isSwiftError())
1113 FuncInfo->SwiftErrorVals.push_back(Alloca);
1117 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo,
1119 const TargetLowering *TLI,
1120 const TargetInstrInfo *TII,
1121 SelectionDAGBuilder *SDB) {
1122 if (!TLI->supportSwiftError())
1125 // We only need to do this when we have swifterror parameter or swifterror
1127 if (FuncInfo->SwiftErrorVals.empty())
1130 assert(FuncInfo->MBB == &*FuncInfo->MF->begin() &&
1131 "expected to insert into entry block");
1132 auto &DL = FuncInfo->MF->getDataLayout();
1133 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1134 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1135 // We will always generate a copy from the argument. It is always used at
1136 // least by the 'return' of the swifterror.
1137 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal)
1139 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1140 // Assign Undef to Vreg. We construct MI directly to make sure it works
1142 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(),
1143 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),
1146 // Keep FastIS informed about the value we just inserted.
1148 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1150 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg);
1154 /// Propagate swifterror values through the machine function CFG.
1155 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) {
1156 auto *TLI = FuncInfo->TLI;
1157 if (!TLI->supportSwiftError())
1160 // We only need to do this when we have swifterror parameter or swifterror
1162 if (FuncInfo->SwiftErrorVals.empty())
1165 // For each machine basic block in reverse post order.
1166 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF);
1167 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1171 MachineBasicBlock *MBB = *It;
1173 // For each swifterror value in the function.
1174 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1175 auto Key = std::make_pair(MBB, SwiftErrorVal);
1176 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1177 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key);
1178 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end();
1179 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0;
1180 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end();
1181 assert(!(UpwardsUse && !DownwardDef) &&
1182 "We can't have an upwards use but no downwards def");
1184 // If there is no upwards exposed use and an entry for the swifterror in
1185 // the def map for this value we don't need to do anything: We already
1186 // have a downward def for this basic block.
1187 if (!UpwardsUse && DownwardDef)
1190 // Otherwise we either have an upwards exposed use vreg that we need to
1191 // materialize or need to forward the downward def from predecessors.
1193 // Check whether we have a single vreg def from all predecessors.
1194 // Otherwise we need a phi.
1195 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs;
1196 SmallSet<const MachineBasicBlock*, 8> Visited;
1197 for (auto *Pred : MBB->predecessors()) {
1198 if (!Visited.insert(Pred).second)
1200 VRegs.push_back(std::make_pair(
1201 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal)));
1204 // We have a self-edge.
1205 // If there was no upwards use in this basic block there is now one: the
1206 // phi needs to use it self.
1209 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1210 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end());
1211 UUseVReg = UUseIt->second;
1215 // We need a phi node if we have more than one predecessor with different
1218 VRegs.size() >= 1 &&
1220 VRegs.begin(), VRegs.end(),
1221 [&](const std::pair<const MachineBasicBlock *, unsigned> &V)
1222 -> bool { return V.second != VRegs[0].second; }) !=
1225 // If there is no upwards exposed used and we don't need a phi just
1226 // forward the swifterror vreg from the predecessor(s).
1227 if (!UpwardsUse && !needPHI) {
1228 assert(!VRegs.empty() &&
1229 "No predecessors? The entry block should bail out earlier");
1230 // Just forward the swifterror vreg from the predecessor(s).
1231 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second);
1235 auto DLoc = isa<Instruction>(SwiftErrorVal)
1236 ? dyn_cast<Instruction>(SwiftErrorVal)->getDebugLoc()
1238 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo();
1240 // If we don't need a phi create a copy to the upward exposed vreg.
1243 unsigned DestReg = UUseVReg;
1244 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY),
1246 .addReg(VRegs[0].second);
1250 // We need a phi: if there is an upwards exposed use we already have a
1251 // destination virtual register number otherwise we generate a new one.
1252 auto &DL = FuncInfo->MF->getDataLayout();
1253 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1255 UpwardsUse ? UUseVReg
1256 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1257 MachineInstrBuilder SwiftErrorPHI =
1258 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc,
1259 TII->get(TargetOpcode::PHI), PHIVReg);
1260 for (auto BBRegPair : VRegs) {
1261 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first);
1264 // We did not have a definition in this block before: store the phi's vreg
1265 // as this block downward exposed def.
1267 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg);
1272 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1273 FastISelFailed = false;
1274 // Initialize the Fast-ISel state, if needed.
1275 FastISel *FastIS = nullptr;
1276 if (TM.Options.EnableFastISel)
1277 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1279 setupSwiftErrorVals(Fn, TLI, FuncInfo);
1281 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1283 // Lower arguments up front. An RPO iteration always visits the entry block
1285 assert(*RPOT.begin() == &Fn.getEntryBlock());
1288 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1289 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1290 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1295 // See if fast isel can lower the arguments.
1296 FastIS->startNewBlock();
1297 if (!FastIS->lowerArguments()) {
1298 FastISelFailed = true;
1299 // Fast isel failed to lower these arguments
1300 ++NumFastIselFailLowerArguments;
1302 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1304 &Fn.getEntryBlock());
1305 R << "FastISel didn't lower all arguments: "
1306 << ore::NV("Prototype", Fn.getType());
1307 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
1309 // Use SelectionDAG argument lowering
1311 CurDAG->setRoot(SDB->getControlRoot());
1313 CodeGenAndEmitDAG();
1316 // If we inserted any instructions at the beginning, make a note of
1317 // where they are, so we can be sure to emit subsequent instructions
1319 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1320 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1322 FastIS->setLastLocalValue(nullptr);
1324 createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB);
1326 // Iterate over all basic blocks in the function.
1327 for (const BasicBlock *LLVMBB : RPOT) {
1328 if (OptLevel != CodeGenOpt::None) {
1329 bool AllPredsVisited = true;
1330 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1332 if (!FuncInfo->VisitedBBs.count(*PI)) {
1333 AllPredsVisited = false;
1338 if (AllPredsVisited) {
1339 for (BasicBlock::const_iterator I = LLVMBB->begin();
1340 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1341 FuncInfo->ComputePHILiveOutRegInfo(PN);
1343 for (BasicBlock::const_iterator I = LLVMBB->begin();
1344 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1345 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1348 FuncInfo->VisitedBBs.insert(LLVMBB);
1351 BasicBlock::const_iterator const Begin =
1352 LLVMBB->getFirstNonPHI()->getIterator();
1353 BasicBlock::const_iterator const End = LLVMBB->end();
1354 BasicBlock::const_iterator BI = End;
1356 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1358 continue; // Some blocks like catchpads have no code or MBB.
1360 // Insert new instructions after any phi or argument setup code.
1361 FuncInfo->InsertPt = FuncInfo->MBB->end();
1363 // Setup an EH landing-pad block.
1364 FuncInfo->ExceptionPointerVirtReg = 0;
1365 FuncInfo->ExceptionSelectorVirtReg = 0;
1366 if (LLVMBB->isEHPad())
1367 if (!PrepareEHLandingPad())
1370 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1372 if (LLVMBB != &Fn.getEntryBlock())
1373 FastIS->startNewBlock();
1375 unsigned NumFastIselRemaining = std::distance(Begin, End);
1376 // Do FastISel on as many instructions as possible.
1377 for (; BI != Begin; --BI) {
1378 const Instruction *Inst = &*std::prev(BI);
1380 // If we no longer require this instruction, skip it.
1381 if (isFoldedOrDeadInstruction(Inst, FuncInfo) ||
1382 ElidedArgCopyInstrs.count(Inst)) {
1383 --NumFastIselRemaining;
1387 // Bottom-up: reset the insert pos at the top, after any local-value
1389 FastIS->recomputeInsertPt();
1391 // Try to select the instruction with FastISel.
1392 if (FastIS->selectInstruction(Inst)) {
1393 FastISelFailed = true;
1394 --NumFastIselRemaining;
1395 ++NumFastIselSuccess;
1396 // If fast isel succeeded, skip over all the folded instructions, and
1397 // then see if there is a load right before the selected instructions.
1398 // Try to fold the load if so.
1399 const Instruction *BeforeInst = Inst;
1400 while (BeforeInst != &*Begin) {
1401 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1402 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1405 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1406 BeforeInst->hasOneUse() &&
1407 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1408 // If we succeeded, don't re-select the load.
1409 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1410 --NumFastIselRemaining;
1411 ++NumFastIselSuccess;
1416 // Then handle certain instructions as single-LLVM-Instruction blocks.
1417 if (isa<CallInst>(Inst)) {
1418 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1419 Inst->getDebugLoc(), LLVMBB);
1421 R << "FastISel missed call";
1423 if (R.isEnabled() || EnableFastISelAbort) {
1424 std::string InstStrStorage;
1425 raw_string_ostream InstStr(InstStrStorage);
1428 R << ": " << InstStr.str();
1431 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
1433 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1434 !Inst->use_empty()) {
1435 unsigned &R = FuncInfo->ValueMap[Inst];
1437 R = FuncInfo->CreateRegs(Inst->getType());
1440 bool HadTailCall = false;
1441 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1442 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1444 // If the call was emitted as a tail call, we're done with the block.
1445 // We also need to delete any previously emitted instructions.
1447 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1452 // Recompute NumFastIselRemaining as Selection DAG instruction
1453 // selection may have handled the call, input args, etc.
1454 unsigned RemainingNow = std::distance(Begin, BI);
1455 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1456 NumFastIselRemaining = RemainingNow;
1460 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1461 Inst->getDebugLoc(), LLVMBB);
1463 bool ShouldAbort = EnableFastISelAbort;
1464 if (isa<TerminatorInst>(Inst)) {
1465 // Use a different message for terminator misses.
1466 R << "FastISel missed terminator";
1467 // Don't abort for terminator unless the level is really high
1468 ShouldAbort = (EnableFastISelAbort > 2);
1470 R << "FastISel missed";
1473 if (R.isEnabled() || EnableFastISelAbort) {
1474 std::string InstStrStorage;
1475 raw_string_ostream InstStr(InstStrStorage);
1477 R << ": " << InstStr.str();
1480 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1482 NumFastIselFailures += NumFastIselRemaining;
1486 FastIS->recomputeInsertPt();
1489 if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB)) {
1490 bool FunctionBasedInstrumentation =
1491 TLI->getSSPStackGuardCheck(*Fn.getParent());
1492 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1493 FunctionBasedInstrumentation);
1499 ++NumFastIselBlocks;
1502 // Run SelectionDAG instruction selection on the remainder of the block
1503 // not handled by FastISel. If FastISel is not run, this is the entire
1506 SelectBasicBlock(Begin, BI, HadTailCall);
1508 // But if FastISel was run, we already selected some of the block.
1509 // If we emitted a tail-call, we need to delete any previously emitted
1510 // instruction that follows it.
1511 if (HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1512 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1516 FuncInfo->PHINodesToUpdate.clear();
1517 ElidedArgCopyInstrs.clear();
1520 propagateSwiftErrorVRegs(FuncInfo);
1523 SDB->clearDanglingDebugInfo();
1524 SDB->SPDescriptor.resetPerFunctionState();
1527 /// Given that the input MI is before a partial terminator sequence TSeq, return
1528 /// true if M + TSeq also a partial terminator sequence.
1530 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1531 /// lowering copy vregs into physical registers, which are then passed into
1532 /// terminator instructors so we can satisfy ABI constraints. A partial
1533 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1534 /// may be the whole terminator sequence).
1535 static bool MIIsInTerminatorSequence(const MachineInstr &MI) {
1536 // If we do not have a copy or an implicit def, we return true if and only if
1537 // MI is a debug value.
1538 if (!MI.isCopy() && !MI.isImplicitDef())
1539 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1540 // physical registers if there is debug info associated with the terminator
1541 // of our mbb. We want to include said debug info in our terminator
1542 // sequence, so we return true in that case.
1543 return MI.isDebugValue();
1545 // We have left the terminator sequence if we are not doing one of the
1548 // 1. Copying a vreg into a physical register.
1549 // 2. Copying a vreg into a vreg.
1550 // 3. Defining a register via an implicit def.
1552 // OPI should always be a register definition...
1553 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
1554 if (!OPI->isReg() || !OPI->isDef())
1557 // Defining any register via an implicit def is always ok.
1558 if (MI.isImplicitDef())
1561 // Grab the copy source...
1562 MachineInstr::const_mop_iterator OPI2 = OPI;
1564 assert(OPI2 != MI.operands_end()
1565 && "Should have a copy implying we should have 2 arguments.");
1567 // Make sure that the copy dest is not a vreg when the copy source is a
1568 // physical register.
1569 if (!OPI2->isReg() ||
1570 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1571 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1577 /// Find the split point at which to splice the end of BB into its success stack
1578 /// protector check machine basic block.
1580 /// On many platforms, due to ABI constraints, terminators, even before register
1581 /// allocation, use physical registers. This creates an issue for us since
1582 /// physical registers at this point can not travel across basic
1583 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1584 /// when they enter functions and moves them through a sequence of copies back
1585 /// into the physical registers right before the terminator creating a
1586 /// ``Terminator Sequence''. This function is searching for the beginning of the
1587 /// terminator sequence so that we can ensure that we splice off not just the
1588 /// terminator, but additionally the copies that move the vregs into the
1589 /// physical registers.
1590 static MachineBasicBlock::iterator
1591 FindSplitPointForStackProtector(MachineBasicBlock *BB) {
1592 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1594 if (SplitPoint == BB->begin())
1597 MachineBasicBlock::iterator Start = BB->begin();
1598 MachineBasicBlock::iterator Previous = SplitPoint;
1601 while (MIIsInTerminatorSequence(*Previous)) {
1602 SplitPoint = Previous;
1603 if (Previous == Start)
1612 SelectionDAGISel::FinishBasicBlock() {
1613 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1614 << FuncInfo->PHINodesToUpdate.size() << "\n";
1615 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1616 dbgs() << "Node " << i << " : ("
1617 << FuncInfo->PHINodesToUpdate[i].first
1618 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1620 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1621 // PHI nodes in successors.
1622 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1623 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1624 assert(PHI->isPHI() &&
1625 "This is not a machine PHI node that we are updating!");
1626 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1628 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1631 // Handle stack protector.
1632 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1633 // The target provides a guard check function. There is no need to
1634 // generate error handling code or to split current basic block.
1635 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1637 // Add load and check to the basicblock.
1638 FuncInfo->MBB = ParentMBB;
1639 FuncInfo->InsertPt =
1640 FindSplitPointForStackProtector(ParentMBB);
1641 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1642 CurDAG->setRoot(SDB->getRoot());
1644 CodeGenAndEmitDAG();
1646 // Clear the Per-BB State.
1647 SDB->SPDescriptor.resetPerBBState();
1648 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1649 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1650 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1652 // Find the split point to split the parent mbb. At the same time copy all
1653 // physical registers used in the tail of parent mbb into virtual registers
1654 // before the split point and back into physical registers after the split
1655 // point. This prevents us needing to deal with Live-ins and many other
1656 // register allocation issues caused by us splitting the parent mbb. The
1657 // register allocator will clean up said virtual copies later on.
1658 MachineBasicBlock::iterator SplitPoint =
1659 FindSplitPointForStackProtector(ParentMBB);
1661 // Splice the terminator of ParentMBB into SuccessMBB.
1662 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1666 // Add compare/jump on neq/jump to the parent BB.
1667 FuncInfo->MBB = ParentMBB;
1668 FuncInfo->InsertPt = ParentMBB->end();
1669 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1670 CurDAG->setRoot(SDB->getRoot());
1672 CodeGenAndEmitDAG();
1674 // CodeGen Failure MBB if we have not codegened it yet.
1675 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1676 if (FailureMBB->empty()) {
1677 FuncInfo->MBB = FailureMBB;
1678 FuncInfo->InsertPt = FailureMBB->end();
1679 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1680 CurDAG->setRoot(SDB->getRoot());
1682 CodeGenAndEmitDAG();
1685 // Clear the Per-BB State.
1686 SDB->SPDescriptor.resetPerBBState();
1689 // Lower each BitTestBlock.
1690 for (auto &BTB : SDB->BitTestCases) {
1691 // Lower header first, if it wasn't already lowered
1693 // Set the current basic block to the mbb we wish to insert the code into
1694 FuncInfo->MBB = BTB.Parent;
1695 FuncInfo->InsertPt = FuncInfo->MBB->end();
1697 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1698 CurDAG->setRoot(SDB->getRoot());
1700 CodeGenAndEmitDAG();
1703 BranchProbability UnhandledProb = BTB.Prob;
1704 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1705 UnhandledProb -= BTB.Cases[j].ExtraProb;
1706 // Set the current basic block to the mbb we wish to insert the code into
1707 FuncInfo->MBB = BTB.Cases[j].ThisBB;
1708 FuncInfo->InsertPt = FuncInfo->MBB->end();
1711 // If all cases cover a contiguous range, it is not necessary to jump to
1712 // the default block after the last bit test fails. This is because the
1713 // range check during bit test header creation has guaranteed that every
1714 // case here doesn't go outside the range. In this case, there is no need
1715 // to perform the last bit test, as it will always be true. Instead, make
1716 // the second-to-last bit-test fall through to the target of the last bit
1717 // test, and delete the last bit test.
1719 MachineBasicBlock *NextMBB;
1720 if (BTB.ContiguousRange && j + 2 == ej) {
1721 // Second-to-last bit-test with contiguous range: fall through to the
1722 // target of the final bit test.
1723 NextMBB = BTB.Cases[j + 1].TargetBB;
1724 } else if (j + 1 == ej) {
1725 // For the last bit test, fall through to Default.
1726 NextMBB = BTB.Default;
1728 // Otherwise, fall through to the next bit test.
1729 NextMBB = BTB.Cases[j + 1].ThisBB;
1732 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1735 CurDAG->setRoot(SDB->getRoot());
1737 CodeGenAndEmitDAG();
1739 if (BTB.ContiguousRange && j + 2 == ej) {
1740 // Since we're not going to use the final bit test, remove it.
1741 BTB.Cases.pop_back();
1747 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1749 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1750 MachineBasicBlock *PHIBB = PHI->getParent();
1751 assert(PHI->isPHI() &&
1752 "This is not a machine PHI node that we are updating!");
1753 // This is "default" BB. We have two jumps to it. From "header" BB and
1754 // from last "case" BB, unless the latter was skipped.
1755 if (PHIBB == BTB.Default) {
1756 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1757 if (!BTB.ContiguousRange) {
1758 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1759 .addMBB(BTB.Cases.back().ThisBB);
1762 // One of "cases" BB.
1763 for (unsigned j = 0, ej = BTB.Cases.size();
1765 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1766 if (cBB->isSuccessor(PHIBB))
1767 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1771 SDB->BitTestCases.clear();
1773 // If the JumpTable record is filled in, then we need to emit a jump table.
1774 // Updating the PHI nodes is tricky in this case, since we need to determine
1775 // whether the PHI is a successor of the range check MBB or the jump table MBB
1776 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1777 // Lower header first, if it wasn't already lowered
1778 if (!SDB->JTCases[i].first.Emitted) {
1779 // Set the current basic block to the mbb we wish to insert the code into
1780 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1781 FuncInfo->InsertPt = FuncInfo->MBB->end();
1783 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1785 CurDAG->setRoot(SDB->getRoot());
1787 CodeGenAndEmitDAG();
1790 // Set the current basic block to the mbb we wish to insert the code into
1791 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1792 FuncInfo->InsertPt = FuncInfo->MBB->end();
1794 SDB->visitJumpTable(SDB->JTCases[i].second);
1795 CurDAG->setRoot(SDB->getRoot());
1797 CodeGenAndEmitDAG();
1800 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1802 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1803 MachineBasicBlock *PHIBB = PHI->getParent();
1804 assert(PHI->isPHI() &&
1805 "This is not a machine PHI node that we are updating!");
1806 // "default" BB. We can go there only from header BB.
1807 if (PHIBB == SDB->JTCases[i].second.Default)
1808 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1809 .addMBB(SDB->JTCases[i].first.HeaderBB);
1810 // JT BB. Just iterate over successors here
1811 if (FuncInfo->MBB->isSuccessor(PHIBB))
1812 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1815 SDB->JTCases.clear();
1817 // If we generated any switch lowering information, build and codegen any
1818 // additional DAGs necessary.
1819 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1820 // Set the current basic block to the mbb we wish to insert the code into
1821 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1822 FuncInfo->InsertPt = FuncInfo->MBB->end();
1824 // Determine the unique successors.
1825 SmallVector<MachineBasicBlock *, 2> Succs;
1826 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1827 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1828 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1830 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1831 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1832 CurDAG->setRoot(SDB->getRoot());
1834 CodeGenAndEmitDAG();
1836 // Remember the last block, now that any splitting is done, for use in
1837 // populating PHI nodes in successors.
1838 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1840 // Handle any PHI nodes in successors of this chunk, as if we were coming
1841 // from the original BB before switch expansion. Note that PHI nodes can
1842 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1843 // handle them the right number of times.
1844 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1845 FuncInfo->MBB = Succs[i];
1846 FuncInfo->InsertPt = FuncInfo->MBB->end();
1847 // FuncInfo->MBB may have been removed from the CFG if a branch was
1849 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1850 for (MachineBasicBlock::iterator
1851 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1852 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1853 MachineInstrBuilder PHI(*MF, MBBI);
1854 // This value for this PHI node is recorded in PHINodesToUpdate.
1855 for (unsigned pn = 0; ; ++pn) {
1856 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1857 "Didn't find PHI entry!");
1858 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1859 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1867 SDB->SwitchCases.clear();
1870 /// Create the scheduler. If a specific scheduler was specified
1871 /// via the SchedulerRegistry, use it, otherwise select the
1872 /// one preferred by the target.
1874 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1875 return ISHeuristic(this, OptLevel);
1878 //===----------------------------------------------------------------------===//
1879 // Helper functions used by the generated instruction selector.
1880 //===----------------------------------------------------------------------===//
1881 // Calls to these methods are generated by tblgen.
1883 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1884 /// the dag combiner simplified the 255, we still want to match. RHS is the
1885 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1886 /// specified in the .td file (e.g. 255).
1887 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1888 int64_t DesiredMaskS) const {
1889 const APInt &ActualMask = RHS->getAPIntValue();
1890 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1892 // If the actual mask exactly matches, success!
1893 if (ActualMask == DesiredMask)
1896 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1897 if (ActualMask.intersects(~DesiredMask))
1900 // Otherwise, the DAG Combiner may have proven that the value coming in is
1901 // either already zero or is not demanded. Check for known zero input bits.
1902 APInt NeededMask = DesiredMask & ~ActualMask;
1903 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1906 // TODO: check to see if missing bits are just not demanded.
1908 // Otherwise, this pattern doesn't match.
1912 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1913 /// the dag combiner simplified the 255, we still want to match. RHS is the
1914 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1915 /// specified in the .td file (e.g. 255).
1916 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1917 int64_t DesiredMaskS) const {
1918 const APInt &ActualMask = RHS->getAPIntValue();
1919 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1921 // If the actual mask exactly matches, success!
1922 if (ActualMask == DesiredMask)
1925 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1926 if (ActualMask.intersects(~DesiredMask))
1929 // Otherwise, the DAG Combiner may have proven that the value coming in is
1930 // either already zero or is not demanded. Check for known zero input bits.
1931 APInt NeededMask = DesiredMask & ~ActualMask;
1933 APInt KnownZero, KnownOne;
1934 CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
1936 // If all the missing bits in the or are already known to be set, match!
1937 if ((NeededMask & KnownOne) == NeededMask)
1940 // TODO: check to see if missing bits are just not demanded.
1942 // Otherwise, this pattern doesn't match.
1946 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1947 /// by tblgen. Others should not call it.
1948 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
1950 std::vector<SDValue> InOps;
1951 std::swap(InOps, Ops);
1953 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1954 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1955 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1956 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1958 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1959 if (InOps[e-1].getValueType() == MVT::Glue)
1960 --e; // Don't process a glue operand if it is here.
1963 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1964 if (!InlineAsm::isMemKind(Flags)) {
1965 // Just skip over this operand, copying the operands verbatim.
1966 Ops.insert(Ops.end(), InOps.begin()+i,
1967 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1968 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1970 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1971 "Memory operand with multiple values?");
1973 unsigned TiedToOperand;
1974 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
1975 // We need the constraint ID from the operand this is tied to.
1976 unsigned CurOp = InlineAsm::Op_FirstOperand;
1977 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1978 for (; TiedToOperand; --TiedToOperand) {
1979 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
1980 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1984 // Otherwise, this is a memory operand. Ask the target to select it.
1985 std::vector<SDValue> SelOps;
1986 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
1987 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
1988 report_fatal_error("Could not match memory address. Inline asm"
1991 // Add this to the output node.
1993 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1994 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
1995 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
1996 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2001 // Add the glue input back if present.
2002 if (e != InOps.size())
2003 Ops.push_back(InOps.back());
2006 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2009 static SDNode *findGlueUse(SDNode *N) {
2010 unsigned FlagResNo = N->getNumValues()-1;
2011 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2012 SDUse &Use = I.getUse();
2013 if (Use.getResNo() == FlagResNo)
2014 return Use.getUser();
2019 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
2020 /// This function recursively traverses up the operand chain, ignoring
2022 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
2023 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
2024 bool IgnoreChains) {
2025 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
2026 // greater than all of its (recursive) operands. If we scan to a point where
2027 // 'use' is smaller than the node we're scanning for, then we know we will
2030 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
2031 // happen because we scan down to newly selected nodes in the case of glue
2033 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
2036 // Don't revisit nodes if we already scanned it and didn't fail, we know we
2037 // won't fail if we scan it again.
2038 if (!Visited.insert(Use).second)
2041 for (const SDValue &Op : Use->op_values()) {
2042 // Ignore chain uses, they are validated by HandleMergeInputChains.
2043 if (Op.getValueType() == MVT::Other && IgnoreChains)
2046 SDNode *N = Op.getNode();
2048 if (Use == ImmedUse || Use == Root)
2049 continue; // We are not looking for immediate use.
2054 // Traverse up the operand chain.
2055 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
2061 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2062 /// operand node N of U during instruction selection that starts at Root.
2063 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
2064 SDNode *Root) const {
2065 if (OptLevel == CodeGenOpt::None) return false;
2066 return N.hasOneUse();
2069 /// IsLegalToFold - Returns true if the specific operand node N of
2070 /// U can be folded during instruction selection that starts at Root.
2071 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
2072 CodeGenOpt::Level OptLevel,
2073 bool IgnoreChains) {
2074 if (OptLevel == CodeGenOpt::None) return false;
2076 // If Root use can somehow reach N through a path that that doesn't contain
2077 // U then folding N would create a cycle. e.g. In the following
2078 // diagram, Root can reach N through X. If N is folded into into Root, then
2079 // X is both a predecessor and a successor of U.
2090 // * indicates nodes to be folded together.
2092 // If Root produces glue, then it gets (even more) interesting. Since it
2093 // will be "glued" together with its glue use in the scheduler, we need to
2094 // check if it might reach N.
2113 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2114 // (call it Fold), then X is a predecessor of GU and a successor of
2115 // Fold. But since Fold and GU are glued together, this will create
2116 // a cycle in the scheduling graph.
2118 // If the node has glue, walk down the graph to the "lowest" node in the
2120 EVT VT = Root->getValueType(Root->getNumValues()-1);
2121 while (VT == MVT::Glue) {
2122 SDNode *GU = findGlueUse(Root);
2126 VT = Root->getValueType(Root->getNumValues()-1);
2128 // If our query node has a glue result with a use, we've walked up it. If
2129 // the user (which has already been selected) has a chain or indirectly uses
2130 // the chain, our WalkChainUsers predicate will not consider it. Because of
2131 // this, we cannot ignore chains in this predicate.
2132 IgnoreChains = false;
2135 SmallPtrSet<SDNode*, 16> Visited;
2136 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
2139 void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2142 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2143 SelectInlineAsmMemoryOperands(Ops, DL);
2145 const EVT VTs[] = {MVT::Other, MVT::Glue};
2146 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops);
2148 ReplaceUses(N, New.getNode());
2149 CurDAG->RemoveDeadNode(N);
2152 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2154 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2155 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2157 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0),
2159 SDValue New = CurDAG->getCopyFromReg(
2160 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2162 ReplaceUses(Op, New.getNode());
2163 CurDAG->RemoveDeadNode(Op);
2166 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2168 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2169 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2170 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
2171 Op->getOperand(2).getValueType(),
2173 SDValue New = CurDAG->getCopyToReg(
2174 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2176 ReplaceUses(Op, New.getNode());
2177 CurDAG->RemoveDeadNode(Op);
2180 void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2181 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2184 /// GetVBR - decode a vbr encoding whose top bit is set.
2185 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
2186 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2187 assert(Val >= 128 && "Not a VBR");
2188 Val &= 127; // Remove first vbr bit.
2193 NextBits = MatcherTable[Idx++];
2194 Val |= (NextBits&127) << Shift;
2196 } while (NextBits & 128);
2201 /// When a match is complete, this method updates uses of interior chain results
2202 /// to use the new results.
2203 void SelectionDAGISel::UpdateChains(
2204 SDNode *NodeToMatch, SDValue InputChain,
2205 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2206 SmallVector<SDNode*, 4> NowDeadNodes;
2208 // Now that all the normal results are replaced, we replace the chain and
2209 // glue results if present.
2210 if (!ChainNodesMatched.empty()) {
2211 assert(InputChain.getNode() &&
2212 "Matched input chains but didn't produce a chain");
2213 // Loop over all of the nodes we matched that produced a chain result.
2214 // Replace all the chain results with the final chain we ended up with.
2215 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2216 SDNode *ChainNode = ChainNodesMatched[i];
2217 // If ChainNode is null, it's because we replaced it on a previous
2218 // iteration and we cleared it out of the map. Just skip it.
2222 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2223 "Deleted node left in chain");
2225 // Don't replace the results of the root node if we're doing a
2227 if (ChainNode == NodeToMatch && isMorphNodeTo)
2230 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2231 if (ChainVal.getValueType() == MVT::Glue)
2232 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2233 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2234 SelectionDAG::DAGNodeDeletedListener NDL(
2235 *CurDAG, [&](SDNode *N, SDNode *E) {
2236 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2237 static_cast<SDNode *>(nullptr));
2239 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
2241 // If the node became dead and we haven't already seen it, delete it.
2242 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2243 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2244 NowDeadNodes.push_back(ChainNode);
2248 if (!NowDeadNodes.empty())
2249 CurDAG->RemoveDeadNodes(NowDeadNodes);
2251 DEBUG(dbgs() << "ISEL: Match complete!\n");
2257 CR_LeadsToInteriorNode
2260 /// WalkChainUsers - Walk down the users of the specified chained node that is
2261 /// part of the pattern we're matching, looking at all of the users we find.
2262 /// This determines whether something is an interior node, whether we have a
2263 /// non-pattern node in between two pattern nodes (which prevent folding because
2264 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2265 /// between pattern nodes (in which case the TF becomes part of the pattern).
2267 /// The walk we do here is guaranteed to be small because we quickly get down to
2268 /// already selected nodes "below" us.
2270 WalkChainUsers(const SDNode *ChainedNode,
2271 SmallVectorImpl<SDNode *> &ChainedNodesInPattern,
2272 DenseMap<const SDNode *, ChainResult> &TokenFactorResult,
2273 SmallVectorImpl<SDNode *> &InteriorChainedNodes) {
2274 ChainResult Result = CR_Simple;
2276 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2277 E = ChainedNode->use_end(); UI != E; ++UI) {
2278 // Make sure the use is of the chain, not some other value we produce.
2279 if (UI.getUse().getValueType() != MVT::Other) continue;
2283 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
2286 // If we see an already-selected machine node, then we've gone beyond the
2287 // pattern that we're selecting down into the already selected chunk of the
2289 unsigned UserOpcode = User->getOpcode();
2290 if (User->isMachineOpcode() ||
2291 UserOpcode == ISD::CopyToReg ||
2292 UserOpcode == ISD::CopyFromReg ||
2293 UserOpcode == ISD::INLINEASM ||
2294 UserOpcode == ISD::EH_LABEL ||
2295 UserOpcode == ISD::LIFETIME_START ||
2296 UserOpcode == ISD::LIFETIME_END) {
2297 // If their node ID got reset to -1 then they've already been selected.
2298 // Treat them like a MachineOpcode.
2299 if (User->getNodeId() == -1)
2303 // If we have a TokenFactor, we handle it specially.
2304 if (User->getOpcode() != ISD::TokenFactor) {
2305 // If the node isn't a token factor and isn't part of our pattern, then it
2306 // must be a random chained node in between two nodes we're selecting.
2307 // This happens when we have something like:
2312 // Because we structurally match the load/store as a read/modify/write,
2313 // but the call is chained between them. We cannot fold in this case
2314 // because it would induce a cycle in the graph.
2315 if (!std::count(ChainedNodesInPattern.begin(),
2316 ChainedNodesInPattern.end(), User))
2317 return CR_InducesCycle;
2319 // Otherwise we found a node that is part of our pattern. For example in:
2323 // This would happen when we're scanning down from the load and see the
2324 // store as a user. Record that there is a use of ChainedNode that is
2325 // part of the pattern and keep scanning uses.
2326 Result = CR_LeadsToInteriorNode;
2327 InteriorChainedNodes.push_back(User);
2331 // If we found a TokenFactor, there are two cases to consider: first if the
2332 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2333 // uses of the TF are in our pattern) we just want to ignore it. Second,
2334 // the TokenFactor can be sandwiched in between two chained nodes, like so:
2340 // | \ DAG's like cheese
2343 // [TokenFactor] [Op]
2350 // In this case, the TokenFactor becomes part of our match and we rewrite it
2351 // as a new TokenFactor.
2353 // To distinguish these two cases, do a recursive walk down the uses.
2354 auto MemoizeResult = TokenFactorResult.find(User);
2355 bool Visited = MemoizeResult != TokenFactorResult.end();
2356 // Recursively walk chain users only if the result is not memoized.
2358 auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult,
2359 InteriorChainedNodes);
2360 MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first;
2362 switch (MemoizeResult->second) {
2364 // If the uses of the TokenFactor are just already-selected nodes, ignore
2365 // it, it is "below" our pattern.
2367 case CR_InducesCycle:
2368 // If the uses of the TokenFactor lead to nodes that are not part of our
2369 // pattern that are not selected, folding would turn this into a cycle,
2371 return CR_InducesCycle;
2372 case CR_LeadsToInteriorNode:
2373 break; // Otherwise, keep processing.
2376 // Okay, we know we're in the interesting interior case. The TokenFactor
2377 // is now going to be considered part of the pattern so that we rewrite its
2378 // uses (it may have uses that are not part of the pattern) with the
2379 // ultimate chain result of the generated code. We will also add its chain
2380 // inputs as inputs to the ultimate TokenFactor we create.
2381 Result = CR_LeadsToInteriorNode;
2383 ChainedNodesInPattern.push_back(User);
2384 InteriorChainedNodes.push_back(User);
2391 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2392 /// operation for when the pattern matched at least one node with a chains. The
2393 /// input vector contains a list of all of the chained nodes that we match. We
2394 /// must determine if this is a valid thing to cover (i.e. matching it won't
2395 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2396 /// be used as the input node chain for the generated nodes.
2398 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2399 SelectionDAG *CurDAG) {
2400 // Used for memoization. Without it WalkChainUsers could take exponential
2402 DenseMap<const SDNode *, ChainResult> TokenFactorResult;
2403 // Walk all of the chained nodes we've matched, recursively scanning down the
2404 // users of the chain result. This adds any TokenFactor nodes that are caught
2405 // in between chained nodes to the chained and interior nodes list.
2406 SmallVector<SDNode*, 3> InteriorChainedNodes;
2407 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2408 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2410 InteriorChainedNodes) == CR_InducesCycle)
2411 return SDValue(); // Would induce a cycle.
2414 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2415 // that we are interested in. Form our input TokenFactor node.
2416 SmallVector<SDValue, 3> InputChains;
2417 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2418 // Add the input chain of this node to the InputChains list (which will be
2419 // the operands of the generated TokenFactor) if it's not an interior node.
2420 SDNode *N = ChainNodesMatched[i];
2421 if (N->getOpcode() != ISD::TokenFactor) {
2422 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2425 // Otherwise, add the input chain.
2426 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2427 assert(InChain.getValueType() == MVT::Other && "Not a chain");
2428 InputChains.push_back(InChain);
2432 // If we have a token factor, we want to add all inputs of the token factor
2433 // that are not part of the pattern we're matching.
2434 for (const SDValue &Op : N->op_values()) {
2435 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2437 InputChains.push_back(Op);
2441 if (InputChains.size() == 1)
2442 return InputChains[0];
2443 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2444 MVT::Other, InputChains);
2447 /// MorphNode - Handle morphing a node in place for the selector.
2448 SDNode *SelectionDAGISel::
2449 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2450 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2451 // It is possible we're using MorphNodeTo to replace a node with no
2452 // normal results with one that has a normal result (or we could be
2453 // adding a chain) and the input could have glue and chains as well.
2454 // In this case we need to shift the operands down.
2455 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2456 // than the old isel though.
2457 int OldGlueResultNo = -1, OldChainResultNo = -1;
2459 unsigned NTMNumResults = Node->getNumValues();
2460 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2461 OldGlueResultNo = NTMNumResults-1;
2462 if (NTMNumResults != 1 &&
2463 Node->getValueType(NTMNumResults-2) == MVT::Other)
2464 OldChainResultNo = NTMNumResults-2;
2465 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2466 OldChainResultNo = NTMNumResults-1;
2468 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2469 // that this deletes operands of the old node that become dead.
2470 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2472 // MorphNodeTo can operate in two ways: if an existing node with the
2473 // specified operands exists, it can just return it. Otherwise, it
2474 // updates the node in place to have the requested operands.
2476 // If we updated the node in place, reset the node ID. To the isel,
2477 // this should be just like a newly allocated machine node.
2481 unsigned ResNumResults = Res->getNumValues();
2482 // Move the glue if needed.
2483 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2484 (unsigned)OldGlueResultNo != ResNumResults-1)
2485 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2486 SDValue(Res, ResNumResults-1));
2488 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2491 // Move the chain reference if needed.
2492 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2493 (unsigned)OldChainResultNo != ResNumResults-1)
2494 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2495 SDValue(Res, ResNumResults-1));
2497 // Otherwise, no replacement happened because the node already exists. Replace
2498 // Uses of the old node with the new one.
2500 CurDAG->ReplaceAllUsesWith(Node, Res);
2501 CurDAG->RemoveDeadNode(Node);
2507 /// CheckSame - Implements OP_CheckSame.
2508 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2509 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2511 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2512 // Accept if it is exactly the same as a previously recorded node.
2513 unsigned RecNo = MatcherTable[MatcherIndex++];
2514 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2515 return N == RecordedNodes[RecNo].first;
2518 /// CheckChildSame - Implements OP_CheckChildXSame.
2519 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2520 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2522 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes,
2524 if (ChildNo >= N.getNumOperands())
2525 return false; // Match fails if out of range child #.
2526 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2530 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2531 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2532 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2533 const SelectionDAGISel &SDISel) {
2534 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2537 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2538 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2539 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2540 const SelectionDAGISel &SDISel, SDNode *N) {
2541 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2544 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2545 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2547 uint16_t Opc = MatcherTable[MatcherIndex++];
2548 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2549 return N->getOpcode() == Opc;
2552 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2553 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2554 const TargetLowering *TLI, const DataLayout &DL) {
2555 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2556 if (N.getValueType() == VT) return true;
2558 // Handle the case when VT is iPTR.
2559 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2562 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2563 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2564 SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2566 if (ChildNo >= N.getNumOperands())
2567 return false; // Match fails if out of range child #.
2568 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2572 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2573 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2575 return cast<CondCodeSDNode>(N)->get() ==
2576 (ISD::CondCode)MatcherTable[MatcherIndex++];
2579 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2580 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2581 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2582 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2583 if (cast<VTSDNode>(N)->getVT() == VT)
2586 // Handle the case when VT is iPTR.
2587 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2590 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2591 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2593 int64_t Val = MatcherTable[MatcherIndex++];
2595 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2598 return C && C->getSExtValue() == Val;
2601 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2602 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2603 SDValue N, unsigned ChildNo) {
2604 if (ChildNo >= N.getNumOperands())
2605 return false; // Match fails if out of range child #.
2606 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2609 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2610 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2611 SDValue N, const SelectionDAGISel &SDISel) {
2612 int64_t Val = MatcherTable[MatcherIndex++];
2614 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2616 if (N->getOpcode() != ISD::AND) return false;
2618 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2619 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2622 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2623 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2624 SDValue N, const SelectionDAGISel &SDISel) {
2625 int64_t Val = MatcherTable[MatcherIndex++];
2627 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2629 if (N->getOpcode() != ISD::OR) return false;
2631 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2632 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2635 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2636 /// scope, evaluate the current node. If the current predicate is known to
2637 /// fail, set Result=true and return anything. If the current predicate is
2638 /// known to pass, set Result=false and return the MatcherIndex to continue
2639 /// with. If the current predicate is unknown, set Result=false and return the
2640 /// MatcherIndex to continue with.
2641 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2642 unsigned Index, SDValue N,
2644 const SelectionDAGISel &SDISel,
2645 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2646 switch (Table[Index++]) {
2649 return Index-1; // Could not evaluate this predicate.
2650 case SelectionDAGISel::OPC_CheckSame:
2651 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2653 case SelectionDAGISel::OPC_CheckChild0Same:
2654 case SelectionDAGISel::OPC_CheckChild1Same:
2655 case SelectionDAGISel::OPC_CheckChild2Same:
2656 case SelectionDAGISel::OPC_CheckChild3Same:
2657 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2658 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2660 case SelectionDAGISel::OPC_CheckPatternPredicate:
2661 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2663 case SelectionDAGISel::OPC_CheckPredicate:
2664 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2666 case SelectionDAGISel::OPC_CheckOpcode:
2667 Result = !::CheckOpcode(Table, Index, N.getNode());
2669 case SelectionDAGISel::OPC_CheckType:
2670 Result = !::CheckType(Table, Index, N, SDISel.TLI,
2671 SDISel.CurDAG->getDataLayout());
2673 case SelectionDAGISel::OPC_CheckChild0Type:
2674 case SelectionDAGISel::OPC_CheckChild1Type:
2675 case SelectionDAGISel::OPC_CheckChild2Type:
2676 case SelectionDAGISel::OPC_CheckChild3Type:
2677 case SelectionDAGISel::OPC_CheckChild4Type:
2678 case SelectionDAGISel::OPC_CheckChild5Type:
2679 case SelectionDAGISel::OPC_CheckChild6Type:
2680 case SelectionDAGISel::OPC_CheckChild7Type:
2681 Result = !::CheckChildType(
2682 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2683 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2685 case SelectionDAGISel::OPC_CheckCondCode:
2686 Result = !::CheckCondCode(Table, Index, N);
2688 case SelectionDAGISel::OPC_CheckValueType:
2689 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2690 SDISel.CurDAG->getDataLayout());
2692 case SelectionDAGISel::OPC_CheckInteger:
2693 Result = !::CheckInteger(Table, Index, N);
2695 case SelectionDAGISel::OPC_CheckChild0Integer:
2696 case SelectionDAGISel::OPC_CheckChild1Integer:
2697 case SelectionDAGISel::OPC_CheckChild2Integer:
2698 case SelectionDAGISel::OPC_CheckChild3Integer:
2699 case SelectionDAGISel::OPC_CheckChild4Integer:
2700 Result = !::CheckChildInteger(Table, Index, N,
2701 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2703 case SelectionDAGISel::OPC_CheckAndImm:
2704 Result = !::CheckAndImm(Table, Index, N, SDISel);
2706 case SelectionDAGISel::OPC_CheckOrImm:
2707 Result = !::CheckOrImm(Table, Index, N, SDISel);
2715 /// FailIndex - If this match fails, this is the index to continue with.
2718 /// NodeStack - The node stack when the scope was formed.
2719 SmallVector<SDValue, 4> NodeStack;
2721 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2722 unsigned NumRecordedNodes;
2724 /// NumMatchedMemRefs - The number of matched memref entries.
2725 unsigned NumMatchedMemRefs;
2727 /// InputChain/InputGlue - The current chain/glue
2728 SDValue InputChain, InputGlue;
2730 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2731 bool HasChainNodesMatched;
2734 /// \\brief A DAG update listener to keep the matching state
2735 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2736 /// change the DAG while matching. X86 addressing mode matcher is an example
2738 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2740 SDNode **NodeToMatch;
2741 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
2742 SmallVectorImpl<MatchScope> &MatchScopes;
2745 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2746 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2747 SmallVectorImpl<MatchScope> &MS)
2748 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2749 RecordedNodes(RN), MatchScopes(MS) {}
2751 void NodeDeleted(SDNode *N, SDNode *E) override {
2752 // Some early-returns here to avoid the search if we deleted the node or
2753 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2754 // do, so it's unnecessary to update matching state at that point).
2755 // Neither of these can occur currently because we only install this
2756 // update listener during matching a complex patterns.
2757 if (!E || E->isMachineOpcode())
2759 // Check if NodeToMatch was updated.
2760 if (N == *NodeToMatch)
2762 // Performing linear search here does not matter because we almost never
2763 // run this code. You'd have to have a CSE during complex pattern
2765 for (auto &I : RecordedNodes)
2766 if (I.first.getNode() == N)
2769 for (auto &I : MatchScopes)
2770 for (auto &J : I.NodeStack)
2771 if (J.getNode() == N)
2776 } // end anonymous namespace
2778 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
2779 const unsigned char *MatcherTable,
2780 unsigned TableSize) {
2781 // FIXME: Should these even be selected? Handle these cases in the caller?
2782 switch (NodeToMatch->getOpcode()) {
2785 case ISD::EntryToken: // These nodes remain the same.
2786 case ISD::BasicBlock:
2788 case ISD::RegisterMask:
2789 case ISD::HANDLENODE:
2790 case ISD::MDNODE_SDNODE:
2791 case ISD::TargetConstant:
2792 case ISD::TargetConstantFP:
2793 case ISD::TargetConstantPool:
2794 case ISD::TargetFrameIndex:
2795 case ISD::TargetExternalSymbol:
2797 case ISD::TargetBlockAddress:
2798 case ISD::TargetJumpTable:
2799 case ISD::TargetGlobalTLSAddress:
2800 case ISD::TargetGlobalAddress:
2801 case ISD::TokenFactor:
2802 case ISD::CopyFromReg:
2803 case ISD::CopyToReg:
2805 case ISD::LIFETIME_START:
2806 case ISD::LIFETIME_END:
2807 NodeToMatch->setNodeId(-1); // Mark selected.
2809 case ISD::AssertSext:
2810 case ISD::AssertZext:
2811 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2812 NodeToMatch->getOperand(0));
2813 CurDAG->RemoveDeadNode(NodeToMatch);
2815 case ISD::INLINEASM:
2816 Select_INLINEASM(NodeToMatch);
2818 case ISD::READ_REGISTER:
2819 Select_READ_REGISTER(NodeToMatch);
2821 case ISD::WRITE_REGISTER:
2822 Select_WRITE_REGISTER(NodeToMatch);
2825 Select_UNDEF(NodeToMatch);
2829 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2831 // Set up the node stack with NodeToMatch as the only node on the stack.
2832 SmallVector<SDValue, 8> NodeStack;
2833 SDValue N = SDValue(NodeToMatch, 0);
2834 NodeStack.push_back(N);
2836 // MatchScopes - Scopes used when matching, if a match failure happens, this
2837 // indicates where to continue checking.
2838 SmallVector<MatchScope, 8> MatchScopes;
2840 // RecordedNodes - This is the set of nodes that have been recorded by the
2841 // state machine. The second value is the parent of the node, or null if the
2842 // root is recorded.
2843 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2845 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2847 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2849 // These are the current input chain and glue for use when generating nodes.
2850 // Various Emit operations change these. For example, emitting a copytoreg
2851 // uses and updates these.
2852 SDValue InputChain, InputGlue;
2854 // ChainNodesMatched - If a pattern matches nodes that have input/output
2855 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2856 // which ones they are. The result is captured into this list so that we can
2857 // update the chain results when the pattern is complete.
2858 SmallVector<SDNode*, 3> ChainNodesMatched;
2860 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2861 NodeToMatch->dump(CurDAG);
2864 // Determine where to start the interpreter. Normally we start at opcode #0,
2865 // but if the state machine starts with an OPC_SwitchOpcode, then we
2866 // accelerate the first lookup (which is guaranteed to be hot) with the
2867 // OpcodeOffset table.
2868 unsigned MatcherIndex = 0;
2870 if (!OpcodeOffset.empty()) {
2871 // Already computed the OpcodeOffset table, just index into it.
2872 if (N.getOpcode() < OpcodeOffset.size())
2873 MatcherIndex = OpcodeOffset[N.getOpcode()];
2874 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2876 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2877 // Otherwise, the table isn't computed, but the state machine does start
2878 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2879 // is the first time we're selecting an instruction.
2882 // Get the size of this case.
2883 unsigned CaseSize = MatcherTable[Idx++];
2885 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2886 if (CaseSize == 0) break;
2888 // Get the opcode, add the index to the table.
2889 uint16_t Opc = MatcherTable[Idx++];
2890 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2891 if (Opc >= OpcodeOffset.size())
2892 OpcodeOffset.resize((Opc+1)*2);
2893 OpcodeOffset[Opc] = Idx;
2897 // Okay, do the lookup for the first opcode.
2898 if (N.getOpcode() < OpcodeOffset.size())
2899 MatcherIndex = OpcodeOffset[N.getOpcode()];
2903 assert(MatcherIndex < TableSize && "Invalid index");
2905 unsigned CurrentOpcodeIndex = MatcherIndex;
2907 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2910 // Okay, the semantics of this operation are that we should push a scope
2911 // then evaluate the first child. However, pushing a scope only to have
2912 // the first check fail (which then pops it) is inefficient. If we can
2913 // determine immediately that the first check (or first several) will
2914 // immediately fail, don't even bother pushing a scope for them.
2918 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2919 if (NumToSkip & 128)
2920 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2921 // Found the end of the scope with no match.
2922 if (NumToSkip == 0) {
2927 FailIndex = MatcherIndex+NumToSkip;
2929 unsigned MatcherIndexOfPredicate = MatcherIndex;
2930 (void)MatcherIndexOfPredicate; // silence warning.
2932 // If we can't evaluate this predicate without pushing a scope (e.g. if
2933 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2934 // push the scope and evaluate the full predicate chain.
2936 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2937 Result, *this, RecordedNodes);
2941 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2942 << "index " << MatcherIndexOfPredicate
2943 << ", continuing at " << FailIndex << "\n");
2944 ++NumDAGIselRetries;
2946 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2947 // move to the next case.
2948 MatcherIndex = FailIndex;
2951 // If the whole scope failed to match, bail.
2952 if (FailIndex == 0) break;
2954 // Push a MatchScope which indicates where to go if the first child fails
2956 MatchScope NewEntry;
2957 NewEntry.FailIndex = FailIndex;
2958 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2959 NewEntry.NumRecordedNodes = RecordedNodes.size();
2960 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2961 NewEntry.InputChain = InputChain;
2962 NewEntry.InputGlue = InputGlue;
2963 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2964 MatchScopes.push_back(NewEntry);
2967 case OPC_RecordNode: {
2968 // Remember this node, it may end up being an operand in the pattern.
2969 SDNode *Parent = nullptr;
2970 if (NodeStack.size() > 1)
2971 Parent = NodeStack[NodeStack.size()-2].getNode();
2972 RecordedNodes.push_back(std::make_pair(N, Parent));
2976 case OPC_RecordChild0: case OPC_RecordChild1:
2977 case OPC_RecordChild2: case OPC_RecordChild3:
2978 case OPC_RecordChild4: case OPC_RecordChild5:
2979 case OPC_RecordChild6: case OPC_RecordChild7: {
2980 unsigned ChildNo = Opcode-OPC_RecordChild0;
2981 if (ChildNo >= N.getNumOperands())
2982 break; // Match fails if out of range child #.
2984 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2988 case OPC_RecordMemRef:
2989 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2992 case OPC_CaptureGlueInput:
2993 // If the current node has an input glue, capture it in InputGlue.
2994 if (N->getNumOperands() != 0 &&
2995 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2996 InputGlue = N->getOperand(N->getNumOperands()-1);
2999 case OPC_MoveChild: {
3000 unsigned ChildNo = MatcherTable[MatcherIndex++];
3001 if (ChildNo >= N.getNumOperands())
3002 break; // Match fails if out of range child #.
3003 N = N.getOperand(ChildNo);
3004 NodeStack.push_back(N);
3008 case OPC_MoveChild0: case OPC_MoveChild1:
3009 case OPC_MoveChild2: case OPC_MoveChild3:
3010 case OPC_MoveChild4: case OPC_MoveChild5:
3011 case OPC_MoveChild6: case OPC_MoveChild7: {
3012 unsigned ChildNo = Opcode-OPC_MoveChild0;
3013 if (ChildNo >= N.getNumOperands())
3014 break; // Match fails if out of range child #.
3015 N = N.getOperand(ChildNo);
3016 NodeStack.push_back(N);
3020 case OPC_MoveParent:
3021 // Pop the current node off the NodeStack.
3022 NodeStack.pop_back();
3023 assert(!NodeStack.empty() && "Node stack imbalance!");
3024 N = NodeStack.back();
3028 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3031 case OPC_CheckChild0Same: case OPC_CheckChild1Same:
3032 case OPC_CheckChild2Same: case OPC_CheckChild3Same:
3033 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3034 Opcode-OPC_CheckChild0Same))
3038 case OPC_CheckPatternPredicate:
3039 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
3041 case OPC_CheckPredicate:
3042 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3046 case OPC_CheckComplexPat: {
3047 unsigned CPNum = MatcherTable[MatcherIndex++];
3048 unsigned RecNo = MatcherTable[MatcherIndex++];
3049 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3051 // If target can modify DAG during matching, keep the matching state
3053 std::unique_ptr<MatchStateUpdater> MSU;
3054 if (ComplexPatternFuncMutatesDAG())
3055 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3058 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3059 RecordedNodes[RecNo].first, CPNum,
3064 case OPC_CheckOpcode:
3065 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3069 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3070 CurDAG->getDataLayout()))
3074 case OPC_SwitchOpcode: {
3075 unsigned CurNodeOpcode = N.getOpcode();
3076 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3079 // Get the size of this case.
3080 CaseSize = MatcherTable[MatcherIndex++];
3082 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3083 if (CaseSize == 0) break;
3085 uint16_t Opc = MatcherTable[MatcherIndex++];
3086 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3088 // If the opcode matches, then we will execute this case.
3089 if (CurNodeOpcode == Opc)
3092 // Otherwise, skip over this case.
3093 MatcherIndex += CaseSize;
3096 // If no cases matched, bail out.
3097 if (CaseSize == 0) break;
3099 // Otherwise, execute the case we found.
3100 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
3101 << " to " << MatcherIndex << "\n");
3105 case OPC_SwitchType: {
3106 MVT CurNodeVT = N.getSimpleValueType();
3107 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3110 // Get the size of this case.
3111 CaseSize = MatcherTable[MatcherIndex++];
3113 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3114 if (CaseSize == 0) break;
3116 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3117 if (CaseVT == MVT::iPTR)
3118 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3120 // If the VT matches, then we will execute this case.
3121 if (CurNodeVT == CaseVT)
3124 // Otherwise, skip over this case.
3125 MatcherIndex += CaseSize;
3128 // If no cases matched, bail out.
3129 if (CaseSize == 0) break;
3131 // Otherwise, execute the case we found.
3132 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3133 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
3136 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
3137 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
3138 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
3139 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
3140 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3141 CurDAG->getDataLayout(),
3142 Opcode - OPC_CheckChild0Type))
3145 case OPC_CheckCondCode:
3146 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3148 case OPC_CheckValueType:
3149 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3150 CurDAG->getDataLayout()))
3153 case OPC_CheckInteger:
3154 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3156 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
3157 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
3158 case OPC_CheckChild4Integer:
3159 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3160 Opcode-OPC_CheckChild0Integer)) break;
3162 case OPC_CheckAndImm:
3163 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3165 case OPC_CheckOrImm:
3166 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3169 case OPC_CheckFoldableChainNode: {
3170 assert(NodeStack.size() != 1 && "No parent node");
3171 // Verify that all intermediate nodes between the root and this one have
3173 bool HasMultipleUses = false;
3174 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
3175 if (!NodeStack[i].getNode()->hasOneUse()) {
3176 HasMultipleUses = true;
3179 if (HasMultipleUses) break;
3181 // Check to see that the target thinks this is profitable to fold and that
3182 // we can fold it without inducing cycles in the graph.
3183 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3185 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3186 NodeToMatch, OptLevel,
3187 true/*We validate our own chains*/))
3192 case OPC_EmitInteger: {
3193 MVT::SimpleValueType VT =
3194 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3195 int64_t Val = MatcherTable[MatcherIndex++];
3197 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3198 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3199 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3203 case OPC_EmitRegister: {
3204 MVT::SimpleValueType VT =
3205 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3206 unsigned RegNo = MatcherTable[MatcherIndex++];
3207 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3208 CurDAG->getRegister(RegNo, VT), nullptr));
3211 case OPC_EmitRegister2: {
3212 // For targets w/ more than 256 register names, the register enum
3213 // values are stored in two bytes in the matcher table (just like
3215 MVT::SimpleValueType VT =
3216 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3217 unsigned RegNo = MatcherTable[MatcherIndex++];
3218 RegNo |= MatcherTable[MatcherIndex++] << 8;
3219 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3220 CurDAG->getRegister(RegNo, VT), nullptr));
3224 case OPC_EmitConvertToTarget: {
3225 // Convert from IMM/FPIMM to target version.
3226 unsigned RecNo = MatcherTable[MatcherIndex++];
3227 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3228 SDValue Imm = RecordedNodes[RecNo].first;
3230 if (Imm->getOpcode() == ISD::Constant) {
3231 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3232 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3233 Imm.getValueType());
3234 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3235 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3236 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3237 Imm.getValueType());
3240 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3244 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3245 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3246 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3247 // These are space-optimized forms of OPC_EmitMergeInputChains.
3248 assert(!InputChain.getNode() &&
3249 "EmitMergeInputChains should be the first chain producing node");
3250 assert(ChainNodesMatched.empty() &&
3251 "Should only have one EmitMergeInputChains per match");
3253 // Read all of the chained nodes.
3254 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3255 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3256 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3258 // FIXME: What if other value results of the node have uses not matched
3260 if (ChainNodesMatched.back() != NodeToMatch &&
3261 !RecordedNodes[RecNo].first.hasOneUse()) {
3262 ChainNodesMatched.clear();
3266 // Merge the input chains if they are not intra-pattern references.
3267 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3269 if (!InputChain.getNode())
3270 break; // Failed to merge.
3274 case OPC_EmitMergeInputChains: {
3275 assert(!InputChain.getNode() &&
3276 "EmitMergeInputChains should be the first chain producing node");
3277 // This node gets a list of nodes we matched in the input that have
3278 // chains. We want to token factor all of the input chains to these nodes
3279 // together. However, if any of the input chains is actually one of the
3280 // nodes matched in this pattern, then we have an intra-match reference.
3281 // Ignore these because the newly token factored chain should not refer to
3283 unsigned NumChains = MatcherTable[MatcherIndex++];
3284 assert(NumChains != 0 && "Can't TF zero chains");
3286 assert(ChainNodesMatched.empty() &&
3287 "Should only have one EmitMergeInputChains per match");
3289 // Read all of the chained nodes.
3290 for (unsigned i = 0; i != NumChains; ++i) {
3291 unsigned RecNo = MatcherTable[MatcherIndex++];
3292 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3293 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3295 // FIXME: What if other value results of the node have uses not matched
3297 if (ChainNodesMatched.back() != NodeToMatch &&
3298 !RecordedNodes[RecNo].first.hasOneUse()) {
3299 ChainNodesMatched.clear();
3304 // If the inner loop broke out, the match fails.
3305 if (ChainNodesMatched.empty())
3308 // Merge the input chains if they are not intra-pattern references.
3309 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3311 if (!InputChain.getNode())
3312 break; // Failed to merge.
3317 case OPC_EmitCopyToReg: {
3318 unsigned RecNo = MatcherTable[MatcherIndex++];
3319 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3320 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3322 if (!InputChain.getNode())
3323 InputChain = CurDAG->getEntryNode();
3325 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3326 DestPhysReg, RecordedNodes[RecNo].first,
3329 InputGlue = InputChain.getValue(1);
3333 case OPC_EmitNodeXForm: {
3334 unsigned XFormNo = MatcherTable[MatcherIndex++];
3335 unsigned RecNo = MatcherTable[MatcherIndex++];
3336 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3337 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3338 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3341 case OPC_Coverage: {
3342 // This is emitted right before MorphNode/EmitNode.
3343 // So it should be safe to assume that this node has been selected
3344 unsigned index = MatcherTable[MatcherIndex++];
3345 index |= (MatcherTable[MatcherIndex++] << 8);
3346 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3347 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3351 case OPC_EmitNode: case OPC_MorphNodeTo:
3352 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
3353 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
3354 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3355 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3356 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3357 // Get the result VT list.
3359 // If this is one of the compressed forms, get the number of VTs based
3360 // on the Opcode. Otherwise read the next byte from the table.
3361 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3362 NumVTs = Opcode - OPC_MorphNodeTo0;
3363 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3364 NumVTs = Opcode - OPC_EmitNode0;
3366 NumVTs = MatcherTable[MatcherIndex++];
3367 SmallVector<EVT, 4> VTs;
3368 for (unsigned i = 0; i != NumVTs; ++i) {
3369 MVT::SimpleValueType VT =
3370 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3371 if (VT == MVT::iPTR)
3372 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3376 if (EmitNodeInfo & OPFL_Chain)
3377 VTs.push_back(MVT::Other);
3378 if (EmitNodeInfo & OPFL_GlueOutput)
3379 VTs.push_back(MVT::Glue);
3381 // This is hot code, so optimize the two most common cases of 1 and 2
3384 if (VTs.size() == 1)
3385 VTList = CurDAG->getVTList(VTs[0]);
3386 else if (VTs.size() == 2)
3387 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3389 VTList = CurDAG->getVTList(VTs);
3391 // Get the operand list.
3392 unsigned NumOps = MatcherTable[MatcherIndex++];
3393 SmallVector<SDValue, 8> Ops;
3394 for (unsigned i = 0; i != NumOps; ++i) {
3395 unsigned RecNo = MatcherTable[MatcherIndex++];
3397 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3399 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3400 Ops.push_back(RecordedNodes[RecNo].first);
3403 // If there are variadic operands to add, handle them now.
3404 if (EmitNodeInfo & OPFL_VariadicInfo) {
3405 // Determine the start index to copy from.
3406 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3407 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3408 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3409 "Invalid variadic node");
3410 // Copy all of the variadic operands, not including a potential glue
3412 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3414 SDValue V = NodeToMatch->getOperand(i);
3415 if (V.getValueType() == MVT::Glue) break;
3420 // If this has chain/glue inputs, add them.
3421 if (EmitNodeInfo & OPFL_Chain)
3422 Ops.push_back(InputChain);
3423 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3424 Ops.push_back(InputGlue);
3427 SDNode *Res = nullptr;
3428 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3429 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3430 if (!IsMorphNodeTo) {
3431 // If this is a normal EmitNode command, just create the new node and
3432 // add the results to the RecordedNodes list.
3433 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3436 // Add all the non-glue/non-chain results to the RecordedNodes list.
3437 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3438 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3439 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3443 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3444 "NodeToMatch was removed partway through selection");
3445 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
3447 auto &Chain = ChainNodesMatched;
3448 assert((!E || !is_contained(Chain, N)) &&
3449 "Chain node replaced during MorphNode");
3450 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end());
3452 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3455 // If the node had chain/glue results, update our notion of the current
3457 if (EmitNodeInfo & OPFL_GlueOutput) {
3458 InputGlue = SDValue(Res, VTs.size()-1);
3459 if (EmitNodeInfo & OPFL_Chain)
3460 InputChain = SDValue(Res, VTs.size()-2);
3461 } else if (EmitNodeInfo & OPFL_Chain)
3462 InputChain = SDValue(Res, VTs.size()-1);
3464 // If the OPFL_MemRefs glue is set on this node, slap all of the
3465 // accumulated memrefs onto it.
3467 // FIXME: This is vastly incorrect for patterns with multiple outputs
3468 // instructions that access memory and for ComplexPatterns that match
3470 if (EmitNodeInfo & OPFL_MemRefs) {
3471 // Only attach load or store memory operands if the generated
3472 // instruction may load or store.
3473 const MCInstrDesc &MCID = TII->get(TargetOpc);
3474 bool mayLoad = MCID.mayLoad();
3475 bool mayStore = MCID.mayStore();
3477 unsigned NumMemRefs = 0;
3478 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3479 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3480 if ((*I)->isLoad()) {
3483 } else if ((*I)->isStore()) {
3491 MachineSDNode::mmo_iterator MemRefs =
3492 MF->allocateMemRefsArray(NumMemRefs);
3494 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3495 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3496 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3497 if ((*I)->isLoad()) {
3500 } else if ((*I)->isStore()) {
3508 cast<MachineSDNode>(Res)
3509 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3513 << (IsMorphNodeTo ? "Morphed" : "Created")
3514 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3516 // If this was a MorphNodeTo then we're completely done!
3517 if (IsMorphNodeTo) {
3518 // Update chain uses.
3519 UpdateChains(Res, InputChain, ChainNodesMatched, true);
3525 case OPC_CompleteMatch: {
3526 // The match has been completed, and any new nodes (if any) have been
3527 // created. Patch up references to the matched dag to use the newly
3529 unsigned NumResults = MatcherTable[MatcherIndex++];
3531 for (unsigned i = 0; i != NumResults; ++i) {
3532 unsigned ResSlot = MatcherTable[MatcherIndex++];
3534 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3536 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3537 SDValue Res = RecordedNodes[ResSlot].first;
3539 assert(i < NodeToMatch->getNumValues() &&
3540 NodeToMatch->getValueType(i) != MVT::Other &&
3541 NodeToMatch->getValueType(i) != MVT::Glue &&
3542 "Invalid number of results to complete!");
3543 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3544 NodeToMatch->getValueType(i) == MVT::iPTR ||
3545 Res.getValueType() == MVT::iPTR ||
3546 NodeToMatch->getValueType(i).getSizeInBits() ==
3547 Res.getValueSizeInBits()) &&
3548 "invalid replacement");
3549 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3552 // Update chain uses.
3553 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3555 // If the root node defines glue, we need to update it to the glue result.
3556 // TODO: This never happens in our tests and I think it can be removed /
3557 // replaced with an assert, but if we do it this the way the change is
3559 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3561 InputGlue.getNode())
3562 CurDAG->ReplaceAllUsesOfValueWith(
3563 SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue);
3565 assert(NodeToMatch->use_empty() &&
3566 "Didn't replace all uses of the node?");
3567 CurDAG->RemoveDeadNode(NodeToMatch);
3573 // If the code reached this point, then the match failed. See if there is
3574 // another child to try in the current 'Scope', otherwise pop it until we
3575 // find a case to check.
3576 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
3577 ++NumDAGIselRetries;
3579 if (MatchScopes.empty()) {
3580 CannotYetSelect(NodeToMatch);
3584 // Restore the interpreter state back to the point where the scope was
3586 MatchScope &LastScope = MatchScopes.back();
3587 RecordedNodes.resize(LastScope.NumRecordedNodes);
3589 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3590 N = NodeStack.back();
3592 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3593 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3594 MatcherIndex = LastScope.FailIndex;
3596 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3598 InputChain = LastScope.InputChain;
3599 InputGlue = LastScope.InputGlue;
3600 if (!LastScope.HasChainNodesMatched)
3601 ChainNodesMatched.clear();
3603 // Check to see what the offset is at the new MatcherIndex. If it is zero
3604 // we have reached the end of this scope, otherwise we have another child
3605 // in the current scope to try.
3606 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3607 if (NumToSkip & 128)
3608 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3610 // If we have another child in this scope to match, update FailIndex and
3612 if (NumToSkip != 0) {
3613 LastScope.FailIndex = MatcherIndex+NumToSkip;
3617 // End of this scope, pop it and try the next child in the containing
3619 MatchScopes.pop_back();
3624 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3626 raw_string_ostream Msg(msg);
3627 Msg << "Cannot select: ";
3629 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3630 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3631 N->getOpcode() != ISD::INTRINSIC_VOID) {
3632 N->printrFull(Msg, CurDAG);
3633 Msg << "\nIn function: " << MF->getName();
3635 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3637 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3638 if (iid < Intrinsic::num_intrinsics)
3639 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None);
3640 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3641 Msg << "target intrinsic %" << TII->getName(iid);
3643 Msg << "unknown intrinsic #" << iid;
3645 report_fatal_error(Msg.str());
3648 char SelectionDAGISel::ID = 0;