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/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineOperand.h"
43 #include "llvm/CodeGen/MachinePassRegistry.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/MachineValueType.h"
46 #include "llvm/CodeGen/SchedulerRegistry.h"
47 #include "llvm/CodeGen/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGISel.h"
49 #include "llvm/CodeGen/SelectionDAGNodes.h"
50 #include "llvm/CodeGen/StackProtector.h"
51 #include "llvm/CodeGen/ValueTypes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DebugInfoMetadata.h"
55 #include "llvm/IR/DebugLoc.h"
56 #include "llvm/IR/DiagnosticInfo.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/InlineAsm.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/User.h"
67 #include "llvm/MC/MCInstrDesc.h"
68 #include "llvm/MC/MCRegisterInfo.h"
69 #include "llvm/Pass.h"
70 #include "llvm/Support/BranchProbability.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/KnownBits.h"
78 #include "llvm/Support/Timer.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Target/TargetInstrInfo.h"
81 #include "llvm/Target/TargetIntrinsicInfo.h"
82 #include "llvm/Target/TargetLowering.h"
83 #include "llvm/Target/TargetMachine.h"
84 #include "llvm/Target/TargetOptions.h"
85 #include "llvm/Target/TargetRegisterInfo.h"
86 #include "llvm/Target/TargetSubtargetInfo.h"
87 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
99 #define DEBUG_TYPE "isel"
101 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
102 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
103 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
104 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
105 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
106 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
107 STATISTIC(NumFastIselFailLowerArguments,
108 "Number of entry blocks where fast isel failed to lower arguments");
110 static cl::opt<int> EnableFastISelAbort(
111 "fast-isel-abort", cl::Hidden,
112 cl::desc("Enable abort calls when \"fast\" instruction selection "
113 "fails to lower an instruction: 0 disable the abort, 1 will "
114 "abort but for args, calls and terminators, 2 will also "
115 "abort for argument lowering, and 3 will never fallback "
116 "to SelectionDAG."));
118 static cl::opt<bool> EnableFastISelFallbackReport(
119 "fast-isel-report-on-fallback", cl::Hidden,
120 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
121 "falls back to SelectionDAG."));
125 cl::desc("use Machine Branch Probability Info"),
126 cl::init(true), cl::Hidden);
129 static cl::opt<std::string>
130 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
131 cl::desc("Only display the basic block whose name "
132 "matches this for all view-*-dags options"));
134 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
135 cl::desc("Pop up a window to show dags before the first "
136 "dag combine pass"));
138 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
139 cl::desc("Pop up a window to show dags before legalize types"));
141 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
142 cl::desc("Pop up a window to show dags before legalize"));
144 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
145 cl::desc("Pop up a window to show dags before the second "
146 "dag combine pass"));
148 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
149 cl::desc("Pop up a window to show dags before the post legalize types"
150 " dag combine pass"));
152 ViewISelDAGs("view-isel-dags", cl::Hidden,
153 cl::desc("Pop up a window to show isel dags as they are selected"));
155 ViewSchedDAGs("view-sched-dags", cl::Hidden,
156 cl::desc("Pop up a window to show sched dags as they are processed"));
158 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
159 cl::desc("Pop up a window to show SUnit dags after they are processed"));
161 static const bool ViewDAGCombine1 = false,
162 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
163 ViewDAGCombine2 = false,
164 ViewDAGCombineLT = false,
165 ViewISelDAGs = false, ViewSchedDAGs = false,
166 ViewSUnitDAGs = false;
169 //===---------------------------------------------------------------------===//
171 /// RegisterScheduler class - Track the registration of instruction schedulers.
173 //===---------------------------------------------------------------------===//
174 MachinePassRegistry RegisterScheduler::Registry;
176 //===---------------------------------------------------------------------===//
178 /// ISHeuristic command line option for instruction schedulers.
180 //===---------------------------------------------------------------------===//
181 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
182 RegisterPassParser<RegisterScheduler>>
183 ISHeuristic("pre-RA-sched",
184 cl::init(&createDefaultScheduler), cl::Hidden,
185 cl::desc("Instruction schedulers available (before register"
188 static RegisterScheduler
189 defaultListDAGScheduler("default", "Best scheduler for the target",
190 createDefaultScheduler);
194 //===--------------------------------------------------------------------===//
195 /// \brief This class is used by SelectionDAGISel to temporarily override
196 /// the optimization level on a per-function basis.
197 class OptLevelChanger {
198 SelectionDAGISel &IS;
199 CodeGenOpt::Level SavedOptLevel;
203 OptLevelChanger(SelectionDAGISel &ISel,
204 CodeGenOpt::Level NewOptLevel) : IS(ISel) {
205 SavedOptLevel = IS.OptLevel;
206 if (NewOptLevel == SavedOptLevel)
208 IS.OptLevel = NewOptLevel;
209 IS.TM.setOptLevel(NewOptLevel);
210 DEBUG(dbgs() << "\nChanging optimization level for Function "
211 << IS.MF->getFunction()->getName() << "\n");
212 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
213 << " ; After: -O" << NewOptLevel << "\n");
214 SavedFastISel = IS.TM.Options.EnableFastISel;
215 if (NewOptLevel == CodeGenOpt::None) {
216 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
217 DEBUG(dbgs() << "\tFastISel is "
218 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
224 if (IS.OptLevel == SavedOptLevel)
226 DEBUG(dbgs() << "\nRestoring optimization level for Function "
227 << IS.MF->getFunction()->getName() << "\n");
228 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
229 << " ; After: -O" << SavedOptLevel << "\n");
230 IS.OptLevel = SavedOptLevel;
231 IS.TM.setOptLevel(SavedOptLevel);
232 IS.TM.setFastISel(SavedFastISel);
236 //===--------------------------------------------------------------------===//
237 /// createDefaultScheduler - This creates an instruction scheduler appropriate
239 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
240 CodeGenOpt::Level OptLevel) {
241 const TargetLowering *TLI = IS->TLI;
242 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
244 // Try first to see if the Target has its own way of selecting a scheduler
245 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
246 return SchedulerCtor(IS, OptLevel);
249 if (OptLevel == CodeGenOpt::None ||
250 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
251 TLI->getSchedulingPreference() == Sched::Source)
252 return createSourceListDAGScheduler(IS, OptLevel);
253 if (TLI->getSchedulingPreference() == Sched::RegPressure)
254 return createBURRListDAGScheduler(IS, OptLevel);
255 if (TLI->getSchedulingPreference() == Sched::Hybrid)
256 return createHybridListDAGScheduler(IS, OptLevel);
257 if (TLI->getSchedulingPreference() == Sched::VLIW)
258 return createVLIWDAGScheduler(IS, OptLevel);
259 assert(TLI->getSchedulingPreference() == Sched::ILP &&
260 "Unknown sched type!");
261 return createILPListDAGScheduler(IS, OptLevel);
264 } // end namespace llvm
266 // EmitInstrWithCustomInserter - This method should be implemented by targets
267 // that mark instructions with the 'usesCustomInserter' flag. These
268 // instructions are special in various ways, which require special support to
269 // insert. The specified MachineInstr is created but not inserted into any
270 // basic blocks, and this method is called to expand it into a sequence of
271 // instructions, potentially also creating new basic blocks and control flow.
272 // When new basic blocks are inserted and the edges from MBB to its successors
273 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
276 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
277 MachineBasicBlock *MBB) const {
279 dbgs() << "If a target marks an instruction with "
280 "'usesCustomInserter', it must implement "
281 "TargetLowering::EmitInstrWithCustomInserter!";
283 llvm_unreachable(nullptr);
286 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
287 SDNode *Node) const {
288 assert(!MI.hasPostISelHook() &&
289 "If a target marks an instruction with 'hasPostISelHook', "
290 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
293 //===----------------------------------------------------------------------===//
294 // SelectionDAGISel code
295 //===----------------------------------------------------------------------===//
297 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
298 CodeGenOpt::Level OL) :
299 MachineFunctionPass(ID), TM(tm),
300 FuncInfo(new FunctionLoweringInfo()),
301 CurDAG(new SelectionDAG(tm, OL)),
302 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
306 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
307 initializeBranchProbabilityInfoWrapperPassPass(
308 *PassRegistry::getPassRegistry());
309 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
310 initializeTargetLibraryInfoWrapperPassPass(
311 *PassRegistry::getPassRegistry());
314 SelectionDAGISel::~SelectionDAGISel() {
320 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
321 if (OptLevel != CodeGenOpt::None)
322 AU.addRequired<AAResultsWrapperPass>();
323 AU.addRequired<GCModuleInfo>();
324 AU.addRequired<StackProtector>();
325 AU.addPreserved<StackProtector>();
326 AU.addPreserved<GCModuleInfo>();
327 AU.addRequired<TargetLibraryInfoWrapperPass>();
328 if (UseMBPI && OptLevel != CodeGenOpt::None)
329 AU.addRequired<BranchProbabilityInfoWrapperPass>();
330 MachineFunctionPass::getAnalysisUsage(AU);
333 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
334 /// may trap on it. In this case we have to split the edge so that the path
335 /// through the predecessor block that doesn't go to the phi block doesn't
336 /// execute the possibly trapping instruction.
338 /// This is required for correctness, so it must be done at -O0.
340 static void SplitCriticalSideEffectEdges(Function &Fn) {
341 // Loop for blocks with phi nodes.
342 for (BasicBlock &BB : Fn) {
343 PHINode *PN = dyn_cast<PHINode>(BB.begin());
347 // For each block with a PHI node, check to see if any of the input values
348 // are potentially trapping constant expressions. Constant expressions are
349 // the only potentially trapping value that can occur as the argument to a
351 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
352 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
353 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
354 if (!CE || !CE->canTrap()) continue;
356 // The only case we have to worry about is when the edge is critical.
357 // Since this block has a PHI Node, we assume it has multiple input
358 // edges: check to see if the pred has multiple successors.
359 BasicBlock *Pred = PN->getIncomingBlock(i);
360 if (Pred->getTerminator()->getNumSuccessors() == 1)
363 // Okay, we have to split this edge.
365 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
366 CriticalEdgeSplittingOptions().setMergeIdenticalEdges());
372 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
373 // If we already selected that function, we do not need to run SDISel.
374 if (mf.getProperties().hasProperty(
375 MachineFunctionProperties::Property::Selected))
377 // Do some sanity-checking on the command-line options.
378 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
379 "-fast-isel-abort > 0 requires -fast-isel");
381 const Function &Fn = *mf.getFunction();
384 // Reset the target options before resetting the optimization
386 // FIXME: This is a horrible hack and should be processed via
387 // codegen looking at the optimization level explicitly when
388 // it wants to look at it.
389 TM.resetTargetOptions(Fn);
390 // Reset OptLevel to None for optnone functions.
391 CodeGenOpt::Level NewOptLevel = OptLevel;
392 if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
393 NewOptLevel = CodeGenOpt::None;
394 OptLevelChanger OLC(*this, NewOptLevel);
396 TII = MF->getSubtarget().getInstrInfo();
397 TLI = MF->getSubtarget().getTargetLowering();
398 RegInfo = &MF->getRegInfo();
399 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
400 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
401 ORE = make_unique<OptimizationRemarkEmitter>(&Fn);
403 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
405 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn));
407 CurDAG->init(*MF, *ORE);
408 FuncInfo->set(Fn, *MF, CurDAG);
410 // Now get the optional analyzes if we want to.
411 // This is based on the possibly changed OptLevel (after optnone is taken
412 // into account). That's unfortunate but OK because it just means we won't
413 // ask for passes that have been required anyway.
415 if (UseMBPI && OptLevel != CodeGenOpt::None)
416 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
418 FuncInfo->BPI = nullptr;
420 if (OptLevel != CodeGenOpt::None)
421 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
425 SDB->init(GFI, AA, LibInfo);
427 MF->setHasInlineAsm(false);
429 FuncInfo->SplitCSR = false;
431 // We split CSR if the target supports it for the given function
432 // and the function has only return exits.
433 if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
434 FuncInfo->SplitCSR = true;
436 // Collect all the return blocks.
437 for (const BasicBlock &BB : Fn) {
438 if (!succ_empty(&BB))
441 const TerminatorInst *Term = BB.getTerminator();
442 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
445 // Bail out if the exit block is not Return nor Unreachable.
446 FuncInfo->SplitCSR = false;
451 MachineBasicBlock *EntryMBB = &MF->front();
452 if (FuncInfo->SplitCSR)
453 // This performs initialization so lowering for SplitCSR will be correct.
454 TLI->initializeSplitCSR(EntryMBB);
456 SelectAllBasicBlocks(Fn);
457 if (FastISelFailed && EnableFastISelFallbackReport) {
458 DiagnosticInfoISelFallback DiagFallback(Fn);
459 Fn.getContext().diagnose(DiagFallback);
462 // If the first basic block in the function has live ins that need to be
463 // copied into vregs, emit the copies into the top of the block before
464 // emitting the code for the block.
465 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
466 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
468 // Insert copies in the entry block and the return blocks.
469 if (FuncInfo->SplitCSR) {
470 SmallVector<MachineBasicBlock*, 4> Returns;
471 // Collect all the return blocks.
472 for (MachineBasicBlock &MBB : mf) {
473 if (!MBB.succ_empty())
476 MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
477 if (Term != MBB.end() && Term->isReturn()) {
478 Returns.push_back(&MBB);
482 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
485 DenseMap<unsigned, unsigned> LiveInMap;
486 if (!FuncInfo->ArgDbgValues.empty())
487 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
488 E = RegInfo->livein_end(); LI != E; ++LI)
490 LiveInMap.insert(std::make_pair(LI->first, LI->second));
492 // Insert DBG_VALUE instructions for function arguments to the entry block.
493 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
494 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
495 bool hasFI = MI->getOperand(0).isFI();
497 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
498 if (TargetRegisterInfo::isPhysicalRegister(Reg))
499 EntryMBB->insert(EntryMBB->begin(), MI);
501 MachineInstr *Def = RegInfo->getVRegDef(Reg);
503 MachineBasicBlock::iterator InsertPos = Def;
504 // FIXME: VR def may not be in entry block.
505 Def->getParent()->insert(std::next(InsertPos), MI);
507 DEBUG(dbgs() << "Dropping debug info for dead vreg"
508 << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
511 // If Reg is live-in then update debug info to track its copy in a vreg.
512 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
513 if (LDI != LiveInMap.end()) {
514 assert(!hasFI && "There's no handling of frame pointer updating here yet "
516 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
517 MachineBasicBlock::iterator InsertPos = Def;
518 const MDNode *Variable = MI->getDebugVariable();
519 const MDNode *Expr = MI->getDebugExpression();
520 DebugLoc DL = MI->getDebugLoc();
521 bool IsIndirect = MI->isIndirectDebugValue();
522 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
523 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
524 "Expected inlined-at fields to agree");
525 // Def is never a terminator here, so it is ok to increment InsertPos.
526 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
527 IsIndirect, LDI->second, Offset, Variable, Expr);
529 // If this vreg is directly copied into an exported register then
530 // that COPY instructions also need DBG_VALUE, if it is the only
531 // user of LDI->second.
532 MachineInstr *CopyUseMI = nullptr;
533 for (MachineRegisterInfo::use_instr_iterator
534 UI = RegInfo->use_instr_begin(LDI->second),
535 E = RegInfo->use_instr_end(); UI != E; ) {
536 MachineInstr *UseMI = &*(UI++);
537 if (UseMI->isDebugValue()) continue;
538 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
539 CopyUseMI = UseMI; continue;
541 // Otherwise this is another use or second copy use.
542 CopyUseMI = nullptr; break;
545 // Use MI's debug location, which describes where Variable was
546 // declared, rather than whatever is attached to CopyUseMI.
547 MachineInstr *NewMI =
548 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
549 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
550 MachineBasicBlock::iterator Pos = CopyUseMI;
551 EntryMBB->insertAfter(Pos, NewMI);
556 // Determine if there are any calls in this machine function.
557 MachineFrameInfo &MFI = MF->getFrameInfo();
558 for (const auto &MBB : *MF) {
559 if (MFI.hasCalls() && MF->hasInlineAsm())
562 for (const auto &MI : MBB) {
563 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
564 if ((MCID.isCall() && !MCID.isReturn()) ||
565 MI.isStackAligningInlineAsm()) {
566 MFI.setHasCalls(true);
568 if (MI.isInlineAsm()) {
569 MF->setHasInlineAsm(true);
574 // Determine if there is a call to setjmp in the machine function.
575 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
577 // Replace forward-declared registers with the registers containing
578 // the desired value.
579 MachineRegisterInfo &MRI = MF->getRegInfo();
580 for (DenseMap<unsigned, unsigned>::iterator
581 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
583 unsigned From = I->first;
584 unsigned To = I->second;
585 // If To is also scheduled to be replaced, find what its ultimate
588 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
592 // Make sure the new register has a sufficiently constrained register class.
593 if (TargetRegisterInfo::isVirtualRegister(From) &&
594 TargetRegisterInfo::isVirtualRegister(To))
595 MRI.constrainRegClass(To, MRI.getRegClass(From));
599 // Replacing one register with another won't touch the kill flags.
600 // We need to conservatively clear the kill flags as a kill on the old
601 // register might dominate existing uses of the new register.
602 if (!MRI.use_empty(To))
603 MRI.clearKillFlags(From);
604 MRI.replaceRegWith(From, To);
607 TLI->finalizeLowering(*MF);
609 // Release function-specific state. SDB and CurDAG are already cleared
613 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
614 DEBUG(MF->print(dbgs()));
619 static void reportFastISelFailure(MachineFunction &MF,
620 OptimizationRemarkEmitter &ORE,
621 OptimizationRemarkMissed &R,
623 // Print the function name explicitly if we don't have a debug location (which
624 // makes the diagnostic less useful) or if we're going to emit a raw error.
625 if (!R.getLocation().isValid() || ShouldAbort)
626 R << (" (in function: " + MF.getName() + ")").str();
629 report_fatal_error(R.getMsg());
634 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
635 BasicBlock::const_iterator End,
637 // Lower the instructions. If a call is emitted as a tail call, cease emitting
638 // nodes for this block.
639 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
640 if (!ElidedArgCopyInstrs.count(&*I))
644 // Make sure the root of the DAG is up-to-date.
645 CurDAG->setRoot(SDB->getControlRoot());
646 HadTailCall = SDB->HasTailCall;
649 // Final step, emit the lowered DAG as machine code.
653 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
654 SmallPtrSet<SDNode*, 16> VisitedNodes;
655 SmallVector<SDNode*, 128> Worklist;
657 Worklist.push_back(CurDAG->getRoot().getNode());
662 SDNode *N = Worklist.pop_back_val();
664 // If we've already seen this node, ignore it.
665 if (!VisitedNodes.insert(N).second)
668 // Otherwise, add all chain operands to the worklist.
669 for (const SDValue &Op : N->op_values())
670 if (Op.getValueType() == MVT::Other)
671 Worklist.push_back(Op.getNode());
673 // If this is a CopyToReg with a vreg dest, process it.
674 if (N->getOpcode() != ISD::CopyToReg)
677 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
678 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
681 // Ignore non-scalar or non-integer values.
682 SDValue Src = N->getOperand(2);
683 EVT SrcVT = Src.getValueType();
684 if (!SrcVT.isInteger() || SrcVT.isVector())
687 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
688 CurDAG->computeKnownBits(Src, Known);
689 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
690 } while (!Worklist.empty());
693 void SelectionDAGISel::CodeGenAndEmitDAG() {
694 StringRef GroupName = "sdag";
695 StringRef GroupDescription = "Instruction Selection and Scheduling";
696 std::string BlockName;
697 int BlockNumber = -1;
699 bool MatchFilterBB = false; (void)MatchFilterBB;
701 // Pre-type legalization allow creation of any node types.
702 CurDAG->NewNodesMustHaveLegalTypes = false;
705 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
706 FilterDAGBasicBlockName ==
707 FuncInfo->MBB->getBasicBlock()->getName().str());
710 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
711 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
715 BlockNumber = FuncInfo->MBB->getNumber();
717 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
719 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
720 << " '" << BlockName << "'\n"; CurDAG->dump());
722 if (ViewDAGCombine1 && MatchFilterBB)
723 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
725 // Run the DAG combiner in pre-legalize mode.
727 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
728 GroupDescription, TimePassesIsEnabled);
729 CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
732 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
733 << " '" << BlockName << "'\n"; CurDAG->dump());
735 // Second step, hack on the DAG until it only uses operations and types that
736 // the target supports.
737 if (ViewLegalizeTypesDAGs && MatchFilterBB)
738 CurDAG->viewGraph("legalize-types input for " + BlockName);
742 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
743 GroupDescription, TimePassesIsEnabled);
744 Changed = CurDAG->LegalizeTypes();
747 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
748 << " '" << BlockName << "'\n"; CurDAG->dump());
750 // Only allow creation of legal node types.
751 CurDAG->NewNodesMustHaveLegalTypes = true;
754 if (ViewDAGCombineLT && MatchFilterBB)
755 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
757 // Run the DAG combiner in post-type-legalize mode.
759 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
760 GroupName, GroupDescription, TimePassesIsEnabled);
761 CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
764 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
765 << " '" << BlockName << "'\n"; CurDAG->dump());
770 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
771 GroupDescription, TimePassesIsEnabled);
772 Changed = CurDAG->LegalizeVectors();
776 DEBUG(dbgs() << "Vector-legalized selection DAG: BB#" << BlockNumber
777 << " '" << BlockName << "'\n"; CurDAG->dump());
780 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
781 GroupDescription, TimePassesIsEnabled);
782 CurDAG->LegalizeTypes();
785 DEBUG(dbgs() << "Vector/type-legalized selection DAG: BB#" << BlockNumber
786 << " '" << BlockName << "'\n"; CurDAG->dump());
788 if (ViewDAGCombineLT && MatchFilterBB)
789 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
791 // Run the DAG combiner in post-type-legalize mode.
793 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
794 GroupName, GroupDescription, TimePassesIsEnabled);
795 CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
798 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
799 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
802 if (ViewLegalizeDAGs && MatchFilterBB)
803 CurDAG->viewGraph("legalize input for " + BlockName);
806 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
807 GroupDescription, TimePassesIsEnabled);
811 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
812 << " '" << BlockName << "'\n"; CurDAG->dump());
814 if (ViewDAGCombine2 && MatchFilterBB)
815 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
817 // Run the DAG combiner in post-legalize mode.
819 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
820 GroupDescription, TimePassesIsEnabled);
821 CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
824 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
825 << " '" << BlockName << "'\n"; CurDAG->dump());
827 if (OptLevel != CodeGenOpt::None)
828 ComputeLiveOutVRegInfo();
830 if (ViewISelDAGs && MatchFilterBB)
831 CurDAG->viewGraph("isel input for " + BlockName);
833 // Third, instruction select all of the operations to machine code, adding the
834 // code to the MachineBasicBlock.
836 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
837 GroupDescription, TimePassesIsEnabled);
838 DoInstructionSelection();
841 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
842 << " '" << BlockName << "'\n"; CurDAG->dump());
844 if (ViewSchedDAGs && MatchFilterBB)
845 CurDAG->viewGraph("scheduler input for " + BlockName);
847 // Schedule machine code.
848 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
850 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
851 GroupDescription, TimePassesIsEnabled);
852 Scheduler->Run(CurDAG, FuncInfo->MBB);
855 if (ViewSUnitDAGs && MatchFilterBB)
856 Scheduler->viewGraph();
858 // Emit machine code to BB. This can change 'BB' to the last block being
860 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
862 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
863 GroupDescription, TimePassesIsEnabled);
865 // FuncInfo->InsertPt is passed by reference and set to the end of the
866 // scheduled instructions.
867 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
870 // If the block was split, make sure we update any references that are used to
871 // update PHI nodes later on.
872 if (FirstMBB != LastMBB)
873 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
875 // Free the scheduler state.
877 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
878 GroupDescription, TimePassesIsEnabled);
882 // Free the SelectionDAG state, now that we're finished with it.
888 /// ISelUpdater - helper class to handle updates of the instruction selection
890 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
891 SelectionDAG::allnodes_iterator &ISelPosition;
894 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
895 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
897 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
898 /// deleted is the current ISelPosition node, update ISelPosition.
900 void NodeDeleted(SDNode *N, SDNode *E) override {
901 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
906 } // end anonymous namespace
908 void SelectionDAGISel::DoInstructionSelection() {
909 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
910 << FuncInfo->MBB->getNumber()
911 << " '" << FuncInfo->MBB->getName() << "'\n");
915 // Select target instructions for the DAG.
917 // Number all nodes with a topological order and set DAGSize.
918 DAGSize = CurDAG->AssignTopologicalOrder();
920 // Create a dummy node (which is not added to allnodes), that adds
921 // a reference to the root node, preventing it from being deleted,
922 // and tracking any changes of the root.
923 HandleSDNode Dummy(CurDAG->getRoot());
924 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
927 // Make sure that ISelPosition gets properly updated when nodes are deleted
928 // in calls made from this function.
929 ISelUpdater ISU(*CurDAG, ISelPosition);
931 // The AllNodes list is now topological-sorted. Visit the
932 // nodes by starting at the end of the list (the root of the
933 // graph) and preceding back toward the beginning (the entry
935 while (ISelPosition != CurDAG->allnodes_begin()) {
936 SDNode *Node = &*--ISelPosition;
937 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
938 // but there are currently some corner cases that it misses. Also, this
939 // makes it theoretically possible to disable the DAGCombiner.
940 if (Node->use_empty())
943 // When we are using non-default rounding modes or FP exception behavior
944 // FP operations are represented by StrictFP pseudo-operations. They
945 // need to be simplified here so that the target-specific instruction
946 // selectors know how to handle them.
948 // If the current node is a strict FP pseudo-op, the isStrictFPOp()
949 // function will provide the corresponding normal FP opcode to which the
950 // node should be mutated.
952 // FIXME: The backends need a way to handle FP constraints.
953 if (Node->isStrictFPOpcode())
954 Node = CurDAG->mutateStrictFPToFP(Node);
959 CurDAG->setRoot(Dummy.getValue());
962 DEBUG(dbgs() << "===== Instruction selection ends:\n");
964 PostprocessISelDAG();
967 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
968 for (const User *U : CPI->users()) {
969 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
970 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
971 if (IID == Intrinsic::eh_exceptionpointer ||
972 IID == Intrinsic::eh_exceptioncode)
979 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
980 /// do other setup for EH landing-pad blocks.
981 bool SelectionDAGISel::PrepareEHLandingPad() {
982 MachineBasicBlock *MBB = FuncInfo->MBB;
983 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
984 const BasicBlock *LLVMBB = MBB->getBasicBlock();
985 const TargetRegisterClass *PtrRC =
986 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
988 // Catchpads have one live-in register, which typically holds the exception
990 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
991 if (hasExceptionPointerOrCodeUser(CPI)) {
992 // Get or create the virtual register to hold the pointer or code. Mark
993 // the live in physreg and copy into the vreg.
994 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
995 assert(EHPhysReg && "target lacks exception pointer register");
996 MBB->addLiveIn(EHPhysReg);
997 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
998 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
999 TII->get(TargetOpcode::COPY), VReg)
1000 .addReg(EHPhysReg, RegState::Kill);
1005 if (!LLVMBB->isLandingPad())
1008 // Add a label to mark the beginning of the landing pad. Deletion of the
1009 // landing pad can thus be detected via the MachineModuleInfo.
1010 MCSymbol *Label = MF->addLandingPad(MBB);
1012 // Assign the call site to the landing pad's begin label.
1013 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1015 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1016 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1019 // Mark exception register as live in.
1020 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1021 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1023 // Mark exception selector register as live in.
1024 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1025 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1030 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1031 /// side-effect free and is either dead or folded into a generated instruction.
1032 /// Return false if it needs to be emitted.
1033 static bool isFoldedOrDeadInstruction(const Instruction *I,
1034 FunctionLoweringInfo *FuncInfo) {
1035 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1036 !isa<TerminatorInst>(I) && // Terminators aren't folded.
1037 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1038 !I->isEHPad() && // EH pad instructions aren't folded.
1039 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
1042 /// Set up SwiftErrorVals by going through the function. If the function has
1043 /// swifterror argument, it will be the first entry.
1044 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI,
1045 FunctionLoweringInfo *FuncInfo) {
1046 if (!TLI->supportSwiftError())
1049 FuncInfo->SwiftErrorVals.clear();
1050 FuncInfo->SwiftErrorVRegDefMap.clear();
1051 FuncInfo->SwiftErrorVRegUpwardsUse.clear();
1052 FuncInfo->SwiftErrorArg = nullptr;
1054 // Check if function has a swifterror argument.
1055 bool HaveSeenSwiftErrorArg = false;
1056 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end();
1058 if (AI->hasSwiftErrorAttr()) {
1059 assert(!HaveSeenSwiftErrorArg &&
1060 "Must have only one swifterror parameter");
1061 (void)HaveSeenSwiftErrorArg; // silence warning.
1062 HaveSeenSwiftErrorArg = true;
1063 FuncInfo->SwiftErrorArg = &*AI;
1064 FuncInfo->SwiftErrorVals.push_back(&*AI);
1067 for (const auto &LLVMBB : Fn)
1068 for (const auto &Inst : LLVMBB) {
1069 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst))
1070 if (Alloca->isSwiftError())
1071 FuncInfo->SwiftErrorVals.push_back(Alloca);
1075 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo,
1077 const TargetLowering *TLI,
1078 const TargetInstrInfo *TII,
1079 SelectionDAGBuilder *SDB) {
1080 if (!TLI->supportSwiftError())
1083 // We only need to do this when we have swifterror parameter or swifterror
1085 if (FuncInfo->SwiftErrorVals.empty())
1088 assert(FuncInfo->MBB == &*FuncInfo->MF->begin() &&
1089 "expected to insert into entry block");
1090 auto &DL = FuncInfo->MF->getDataLayout();
1091 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1092 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1093 // We will always generate a copy from the argument. It is always used at
1094 // least by the 'return' of the swifterror.
1095 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal)
1097 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1098 // Assign Undef to Vreg. We construct MI directly to make sure it works
1100 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(),
1101 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),
1104 // Keep FastIS informed about the value we just inserted.
1106 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1108 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg);
1112 /// Collect llvm.dbg.declare information. This is done after argument lowering
1113 /// in case the declarations refer to arguments.
1114 static void processDbgDeclares(FunctionLoweringInfo *FuncInfo) {
1115 MachineFunction *MF = FuncInfo->MF;
1116 const DataLayout &DL = MF->getDataLayout();
1117 for (const BasicBlock &BB : *FuncInfo->Fn) {
1118 for (const Instruction &I : BB) {
1119 const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
1123 assert(DI->getVariable() && "Missing variable");
1124 assert(DI->getDebugLoc() && "Missing location");
1125 const Value *Address = DI->getAddress();
1129 // Look through casts and constant offset GEPs. These mostly come from
1131 APInt Offset(DL.getPointerSizeInBits(0), 0);
1132 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1134 // Check if the variable is a static alloca or a byval or inalloca
1135 // argument passed in memory. If it is not, then we will ignore this
1136 // intrinsic and handle this during isel like dbg.value.
1138 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1139 auto SI = FuncInfo->StaticAllocaMap.find(AI);
1140 if (SI != FuncInfo->StaticAllocaMap.end())
1142 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1143 FI = FuncInfo->getArgumentFrameIndex(Arg);
1148 DIExpression *Expr = DI->getExpression();
1149 if (Offset.getBoolValue())
1150 Expr = DIExpression::prepend(Expr, DIExpression::NoDeref,
1151 Offset.getZExtValue());
1152 MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
1157 /// Propagate swifterror values through the machine function CFG.
1158 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) {
1159 auto *TLI = FuncInfo->TLI;
1160 if (!TLI->supportSwiftError())
1163 // We only need to do this when we have swifterror parameter or swifterror
1165 if (FuncInfo->SwiftErrorVals.empty())
1168 // For each machine basic block in reverse post order.
1169 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF);
1170 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1174 MachineBasicBlock *MBB = *It;
1176 // For each swifterror value in the function.
1177 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1178 auto Key = std::make_pair(MBB, SwiftErrorVal);
1179 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1180 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key);
1181 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end();
1182 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0;
1183 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end();
1184 assert(!(UpwardsUse && !DownwardDef) &&
1185 "We can't have an upwards use but no downwards def");
1187 // If there is no upwards exposed use and an entry for the swifterror in
1188 // the def map for this value we don't need to do anything: We already
1189 // have a downward def for this basic block.
1190 if (!UpwardsUse && DownwardDef)
1193 // Otherwise we either have an upwards exposed use vreg that we need to
1194 // materialize or need to forward the downward def from predecessors.
1196 // Check whether we have a single vreg def from all predecessors.
1197 // Otherwise we need a phi.
1198 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs;
1199 SmallSet<const MachineBasicBlock*, 8> Visited;
1200 for (auto *Pred : MBB->predecessors()) {
1201 if (!Visited.insert(Pred).second)
1203 VRegs.push_back(std::make_pair(
1204 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal)));
1207 // We have a self-edge.
1208 // If there was no upwards use in this basic block there is now one: the
1209 // phi needs to use it self.
1212 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1213 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end());
1214 UUseVReg = UUseIt->second;
1218 // We need a phi node if we have more than one predecessor with different
1221 VRegs.size() >= 1 &&
1223 VRegs.begin(), VRegs.end(),
1224 [&](const std::pair<const MachineBasicBlock *, unsigned> &V)
1225 -> bool { return V.second != VRegs[0].second; }) !=
1228 // If there is no upwards exposed used and we don't need a phi just
1229 // forward the swifterror vreg from the predecessor(s).
1230 if (!UpwardsUse && !needPHI) {
1231 assert(!VRegs.empty() &&
1232 "No predecessors? The entry block should bail out earlier");
1233 // Just forward the swifterror vreg from the predecessor(s).
1234 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second);
1238 auto DLoc = isa<Instruction>(SwiftErrorVal)
1239 ? dyn_cast<Instruction>(SwiftErrorVal)->getDebugLoc()
1241 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo();
1243 // If we don't need a phi create a copy to the upward exposed vreg.
1246 unsigned DestReg = UUseVReg;
1247 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY),
1249 .addReg(VRegs[0].second);
1253 // We need a phi: if there is an upwards exposed use we already have a
1254 // destination virtual register number otherwise we generate a new one.
1255 auto &DL = FuncInfo->MF->getDataLayout();
1256 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1258 UpwardsUse ? UUseVReg
1259 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1260 MachineInstrBuilder SwiftErrorPHI =
1261 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc,
1262 TII->get(TargetOpcode::PHI), PHIVReg);
1263 for (auto BBRegPair : VRegs) {
1264 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first);
1267 // We did not have a definition in this block before: store the phi's vreg
1268 // as this block downward exposed def.
1270 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg);
1275 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1276 FastISelFailed = false;
1277 // Initialize the Fast-ISel state, if needed.
1278 FastISel *FastIS = nullptr;
1279 if (TM.Options.EnableFastISel)
1280 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1282 setupSwiftErrorVals(Fn, TLI, FuncInfo);
1284 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1286 // Lower arguments up front. An RPO iteration always visits the entry block
1288 assert(*RPOT.begin() == &Fn.getEntryBlock());
1291 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1292 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1293 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1298 // See if fast isel can lower the arguments.
1299 FastIS->startNewBlock();
1300 if (!FastIS->lowerArguments()) {
1301 FastISelFailed = true;
1302 // Fast isel failed to lower these arguments
1303 ++NumFastIselFailLowerArguments;
1305 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1307 &Fn.getEntryBlock());
1308 R << "FastISel didn't lower all arguments: "
1309 << ore::NV("Prototype", Fn.getType());
1310 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
1312 // Use SelectionDAG argument lowering
1314 CurDAG->setRoot(SDB->getControlRoot());
1316 CodeGenAndEmitDAG();
1319 // If we inserted any instructions at the beginning, make a note of
1320 // where they are, so we can be sure to emit subsequent instructions
1322 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1323 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1325 FastIS->setLastLocalValue(nullptr);
1327 createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB);
1329 processDbgDeclares(FuncInfo);
1331 // Iterate over all basic blocks in the function.
1332 for (const BasicBlock *LLVMBB : RPOT) {
1333 if (OptLevel != CodeGenOpt::None) {
1334 bool AllPredsVisited = true;
1335 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1337 if (!FuncInfo->VisitedBBs.count(*PI)) {
1338 AllPredsVisited = false;
1343 if (AllPredsVisited) {
1344 for (BasicBlock::const_iterator I = LLVMBB->begin();
1345 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1346 FuncInfo->ComputePHILiveOutRegInfo(PN);
1348 for (BasicBlock::const_iterator I = LLVMBB->begin();
1349 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1350 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1353 FuncInfo->VisitedBBs.insert(LLVMBB);
1356 BasicBlock::const_iterator const Begin =
1357 LLVMBB->getFirstNonPHI()->getIterator();
1358 BasicBlock::const_iterator const End = LLVMBB->end();
1359 BasicBlock::const_iterator BI = End;
1361 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1363 continue; // Some blocks like catchpads have no code or MBB.
1365 // Insert new instructions after any phi or argument setup code.
1366 FuncInfo->InsertPt = FuncInfo->MBB->end();
1368 // Setup an EH landing-pad block.
1369 FuncInfo->ExceptionPointerVirtReg = 0;
1370 FuncInfo->ExceptionSelectorVirtReg = 0;
1371 if (LLVMBB->isEHPad())
1372 if (!PrepareEHLandingPad())
1375 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1377 if (LLVMBB != &Fn.getEntryBlock())
1378 FastIS->startNewBlock();
1380 unsigned NumFastIselRemaining = std::distance(Begin, End);
1381 // Do FastISel on as many instructions as possible.
1382 for (; BI != Begin; --BI) {
1383 const Instruction *Inst = &*std::prev(BI);
1385 // If we no longer require this instruction, skip it.
1386 if (isFoldedOrDeadInstruction(Inst, FuncInfo) ||
1387 ElidedArgCopyInstrs.count(Inst)) {
1388 --NumFastIselRemaining;
1392 // Bottom-up: reset the insert pos at the top, after any local-value
1394 FastIS->recomputeInsertPt();
1396 // Try to select the instruction with FastISel.
1397 if (FastIS->selectInstruction(Inst)) {
1398 FastISelFailed = true;
1399 --NumFastIselRemaining;
1400 ++NumFastIselSuccess;
1401 // If fast isel succeeded, skip over all the folded instructions, and
1402 // then see if there is a load right before the selected instructions.
1403 // Try to fold the load if so.
1404 const Instruction *BeforeInst = Inst;
1405 while (BeforeInst != &*Begin) {
1406 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1407 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1410 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1411 BeforeInst->hasOneUse() &&
1412 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1413 // If we succeeded, don't re-select the load.
1414 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1415 --NumFastIselRemaining;
1416 ++NumFastIselSuccess;
1421 // Then handle certain instructions as single-LLVM-Instruction blocks.
1422 if (isa<CallInst>(Inst)) {
1423 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1424 Inst->getDebugLoc(), LLVMBB);
1426 R << "FastISel missed call";
1428 if (R.isEnabled() || EnableFastISelAbort) {
1429 std::string InstStrStorage;
1430 raw_string_ostream InstStr(InstStrStorage);
1433 R << ": " << InstStr.str();
1436 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
1438 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1439 !Inst->use_empty()) {
1440 unsigned &R = FuncInfo->ValueMap[Inst];
1442 R = FuncInfo->CreateRegs(Inst->getType());
1445 bool HadTailCall = false;
1446 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1447 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1449 // If the call was emitted as a tail call, we're done with the block.
1450 // We also need to delete any previously emitted instructions.
1452 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1457 // Recompute NumFastIselRemaining as Selection DAG instruction
1458 // selection may have handled the call, input args, etc.
1459 unsigned RemainingNow = std::distance(Begin, BI);
1460 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1461 NumFastIselRemaining = RemainingNow;
1465 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1466 Inst->getDebugLoc(), LLVMBB);
1468 bool ShouldAbort = EnableFastISelAbort;
1469 if (isa<TerminatorInst>(Inst)) {
1470 // Use a different message for terminator misses.
1471 R << "FastISel missed terminator";
1472 // Don't abort for terminator unless the level is really high
1473 ShouldAbort = (EnableFastISelAbort > 2);
1475 R << "FastISel missed";
1478 if (R.isEnabled() || EnableFastISelAbort) {
1479 std::string InstStrStorage;
1480 raw_string_ostream InstStr(InstStrStorage);
1482 R << ": " << InstStr.str();
1485 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1487 NumFastIselFailures += NumFastIselRemaining;
1491 FastIS->recomputeInsertPt();
1494 if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB)) {
1495 bool FunctionBasedInstrumentation =
1496 TLI->getSSPStackGuardCheck(*Fn.getParent());
1497 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1498 FunctionBasedInstrumentation);
1504 ++NumFastIselBlocks;
1507 // Run SelectionDAG instruction selection on the remainder of the block
1508 // not handled by FastISel. If FastISel is not run, this is the entire
1511 SelectBasicBlock(Begin, BI, HadTailCall);
1513 // But if FastISel was run, we already selected some of the block.
1514 // If we emitted a tail-call, we need to delete any previously emitted
1515 // instruction that follows it.
1516 if (HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1517 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1521 FuncInfo->PHINodesToUpdate.clear();
1522 ElidedArgCopyInstrs.clear();
1525 propagateSwiftErrorVRegs(FuncInfo);
1528 SDB->clearDanglingDebugInfo();
1529 SDB->SPDescriptor.resetPerFunctionState();
1532 /// Given that the input MI is before a partial terminator sequence TSeq, return
1533 /// true if M + TSeq also a partial terminator sequence.
1535 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1536 /// lowering copy vregs into physical registers, which are then passed into
1537 /// terminator instructors so we can satisfy ABI constraints. A partial
1538 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1539 /// may be the whole terminator sequence).
1540 static bool MIIsInTerminatorSequence(const MachineInstr &MI) {
1541 // If we do not have a copy or an implicit def, we return true if and only if
1542 // MI is a debug value.
1543 if (!MI.isCopy() && !MI.isImplicitDef())
1544 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1545 // physical registers if there is debug info associated with the terminator
1546 // of our mbb. We want to include said debug info in our terminator
1547 // sequence, so we return true in that case.
1548 return MI.isDebugValue();
1550 // We have left the terminator sequence if we are not doing one of the
1553 // 1. Copying a vreg into a physical register.
1554 // 2. Copying a vreg into a vreg.
1555 // 3. Defining a register via an implicit def.
1557 // OPI should always be a register definition...
1558 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
1559 if (!OPI->isReg() || !OPI->isDef())
1562 // Defining any register via an implicit def is always ok.
1563 if (MI.isImplicitDef())
1566 // Grab the copy source...
1567 MachineInstr::const_mop_iterator OPI2 = OPI;
1569 assert(OPI2 != MI.operands_end()
1570 && "Should have a copy implying we should have 2 arguments.");
1572 // Make sure that the copy dest is not a vreg when the copy source is a
1573 // physical register.
1574 if (!OPI2->isReg() ||
1575 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1576 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1582 /// Find the split point at which to splice the end of BB into its success stack
1583 /// protector check machine basic block.
1585 /// On many platforms, due to ABI constraints, terminators, even before register
1586 /// allocation, use physical registers. This creates an issue for us since
1587 /// physical registers at this point can not travel across basic
1588 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1589 /// when they enter functions and moves them through a sequence of copies back
1590 /// into the physical registers right before the terminator creating a
1591 /// ``Terminator Sequence''. This function is searching for the beginning of the
1592 /// terminator sequence so that we can ensure that we splice off not just the
1593 /// terminator, but additionally the copies that move the vregs into the
1594 /// physical registers.
1595 static MachineBasicBlock::iterator
1596 FindSplitPointForStackProtector(MachineBasicBlock *BB) {
1597 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1599 if (SplitPoint == BB->begin())
1602 MachineBasicBlock::iterator Start = BB->begin();
1603 MachineBasicBlock::iterator Previous = SplitPoint;
1606 while (MIIsInTerminatorSequence(*Previous)) {
1607 SplitPoint = Previous;
1608 if (Previous == Start)
1617 SelectionDAGISel::FinishBasicBlock() {
1618 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1619 << FuncInfo->PHINodesToUpdate.size() << "\n";
1620 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1621 dbgs() << "Node " << i << " : ("
1622 << FuncInfo->PHINodesToUpdate[i].first
1623 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1625 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1626 // PHI nodes in successors.
1627 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1628 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1629 assert(PHI->isPHI() &&
1630 "This is not a machine PHI node that we are updating!");
1631 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1633 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1636 // Handle stack protector.
1637 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1638 // The target provides a guard check function. There is no need to
1639 // generate error handling code or to split current basic block.
1640 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1642 // Add load and check to the basicblock.
1643 FuncInfo->MBB = ParentMBB;
1644 FuncInfo->InsertPt =
1645 FindSplitPointForStackProtector(ParentMBB);
1646 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1647 CurDAG->setRoot(SDB->getRoot());
1649 CodeGenAndEmitDAG();
1651 // Clear the Per-BB State.
1652 SDB->SPDescriptor.resetPerBBState();
1653 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1654 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1655 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1657 // Find the split point to split the parent mbb. At the same time copy all
1658 // physical registers used in the tail of parent mbb into virtual registers
1659 // before the split point and back into physical registers after the split
1660 // point. This prevents us needing to deal with Live-ins and many other
1661 // register allocation issues caused by us splitting the parent mbb. The
1662 // register allocator will clean up said virtual copies later on.
1663 MachineBasicBlock::iterator SplitPoint =
1664 FindSplitPointForStackProtector(ParentMBB);
1666 // Splice the terminator of ParentMBB into SuccessMBB.
1667 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1671 // Add compare/jump on neq/jump to the parent BB.
1672 FuncInfo->MBB = ParentMBB;
1673 FuncInfo->InsertPt = ParentMBB->end();
1674 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1675 CurDAG->setRoot(SDB->getRoot());
1677 CodeGenAndEmitDAG();
1679 // CodeGen Failure MBB if we have not codegened it yet.
1680 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1681 if (FailureMBB->empty()) {
1682 FuncInfo->MBB = FailureMBB;
1683 FuncInfo->InsertPt = FailureMBB->end();
1684 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1685 CurDAG->setRoot(SDB->getRoot());
1687 CodeGenAndEmitDAG();
1690 // Clear the Per-BB State.
1691 SDB->SPDescriptor.resetPerBBState();
1694 // Lower each BitTestBlock.
1695 for (auto &BTB : SDB->BitTestCases) {
1696 // Lower header first, if it wasn't already lowered
1698 // Set the current basic block to the mbb we wish to insert the code into
1699 FuncInfo->MBB = BTB.Parent;
1700 FuncInfo->InsertPt = FuncInfo->MBB->end();
1702 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1703 CurDAG->setRoot(SDB->getRoot());
1705 CodeGenAndEmitDAG();
1708 BranchProbability UnhandledProb = BTB.Prob;
1709 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1710 UnhandledProb -= BTB.Cases[j].ExtraProb;
1711 // Set the current basic block to the mbb we wish to insert the code into
1712 FuncInfo->MBB = BTB.Cases[j].ThisBB;
1713 FuncInfo->InsertPt = FuncInfo->MBB->end();
1716 // If all cases cover a contiguous range, it is not necessary to jump to
1717 // the default block after the last bit test fails. This is because the
1718 // range check during bit test header creation has guaranteed that every
1719 // case here doesn't go outside the range. In this case, there is no need
1720 // to perform the last bit test, as it will always be true. Instead, make
1721 // the second-to-last bit-test fall through to the target of the last bit
1722 // test, and delete the last bit test.
1724 MachineBasicBlock *NextMBB;
1725 if (BTB.ContiguousRange && j + 2 == ej) {
1726 // Second-to-last bit-test with contiguous range: fall through to the
1727 // target of the final bit test.
1728 NextMBB = BTB.Cases[j + 1].TargetBB;
1729 } else if (j + 1 == ej) {
1730 // For the last bit test, fall through to Default.
1731 NextMBB = BTB.Default;
1733 // Otherwise, fall through to the next bit test.
1734 NextMBB = BTB.Cases[j + 1].ThisBB;
1737 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1740 CurDAG->setRoot(SDB->getRoot());
1742 CodeGenAndEmitDAG();
1744 if (BTB.ContiguousRange && j + 2 == ej) {
1745 // Since we're not going to use the final bit test, remove it.
1746 BTB.Cases.pop_back();
1752 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1754 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1755 MachineBasicBlock *PHIBB = PHI->getParent();
1756 assert(PHI->isPHI() &&
1757 "This is not a machine PHI node that we are updating!");
1758 // This is "default" BB. We have two jumps to it. From "header" BB and
1759 // from last "case" BB, unless the latter was skipped.
1760 if (PHIBB == BTB.Default) {
1761 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1762 if (!BTB.ContiguousRange) {
1763 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1764 .addMBB(BTB.Cases.back().ThisBB);
1767 // One of "cases" BB.
1768 for (unsigned j = 0, ej = BTB.Cases.size();
1770 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1771 if (cBB->isSuccessor(PHIBB))
1772 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1776 SDB->BitTestCases.clear();
1778 // If the JumpTable record is filled in, then we need to emit a jump table.
1779 // Updating the PHI nodes is tricky in this case, since we need to determine
1780 // whether the PHI is a successor of the range check MBB or the jump table MBB
1781 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1782 // Lower header first, if it wasn't already lowered
1783 if (!SDB->JTCases[i].first.Emitted) {
1784 // Set the current basic block to the mbb we wish to insert the code into
1785 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1786 FuncInfo->InsertPt = FuncInfo->MBB->end();
1788 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1790 CurDAG->setRoot(SDB->getRoot());
1792 CodeGenAndEmitDAG();
1795 // Set the current basic block to the mbb we wish to insert the code into
1796 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1797 FuncInfo->InsertPt = FuncInfo->MBB->end();
1799 SDB->visitJumpTable(SDB->JTCases[i].second);
1800 CurDAG->setRoot(SDB->getRoot());
1802 CodeGenAndEmitDAG();
1805 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1807 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1808 MachineBasicBlock *PHIBB = PHI->getParent();
1809 assert(PHI->isPHI() &&
1810 "This is not a machine PHI node that we are updating!");
1811 // "default" BB. We can go there only from header BB.
1812 if (PHIBB == SDB->JTCases[i].second.Default)
1813 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1814 .addMBB(SDB->JTCases[i].first.HeaderBB);
1815 // JT BB. Just iterate over successors here
1816 if (FuncInfo->MBB->isSuccessor(PHIBB))
1817 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1820 SDB->JTCases.clear();
1822 // If we generated any switch lowering information, build and codegen any
1823 // additional DAGs necessary.
1824 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1825 // Set the current basic block to the mbb we wish to insert the code into
1826 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1827 FuncInfo->InsertPt = FuncInfo->MBB->end();
1829 // Determine the unique successors.
1830 SmallVector<MachineBasicBlock *, 2> Succs;
1831 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1832 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1833 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1835 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1836 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1837 CurDAG->setRoot(SDB->getRoot());
1839 CodeGenAndEmitDAG();
1841 // Remember the last block, now that any splitting is done, for use in
1842 // populating PHI nodes in successors.
1843 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1845 // Handle any PHI nodes in successors of this chunk, as if we were coming
1846 // from the original BB before switch expansion. Note that PHI nodes can
1847 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1848 // handle them the right number of times.
1849 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1850 FuncInfo->MBB = Succs[i];
1851 FuncInfo->InsertPt = FuncInfo->MBB->end();
1852 // FuncInfo->MBB may have been removed from the CFG if a branch was
1854 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1855 for (MachineBasicBlock::iterator
1856 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1857 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1858 MachineInstrBuilder PHI(*MF, MBBI);
1859 // This value for this PHI node is recorded in PHINodesToUpdate.
1860 for (unsigned pn = 0; ; ++pn) {
1861 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1862 "Didn't find PHI entry!");
1863 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1864 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1872 SDB->SwitchCases.clear();
1875 /// Create the scheduler. If a specific scheduler was specified
1876 /// via the SchedulerRegistry, use it, otherwise select the
1877 /// one preferred by the target.
1879 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1880 return ISHeuristic(this, OptLevel);
1883 //===----------------------------------------------------------------------===//
1884 // Helper functions used by the generated instruction selector.
1885 //===----------------------------------------------------------------------===//
1886 // Calls to these methods are generated by tblgen.
1888 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1889 /// the dag combiner simplified the 255, we still want to match. RHS is the
1890 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1891 /// specified in the .td file (e.g. 255).
1892 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1893 int64_t DesiredMaskS) const {
1894 const APInt &ActualMask = RHS->getAPIntValue();
1895 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1897 // If the actual mask exactly matches, success!
1898 if (ActualMask == DesiredMask)
1901 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1902 if (ActualMask.intersects(~DesiredMask))
1905 // Otherwise, the DAG Combiner may have proven that the value coming in is
1906 // either already zero or is not demanded. Check for known zero input bits.
1907 APInt NeededMask = DesiredMask & ~ActualMask;
1908 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1911 // TODO: check to see if missing bits are just not demanded.
1913 // Otherwise, this pattern doesn't match.
1917 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1918 /// the dag combiner simplified the 255, we still want to match. RHS is the
1919 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1920 /// specified in the .td file (e.g. 255).
1921 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1922 int64_t DesiredMaskS) const {
1923 const APInt &ActualMask = RHS->getAPIntValue();
1924 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1926 // If the actual mask exactly matches, success!
1927 if (ActualMask == DesiredMask)
1930 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1931 if (ActualMask.intersects(~DesiredMask))
1934 // Otherwise, the DAG Combiner may have proven that the value coming in is
1935 // either already zero or is not demanded. Check for known zero input bits.
1936 APInt NeededMask = DesiredMask & ~ActualMask;
1939 CurDAG->computeKnownBits(LHS, Known);
1941 // If all the missing bits in the or are already known to be set, match!
1942 if (NeededMask.isSubsetOf(Known.One))
1945 // TODO: check to see if missing bits are just not demanded.
1947 // Otherwise, this pattern doesn't match.
1951 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1952 /// by tblgen. Others should not call it.
1953 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
1955 std::vector<SDValue> InOps;
1956 std::swap(InOps, Ops);
1958 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1959 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1960 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1961 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1963 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1964 if (InOps[e-1].getValueType() == MVT::Glue)
1965 --e; // Don't process a glue operand if it is here.
1968 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1969 if (!InlineAsm::isMemKind(Flags)) {
1970 // Just skip over this operand, copying the operands verbatim.
1971 Ops.insert(Ops.end(), InOps.begin()+i,
1972 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1973 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1975 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1976 "Memory operand with multiple values?");
1978 unsigned TiedToOperand;
1979 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
1980 // We need the constraint ID from the operand this is tied to.
1981 unsigned CurOp = InlineAsm::Op_FirstOperand;
1982 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1983 for (; TiedToOperand; --TiedToOperand) {
1984 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
1985 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1989 // Otherwise, this is a memory operand. Ask the target to select it.
1990 std::vector<SDValue> SelOps;
1991 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
1992 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
1993 report_fatal_error("Could not match memory address. Inline asm"
1996 // Add this to the output node.
1998 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1999 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
2000 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
2001 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2006 // Add the glue input back if present.
2007 if (e != InOps.size())
2008 Ops.push_back(InOps.back());
2011 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2014 static SDNode *findGlueUse(SDNode *N) {
2015 unsigned FlagResNo = N->getNumValues()-1;
2016 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2017 SDUse &Use = I.getUse();
2018 if (Use.getResNo() == FlagResNo)
2019 return Use.getUser();
2024 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
2025 /// This function iteratively traverses up the operand chain, ignoring
2027 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
2028 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
2029 bool IgnoreChains) {
2030 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
2031 // greater than all of its (recursive) operands. If we scan to a point where
2032 // 'use' is smaller than the node we're scanning for, then we know we will
2035 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
2036 // happen because we scan down to newly selected nodes in the case of glue
2038 std::vector<SDNode *> WorkList;
2039 WorkList.push_back(Use);
2041 while (!WorkList.empty()) {
2042 Use = WorkList.back();
2043 WorkList.pop_back();
2044 if (Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1)
2047 // Don't revisit nodes if we already scanned it and didn't fail, we know we
2048 // won't fail if we scan it again.
2049 if (!Visited.insert(Use).second)
2052 for (const SDValue &Op : Use->op_values()) {
2053 // Ignore chain uses, they are validated by HandleMergeInputChains.
2054 if (Op.getValueType() == MVT::Other && IgnoreChains)
2057 SDNode *N = Op.getNode();
2059 if (Use == ImmedUse || Use == Root)
2060 continue; // We are not looking for immediate use.
2065 // Traverse up the operand chain.
2066 WorkList.push_back(N);
2072 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2073 /// operand node N of U during instruction selection that starts at Root.
2074 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
2075 SDNode *Root) const {
2076 if (OptLevel == CodeGenOpt::None) return false;
2077 return N.hasOneUse();
2080 /// IsLegalToFold - Returns true if the specific operand node N of
2081 /// U can be folded during instruction selection that starts at Root.
2082 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
2083 CodeGenOpt::Level OptLevel,
2084 bool IgnoreChains) {
2085 if (OptLevel == CodeGenOpt::None) return false;
2087 // If Root use can somehow reach N through a path that that doesn't contain
2088 // U then folding N would create a cycle. e.g. In the following
2089 // diagram, Root can reach N through X. If N is folded into into Root, then
2090 // X is both a predecessor and a successor of U.
2101 // * indicates nodes to be folded together.
2103 // If Root produces glue, then it gets (even more) interesting. Since it
2104 // will be "glued" together with its glue use in the scheduler, we need to
2105 // check if it might reach N.
2124 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2125 // (call it Fold), then X is a predecessor of GU and a successor of
2126 // Fold. But since Fold and GU are glued together, this will create
2127 // a cycle in the scheduling graph.
2129 // If the node has glue, walk down the graph to the "lowest" node in the
2131 EVT VT = Root->getValueType(Root->getNumValues()-1);
2132 while (VT == MVT::Glue) {
2133 SDNode *GU = findGlueUse(Root);
2137 VT = Root->getValueType(Root->getNumValues()-1);
2139 // If our query node has a glue result with a use, we've walked up it. If
2140 // the user (which has already been selected) has a chain or indirectly uses
2141 // the chain, our WalkChainUsers predicate will not consider it. Because of
2142 // this, we cannot ignore chains in this predicate.
2143 IgnoreChains = false;
2146 SmallPtrSet<SDNode*, 16> Visited;
2147 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
2150 void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2153 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2154 SelectInlineAsmMemoryOperands(Ops, DL);
2156 const EVT VTs[] = {MVT::Other, MVT::Glue};
2157 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops);
2159 ReplaceUses(N, New.getNode());
2160 CurDAG->RemoveDeadNode(N);
2163 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2165 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2166 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2168 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0),
2170 SDValue New = CurDAG->getCopyFromReg(
2171 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2173 ReplaceUses(Op, New.getNode());
2174 CurDAG->RemoveDeadNode(Op);
2177 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2179 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2180 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2181 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
2182 Op->getOperand(2).getValueType(),
2184 SDValue New = CurDAG->getCopyToReg(
2185 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2187 ReplaceUses(Op, New.getNode());
2188 CurDAG->RemoveDeadNode(Op);
2191 void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2192 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2195 /// GetVBR - decode a vbr encoding whose top bit is set.
2196 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
2197 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2198 assert(Val >= 128 && "Not a VBR");
2199 Val &= 127; // Remove first vbr bit.
2204 NextBits = MatcherTable[Idx++];
2205 Val |= (NextBits&127) << Shift;
2207 } while (NextBits & 128);
2212 /// When a match is complete, this method updates uses of interior chain results
2213 /// to use the new results.
2214 void SelectionDAGISel::UpdateChains(
2215 SDNode *NodeToMatch, SDValue InputChain,
2216 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2217 SmallVector<SDNode*, 4> NowDeadNodes;
2219 // Now that all the normal results are replaced, we replace the chain and
2220 // glue results if present.
2221 if (!ChainNodesMatched.empty()) {
2222 assert(InputChain.getNode() &&
2223 "Matched input chains but didn't produce a chain");
2224 // Loop over all of the nodes we matched that produced a chain result.
2225 // Replace all the chain results with the final chain we ended up with.
2226 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2227 SDNode *ChainNode = ChainNodesMatched[i];
2228 // If ChainNode is null, it's because we replaced it on a previous
2229 // iteration and we cleared it out of the map. Just skip it.
2233 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2234 "Deleted node left in chain");
2236 // Don't replace the results of the root node if we're doing a
2238 if (ChainNode == NodeToMatch && isMorphNodeTo)
2241 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2242 if (ChainVal.getValueType() == MVT::Glue)
2243 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2244 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2245 SelectionDAG::DAGNodeDeletedListener NDL(
2246 *CurDAG, [&](SDNode *N, SDNode *E) {
2247 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2248 static_cast<SDNode *>(nullptr));
2250 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
2252 // If the node became dead and we haven't already seen it, delete it.
2253 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2254 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2255 NowDeadNodes.push_back(ChainNode);
2259 if (!NowDeadNodes.empty())
2260 CurDAG->RemoveDeadNodes(NowDeadNodes);
2262 DEBUG(dbgs() << "ISEL: Match complete!\n");
2268 CR_LeadsToInteriorNode
2271 /// WalkChainUsers - Walk down the users of the specified chained node that is
2272 /// part of the pattern we're matching, looking at all of the users we find.
2273 /// This determines whether something is an interior node, whether we have a
2274 /// non-pattern node in between two pattern nodes (which prevent folding because
2275 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2276 /// between pattern nodes (in which case the TF becomes part of the pattern).
2278 /// The walk we do here is guaranteed to be small because we quickly get down to
2279 /// already selected nodes "below" us.
2281 WalkChainUsers(const SDNode *ChainedNode,
2282 SmallVectorImpl<SDNode *> &ChainedNodesInPattern,
2283 DenseMap<const SDNode *, ChainResult> &TokenFactorResult,
2284 SmallVectorImpl<SDNode *> &InteriorChainedNodes) {
2285 ChainResult Result = CR_Simple;
2287 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2288 E = ChainedNode->use_end(); UI != E; ++UI) {
2289 // Make sure the use is of the chain, not some other value we produce.
2290 if (UI.getUse().getValueType() != MVT::Other) continue;
2294 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
2297 // If we see an already-selected machine node, then we've gone beyond the
2298 // pattern that we're selecting down into the already selected chunk of the
2300 unsigned UserOpcode = User->getOpcode();
2301 if (User->isMachineOpcode() ||
2302 UserOpcode == ISD::CopyToReg ||
2303 UserOpcode == ISD::CopyFromReg ||
2304 UserOpcode == ISD::INLINEASM ||
2305 UserOpcode == ISD::EH_LABEL ||
2306 UserOpcode == ISD::LIFETIME_START ||
2307 UserOpcode == ISD::LIFETIME_END) {
2308 // If their node ID got reset to -1 then they've already been selected.
2309 // Treat them like a MachineOpcode.
2310 if (User->getNodeId() == -1)
2314 // If we have a TokenFactor, we handle it specially.
2315 if (User->getOpcode() != ISD::TokenFactor) {
2316 // If the node isn't a token factor and isn't part of our pattern, then it
2317 // must be a random chained node in between two nodes we're selecting.
2318 // This happens when we have something like:
2323 // Because we structurally match the load/store as a read/modify/write,
2324 // but the call is chained between them. We cannot fold in this case
2325 // because it would induce a cycle in the graph.
2326 if (!std::count(ChainedNodesInPattern.begin(),
2327 ChainedNodesInPattern.end(), User))
2328 return CR_InducesCycle;
2330 // Otherwise we found a node that is part of our pattern. For example in:
2334 // This would happen when we're scanning down from the load and see the
2335 // store as a user. Record that there is a use of ChainedNode that is
2336 // part of the pattern and keep scanning uses.
2337 Result = CR_LeadsToInteriorNode;
2338 InteriorChainedNodes.push_back(User);
2342 // If we found a TokenFactor, there are two cases to consider: first if the
2343 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2344 // uses of the TF are in our pattern) we just want to ignore it. Second,
2345 // the TokenFactor can be sandwiched in between two chained nodes, like so:
2351 // | \ DAG's like cheese
2354 // [TokenFactor] [Op]
2361 // In this case, the TokenFactor becomes part of our match and we rewrite it
2362 // as a new TokenFactor.
2364 // To distinguish these two cases, do a recursive walk down the uses.
2365 auto MemoizeResult = TokenFactorResult.find(User);
2366 bool Visited = MemoizeResult != TokenFactorResult.end();
2367 // Recursively walk chain users only if the result is not memoized.
2369 auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult,
2370 InteriorChainedNodes);
2371 MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first;
2373 switch (MemoizeResult->second) {
2375 // If the uses of the TokenFactor are just already-selected nodes, ignore
2376 // it, it is "below" our pattern.
2378 case CR_InducesCycle:
2379 // If the uses of the TokenFactor lead to nodes that are not part of our
2380 // pattern that are not selected, folding would turn this into a cycle,
2382 return CR_InducesCycle;
2383 case CR_LeadsToInteriorNode:
2384 break; // Otherwise, keep processing.
2387 // Okay, we know we're in the interesting interior case. The TokenFactor
2388 // is now going to be considered part of the pattern so that we rewrite its
2389 // uses (it may have uses that are not part of the pattern) with the
2390 // ultimate chain result of the generated code. We will also add its chain
2391 // inputs as inputs to the ultimate TokenFactor we create.
2392 Result = CR_LeadsToInteriorNode;
2394 ChainedNodesInPattern.push_back(User);
2395 InteriorChainedNodes.push_back(User);
2402 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2403 /// operation for when the pattern matched at least one node with a chains. The
2404 /// input vector contains a list of all of the chained nodes that we match. We
2405 /// must determine if this is a valid thing to cover (i.e. matching it won't
2406 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2407 /// be used as the input node chain for the generated nodes.
2409 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2410 SelectionDAG *CurDAG) {
2411 // Used for memoization. Without it WalkChainUsers could take exponential
2413 DenseMap<const SDNode *, ChainResult> TokenFactorResult;
2414 // Walk all of the chained nodes we've matched, recursively scanning down the
2415 // users of the chain result. This adds any TokenFactor nodes that are caught
2416 // in between chained nodes to the chained and interior nodes list.
2417 SmallVector<SDNode*, 3> InteriorChainedNodes;
2418 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2419 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2421 InteriorChainedNodes) == CR_InducesCycle)
2422 return SDValue(); // Would induce a cycle.
2425 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2426 // that we are interested in. Form our input TokenFactor node.
2427 SmallVector<SDValue, 3> InputChains;
2428 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2429 // Add the input chain of this node to the InputChains list (which will be
2430 // the operands of the generated TokenFactor) if it's not an interior node.
2431 SDNode *N = ChainNodesMatched[i];
2432 if (N->getOpcode() != ISD::TokenFactor) {
2433 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2436 // Otherwise, add the input chain.
2437 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2438 assert(InChain.getValueType() == MVT::Other && "Not a chain");
2439 InputChains.push_back(InChain);
2443 // If we have a token factor, we want to add all inputs of the token factor
2444 // that are not part of the pattern we're matching.
2445 for (const SDValue &Op : N->op_values()) {
2446 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2448 InputChains.push_back(Op);
2452 if (InputChains.size() == 1)
2453 return InputChains[0];
2454 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2455 MVT::Other, InputChains);
2458 /// MorphNode - Handle morphing a node in place for the selector.
2459 SDNode *SelectionDAGISel::
2460 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2461 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2462 // It is possible we're using MorphNodeTo to replace a node with no
2463 // normal results with one that has a normal result (or we could be
2464 // adding a chain) and the input could have glue and chains as well.
2465 // In this case we need to shift the operands down.
2466 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2467 // than the old isel though.
2468 int OldGlueResultNo = -1, OldChainResultNo = -1;
2470 unsigned NTMNumResults = Node->getNumValues();
2471 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2472 OldGlueResultNo = NTMNumResults-1;
2473 if (NTMNumResults != 1 &&
2474 Node->getValueType(NTMNumResults-2) == MVT::Other)
2475 OldChainResultNo = NTMNumResults-2;
2476 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2477 OldChainResultNo = NTMNumResults-1;
2479 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2480 // that this deletes operands of the old node that become dead.
2481 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2483 // MorphNodeTo can operate in two ways: if an existing node with the
2484 // specified operands exists, it can just return it. Otherwise, it
2485 // updates the node in place to have the requested operands.
2487 // If we updated the node in place, reset the node ID. To the isel,
2488 // this should be just like a newly allocated machine node.
2492 unsigned ResNumResults = Res->getNumValues();
2493 // Move the glue if needed.
2494 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2495 (unsigned)OldGlueResultNo != ResNumResults-1)
2496 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2497 SDValue(Res, ResNumResults-1));
2499 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2502 // Move the chain reference if needed.
2503 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2504 (unsigned)OldChainResultNo != ResNumResults-1)
2505 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2506 SDValue(Res, ResNumResults-1));
2508 // Otherwise, no replacement happened because the node already exists. Replace
2509 // Uses of the old node with the new one.
2511 CurDAG->ReplaceAllUsesWith(Node, Res);
2512 CurDAG->RemoveDeadNode(Node);
2518 /// CheckSame - Implements OP_CheckSame.
2519 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2520 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2522 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2523 // Accept if it is exactly the same as a previously recorded node.
2524 unsigned RecNo = MatcherTable[MatcherIndex++];
2525 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2526 return N == RecordedNodes[RecNo].first;
2529 /// CheckChildSame - Implements OP_CheckChildXSame.
2530 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2531 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2533 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes,
2535 if (ChildNo >= N.getNumOperands())
2536 return false; // Match fails if out of range child #.
2537 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2541 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2542 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2543 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2544 const SelectionDAGISel &SDISel) {
2545 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2548 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2549 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2550 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2551 const SelectionDAGISel &SDISel, SDNode *N) {
2552 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2555 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2556 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2558 uint16_t Opc = MatcherTable[MatcherIndex++];
2559 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2560 return N->getOpcode() == Opc;
2563 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2564 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2565 const TargetLowering *TLI, const DataLayout &DL) {
2566 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2567 if (N.getValueType() == VT) return true;
2569 // Handle the case when VT is iPTR.
2570 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2573 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2574 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2575 SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2577 if (ChildNo >= N.getNumOperands())
2578 return false; // Match fails if out of range child #.
2579 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2583 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2584 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2586 return cast<CondCodeSDNode>(N)->get() ==
2587 (ISD::CondCode)MatcherTable[MatcherIndex++];
2590 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2591 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2592 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2593 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2594 if (cast<VTSDNode>(N)->getVT() == VT)
2597 // Handle the case when VT is iPTR.
2598 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2601 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2602 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2604 int64_t Val = MatcherTable[MatcherIndex++];
2606 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2608 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2609 return C && C->getSExtValue() == Val;
2612 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2613 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2614 SDValue N, unsigned ChildNo) {
2615 if (ChildNo >= N.getNumOperands())
2616 return false; // Match fails if out of range child #.
2617 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2620 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2621 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2622 SDValue N, const SelectionDAGISel &SDISel) {
2623 int64_t Val = MatcherTable[MatcherIndex++];
2625 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2627 if (N->getOpcode() != ISD::AND) return false;
2629 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2630 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2633 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2634 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2635 SDValue N, const SelectionDAGISel &SDISel) {
2636 int64_t Val = MatcherTable[MatcherIndex++];
2638 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2640 if (N->getOpcode() != ISD::OR) return false;
2642 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2643 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2646 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2647 /// scope, evaluate the current node. If the current predicate is known to
2648 /// fail, set Result=true and return anything. If the current predicate is
2649 /// known to pass, set Result=false and return the MatcherIndex to continue
2650 /// with. If the current predicate is unknown, set Result=false and return the
2651 /// MatcherIndex to continue with.
2652 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2653 unsigned Index, SDValue N,
2655 const SelectionDAGISel &SDISel,
2656 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2657 switch (Table[Index++]) {
2660 return Index-1; // Could not evaluate this predicate.
2661 case SelectionDAGISel::OPC_CheckSame:
2662 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2664 case SelectionDAGISel::OPC_CheckChild0Same:
2665 case SelectionDAGISel::OPC_CheckChild1Same:
2666 case SelectionDAGISel::OPC_CheckChild2Same:
2667 case SelectionDAGISel::OPC_CheckChild3Same:
2668 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2669 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2671 case SelectionDAGISel::OPC_CheckPatternPredicate:
2672 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2674 case SelectionDAGISel::OPC_CheckPredicate:
2675 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2677 case SelectionDAGISel::OPC_CheckOpcode:
2678 Result = !::CheckOpcode(Table, Index, N.getNode());
2680 case SelectionDAGISel::OPC_CheckType:
2681 Result = !::CheckType(Table, Index, N, SDISel.TLI,
2682 SDISel.CurDAG->getDataLayout());
2684 case SelectionDAGISel::OPC_CheckChild0Type:
2685 case SelectionDAGISel::OPC_CheckChild1Type:
2686 case SelectionDAGISel::OPC_CheckChild2Type:
2687 case SelectionDAGISel::OPC_CheckChild3Type:
2688 case SelectionDAGISel::OPC_CheckChild4Type:
2689 case SelectionDAGISel::OPC_CheckChild5Type:
2690 case SelectionDAGISel::OPC_CheckChild6Type:
2691 case SelectionDAGISel::OPC_CheckChild7Type:
2692 Result = !::CheckChildType(
2693 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2694 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2696 case SelectionDAGISel::OPC_CheckCondCode:
2697 Result = !::CheckCondCode(Table, Index, N);
2699 case SelectionDAGISel::OPC_CheckValueType:
2700 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2701 SDISel.CurDAG->getDataLayout());
2703 case SelectionDAGISel::OPC_CheckInteger:
2704 Result = !::CheckInteger(Table, Index, N);
2706 case SelectionDAGISel::OPC_CheckChild0Integer:
2707 case SelectionDAGISel::OPC_CheckChild1Integer:
2708 case SelectionDAGISel::OPC_CheckChild2Integer:
2709 case SelectionDAGISel::OPC_CheckChild3Integer:
2710 case SelectionDAGISel::OPC_CheckChild4Integer:
2711 Result = !::CheckChildInteger(Table, Index, N,
2712 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2714 case SelectionDAGISel::OPC_CheckAndImm:
2715 Result = !::CheckAndImm(Table, Index, N, SDISel);
2717 case SelectionDAGISel::OPC_CheckOrImm:
2718 Result = !::CheckOrImm(Table, Index, N, SDISel);
2726 /// FailIndex - If this match fails, this is the index to continue with.
2729 /// NodeStack - The node stack when the scope was formed.
2730 SmallVector<SDValue, 4> NodeStack;
2732 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2733 unsigned NumRecordedNodes;
2735 /// NumMatchedMemRefs - The number of matched memref entries.
2736 unsigned NumMatchedMemRefs;
2738 /// InputChain/InputGlue - The current chain/glue
2739 SDValue InputChain, InputGlue;
2741 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2742 bool HasChainNodesMatched;
2745 /// \\brief A DAG update listener to keep the matching state
2746 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2747 /// change the DAG while matching. X86 addressing mode matcher is an example
2749 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2751 SDNode **NodeToMatch;
2752 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
2753 SmallVectorImpl<MatchScope> &MatchScopes;
2756 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2757 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2758 SmallVectorImpl<MatchScope> &MS)
2759 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2760 RecordedNodes(RN), MatchScopes(MS) {}
2762 void NodeDeleted(SDNode *N, SDNode *E) override {
2763 // Some early-returns here to avoid the search if we deleted the node or
2764 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2765 // do, so it's unnecessary to update matching state at that point).
2766 // Neither of these can occur currently because we only install this
2767 // update listener during matching a complex patterns.
2768 if (!E || E->isMachineOpcode())
2770 // Check if NodeToMatch was updated.
2771 if (N == *NodeToMatch)
2773 // Performing linear search here does not matter because we almost never
2774 // run this code. You'd have to have a CSE during complex pattern
2776 for (auto &I : RecordedNodes)
2777 if (I.first.getNode() == N)
2780 for (auto &I : MatchScopes)
2781 for (auto &J : I.NodeStack)
2782 if (J.getNode() == N)
2787 } // end anonymous namespace
2789 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
2790 const unsigned char *MatcherTable,
2791 unsigned TableSize) {
2792 // FIXME: Should these even be selected? Handle these cases in the caller?
2793 switch (NodeToMatch->getOpcode()) {
2796 case ISD::EntryToken: // These nodes remain the same.
2797 case ISD::BasicBlock:
2799 case ISD::RegisterMask:
2800 case ISD::HANDLENODE:
2801 case ISD::MDNODE_SDNODE:
2802 case ISD::TargetConstant:
2803 case ISD::TargetConstantFP:
2804 case ISD::TargetConstantPool:
2805 case ISD::TargetFrameIndex:
2806 case ISD::TargetExternalSymbol:
2808 case ISD::TargetBlockAddress:
2809 case ISD::TargetJumpTable:
2810 case ISD::TargetGlobalTLSAddress:
2811 case ISD::TargetGlobalAddress:
2812 case ISD::TokenFactor:
2813 case ISD::CopyFromReg:
2814 case ISD::CopyToReg:
2816 case ISD::LIFETIME_START:
2817 case ISD::LIFETIME_END:
2818 NodeToMatch->setNodeId(-1); // Mark selected.
2820 case ISD::AssertSext:
2821 case ISD::AssertZext:
2822 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2823 NodeToMatch->getOperand(0));
2824 CurDAG->RemoveDeadNode(NodeToMatch);
2826 case ISD::INLINEASM:
2827 Select_INLINEASM(NodeToMatch);
2829 case ISD::READ_REGISTER:
2830 Select_READ_REGISTER(NodeToMatch);
2832 case ISD::WRITE_REGISTER:
2833 Select_WRITE_REGISTER(NodeToMatch);
2836 Select_UNDEF(NodeToMatch);
2840 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2842 // Set up the node stack with NodeToMatch as the only node on the stack.
2843 SmallVector<SDValue, 8> NodeStack;
2844 SDValue N = SDValue(NodeToMatch, 0);
2845 NodeStack.push_back(N);
2847 // MatchScopes - Scopes used when matching, if a match failure happens, this
2848 // indicates where to continue checking.
2849 SmallVector<MatchScope, 8> MatchScopes;
2851 // RecordedNodes - This is the set of nodes that have been recorded by the
2852 // state machine. The second value is the parent of the node, or null if the
2853 // root is recorded.
2854 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2856 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2858 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2860 // These are the current input chain and glue for use when generating nodes.
2861 // Various Emit operations change these. For example, emitting a copytoreg
2862 // uses and updates these.
2863 SDValue InputChain, InputGlue;
2865 // ChainNodesMatched - If a pattern matches nodes that have input/output
2866 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2867 // which ones they are. The result is captured into this list so that we can
2868 // update the chain results when the pattern is complete.
2869 SmallVector<SDNode*, 3> ChainNodesMatched;
2871 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2872 NodeToMatch->dump(CurDAG);
2875 // Determine where to start the interpreter. Normally we start at opcode #0,
2876 // but if the state machine starts with an OPC_SwitchOpcode, then we
2877 // accelerate the first lookup (which is guaranteed to be hot) with the
2878 // OpcodeOffset table.
2879 unsigned MatcherIndex = 0;
2881 if (!OpcodeOffset.empty()) {
2882 // Already computed the OpcodeOffset table, just index into it.
2883 if (N.getOpcode() < OpcodeOffset.size())
2884 MatcherIndex = OpcodeOffset[N.getOpcode()];
2885 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2887 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2888 // Otherwise, the table isn't computed, but the state machine does start
2889 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2890 // is the first time we're selecting an instruction.
2893 // Get the size of this case.
2894 unsigned CaseSize = MatcherTable[Idx++];
2896 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2897 if (CaseSize == 0) break;
2899 // Get the opcode, add the index to the table.
2900 uint16_t Opc = MatcherTable[Idx++];
2901 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2902 if (Opc >= OpcodeOffset.size())
2903 OpcodeOffset.resize((Opc+1)*2);
2904 OpcodeOffset[Opc] = Idx;
2908 // Okay, do the lookup for the first opcode.
2909 if (N.getOpcode() < OpcodeOffset.size())
2910 MatcherIndex = OpcodeOffset[N.getOpcode()];
2914 assert(MatcherIndex < TableSize && "Invalid index");
2916 unsigned CurrentOpcodeIndex = MatcherIndex;
2918 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2921 // Okay, the semantics of this operation are that we should push a scope
2922 // then evaluate the first child. However, pushing a scope only to have
2923 // the first check fail (which then pops it) is inefficient. If we can
2924 // determine immediately that the first check (or first several) will
2925 // immediately fail, don't even bother pushing a scope for them.
2929 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2930 if (NumToSkip & 128)
2931 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2932 // Found the end of the scope with no match.
2933 if (NumToSkip == 0) {
2938 FailIndex = MatcherIndex+NumToSkip;
2940 unsigned MatcherIndexOfPredicate = MatcherIndex;
2941 (void)MatcherIndexOfPredicate; // silence warning.
2943 // If we can't evaluate this predicate without pushing a scope (e.g. if
2944 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2945 // push the scope and evaluate the full predicate chain.
2947 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2948 Result, *this, RecordedNodes);
2952 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2953 << "index " << MatcherIndexOfPredicate
2954 << ", continuing at " << FailIndex << "\n");
2955 ++NumDAGIselRetries;
2957 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2958 // move to the next case.
2959 MatcherIndex = FailIndex;
2962 // If the whole scope failed to match, bail.
2963 if (FailIndex == 0) break;
2965 // Push a MatchScope which indicates where to go if the first child fails
2967 MatchScope NewEntry;
2968 NewEntry.FailIndex = FailIndex;
2969 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2970 NewEntry.NumRecordedNodes = RecordedNodes.size();
2971 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2972 NewEntry.InputChain = InputChain;
2973 NewEntry.InputGlue = InputGlue;
2974 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2975 MatchScopes.push_back(NewEntry);
2978 case OPC_RecordNode: {
2979 // Remember this node, it may end up being an operand in the pattern.
2980 SDNode *Parent = nullptr;
2981 if (NodeStack.size() > 1)
2982 Parent = NodeStack[NodeStack.size()-2].getNode();
2983 RecordedNodes.push_back(std::make_pair(N, Parent));
2987 case OPC_RecordChild0: case OPC_RecordChild1:
2988 case OPC_RecordChild2: case OPC_RecordChild3:
2989 case OPC_RecordChild4: case OPC_RecordChild5:
2990 case OPC_RecordChild6: case OPC_RecordChild7: {
2991 unsigned ChildNo = Opcode-OPC_RecordChild0;
2992 if (ChildNo >= N.getNumOperands())
2993 break; // Match fails if out of range child #.
2995 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2999 case OPC_RecordMemRef:
3000 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
3003 case OPC_CaptureGlueInput:
3004 // If the current node has an input glue, capture it in InputGlue.
3005 if (N->getNumOperands() != 0 &&
3006 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3007 InputGlue = N->getOperand(N->getNumOperands()-1);
3010 case OPC_MoveChild: {
3011 unsigned ChildNo = MatcherTable[MatcherIndex++];
3012 if (ChildNo >= N.getNumOperands())
3013 break; // Match fails if out of range child #.
3014 N = N.getOperand(ChildNo);
3015 NodeStack.push_back(N);
3019 case OPC_MoveChild0: case OPC_MoveChild1:
3020 case OPC_MoveChild2: case OPC_MoveChild3:
3021 case OPC_MoveChild4: case OPC_MoveChild5:
3022 case OPC_MoveChild6: case OPC_MoveChild7: {
3023 unsigned ChildNo = Opcode-OPC_MoveChild0;
3024 if (ChildNo >= N.getNumOperands())
3025 break; // Match fails if out of range child #.
3026 N = N.getOperand(ChildNo);
3027 NodeStack.push_back(N);
3031 case OPC_MoveParent:
3032 // Pop the current node off the NodeStack.
3033 NodeStack.pop_back();
3034 assert(!NodeStack.empty() && "Node stack imbalance!");
3035 N = NodeStack.back();
3039 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3042 case OPC_CheckChild0Same: case OPC_CheckChild1Same:
3043 case OPC_CheckChild2Same: case OPC_CheckChild3Same:
3044 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3045 Opcode-OPC_CheckChild0Same))
3049 case OPC_CheckPatternPredicate:
3050 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
3052 case OPC_CheckPredicate:
3053 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3057 case OPC_CheckComplexPat: {
3058 unsigned CPNum = MatcherTable[MatcherIndex++];
3059 unsigned RecNo = MatcherTable[MatcherIndex++];
3060 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3062 // If target can modify DAG during matching, keep the matching state
3064 std::unique_ptr<MatchStateUpdater> MSU;
3065 if (ComplexPatternFuncMutatesDAG())
3066 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3069 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3070 RecordedNodes[RecNo].first, CPNum,
3075 case OPC_CheckOpcode:
3076 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3080 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3081 CurDAG->getDataLayout()))
3085 case OPC_SwitchOpcode: {
3086 unsigned CurNodeOpcode = N.getOpcode();
3087 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3090 // Get the size of this case.
3091 CaseSize = MatcherTable[MatcherIndex++];
3093 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3094 if (CaseSize == 0) break;
3096 uint16_t Opc = MatcherTable[MatcherIndex++];
3097 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3099 // If the opcode matches, then we will execute this case.
3100 if (CurNodeOpcode == Opc)
3103 // Otherwise, skip over this case.
3104 MatcherIndex += CaseSize;
3107 // If no cases matched, bail out.
3108 if (CaseSize == 0) break;
3110 // Otherwise, execute the case we found.
3111 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
3112 << " to " << MatcherIndex << "\n");
3116 case OPC_SwitchType: {
3117 MVT CurNodeVT = N.getSimpleValueType();
3118 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3121 // Get the size of this case.
3122 CaseSize = MatcherTable[MatcherIndex++];
3124 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3125 if (CaseSize == 0) break;
3127 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3128 if (CaseVT == MVT::iPTR)
3129 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3131 // If the VT matches, then we will execute this case.
3132 if (CurNodeVT == CaseVT)
3135 // Otherwise, skip over this case.
3136 MatcherIndex += CaseSize;
3139 // If no cases matched, bail out.
3140 if (CaseSize == 0) break;
3142 // Otherwise, execute the case we found.
3143 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3144 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
3147 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
3148 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
3149 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
3150 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
3151 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3152 CurDAG->getDataLayout(),
3153 Opcode - OPC_CheckChild0Type))
3156 case OPC_CheckCondCode:
3157 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3159 case OPC_CheckValueType:
3160 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3161 CurDAG->getDataLayout()))
3164 case OPC_CheckInteger:
3165 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3167 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
3168 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
3169 case OPC_CheckChild4Integer:
3170 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3171 Opcode-OPC_CheckChild0Integer)) break;
3173 case OPC_CheckAndImm:
3174 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3176 case OPC_CheckOrImm:
3177 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3180 case OPC_CheckFoldableChainNode: {
3181 assert(NodeStack.size() != 1 && "No parent node");
3182 // Verify that all intermediate nodes between the root and this one have
3184 bool HasMultipleUses = false;
3185 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
3186 if (!NodeStack[i].getNode()->hasOneUse()) {
3187 HasMultipleUses = true;
3190 if (HasMultipleUses) break;
3192 // Check to see that the target thinks this is profitable to fold and that
3193 // we can fold it without inducing cycles in the graph.
3194 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3196 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3197 NodeToMatch, OptLevel,
3198 true/*We validate our own chains*/))
3203 case OPC_EmitInteger: {
3204 MVT::SimpleValueType VT =
3205 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3206 int64_t Val = MatcherTable[MatcherIndex++];
3208 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3209 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3210 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3214 case OPC_EmitRegister: {
3215 MVT::SimpleValueType VT =
3216 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3217 unsigned RegNo = MatcherTable[MatcherIndex++];
3218 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3219 CurDAG->getRegister(RegNo, VT), nullptr));
3222 case OPC_EmitRegister2: {
3223 // For targets w/ more than 256 register names, the register enum
3224 // values are stored in two bytes in the matcher table (just like
3226 MVT::SimpleValueType VT =
3227 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3228 unsigned RegNo = MatcherTable[MatcherIndex++];
3229 RegNo |= MatcherTable[MatcherIndex++] << 8;
3230 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3231 CurDAG->getRegister(RegNo, VT), nullptr));
3235 case OPC_EmitConvertToTarget: {
3236 // Convert from IMM/FPIMM to target version.
3237 unsigned RecNo = MatcherTable[MatcherIndex++];
3238 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3239 SDValue Imm = RecordedNodes[RecNo].first;
3241 if (Imm->getOpcode() == ISD::Constant) {
3242 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3243 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3244 Imm.getValueType());
3245 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3246 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3247 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3248 Imm.getValueType());
3251 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3255 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3256 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3257 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3258 // These are space-optimized forms of OPC_EmitMergeInputChains.
3259 assert(!InputChain.getNode() &&
3260 "EmitMergeInputChains should be the first chain producing node");
3261 assert(ChainNodesMatched.empty() &&
3262 "Should only have one EmitMergeInputChains per match");
3264 // Read all of the chained nodes.
3265 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3266 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3267 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3269 // FIXME: What if other value results of the node have uses not matched
3271 if (ChainNodesMatched.back() != NodeToMatch &&
3272 !RecordedNodes[RecNo].first.hasOneUse()) {
3273 ChainNodesMatched.clear();
3277 // Merge the input chains if they are not intra-pattern references.
3278 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3280 if (!InputChain.getNode())
3281 break; // Failed to merge.
3285 case OPC_EmitMergeInputChains: {
3286 assert(!InputChain.getNode() &&
3287 "EmitMergeInputChains should be the first chain producing node");
3288 // This node gets a list of nodes we matched in the input that have
3289 // chains. We want to token factor all of the input chains to these nodes
3290 // together. However, if any of the input chains is actually one of the
3291 // nodes matched in this pattern, then we have an intra-match reference.
3292 // Ignore these because the newly token factored chain should not refer to
3294 unsigned NumChains = MatcherTable[MatcherIndex++];
3295 assert(NumChains != 0 && "Can't TF zero chains");
3297 assert(ChainNodesMatched.empty() &&
3298 "Should only have one EmitMergeInputChains per match");
3300 // Read all of the chained nodes.
3301 for (unsigned i = 0; i != NumChains; ++i) {
3302 unsigned RecNo = MatcherTable[MatcherIndex++];
3303 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3304 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3306 // FIXME: What if other value results of the node have uses not matched
3308 if (ChainNodesMatched.back() != NodeToMatch &&
3309 !RecordedNodes[RecNo].first.hasOneUse()) {
3310 ChainNodesMatched.clear();
3315 // If the inner loop broke out, the match fails.
3316 if (ChainNodesMatched.empty())
3319 // Merge the input chains if they are not intra-pattern references.
3320 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3322 if (!InputChain.getNode())
3323 break; // Failed to merge.
3328 case OPC_EmitCopyToReg: {
3329 unsigned RecNo = MatcherTable[MatcherIndex++];
3330 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3331 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3333 if (!InputChain.getNode())
3334 InputChain = CurDAG->getEntryNode();
3336 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3337 DestPhysReg, RecordedNodes[RecNo].first,
3340 InputGlue = InputChain.getValue(1);
3344 case OPC_EmitNodeXForm: {
3345 unsigned XFormNo = MatcherTable[MatcherIndex++];
3346 unsigned RecNo = MatcherTable[MatcherIndex++];
3347 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3348 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3349 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3352 case OPC_Coverage: {
3353 // This is emitted right before MorphNode/EmitNode.
3354 // So it should be safe to assume that this node has been selected
3355 unsigned index = MatcherTable[MatcherIndex++];
3356 index |= (MatcherTable[MatcherIndex++] << 8);
3357 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3358 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3362 case OPC_EmitNode: case OPC_MorphNodeTo:
3363 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
3364 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
3365 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3366 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3367 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3368 // Get the result VT list.
3370 // If this is one of the compressed forms, get the number of VTs based
3371 // on the Opcode. Otherwise read the next byte from the table.
3372 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3373 NumVTs = Opcode - OPC_MorphNodeTo0;
3374 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3375 NumVTs = Opcode - OPC_EmitNode0;
3377 NumVTs = MatcherTable[MatcherIndex++];
3378 SmallVector<EVT, 4> VTs;
3379 for (unsigned i = 0; i != NumVTs; ++i) {
3380 MVT::SimpleValueType VT =
3381 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3382 if (VT == MVT::iPTR)
3383 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3387 if (EmitNodeInfo & OPFL_Chain)
3388 VTs.push_back(MVT::Other);
3389 if (EmitNodeInfo & OPFL_GlueOutput)
3390 VTs.push_back(MVT::Glue);
3392 // This is hot code, so optimize the two most common cases of 1 and 2
3395 if (VTs.size() == 1)
3396 VTList = CurDAG->getVTList(VTs[0]);
3397 else if (VTs.size() == 2)
3398 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3400 VTList = CurDAG->getVTList(VTs);
3402 // Get the operand list.
3403 unsigned NumOps = MatcherTable[MatcherIndex++];
3404 SmallVector<SDValue, 8> Ops;
3405 for (unsigned i = 0; i != NumOps; ++i) {
3406 unsigned RecNo = MatcherTable[MatcherIndex++];
3408 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3410 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3411 Ops.push_back(RecordedNodes[RecNo].first);
3414 // If there are variadic operands to add, handle them now.
3415 if (EmitNodeInfo & OPFL_VariadicInfo) {
3416 // Determine the start index to copy from.
3417 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3418 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3419 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3420 "Invalid variadic node");
3421 // Copy all of the variadic operands, not including a potential glue
3423 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3425 SDValue V = NodeToMatch->getOperand(i);
3426 if (V.getValueType() == MVT::Glue) break;
3431 // If this has chain/glue inputs, add them.
3432 if (EmitNodeInfo & OPFL_Chain)
3433 Ops.push_back(InputChain);
3434 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3435 Ops.push_back(InputGlue);
3438 SDNode *Res = nullptr;
3439 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3440 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3441 if (!IsMorphNodeTo) {
3442 // If this is a normal EmitNode command, just create the new node and
3443 // add the results to the RecordedNodes list.
3444 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3447 // Add all the non-glue/non-chain results to the RecordedNodes list.
3448 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3449 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3450 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3454 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3455 "NodeToMatch was removed partway through selection");
3456 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
3458 auto &Chain = ChainNodesMatched;
3459 assert((!E || !is_contained(Chain, N)) &&
3460 "Chain node replaced during MorphNode");
3461 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end());
3463 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3466 // If the node had chain/glue results, update our notion of the current
3468 if (EmitNodeInfo & OPFL_GlueOutput) {
3469 InputGlue = SDValue(Res, VTs.size()-1);
3470 if (EmitNodeInfo & OPFL_Chain)
3471 InputChain = SDValue(Res, VTs.size()-2);
3472 } else if (EmitNodeInfo & OPFL_Chain)
3473 InputChain = SDValue(Res, VTs.size()-1);
3475 // If the OPFL_MemRefs glue is set on this node, slap all of the
3476 // accumulated memrefs onto it.
3478 // FIXME: This is vastly incorrect for patterns with multiple outputs
3479 // instructions that access memory and for ComplexPatterns that match
3481 if (EmitNodeInfo & OPFL_MemRefs) {
3482 // Only attach load or store memory operands if the generated
3483 // instruction may load or store.
3484 const MCInstrDesc &MCID = TII->get(TargetOpc);
3485 bool mayLoad = MCID.mayLoad();
3486 bool mayStore = MCID.mayStore();
3488 unsigned NumMemRefs = 0;
3489 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3490 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3491 if ((*I)->isLoad()) {
3494 } else if ((*I)->isStore()) {
3502 MachineSDNode::mmo_iterator MemRefs =
3503 MF->allocateMemRefsArray(NumMemRefs);
3505 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3506 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3507 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3508 if ((*I)->isLoad()) {
3511 } else if ((*I)->isStore()) {
3519 cast<MachineSDNode>(Res)
3520 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3524 << (IsMorphNodeTo ? "Morphed" : "Created")
3525 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3527 // If this was a MorphNodeTo then we're completely done!
3528 if (IsMorphNodeTo) {
3529 // Update chain uses.
3530 UpdateChains(Res, InputChain, ChainNodesMatched, true);
3536 case OPC_CompleteMatch: {
3537 // The match has been completed, and any new nodes (if any) have been
3538 // created. Patch up references to the matched dag to use the newly
3540 unsigned NumResults = MatcherTable[MatcherIndex++];
3542 for (unsigned i = 0; i != NumResults; ++i) {
3543 unsigned ResSlot = MatcherTable[MatcherIndex++];
3545 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3547 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3548 SDValue Res = RecordedNodes[ResSlot].first;
3550 assert(i < NodeToMatch->getNumValues() &&
3551 NodeToMatch->getValueType(i) != MVT::Other &&
3552 NodeToMatch->getValueType(i) != MVT::Glue &&
3553 "Invalid number of results to complete!");
3554 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3555 NodeToMatch->getValueType(i) == MVT::iPTR ||
3556 Res.getValueType() == MVT::iPTR ||
3557 NodeToMatch->getValueType(i).getSizeInBits() ==
3558 Res.getValueSizeInBits()) &&
3559 "invalid replacement");
3560 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3563 // Update chain uses.
3564 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3566 // If the root node defines glue, we need to update it to the glue result.
3567 // TODO: This never happens in our tests and I think it can be removed /
3568 // replaced with an assert, but if we do it this the way the change is
3570 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3572 InputGlue.getNode())
3573 CurDAG->ReplaceAllUsesOfValueWith(
3574 SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue);
3576 assert(NodeToMatch->use_empty() &&
3577 "Didn't replace all uses of the node?");
3578 CurDAG->RemoveDeadNode(NodeToMatch);
3584 // If the code reached this point, then the match failed. See if there is
3585 // another child to try in the current 'Scope', otherwise pop it until we
3586 // find a case to check.
3587 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
3588 ++NumDAGIselRetries;
3590 if (MatchScopes.empty()) {
3591 CannotYetSelect(NodeToMatch);
3595 // Restore the interpreter state back to the point where the scope was
3597 MatchScope &LastScope = MatchScopes.back();
3598 RecordedNodes.resize(LastScope.NumRecordedNodes);
3600 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3601 N = NodeStack.back();
3603 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3604 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3605 MatcherIndex = LastScope.FailIndex;
3607 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3609 InputChain = LastScope.InputChain;
3610 InputGlue = LastScope.InputGlue;
3611 if (!LastScope.HasChainNodesMatched)
3612 ChainNodesMatched.clear();
3614 // Check to see what the offset is at the new MatcherIndex. If it is zero
3615 // we have reached the end of this scope, otherwise we have another child
3616 // in the current scope to try.
3617 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3618 if (NumToSkip & 128)
3619 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3621 // If we have another child in this scope to match, update FailIndex and
3623 if (NumToSkip != 0) {
3624 LastScope.FailIndex = MatcherIndex+NumToSkip;
3628 // End of this scope, pop it and try the next child in the containing
3630 MatchScopes.pop_back();
3635 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3637 raw_string_ostream Msg(msg);
3638 Msg << "Cannot select: ";
3640 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3641 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3642 N->getOpcode() != ISD::INTRINSIC_VOID) {
3643 N->printrFull(Msg, CurDAG);
3644 Msg << "\nIn function: " << MF->getName();
3646 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3648 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3649 if (iid < Intrinsic::num_intrinsics)
3650 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None);
3651 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3652 Msg << "target intrinsic %" << TII->getName(iid);
3654 Msg << "unknown intrinsic #" << iid;
3656 report_fatal_error(Msg.str());
3659 char SelectionDAGISel::ID = 0;