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 #define DEBUG_TYPE "isel"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuilder.h"
17 #include "FunctionLoweringInfo.h"
18 #include "llvm/CodeGen/SelectionDAGISel.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/DebugInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetIntrinsicInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/Statistic.h"
53 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
54 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
57 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
58 cl::desc("Enable verbose messages in the \"fast\" "
59 "instruction selector"));
61 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
62 cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
67 cl::desc("Pop up a window to show dags before the first "
70 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
71 cl::desc("Pop up a window to show dags before legalize types"));
73 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before legalize"));
76 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before the second "
80 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
81 cl::desc("Pop up a window to show dags before the post legalize types"
82 " dag combine pass"));
84 ViewISelDAGs("view-isel-dags", cl::Hidden,
85 cl::desc("Pop up a window to show isel dags as they are selected"));
87 ViewSchedDAGs("view-sched-dags", cl::Hidden,
88 cl::desc("Pop up a window to show sched dags as they are processed"));
90 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
91 cl::desc("Pop up a window to show SUnit dags after they are processed"));
93 static const bool ViewDAGCombine1 = false,
94 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
95 ViewDAGCombine2 = false,
96 ViewDAGCombineLT = false,
97 ViewISelDAGs = false, ViewSchedDAGs = false,
98 ViewSUnitDAGs = false;
101 //===---------------------------------------------------------------------===//
103 /// RegisterScheduler class - Track the registration of instruction schedulers.
105 //===---------------------------------------------------------------------===//
106 MachinePassRegistry RegisterScheduler::Registry;
108 //===---------------------------------------------------------------------===//
110 /// ISHeuristic command line option for instruction schedulers.
112 //===---------------------------------------------------------------------===//
113 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
114 RegisterPassParser<RegisterScheduler> >
115 ISHeuristic("pre-RA-sched",
116 cl::init(&createDefaultScheduler),
117 cl::desc("Instruction schedulers available (before register"
120 static RegisterScheduler
121 defaultListDAGScheduler("default", "Best scheduler for the target",
122 createDefaultScheduler);
125 //===--------------------------------------------------------------------===//
126 /// createDefaultScheduler - This creates an instruction scheduler appropriate
128 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
129 CodeGenOpt::Level OptLevel) {
130 const TargetLowering &TLI = IS->getTargetLowering();
132 if (OptLevel == CodeGenOpt::None)
133 return createFastDAGScheduler(IS, OptLevel);
134 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
135 return createTDListDAGScheduler(IS, OptLevel);
136 assert(TLI.getSchedulingPreference() ==
137 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
138 return createBURRListDAGScheduler(IS, OptLevel);
142 // EmitInstrWithCustomInserter - This method should be implemented by targets
143 // that mark instructions with the 'usesCustomInserter' flag. These
144 // instructions are special in various ways, which require special support to
145 // insert. The specified MachineInstr is created but not inserted into any
146 // basic blocks, and this method is called to expand it into a sequence of
147 // instructions, potentially also creating new basic blocks and control flow.
148 // When new basic blocks are inserted and the edges from MBB to its successors
149 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
151 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
152 MachineBasicBlock *MBB,
153 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
155 dbgs() << "If a target marks an instruction with "
156 "'usesCustomInserter', it must implement "
157 "TargetLowering::EmitInstrWithCustomInserter!";
163 //===----------------------------------------------------------------------===//
164 // SelectionDAGISel code
165 //===----------------------------------------------------------------------===//
167 SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm, CodeGenOpt::Level OL) :
168 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
169 FuncInfo(new FunctionLoweringInfo(TLI)),
170 CurDAG(new SelectionDAG(tm, *FuncInfo)),
171 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
177 SelectionDAGISel::~SelectionDAGISel() {
183 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.addRequired<AliasAnalysis>();
185 AU.addPreserved<AliasAnalysis>();
186 AU.addRequired<GCModuleInfo>();
187 AU.addPreserved<GCModuleInfo>();
188 MachineFunctionPass::getAnalysisUsage(AU);
191 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
192 // Do some sanity-checking on the command-line options.
193 assert((!EnableFastISelVerbose || EnableFastISel) &&
194 "-fast-isel-verbose requires -fast-isel");
195 assert((!EnableFastISelAbort || EnableFastISel) &&
196 "-fast-isel-abort requires -fast-isel");
198 const Function &Fn = *mf.getFunction();
199 const TargetInstrInfo &TII = *TM.getInstrInfo();
200 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
203 RegInfo = &MF->getRegInfo();
204 AA = &getAnalysis<AliasAnalysis>();
205 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
207 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
210 FuncInfo->set(Fn, *MF, EnableFastISel);
213 SelectAllBasicBlocks(Fn);
215 // Release function-specific state. SDB and CurDAG are already cleared
219 // If the first basic block in the function has live ins that need to be
220 // copied into vregs, emit the copies into the top of the block before
221 // emitting the code for the block.
222 RegInfo->EmitLiveInCopies(MF->begin(), TRI, TII);
228 SelectionDAGISel::SelectBasicBlock(MachineBasicBlock *BB,
229 const BasicBlock *LLVMBB,
230 BasicBlock::const_iterator Begin,
231 BasicBlock::const_iterator End,
233 // Lower all of the non-terminator instructions. If a call is emitted
234 // as a tail call, cease emitting nodes for this block. Terminators
235 // are handled below.
236 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
239 // Make sure the root of the DAG is up-to-date.
240 CurDAG->setRoot(SDB->getControlRoot());
242 // Final step, emit the lowered DAG as machine code.
243 BB = CodeGenAndEmitDAG(BB);
244 HadTailCall = SDB->HasTailCall;
250 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
251 /// nodes from the worklist.
252 class SDOPsWorkListRemover : public SelectionDAG::DAGUpdateListener {
253 SmallVector<SDNode*, 128> &Worklist;
254 SmallPtrSet<SDNode*, 128> &InWorklist;
256 SDOPsWorkListRemover(SmallVector<SDNode*, 128> &wl,
257 SmallPtrSet<SDNode*, 128> &inwl)
258 : Worklist(wl), InWorklist(inwl) {}
260 void RemoveFromWorklist(SDNode *N) {
261 if (!InWorklist.erase(N)) return;
263 SmallVector<SDNode*, 128>::iterator I =
264 std::find(Worklist.begin(), Worklist.end(), N);
265 assert(I != Worklist.end() && "Not in worklist");
267 *I = Worklist.back();
271 virtual void NodeDeleted(SDNode *N, SDNode *E) {
272 RemoveFromWorklist(N);
275 virtual void NodeUpdated(SDNode *N) {
281 /// TrivialTruncElim - Eliminate some trivial nops that can result from
282 /// ShrinkDemandedOps: (trunc (ext n)) -> n.
283 static bool TrivialTruncElim(SDValue Op,
284 TargetLowering::TargetLoweringOpt &TLO) {
285 SDValue N0 = Op.getOperand(0);
286 EVT VT = Op.getValueType();
287 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
288 N0.getOpcode() == ISD::SIGN_EXTEND ||
289 N0.getOpcode() == ISD::ANY_EXTEND) &&
290 N0.getOperand(0).getValueType() == VT) {
291 return TLO.CombineTo(Op, N0.getOperand(0));
296 /// ShrinkDemandedOps - A late transformation pass that shrink expressions
297 /// using TargetLowering::TargetLoweringOpt::ShrinkDemandedOp. It converts
298 /// x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
299 void SelectionDAGISel::ShrinkDemandedOps() {
300 SmallVector<SDNode*, 128> Worklist;
301 SmallPtrSet<SDNode*, 128> InWorklist;
303 // Add all the dag nodes to the worklist.
304 Worklist.reserve(CurDAG->allnodes_size());
305 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
306 E = CurDAG->allnodes_end(); I != E; ++I) {
307 Worklist.push_back(I);
308 InWorklist.insert(I);
311 TargetLowering::TargetLoweringOpt TLO(*CurDAG, true, true, true);
312 while (!Worklist.empty()) {
313 SDNode *N = Worklist.pop_back_val();
316 if (N->use_empty() && N != CurDAG->getRoot().getNode()) {
317 // Deleting this node may make its operands dead, add them to the worklist
318 // if they aren't already there.
319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
320 if (InWorklist.insert(N->getOperand(i).getNode()))
321 Worklist.push_back(N->getOperand(i).getNode());
323 CurDAG->DeleteNode(N);
327 // Run ShrinkDemandedOp on scalar binary operations.
328 if (N->getNumValues() != 1 ||
329 !N->getValueType(0).isSimple() || !N->getValueType(0).isInteger())
332 unsigned BitWidth = N->getValueType(0).getScalarType().getSizeInBits();
333 APInt Demanded = APInt::getAllOnesValue(BitWidth);
334 APInt KnownZero, KnownOne;
335 if (!TLI.SimplifyDemandedBits(SDValue(N, 0), Demanded,
336 KnownZero, KnownOne, TLO) &&
337 (N->getOpcode() != ISD::TRUNCATE ||
338 !TrivialTruncElim(SDValue(N, 0), TLO)))
342 assert(!InWorklist.count(N) && "Already in worklist");
343 Worklist.push_back(N);
344 InWorklist.insert(N);
346 // Replace the old value with the new one.
347 DEBUG(errs() << "\nShrinkDemandedOps replacing ";
348 TLO.Old.getNode()->dump(CurDAG);
349 errs() << "\nWith: ";
350 TLO.New.getNode()->dump(CurDAG);
353 if (InWorklist.insert(TLO.New.getNode()))
354 Worklist.push_back(TLO.New.getNode());
356 SDOPsWorkListRemover DeadNodes(Worklist, InWorklist);
357 CurDAG->ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
359 if (!TLO.Old.getNode()->use_empty()) continue;
361 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands();
363 SDNode *OpNode = TLO.Old.getNode()->getOperand(i).getNode();
364 if (OpNode->hasOneUse()) {
365 // Add OpNode to the end of the list to revisit.
366 DeadNodes.RemoveFromWorklist(OpNode);
367 Worklist.push_back(OpNode);
368 InWorklist.insert(OpNode);
372 DeadNodes.RemoveFromWorklist(TLO.Old.getNode());
373 CurDAG->DeleteNode(TLO.Old.getNode());
377 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
378 SmallPtrSet<SDNode*, 128> VisitedNodes;
379 SmallVector<SDNode*, 128> Worklist;
381 Worklist.push_back(CurDAG->getRoot().getNode());
388 SDNode *N = Worklist.pop_back_val();
390 // If we've already seen this node, ignore it.
391 if (!VisitedNodes.insert(N))
394 // Otherwise, add all chain operands to the worklist.
395 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
396 if (N->getOperand(i).getValueType() == MVT::Other)
397 Worklist.push_back(N->getOperand(i).getNode());
399 // If this is a CopyToReg with a vreg dest, process it.
400 if (N->getOpcode() != ISD::CopyToReg)
403 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
404 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
407 // Ignore non-scalar or non-integer values.
408 SDValue Src = N->getOperand(2);
409 EVT SrcVT = Src.getValueType();
410 if (!SrcVT.isInteger() || SrcVT.isVector())
413 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
414 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
415 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
417 // Only install this information if it tells us something.
418 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
419 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
420 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
421 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
422 FunctionLoweringInfo::LiveOutInfo &LOI =
423 FuncInfo->LiveOutRegInfo[DestReg];
424 LOI.NumSignBits = NumSignBits;
425 LOI.KnownOne = KnownOne;
426 LOI.KnownZero = KnownZero;
428 } while (!Worklist.empty());
431 MachineBasicBlock *SelectionDAGISel::CodeGenAndEmitDAG(MachineBasicBlock *BB) {
432 std::string GroupName;
433 if (TimePassesIsEnabled)
434 GroupName = "Instruction Selection and Scheduling";
435 std::string BlockName;
436 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
437 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
439 BlockName = MF->getFunction()->getNameStr() + ":" +
440 BB->getBasicBlock()->getNameStr();
442 DEBUG(dbgs() << "Initial selection DAG:\n");
443 DEBUG(CurDAG->dump());
445 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
447 // Run the DAG combiner in pre-legalize mode.
448 if (TimePassesIsEnabled) {
449 NamedRegionTimer T("DAG Combining 1", GroupName);
450 CurDAG->Combine(Unrestricted, *AA, OptLevel);
452 CurDAG->Combine(Unrestricted, *AA, OptLevel);
455 DEBUG(dbgs() << "Optimized lowered selection DAG:\n");
456 DEBUG(CurDAG->dump());
458 // Second step, hack on the DAG until it only uses operations and types that
459 // the target supports.
460 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
464 if (TimePassesIsEnabled) {
465 NamedRegionTimer T("Type Legalization", GroupName);
466 Changed = CurDAG->LegalizeTypes();
468 Changed = CurDAG->LegalizeTypes();
471 DEBUG(dbgs() << "Type-legalized selection DAG:\n");
472 DEBUG(CurDAG->dump());
475 if (ViewDAGCombineLT)
476 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
478 // Run the DAG combiner in post-type-legalize mode.
479 if (TimePassesIsEnabled) {
480 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
481 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
483 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
486 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n");
487 DEBUG(CurDAG->dump());
490 if (TimePassesIsEnabled) {
491 NamedRegionTimer T("Vector Legalization", GroupName);
492 Changed = CurDAG->LegalizeVectors();
494 Changed = CurDAG->LegalizeVectors();
498 if (TimePassesIsEnabled) {
499 NamedRegionTimer T("Type Legalization 2", GroupName);
500 CurDAG->LegalizeTypes();
502 CurDAG->LegalizeTypes();
505 if (ViewDAGCombineLT)
506 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
508 // Run the DAG combiner in post-type-legalize mode.
509 if (TimePassesIsEnabled) {
510 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
511 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
513 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
516 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n");
517 DEBUG(CurDAG->dump());
520 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
522 if (TimePassesIsEnabled) {
523 NamedRegionTimer T("DAG Legalization", GroupName);
524 CurDAG->Legalize(OptLevel);
526 CurDAG->Legalize(OptLevel);
529 DEBUG(dbgs() << "Legalized selection DAG:\n");
530 DEBUG(CurDAG->dump());
532 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
534 // Run the DAG combiner in post-legalize mode.
535 if (TimePassesIsEnabled) {
536 NamedRegionTimer T("DAG Combining 2", GroupName);
537 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
539 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
542 DEBUG(dbgs() << "Optimized legalized selection DAG:\n");
543 DEBUG(CurDAG->dump());
545 if (OptLevel != CodeGenOpt::None) {
547 ComputeLiveOutVRegInfo();
550 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
552 // Third, instruction select all of the operations to machine code, adding the
553 // code to the MachineBasicBlock.
554 if (TimePassesIsEnabled) {
555 NamedRegionTimer T("Instruction Selection", GroupName);
556 DoInstructionSelection();
558 DoInstructionSelection();
561 DEBUG(dbgs() << "Selected selection DAG:\n");
562 DEBUG(CurDAG->dump());
564 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
566 // Schedule machine code.
567 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
568 if (TimePassesIsEnabled) {
569 NamedRegionTimer T("Instruction Scheduling", GroupName);
570 Scheduler->Run(CurDAG, BB, BB->end());
572 Scheduler->Run(CurDAG, BB, BB->end());
575 if (ViewSUnitDAGs) Scheduler->viewGraph();
577 // Emit machine code to BB. This can change 'BB' to the last block being
579 if (TimePassesIsEnabled) {
580 NamedRegionTimer T("Instruction Creation", GroupName);
581 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
583 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
586 // Free the scheduler state.
587 if (TimePassesIsEnabled) {
588 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
597 void SelectionDAGISel::DoInstructionSelection() {
598 DEBUG(errs() << "===== Instruction selection begins:\n");
602 // Select target instructions for the DAG.
604 // Number all nodes with a topological order and set DAGSize.
605 DAGSize = CurDAG->AssignTopologicalOrder();
607 // Create a dummy node (which is not added to allnodes), that adds
608 // a reference to the root node, preventing it from being deleted,
609 // and tracking any changes of the root.
610 HandleSDNode Dummy(CurDAG->getRoot());
611 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
614 // The AllNodes list is now topological-sorted. Visit the
615 // nodes by starting at the end of the list (the root of the
616 // graph) and preceding back toward the beginning (the entry
618 while (ISelPosition != CurDAG->allnodes_begin()) {
619 SDNode *Node = --ISelPosition;
620 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
621 // but there are currently some corner cases that it misses. Also, this
622 // makes it theoretically possible to disable the DAGCombiner.
623 if (Node->use_empty())
626 SDNode *ResNode = Select(Node);
628 // FIXME: This is pretty gross. 'Select' should be changed to not return
629 // anything at all and this code should be nuked with a tactical strike.
631 // If node should not be replaced, continue with the next one.
632 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
636 ReplaceUses(Node, ResNode);
638 // If after the replacement this node is not used any more,
639 // remove this dead node.
640 if (Node->use_empty()) { // Don't delete EntryToken, etc.
641 ISelUpdater ISU(ISelPosition);
642 CurDAG->RemoveDeadNode(Node, &ISU);
646 CurDAG->setRoot(Dummy.getValue());
648 DEBUG(errs() << "===== Instruction selection ends:\n");
650 PostprocessISelDAG();
653 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
654 /// do other setup for EH landing-pad blocks.
655 void SelectionDAGISel::PrepareEHLandingPad(MachineBasicBlock *BB) {
656 // Add a label to mark the beginning of the landing pad. Deletion of the
657 // landing pad can thus be detected via the MachineModuleInfo.
658 MCSymbol *Label = MF->getMMI().addLandingPad(BB);
660 const TargetInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
661 BuildMI(BB, SDB->getCurDebugLoc(), II).addSym(Label);
663 // Mark exception register as live in.
664 unsigned Reg = TLI.getExceptionAddressRegister();
665 if (Reg) BB->addLiveIn(Reg);
667 // Mark exception selector register as live in.
668 Reg = TLI.getExceptionSelectorRegister();
669 if (Reg) BB->addLiveIn(Reg);
671 // FIXME: Hack around an exception handling flaw (PR1508): the personality
672 // function and list of typeids logically belong to the invoke (or, if you
673 // like, the basic block containing the invoke), and need to be associated
674 // with it in the dwarf exception handling tables. Currently however the
675 // information is provided by an intrinsic (eh.selector) that can be moved
676 // to unexpected places by the optimizers: if the unwind edge is critical,
677 // then breaking it can result in the intrinsics being in the successor of
678 // the landing pad, not the landing pad itself. This results
679 // in exceptions not being caught because no typeids are associated with
680 // the invoke. This may not be the only way things can go wrong, but it
681 // is the only way we try to work around for the moment.
682 const BasicBlock *LLVMBB = BB->getBasicBlock();
683 const BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
685 if (Br && Br->isUnconditional()) { // Critical edge?
686 BasicBlock::const_iterator I, E;
687 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
688 if (isa<EHSelectorInst>(I))
692 // No catch info found - try to extract some from the successor.
693 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
697 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
698 // Initialize the Fast-ISel state, if needed.
699 FastISel *FastIS = 0;
701 FastIS = TLI.createFastISel(*MF, FuncInfo->ValueMap, FuncInfo->MBBMap,
702 FuncInfo->StaticAllocaMap,
703 FuncInfo->PHINodesToUpdate
705 , FuncInfo->CatchInfoLost
709 // Iterate over all basic blocks in the function.
710 for (Function::const_iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
711 const BasicBlock *LLVMBB = &*I;
712 MachineBasicBlock *BB = FuncInfo->MBBMap[LLVMBB];
714 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
715 BasicBlock::const_iterator const End = LLVMBB->end();
716 BasicBlock::const_iterator BI = Begin;
718 // Lower any arguments needed in this block if this is the entry block.
719 bool SuppressFastISel = false;
720 if (LLVMBB == &Fn.getEntryBlock()) {
721 LowerArguments(LLVMBB);
723 // If any of the arguments has the byval attribute, forgo
724 // fast-isel in the entry block.
727 for (Function::const_arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
729 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
730 if (EnableFastISelVerbose || EnableFastISelAbort)
731 dbgs() << "FastISel skips entry block due to byval argument\n";
732 SuppressFastISel = true;
738 // Setup an EH landing-pad block.
739 if (BB->isLandingPad())
740 PrepareEHLandingPad(BB);
742 // Before doing SelectionDAG ISel, see if FastISel has been requested.
743 if (FastIS && !SuppressFastISel) {
744 // Emit code for any incoming arguments. This must happen before
745 // beginning FastISel on the entry block.
746 if (LLVMBB == &Fn.getEntryBlock()) {
747 CurDAG->setRoot(SDB->getControlRoot());
748 BB = CodeGenAndEmitDAG(BB);
751 FastIS->startNewBlock(BB);
752 // Do FastISel on as many instructions as possible.
753 for (; BI != End; ++BI) {
754 // Try to select the instruction with FastISel.
755 if (FastIS->SelectInstruction(BI))
758 // Then handle certain instructions as single-LLVM-Instruction blocks.
759 if (isa<CallInst>(BI)) {
760 ++NumFastIselFailures;
761 if (EnableFastISelVerbose || EnableFastISelAbort) {
762 dbgs() << "FastISel missed call: ";
766 if (!BI->getType()->isVoidTy() && !BI->use_empty()) {
767 unsigned &R = FuncInfo->ValueMap[BI];
769 R = FuncInfo->CreateRegForValue(BI);
772 bool HadTailCall = false;
773 BB = SelectBasicBlock(BB, LLVMBB, BI, llvm::next(BI), HadTailCall);
775 // If the call was emitted as a tail call, we're done with the block.
781 // If the instruction was codegen'd with multiple blocks,
782 // inform the FastISel object where to resume inserting.
783 FastIS->setCurrentBlock(BB);
787 // Otherwise, give up on FastISel for the rest of the block.
788 // For now, be a little lenient about non-branch terminators.
789 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
790 ++NumFastIselFailures;
791 if (EnableFastISelVerbose || EnableFastISelAbort) {
792 dbgs() << "FastISel miss: ";
795 if (EnableFastISelAbort)
796 // The "fast" selector couldn't handle something and bailed.
797 // For the purpose of debugging, just abort.
798 llvm_unreachable("FastISel didn't select the entire block");
804 // Run SelectionDAG instruction selection on the remainder of the block
805 // not handled by FastISel. If FastISel is not run, this is the entire
809 BB = SelectBasicBlock(BB, LLVMBB, BI, End, HadTailCall);
812 FinishBasicBlock(BB);
813 FuncInfo->PHINodesToUpdate.clear();
820 SelectionDAGISel::FinishBasicBlock(MachineBasicBlock *BB) {
822 DEBUG(dbgs() << "Target-post-processed machine code:\n");
825 DEBUG(dbgs() << "Total amount of phi nodes to update: "
826 << FuncInfo->PHINodesToUpdate.size() << "\n");
827 DEBUG(for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
828 dbgs() << "Node " << i << " : ("
829 << FuncInfo->PHINodesToUpdate[i].first
830 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
832 // Next, now that we know what the last MBB the LLVM BB expanded is, update
833 // PHI nodes in successors.
834 if (SDB->SwitchCases.empty() &&
835 SDB->JTCases.empty() &&
836 SDB->BitTestCases.empty()) {
837 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
838 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
839 assert(PHI->isPHI() &&
840 "This is not a machine PHI node that we are updating!");
841 if (!BB->isSuccessor(PHI->getParent()))
844 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
845 PHI->addOperand(MachineOperand::CreateMBB(BB));
850 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
851 // Lower header first, if it wasn't already lowered
852 if (!SDB->BitTestCases[i].Emitted) {
853 // Set the current basic block to the mbb we wish to insert the code into
854 BB = SDB->BitTestCases[i].Parent;
856 SDB->visitBitTestHeader(SDB->BitTestCases[i], BB);
857 CurDAG->setRoot(SDB->getRoot());
858 BB = CodeGenAndEmitDAG(BB);
862 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
863 // Set the current basic block to the mbb we wish to insert the code into
864 BB = SDB->BitTestCases[i].Cases[j].ThisBB;
867 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
868 SDB->BitTestCases[i].Reg,
869 SDB->BitTestCases[i].Cases[j],
872 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
873 SDB->BitTestCases[i].Reg,
874 SDB->BitTestCases[i].Cases[j],
878 CurDAG->setRoot(SDB->getRoot());
879 BB = CodeGenAndEmitDAG(BB);
884 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
886 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
887 MachineBasicBlock *PHIBB = PHI->getParent();
888 assert(PHI->isPHI() &&
889 "This is not a machine PHI node that we are updating!");
890 // This is "default" BB. We have two jumps to it. From "header" BB and
891 // from last "case" BB.
892 if (PHIBB == SDB->BitTestCases[i].Default) {
893 PHI->addOperand(MachineOperand::
894 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
896 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
897 PHI->addOperand(MachineOperand::
898 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
900 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
903 // One of "cases" BB.
904 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
906 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
907 if (cBB->isSuccessor(PHIBB)) {
908 PHI->addOperand(MachineOperand::
909 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
911 PHI->addOperand(MachineOperand::CreateMBB(cBB));
916 SDB->BitTestCases.clear();
918 // If the JumpTable record is filled in, then we need to emit a jump table.
919 // Updating the PHI nodes is tricky in this case, since we need to determine
920 // whether the PHI is a successor of the range check MBB or the jump table MBB
921 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
922 // Lower header first, if it wasn't already lowered
923 if (!SDB->JTCases[i].first.Emitted) {
924 // Set the current basic block to the mbb we wish to insert the code into
925 BB = SDB->JTCases[i].first.HeaderBB;
927 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
929 CurDAG->setRoot(SDB->getRoot());
930 BB = CodeGenAndEmitDAG(BB);
934 // Set the current basic block to the mbb we wish to insert the code into
935 BB = SDB->JTCases[i].second.MBB;
937 SDB->visitJumpTable(SDB->JTCases[i].second);
938 CurDAG->setRoot(SDB->getRoot());
939 BB = CodeGenAndEmitDAG(BB);
943 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
945 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
946 MachineBasicBlock *PHIBB = PHI->getParent();
947 assert(PHI->isPHI() &&
948 "This is not a machine PHI node that we are updating!");
949 // "default" BB. We can go there only from header BB.
950 if (PHIBB == SDB->JTCases[i].second.Default) {
952 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
955 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
957 // JT BB. Just iterate over successors here
958 if (BB->isSuccessor(PHIBB)) {
960 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
962 PHI->addOperand(MachineOperand::CreateMBB(BB));
966 SDB->JTCases.clear();
968 // If the switch block involved a branch to one of the actual successors, we
969 // need to update PHI nodes in that block.
970 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
971 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
972 assert(PHI->isPHI() &&
973 "This is not a machine PHI node that we are updating!");
974 if (BB->isSuccessor(PHI->getParent())) {
976 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
977 PHI->addOperand(MachineOperand::CreateMBB(BB));
981 // If we generated any switch lowering information, build and codegen any
982 // additional DAGs necessary.
983 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
984 // Set the current basic block to the mbb we wish to insert the code into
985 MachineBasicBlock *ThisBB = BB = SDB->SwitchCases[i].ThisBB;
988 SDB->visitSwitchCase(SDB->SwitchCases[i], BB);
989 CurDAG->setRoot(SDB->getRoot());
990 BB = CodeGenAndEmitDAG(BB);
992 // Handle any PHI nodes in successors of this chunk, as if we were coming
993 // from the original BB before switch expansion. Note that PHI nodes can
994 // occur multiple times in PHINodesToUpdate. We have to be very careful to
995 // handle them the right number of times.
996 while ((BB = SDB->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
997 // If new BB's are created during scheduling, the edges may have been
998 // updated. That is, the edge from ThisBB to BB may have been split and
999 // BB's predecessor is now another block.
1000 DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
1001 SDB->EdgeMapping.find(BB);
1002 if (EI != SDB->EdgeMapping.end())
1003 ThisBB = EI->second;
1005 // BB may have been removed from the CFG if a branch was constant folded.
1006 if (ThisBB->isSuccessor(BB)) {
1007 for (MachineBasicBlock::iterator Phi = BB->begin();
1008 Phi != BB->end() && Phi->isPHI();
1010 // This value for this PHI node is recorded in PHINodesToUpdate.
1011 for (unsigned pn = 0; ; ++pn) {
1012 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1013 "Didn't find PHI entry!");
1014 if (FuncInfo->PHINodesToUpdate[pn].first == Phi) {
1015 Phi->addOperand(MachineOperand::
1016 CreateReg(FuncInfo->PHINodesToUpdate[pn].second,
1018 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1025 // Don't process RHS if same block as LHS.
1026 if (BB == SDB->SwitchCases[i].FalseBB)
1027 SDB->SwitchCases[i].FalseBB = 0;
1029 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1030 SDB->SwitchCases[i].TrueBB = SDB->SwitchCases[i].FalseBB;
1031 SDB->SwitchCases[i].FalseBB = 0;
1033 assert(SDB->SwitchCases[i].TrueBB == 0 && SDB->SwitchCases[i].FalseBB == 0);
1036 SDB->SwitchCases.clear();
1040 /// Create the scheduler. If a specific scheduler was specified
1041 /// via the SchedulerRegistry, use it, otherwise select the
1042 /// one preferred by the target.
1044 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1045 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1049 RegisterScheduler::setDefault(Ctor);
1052 return Ctor(this, OptLevel);
1055 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1056 return new ScheduleHazardRecognizer();
1059 //===----------------------------------------------------------------------===//
1060 // Helper functions used by the generated instruction selector.
1061 //===----------------------------------------------------------------------===//
1062 // Calls to these methods are generated by tblgen.
1064 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1065 /// the dag combiner simplified the 255, we still want to match. RHS is the
1066 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1067 /// specified in the .td file (e.g. 255).
1068 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1069 int64_t DesiredMaskS) const {
1070 const APInt &ActualMask = RHS->getAPIntValue();
1071 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1073 // If the actual mask exactly matches, success!
1074 if (ActualMask == DesiredMask)
1077 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1078 if (ActualMask.intersects(~DesiredMask))
1081 // Otherwise, the DAG Combiner may have proven that the value coming in is
1082 // either already zero or is not demanded. Check for known zero input bits.
1083 APInt NeededMask = DesiredMask & ~ActualMask;
1084 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1087 // TODO: check to see if missing bits are just not demanded.
1089 // Otherwise, this pattern doesn't match.
1093 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1094 /// the dag combiner simplified the 255, we still want to match. RHS is the
1095 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1096 /// specified in the .td file (e.g. 255).
1097 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1098 int64_t DesiredMaskS) const {
1099 const APInt &ActualMask = RHS->getAPIntValue();
1100 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1102 // If the actual mask exactly matches, success!
1103 if (ActualMask == DesiredMask)
1106 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1107 if (ActualMask.intersects(~DesiredMask))
1110 // Otherwise, the DAG Combiner may have proven that the value coming in is
1111 // either already zero or is not demanded. Check for known zero input bits.
1112 APInt NeededMask = DesiredMask & ~ActualMask;
1114 APInt KnownZero, KnownOne;
1115 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1117 // If all the missing bits in the or are already known to be set, match!
1118 if ((NeededMask & KnownOne) == NeededMask)
1121 // TODO: check to see if missing bits are just not demanded.
1123 // Otherwise, this pattern doesn't match.
1128 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1129 /// by tblgen. Others should not call it.
1130 void SelectionDAGISel::
1131 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1132 std::vector<SDValue> InOps;
1133 std::swap(InOps, Ops);
1135 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1136 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1137 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1139 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1140 if (InOps[e-1].getValueType() == MVT::Flag)
1141 --e; // Don't process a flag operand if it is here.
1144 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1145 if (!InlineAsm::isMemKind(Flags)) {
1146 // Just skip over this operand, copying the operands verbatim.
1147 Ops.insert(Ops.end(), InOps.begin()+i,
1148 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1149 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1151 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1152 "Memory operand with multiple values?");
1153 // Otherwise, this is a memory operand. Ask the target to select it.
1154 std::vector<SDValue> SelOps;
1155 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1156 report_fatal_error("Could not match memory address. Inline asm"
1159 // Add this to the output node.
1161 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1162 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1163 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1168 // Add the flag input back if present.
1169 if (e != InOps.size())
1170 Ops.push_back(InOps.back());
1173 /// findFlagUse - Return use of EVT::Flag value produced by the specified
1176 static SDNode *findFlagUse(SDNode *N) {
1177 unsigned FlagResNo = N->getNumValues()-1;
1178 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1179 SDUse &Use = I.getUse();
1180 if (Use.getResNo() == FlagResNo)
1181 return Use.getUser();
1186 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1187 /// This function recursively traverses up the operand chain, ignoring
1189 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1190 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1191 bool IgnoreChains) {
1192 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1193 // greater than all of its (recursive) operands. If we scan to a point where
1194 // 'use' is smaller than the node we're scanning for, then we know we will
1197 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1198 // happen because we scan down to newly selected nodes in the case of flag
1200 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1203 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1204 // won't fail if we scan it again.
1205 if (!Visited.insert(Use))
1208 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1209 // Ignore chain uses, they are validated by HandleMergeInputChains.
1210 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1213 SDNode *N = Use->getOperand(i).getNode();
1215 if (Use == ImmedUse || Use == Root)
1216 continue; // We are not looking for immediate use.
1221 // Traverse up the operand chain.
1222 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1228 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1229 /// operand node N of U during instruction selection that starts at Root.
1230 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1231 SDNode *Root) const {
1232 if (OptLevel == CodeGenOpt::None) return false;
1233 return N.hasOneUse();
1236 /// IsLegalToFold - Returns true if the specific operand node N of
1237 /// U can be folded during instruction selection that starts at Root.
1238 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1239 CodeGenOpt::Level OptLevel,
1240 bool IgnoreChains) {
1241 if (OptLevel == CodeGenOpt::None) return false;
1243 // If Root use can somehow reach N through a path that that doesn't contain
1244 // U then folding N would create a cycle. e.g. In the following
1245 // diagram, Root can reach N through X. If N is folded into into Root, then
1246 // X is both a predecessor and a successor of U.
1257 // * indicates nodes to be folded together.
1259 // If Root produces a flag, then it gets (even more) interesting. Since it
1260 // will be "glued" together with its flag use in the scheduler, we need to
1261 // check if it might reach N.
1280 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1281 // (call it Fold), then X is a predecessor of FU and a successor of
1282 // Fold. But since Fold and FU are flagged together, this will create
1283 // a cycle in the scheduling graph.
1285 // If the node has flags, walk down the graph to the "lowest" node in the
1287 EVT VT = Root->getValueType(Root->getNumValues()-1);
1288 while (VT == MVT::Flag) {
1289 SDNode *FU = findFlagUse(Root);
1293 VT = Root->getValueType(Root->getNumValues()-1);
1295 // If our query node has a flag result with a use, we've walked up it. If
1296 // the user (which has already been selected) has a chain or indirectly uses
1297 // the chain, our WalkChainUsers predicate will not consider it. Because of
1298 // this, we cannot ignore chains in this predicate.
1299 IgnoreChains = false;
1303 SmallPtrSet<SDNode*, 16> Visited;
1304 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1307 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1308 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1309 SelectInlineAsmMemoryOperands(Ops);
1311 std::vector<EVT> VTs;
1312 VTs.push_back(MVT::Other);
1313 VTs.push_back(MVT::Flag);
1314 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
1315 VTs, &Ops[0], Ops.size());
1317 return New.getNode();
1320 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1321 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1324 /// GetVBR - decode a vbr encoding whose top bit is set.
1325 ALWAYS_INLINE static uint64_t
1326 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1327 assert(Val >= 128 && "Not a VBR");
1328 Val &= 127; // Remove first vbr bit.
1333 NextBits = MatcherTable[Idx++];
1334 Val |= (NextBits&127) << Shift;
1336 } while (NextBits & 128);
1342 /// UpdateChainsAndFlags - When a match is complete, this method updates uses of
1343 /// interior flag and chain results to use the new flag and chain results.
1344 void SelectionDAGISel::
1345 UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
1346 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1348 const SmallVectorImpl<SDNode*> &FlagResultNodesMatched,
1349 bool isMorphNodeTo) {
1350 SmallVector<SDNode*, 4> NowDeadNodes;
1352 ISelUpdater ISU(ISelPosition);
1354 // Now that all the normal results are replaced, we replace the chain and
1355 // flag results if present.
1356 if (!ChainNodesMatched.empty()) {
1357 assert(InputChain.getNode() != 0 &&
1358 "Matched input chains but didn't produce a chain");
1359 // Loop over all of the nodes we matched that produced a chain result.
1360 // Replace all the chain results with the final chain we ended up with.
1361 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1362 SDNode *ChainNode = ChainNodesMatched[i];
1364 // If this node was already deleted, don't look at it.
1365 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1368 // Don't replace the results of the root node if we're doing a
1370 if (ChainNode == NodeToMatch && isMorphNodeTo)
1373 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1374 if (ChainVal.getValueType() == MVT::Flag)
1375 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1376 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1377 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1379 // If the node became dead and we haven't already seen it, delete it.
1380 if (ChainNode->use_empty() &&
1381 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1382 NowDeadNodes.push_back(ChainNode);
1386 // If the result produces a flag, update any flag results in the matched
1387 // pattern with the flag result.
1388 if (InputFlag.getNode() != 0) {
1389 // Handle any interior nodes explicitly marked.
1390 for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
1391 SDNode *FRN = FlagResultNodesMatched[i];
1393 // If this node was already deleted, don't look at it.
1394 if (FRN->getOpcode() == ISD::DELETED_NODE)
1397 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
1398 "Doesn't have a flag result");
1399 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1402 // If the node became dead and we haven't already seen it, delete it.
1403 if (FRN->use_empty() &&
1404 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1405 NowDeadNodes.push_back(FRN);
1409 if (!NowDeadNodes.empty())
1410 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1412 DEBUG(errs() << "ISEL: Match complete!\n");
1418 CR_LeadsToInteriorNode
1421 /// WalkChainUsers - Walk down the users of the specified chained node that is
1422 /// part of the pattern we're matching, looking at all of the users we find.
1423 /// This determines whether something is an interior node, whether we have a
1424 /// non-pattern node in between two pattern nodes (which prevent folding because
1425 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1426 /// between pattern nodes (in which case the TF becomes part of the pattern).
1428 /// The walk we do here is guaranteed to be small because we quickly get down to
1429 /// already selected nodes "below" us.
1431 WalkChainUsers(SDNode *ChainedNode,
1432 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1433 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1434 ChainResult Result = CR_Simple;
1436 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1437 E = ChainedNode->use_end(); UI != E; ++UI) {
1438 // Make sure the use is of the chain, not some other value we produce.
1439 if (UI.getUse().getValueType() != MVT::Other) continue;
1443 // If we see an already-selected machine node, then we've gone beyond the
1444 // pattern that we're selecting down into the already selected chunk of the
1446 if (User->isMachineOpcode() ||
1447 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1450 if (User->getOpcode() == ISD::CopyToReg ||
1451 User->getOpcode() == ISD::CopyFromReg ||
1452 User->getOpcode() == ISD::INLINEASM ||
1453 User->getOpcode() == ISD::EH_LABEL) {
1454 // If their node ID got reset to -1 then they've already been selected.
1455 // Treat them like a MachineOpcode.
1456 if (User->getNodeId() == -1)
1460 // If we have a TokenFactor, we handle it specially.
1461 if (User->getOpcode() != ISD::TokenFactor) {
1462 // If the node isn't a token factor and isn't part of our pattern, then it
1463 // must be a random chained node in between two nodes we're selecting.
1464 // This happens when we have something like:
1469 // Because we structurally match the load/store as a read/modify/write,
1470 // but the call is chained between them. We cannot fold in this case
1471 // because it would induce a cycle in the graph.
1472 if (!std::count(ChainedNodesInPattern.begin(),
1473 ChainedNodesInPattern.end(), User))
1474 return CR_InducesCycle;
1476 // Otherwise we found a node that is part of our pattern. For example in:
1480 // This would happen when we're scanning down from the load and see the
1481 // store as a user. Record that there is a use of ChainedNode that is
1482 // part of the pattern and keep scanning uses.
1483 Result = CR_LeadsToInteriorNode;
1484 InteriorChainedNodes.push_back(User);
1488 // If we found a TokenFactor, there are two cases to consider: first if the
1489 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1490 // uses of the TF are in our pattern) we just want to ignore it. Second,
1491 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1497 // | \ DAG's like cheese
1500 // [TokenFactor] [Op]
1507 // In this case, the TokenFactor becomes part of our match and we rewrite it
1508 // as a new TokenFactor.
1510 // To distinguish these two cases, do a recursive walk down the uses.
1511 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1513 // If the uses of the TokenFactor are just already-selected nodes, ignore
1514 // it, it is "below" our pattern.
1516 case CR_InducesCycle:
1517 // If the uses of the TokenFactor lead to nodes that are not part of our
1518 // pattern that are not selected, folding would turn this into a cycle,
1520 return CR_InducesCycle;
1521 case CR_LeadsToInteriorNode:
1522 break; // Otherwise, keep processing.
1525 // Okay, we know we're in the interesting interior case. The TokenFactor
1526 // is now going to be considered part of the pattern so that we rewrite its
1527 // uses (it may have uses that are not part of the pattern) with the
1528 // ultimate chain result of the generated code. We will also add its chain
1529 // inputs as inputs to the ultimate TokenFactor we create.
1530 Result = CR_LeadsToInteriorNode;
1531 ChainedNodesInPattern.push_back(User);
1532 InteriorChainedNodes.push_back(User);
1539 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1540 /// operation for when the pattern matched at least one node with a chains. The
1541 /// input vector contains a list of all of the chained nodes that we match. We
1542 /// must determine if this is a valid thing to cover (i.e. matching it won't
1543 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1544 /// be used as the input node chain for the generated nodes.
1546 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1547 SelectionDAG *CurDAG) {
1548 // Walk all of the chained nodes we've matched, recursively scanning down the
1549 // users of the chain result. This adds any TokenFactor nodes that are caught
1550 // in between chained nodes to the chained and interior nodes list.
1551 SmallVector<SDNode*, 3> InteriorChainedNodes;
1552 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1553 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1554 InteriorChainedNodes) == CR_InducesCycle)
1555 return SDValue(); // Would induce a cycle.
1558 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1559 // that we are interested in. Form our input TokenFactor node.
1560 SmallVector<SDValue, 3> InputChains;
1561 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1562 // Add the input chain of this node to the InputChains list (which will be
1563 // the operands of the generated TokenFactor) if it's not an interior node.
1564 SDNode *N = ChainNodesMatched[i];
1565 if (N->getOpcode() != ISD::TokenFactor) {
1566 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1569 // Otherwise, add the input chain.
1570 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1571 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1572 InputChains.push_back(InChain);
1576 // If we have a token factor, we want to add all inputs of the token factor
1577 // that are not part of the pattern we're matching.
1578 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1579 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1580 N->getOperand(op).getNode()))
1581 InputChains.push_back(N->getOperand(op));
1586 if (InputChains.size() == 1)
1587 return InputChains[0];
1588 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1589 MVT::Other, &InputChains[0], InputChains.size());
1592 /// MorphNode - Handle morphing a node in place for the selector.
1593 SDNode *SelectionDAGISel::
1594 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1595 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1596 // It is possible we're using MorphNodeTo to replace a node with no
1597 // normal results with one that has a normal result (or we could be
1598 // adding a chain) and the input could have flags and chains as well.
1599 // In this case we need to shift the operands down.
1600 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1601 // than the old isel though.
1602 int OldFlagResultNo = -1, OldChainResultNo = -1;
1604 unsigned NTMNumResults = Node->getNumValues();
1605 if (Node->getValueType(NTMNumResults-1) == MVT::Flag) {
1606 OldFlagResultNo = NTMNumResults-1;
1607 if (NTMNumResults != 1 &&
1608 Node->getValueType(NTMNumResults-2) == MVT::Other)
1609 OldChainResultNo = NTMNumResults-2;
1610 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1611 OldChainResultNo = NTMNumResults-1;
1613 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1614 // that this deletes operands of the old node that become dead.
1615 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1617 // MorphNodeTo can operate in two ways: if an existing node with the
1618 // specified operands exists, it can just return it. Otherwise, it
1619 // updates the node in place to have the requested operands.
1621 // If we updated the node in place, reset the node ID. To the isel,
1622 // this should be just like a newly allocated machine node.
1626 unsigned ResNumResults = Res->getNumValues();
1627 // Move the flag if needed.
1628 if ((EmitNodeInfo & OPFL_FlagOutput) && OldFlagResultNo != -1 &&
1629 (unsigned)OldFlagResultNo != ResNumResults-1)
1630 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldFlagResultNo),
1631 SDValue(Res, ResNumResults-1));
1633 if ((EmitNodeInfo & OPFL_FlagOutput) != 0)
1636 // Move the chain reference if needed.
1637 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1638 (unsigned)OldChainResultNo != ResNumResults-1)
1639 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1640 SDValue(Res, ResNumResults-1));
1642 // Otherwise, no replacement happened because the node already exists. Replace
1643 // Uses of the old node with the new one.
1645 CurDAG->ReplaceAllUsesWith(Node, Res);
1650 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1651 ALWAYS_INLINE static bool
1652 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1653 SDValue N, const SmallVectorImpl<SDValue> &RecordedNodes) {
1654 // Accept if it is exactly the same as a previously recorded node.
1655 unsigned RecNo = MatcherTable[MatcherIndex++];
1656 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1657 return N == RecordedNodes[RecNo];
1660 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1661 ALWAYS_INLINE static bool
1662 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1663 SelectionDAGISel &SDISel) {
1664 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1667 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
1668 ALWAYS_INLINE static bool
1669 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1670 SelectionDAGISel &SDISel, SDNode *N) {
1671 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1674 ALWAYS_INLINE static bool
1675 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1677 uint16_t Opc = MatcherTable[MatcherIndex++];
1678 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1679 return N->getOpcode() == Opc;
1682 ALWAYS_INLINE static bool
1683 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1684 SDValue N, const TargetLowering &TLI) {
1685 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1686 if (N.getValueType() == VT) return true;
1688 // Handle the case when VT is iPTR.
1689 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1692 ALWAYS_INLINE static bool
1693 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1694 SDValue N, const TargetLowering &TLI,
1696 if (ChildNo >= N.getNumOperands())
1697 return false; // Match fails if out of range child #.
1698 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1702 ALWAYS_INLINE static bool
1703 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1705 return cast<CondCodeSDNode>(N)->get() ==
1706 (ISD::CondCode)MatcherTable[MatcherIndex++];
1709 ALWAYS_INLINE static bool
1710 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1711 SDValue N, const TargetLowering &TLI) {
1712 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1713 if (cast<VTSDNode>(N)->getVT() == VT)
1716 // Handle the case when VT is iPTR.
1717 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1720 ALWAYS_INLINE static bool
1721 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1723 int64_t Val = MatcherTable[MatcherIndex++];
1725 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1728 return C != 0 && C->getSExtValue() == Val;
1731 ALWAYS_INLINE static bool
1732 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1733 SDValue N, SelectionDAGISel &SDISel) {
1734 int64_t Val = MatcherTable[MatcherIndex++];
1736 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1738 if (N->getOpcode() != ISD::AND) return false;
1740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1741 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1744 ALWAYS_INLINE static bool
1745 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1746 SDValue N, SelectionDAGISel &SDISel) {
1747 int64_t Val = MatcherTable[MatcherIndex++];
1749 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1751 if (N->getOpcode() != ISD::OR) return false;
1753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1754 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1757 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
1758 /// scope, evaluate the current node. If the current predicate is known to
1759 /// fail, set Result=true and return anything. If the current predicate is
1760 /// known to pass, set Result=false and return the MatcherIndex to continue
1761 /// with. If the current predicate is unknown, set Result=false and return the
1762 /// MatcherIndex to continue with.
1763 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1764 unsigned Index, SDValue N,
1765 bool &Result, SelectionDAGISel &SDISel,
1766 SmallVectorImpl<SDValue> &RecordedNodes){
1767 switch (Table[Index++]) {
1770 return Index-1; // Could not evaluate this predicate.
1771 case SelectionDAGISel::OPC_CheckSame:
1772 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1774 case SelectionDAGISel::OPC_CheckPatternPredicate:
1775 Result = !::CheckPatternPredicate(Table, Index, SDISel);
1777 case SelectionDAGISel::OPC_CheckPredicate:
1778 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
1780 case SelectionDAGISel::OPC_CheckOpcode:
1781 Result = !::CheckOpcode(Table, Index, N.getNode());
1783 case SelectionDAGISel::OPC_CheckType:
1784 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1786 case SelectionDAGISel::OPC_CheckChild0Type:
1787 case SelectionDAGISel::OPC_CheckChild1Type:
1788 case SelectionDAGISel::OPC_CheckChild2Type:
1789 case SelectionDAGISel::OPC_CheckChild3Type:
1790 case SelectionDAGISel::OPC_CheckChild4Type:
1791 case SelectionDAGISel::OPC_CheckChild5Type:
1792 case SelectionDAGISel::OPC_CheckChild6Type:
1793 case SelectionDAGISel::OPC_CheckChild7Type:
1794 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1795 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
1797 case SelectionDAGISel::OPC_CheckCondCode:
1798 Result = !::CheckCondCode(Table, Index, N);
1800 case SelectionDAGISel::OPC_CheckValueType:
1801 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1803 case SelectionDAGISel::OPC_CheckInteger:
1804 Result = !::CheckInteger(Table, Index, N);
1806 case SelectionDAGISel::OPC_CheckAndImm:
1807 Result = !::CheckAndImm(Table, Index, N, SDISel);
1809 case SelectionDAGISel::OPC_CheckOrImm:
1810 Result = !::CheckOrImm(Table, Index, N, SDISel);
1818 /// FailIndex - If this match fails, this is the index to continue with.
1821 /// NodeStack - The node stack when the scope was formed.
1822 SmallVector<SDValue, 4> NodeStack;
1824 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1825 unsigned NumRecordedNodes;
1827 /// NumMatchedMemRefs - The number of matched memref entries.
1828 unsigned NumMatchedMemRefs;
1830 /// InputChain/InputFlag - The current chain/flag
1831 SDValue InputChain, InputFlag;
1833 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1834 bool HasChainNodesMatched, HasFlagResultNodesMatched;
1839 SDNode *SelectionDAGISel::
1840 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1841 unsigned TableSize) {
1842 // FIXME: Should these even be selected? Handle these cases in the caller?
1843 switch (NodeToMatch->getOpcode()) {
1846 case ISD::EntryToken: // These nodes remain the same.
1847 case ISD::BasicBlock:
1849 //case ISD::VALUETYPE:
1850 //case ISD::CONDCODE:
1851 case ISD::HANDLENODE:
1852 case ISD::MDNODE_SDNODE:
1853 case ISD::TargetConstant:
1854 case ISD::TargetConstantFP:
1855 case ISD::TargetConstantPool:
1856 case ISD::TargetFrameIndex:
1857 case ISD::TargetExternalSymbol:
1858 case ISD::TargetBlockAddress:
1859 case ISD::TargetJumpTable:
1860 case ISD::TargetGlobalTLSAddress:
1861 case ISD::TargetGlobalAddress:
1862 case ISD::TokenFactor:
1863 case ISD::CopyFromReg:
1864 case ISD::CopyToReg:
1866 NodeToMatch->setNodeId(-1); // Mark selected.
1868 case ISD::AssertSext:
1869 case ISD::AssertZext:
1870 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
1871 NodeToMatch->getOperand(0));
1873 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
1874 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
1877 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
1879 // Set up the node stack with NodeToMatch as the only node on the stack.
1880 SmallVector<SDValue, 8> NodeStack;
1881 SDValue N = SDValue(NodeToMatch, 0);
1882 NodeStack.push_back(N);
1884 // MatchScopes - Scopes used when matching, if a match failure happens, this
1885 // indicates where to continue checking.
1886 SmallVector<MatchScope, 8> MatchScopes;
1888 // RecordedNodes - This is the set of nodes that have been recorded by the
1890 SmallVector<SDValue, 8> RecordedNodes;
1892 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
1894 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
1896 // These are the current input chain and flag for use when generating nodes.
1897 // Various Emit operations change these. For example, emitting a copytoreg
1898 // uses and updates these.
1899 SDValue InputChain, InputFlag;
1901 // ChainNodesMatched - If a pattern matches nodes that have input/output
1902 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
1903 // which ones they are. The result is captured into this list so that we can
1904 // update the chain results when the pattern is complete.
1905 SmallVector<SDNode*, 3> ChainNodesMatched;
1906 SmallVector<SDNode*, 3> FlagResultNodesMatched;
1908 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
1909 NodeToMatch->dump(CurDAG);
1912 // Determine where to start the interpreter. Normally we start at opcode #0,
1913 // but if the state machine starts with an OPC_SwitchOpcode, then we
1914 // accelerate the first lookup (which is guaranteed to be hot) with the
1915 // OpcodeOffset table.
1916 unsigned MatcherIndex = 0;
1918 if (!OpcodeOffset.empty()) {
1919 // Already computed the OpcodeOffset table, just index into it.
1920 if (N.getOpcode() < OpcodeOffset.size())
1921 MatcherIndex = OpcodeOffset[N.getOpcode()];
1922 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
1924 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
1925 // Otherwise, the table isn't computed, but the state machine does start
1926 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
1927 // is the first time we're selecting an instruction.
1930 // Get the size of this case.
1931 unsigned CaseSize = MatcherTable[Idx++];
1933 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
1934 if (CaseSize == 0) break;
1936 // Get the opcode, add the index to the table.
1937 uint16_t Opc = MatcherTable[Idx++];
1938 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
1939 if (Opc >= OpcodeOffset.size())
1940 OpcodeOffset.resize((Opc+1)*2);
1941 OpcodeOffset[Opc] = Idx;
1945 // Okay, do the lookup for the first opcode.
1946 if (N.getOpcode() < OpcodeOffset.size())
1947 MatcherIndex = OpcodeOffset[N.getOpcode()];
1951 assert(MatcherIndex < TableSize && "Invalid index");
1953 unsigned CurrentOpcodeIndex = MatcherIndex;
1955 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
1958 // Okay, the semantics of this operation are that we should push a scope
1959 // then evaluate the first child. However, pushing a scope only to have
1960 // the first check fail (which then pops it) is inefficient. If we can
1961 // determine immediately that the first check (or first several) will
1962 // immediately fail, don't even bother pushing a scope for them.
1966 unsigned NumToSkip = MatcherTable[MatcherIndex++];
1967 if (NumToSkip & 128)
1968 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
1969 // Found the end of the scope with no match.
1970 if (NumToSkip == 0) {
1975 FailIndex = MatcherIndex+NumToSkip;
1977 unsigned MatcherIndexOfPredicate = MatcherIndex;
1978 (void)MatcherIndexOfPredicate; // silence warning.
1980 // If we can't evaluate this predicate without pushing a scope (e.g. if
1981 // it is a 'MoveParent') or if the predicate succeeds on this node, we
1982 // push the scope and evaluate the full predicate chain.
1984 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
1985 Result, *this, RecordedNodes);
1989 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
1990 << "index " << MatcherIndexOfPredicate
1991 << ", continuing at " << FailIndex << "\n");
1992 ++NumDAGIselRetries;
1994 // Otherwise, we know that this case of the Scope is guaranteed to fail,
1995 // move to the next case.
1996 MatcherIndex = FailIndex;
1999 // If the whole scope failed to match, bail.
2000 if (FailIndex == 0) break;
2002 // Push a MatchScope which indicates where to go if the first child fails
2004 MatchScope NewEntry;
2005 NewEntry.FailIndex = FailIndex;
2006 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2007 NewEntry.NumRecordedNodes = RecordedNodes.size();
2008 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2009 NewEntry.InputChain = InputChain;
2010 NewEntry.InputFlag = InputFlag;
2011 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2012 NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
2013 MatchScopes.push_back(NewEntry);
2016 case OPC_RecordNode:
2017 // Remember this node, it may end up being an operand in the pattern.
2018 RecordedNodes.push_back(N);
2021 case OPC_RecordChild0: case OPC_RecordChild1:
2022 case OPC_RecordChild2: case OPC_RecordChild3:
2023 case OPC_RecordChild4: case OPC_RecordChild5:
2024 case OPC_RecordChild6: case OPC_RecordChild7: {
2025 unsigned ChildNo = Opcode-OPC_RecordChild0;
2026 if (ChildNo >= N.getNumOperands())
2027 break; // Match fails if out of range child #.
2029 RecordedNodes.push_back(N->getOperand(ChildNo));
2032 case OPC_RecordMemRef:
2033 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2036 case OPC_CaptureFlagInput:
2037 // If the current node has an input flag, capture it in InputFlag.
2038 if (N->getNumOperands() != 0 &&
2039 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
2040 InputFlag = N->getOperand(N->getNumOperands()-1);
2043 case OPC_MoveChild: {
2044 unsigned ChildNo = MatcherTable[MatcherIndex++];
2045 if (ChildNo >= N.getNumOperands())
2046 break; // Match fails if out of range child #.
2047 N = N.getOperand(ChildNo);
2048 NodeStack.push_back(N);
2052 case OPC_MoveParent:
2053 // Pop the current node off the NodeStack.
2054 NodeStack.pop_back();
2055 assert(!NodeStack.empty() && "Node stack imbalance!");
2056 N = NodeStack.back();
2060 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2062 case OPC_CheckPatternPredicate:
2063 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2065 case OPC_CheckPredicate:
2066 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2070 case OPC_CheckComplexPat: {
2071 unsigned CPNum = MatcherTable[MatcherIndex++];
2072 unsigned RecNo = MatcherTable[MatcherIndex++];
2073 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2074 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo], CPNum,
2079 case OPC_CheckOpcode:
2080 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2084 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
2087 case OPC_SwitchOpcode: {
2088 unsigned CurNodeOpcode = N.getOpcode();
2089 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2092 // Get the size of this case.
2093 CaseSize = MatcherTable[MatcherIndex++];
2095 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2096 if (CaseSize == 0) break;
2098 uint16_t Opc = MatcherTable[MatcherIndex++];
2099 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2101 // If the opcode matches, then we will execute this case.
2102 if (CurNodeOpcode == Opc)
2105 // Otherwise, skip over this case.
2106 MatcherIndex += CaseSize;
2109 // If no cases matched, bail out.
2110 if (CaseSize == 0) break;
2112 // Otherwise, execute the case we found.
2113 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2114 << " to " << MatcherIndex << "\n");
2118 case OPC_SwitchType: {
2119 MVT::SimpleValueType CurNodeVT = N.getValueType().getSimpleVT().SimpleTy;
2120 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2123 // Get the size of this case.
2124 CaseSize = MatcherTable[MatcherIndex++];
2126 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2127 if (CaseSize == 0) break;
2129 MVT::SimpleValueType CaseVT =
2130 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2131 if (CaseVT == MVT::iPTR)
2132 CaseVT = TLI.getPointerTy().SimpleTy;
2134 // If the VT matches, then we will execute this case.
2135 if (CurNodeVT == CaseVT)
2138 // Otherwise, skip over this case.
2139 MatcherIndex += CaseSize;
2142 // If no cases matched, bail out.
2143 if (CaseSize == 0) break;
2145 // Otherwise, execute the case we found.
2146 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2147 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2150 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2151 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2152 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2153 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2154 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2155 Opcode-OPC_CheckChild0Type))
2158 case OPC_CheckCondCode:
2159 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2161 case OPC_CheckValueType:
2162 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
2164 case OPC_CheckInteger:
2165 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2167 case OPC_CheckAndImm:
2168 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2170 case OPC_CheckOrImm:
2171 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2174 case OPC_CheckFoldableChainNode: {
2175 assert(NodeStack.size() != 1 && "No parent node");
2176 // Verify that all intermediate nodes between the root and this one have
2178 bool HasMultipleUses = false;
2179 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2180 if (!NodeStack[i].hasOneUse()) {
2181 HasMultipleUses = true;
2184 if (HasMultipleUses) break;
2186 // Check to see that the target thinks this is profitable to fold and that
2187 // we can fold it without inducing cycles in the graph.
2188 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2190 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2191 NodeToMatch, OptLevel,
2192 true/*We validate our own chains*/))
2197 case OPC_EmitInteger: {
2198 MVT::SimpleValueType VT =
2199 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2200 int64_t Val = MatcherTable[MatcherIndex++];
2202 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2203 RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
2206 case OPC_EmitRegister: {
2207 MVT::SimpleValueType VT =
2208 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2209 unsigned RegNo = MatcherTable[MatcherIndex++];
2210 RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
2214 case OPC_EmitConvertToTarget: {
2215 // Convert from IMM/FPIMM to target version.
2216 unsigned RecNo = MatcherTable[MatcherIndex++];
2217 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2218 SDValue Imm = RecordedNodes[RecNo];
2220 if (Imm->getOpcode() == ISD::Constant) {
2221 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2222 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2223 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2224 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2225 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2228 RecordedNodes.push_back(Imm);
2232 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2233 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2234 // These are space-optimized forms of OPC_EmitMergeInputChains.
2235 assert(InputChain.getNode() == 0 &&
2236 "EmitMergeInputChains should be the first chain producing node");
2237 assert(ChainNodesMatched.empty() &&
2238 "Should only have one EmitMergeInputChains per match");
2240 // Read all of the chained nodes.
2241 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2242 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2243 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2245 // FIXME: What if other value results of the node have uses not matched
2247 if (ChainNodesMatched.back() != NodeToMatch &&
2248 !RecordedNodes[RecNo].hasOneUse()) {
2249 ChainNodesMatched.clear();
2253 // Merge the input chains if they are not intra-pattern references.
2254 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2256 if (InputChain.getNode() == 0)
2257 break; // Failed to merge.
2261 case OPC_EmitMergeInputChains: {
2262 assert(InputChain.getNode() == 0 &&
2263 "EmitMergeInputChains should be the first chain producing node");
2264 // This node gets a list of nodes we matched in the input that have
2265 // chains. We want to token factor all of the input chains to these nodes
2266 // together. However, if any of the input chains is actually one of the
2267 // nodes matched in this pattern, then we have an intra-match reference.
2268 // Ignore these because the newly token factored chain should not refer to
2270 unsigned NumChains = MatcherTable[MatcherIndex++];
2271 assert(NumChains != 0 && "Can't TF zero chains");
2273 assert(ChainNodesMatched.empty() &&
2274 "Should only have one EmitMergeInputChains per match");
2276 // Read all of the chained nodes.
2277 for (unsigned i = 0; i != NumChains; ++i) {
2278 unsigned RecNo = MatcherTable[MatcherIndex++];
2279 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2280 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2282 // FIXME: What if other value results of the node have uses not matched
2284 if (ChainNodesMatched.back() != NodeToMatch &&
2285 !RecordedNodes[RecNo].hasOneUse()) {
2286 ChainNodesMatched.clear();
2291 // If the inner loop broke out, the match fails.
2292 if (ChainNodesMatched.empty())
2295 // Merge the input chains if they are not intra-pattern references.
2296 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2298 if (InputChain.getNode() == 0)
2299 break; // Failed to merge.
2304 case OPC_EmitCopyToReg: {
2305 unsigned RecNo = MatcherTable[MatcherIndex++];
2306 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2307 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2309 if (InputChain.getNode() == 0)
2310 InputChain = CurDAG->getEntryNode();
2312 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2313 DestPhysReg, RecordedNodes[RecNo],
2316 InputFlag = InputChain.getValue(1);
2320 case OPC_EmitNodeXForm: {
2321 unsigned XFormNo = MatcherTable[MatcherIndex++];
2322 unsigned RecNo = MatcherTable[MatcherIndex++];
2323 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2324 RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
2329 case OPC_MorphNodeTo: {
2330 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2331 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2332 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2333 // Get the result VT list.
2334 unsigned NumVTs = MatcherTable[MatcherIndex++];
2335 SmallVector<EVT, 4> VTs;
2336 for (unsigned i = 0; i != NumVTs; ++i) {
2337 MVT::SimpleValueType VT =
2338 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2339 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2343 if (EmitNodeInfo & OPFL_Chain)
2344 VTs.push_back(MVT::Other);
2345 if (EmitNodeInfo & OPFL_FlagOutput)
2346 VTs.push_back(MVT::Flag);
2348 // This is hot code, so optimize the two most common cases of 1 and 2
2351 if (VTs.size() == 1)
2352 VTList = CurDAG->getVTList(VTs[0]);
2353 else if (VTs.size() == 2)
2354 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2356 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2358 // Get the operand list.
2359 unsigned NumOps = MatcherTable[MatcherIndex++];
2360 SmallVector<SDValue, 8> Ops;
2361 for (unsigned i = 0; i != NumOps; ++i) {
2362 unsigned RecNo = MatcherTable[MatcherIndex++];
2364 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2366 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2367 Ops.push_back(RecordedNodes[RecNo]);
2370 // If there are variadic operands to add, handle them now.
2371 if (EmitNodeInfo & OPFL_VariadicInfo) {
2372 // Determine the start index to copy from.
2373 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2374 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2375 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2376 "Invalid variadic node");
2377 // Copy all of the variadic operands, not including a potential flag
2379 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2381 SDValue V = NodeToMatch->getOperand(i);
2382 if (V.getValueType() == MVT::Flag) break;
2387 // If this has chain/flag inputs, add them.
2388 if (EmitNodeInfo & OPFL_Chain)
2389 Ops.push_back(InputChain);
2390 if ((EmitNodeInfo & OPFL_FlagInput) && InputFlag.getNode() != 0)
2391 Ops.push_back(InputFlag);
2395 if (Opcode != OPC_MorphNodeTo) {
2396 // If this is a normal EmitNode command, just create the new node and
2397 // add the results to the RecordedNodes list.
2398 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2399 VTList, Ops.data(), Ops.size());
2401 // Add all the non-flag/non-chain results to the RecordedNodes list.
2402 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2403 if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
2404 RecordedNodes.push_back(SDValue(Res, i));
2408 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2412 // If the node had chain/flag results, update our notion of the current
2414 if (EmitNodeInfo & OPFL_FlagOutput) {
2415 InputFlag = SDValue(Res, VTs.size()-1);
2416 if (EmitNodeInfo & OPFL_Chain)
2417 InputChain = SDValue(Res, VTs.size()-2);
2418 } else if (EmitNodeInfo & OPFL_Chain)
2419 InputChain = SDValue(Res, VTs.size()-1);
2421 // If the OPFL_MemRefs flag is set on this node, slap all of the
2422 // accumulated memrefs onto it.
2424 // FIXME: This is vastly incorrect for patterns with multiple outputs
2425 // instructions that access memory and for ComplexPatterns that match
2427 if (EmitNodeInfo & OPFL_MemRefs) {
2428 MachineSDNode::mmo_iterator MemRefs =
2429 MF->allocateMemRefsArray(MatchedMemRefs.size());
2430 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2431 cast<MachineSDNode>(Res)
2432 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2436 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2437 << " node: "; Res->dump(CurDAG); errs() << "\n");
2439 // If this was a MorphNodeTo then we're completely done!
2440 if (Opcode == OPC_MorphNodeTo) {
2441 // Update chain and flag uses.
2442 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
2443 InputFlag, FlagResultNodesMatched, true);
2450 case OPC_MarkFlagResults: {
2451 unsigned NumNodes = MatcherTable[MatcherIndex++];
2453 // Read and remember all the flag-result nodes.
2454 for (unsigned i = 0; i != NumNodes; ++i) {
2455 unsigned RecNo = MatcherTable[MatcherIndex++];
2457 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2459 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2460 FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2465 case OPC_CompleteMatch: {
2466 // The match has been completed, and any new nodes (if any) have been
2467 // created. Patch up references to the matched dag to use the newly
2469 unsigned NumResults = MatcherTable[MatcherIndex++];
2471 for (unsigned i = 0; i != NumResults; ++i) {
2472 unsigned ResSlot = MatcherTable[MatcherIndex++];
2474 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2476 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2477 SDValue Res = RecordedNodes[ResSlot];
2479 assert(i < NodeToMatch->getNumValues() &&
2480 NodeToMatch->getValueType(i) != MVT::Other &&
2481 NodeToMatch->getValueType(i) != MVT::Flag &&
2482 "Invalid number of results to complete!");
2483 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2484 NodeToMatch->getValueType(i) == MVT::iPTR ||
2485 Res.getValueType() == MVT::iPTR ||
2486 NodeToMatch->getValueType(i).getSizeInBits() ==
2487 Res.getValueType().getSizeInBits()) &&
2488 "invalid replacement");
2489 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2492 // If the root node defines a flag, add it to the flag nodes to update
2494 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
2495 FlagResultNodesMatched.push_back(NodeToMatch);
2497 // Update chain and flag uses.
2498 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
2499 InputFlag, FlagResultNodesMatched, false);
2501 assert(NodeToMatch->use_empty() &&
2502 "Didn't replace all uses of the node?");
2504 // FIXME: We just return here, which interacts correctly with SelectRoot
2505 // above. We should fix this to not return an SDNode* anymore.
2510 // If the code reached this point, then the match failed. See if there is
2511 // another child to try in the current 'Scope', otherwise pop it until we
2512 // find a case to check.
2513 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2514 ++NumDAGIselRetries;
2516 if (MatchScopes.empty()) {
2517 CannotYetSelect(NodeToMatch);
2521 // Restore the interpreter state back to the point where the scope was
2523 MatchScope &LastScope = MatchScopes.back();
2524 RecordedNodes.resize(LastScope.NumRecordedNodes);
2526 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2527 N = NodeStack.back();
2529 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2530 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2531 MatcherIndex = LastScope.FailIndex;
2533 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2535 InputChain = LastScope.InputChain;
2536 InputFlag = LastScope.InputFlag;
2537 if (!LastScope.HasChainNodesMatched)
2538 ChainNodesMatched.clear();
2539 if (!LastScope.HasFlagResultNodesMatched)
2540 FlagResultNodesMatched.clear();
2542 // Check to see what the offset is at the new MatcherIndex. If it is zero
2543 // we have reached the end of this scope, otherwise we have another child
2544 // in the current scope to try.
2545 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2546 if (NumToSkip & 128)
2547 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2549 // If we have another child in this scope to match, update FailIndex and
2551 if (NumToSkip != 0) {
2552 LastScope.FailIndex = MatcherIndex+NumToSkip;
2556 // End of this scope, pop it and try the next child in the containing
2558 MatchScopes.pop_back();
2565 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2567 raw_string_ostream Msg(msg);
2568 Msg << "Cannot yet select: ";
2570 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2571 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2572 N->getOpcode() != ISD::INTRINSIC_VOID) {
2573 N->printrFull(Msg, CurDAG);
2575 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2577 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2578 if (iid < Intrinsic::num_intrinsics)
2579 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2580 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2581 Msg << "target intrinsic %" << TII->getName(iid);
2583 Msg << "unknown intrinsic #" << iid;
2585 report_fatal_error(Msg.str());
2588 char SelectionDAGISel::ID = 0;