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 "llvm/CodeGen/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/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetIntrinsicInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/Timer.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/ADT/PostOrderIterator.h"
53 #include "llvm/ADT/Statistic.h"
57 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
58 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
59 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
60 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
63 STATISTIC(NumBBWithOutOfOrderLineInfo,
64 "Number of blocks with out of order line number info");
65 STATISTIC(NumMBBWithOutOfOrderLineInfo,
66 "Number of machine blocks with out of order line number info");
70 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
71 cl::desc("Enable verbose messages in the \"fast\" "
72 "instruction selector"));
74 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
75 cl::desc("Enable abort calls when \"fast\" instruction fails"));
79 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before the first "
83 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
84 cl::desc("Pop up a window to show dags before legalize types"));
86 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
87 cl::desc("Pop up a window to show dags before legalize"));
89 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
90 cl::desc("Pop up a window to show dags before the second "
93 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
94 cl::desc("Pop up a window to show dags before the post legalize types"
95 " dag combine pass"));
97 ViewISelDAGs("view-isel-dags", cl::Hidden,
98 cl::desc("Pop up a window to show isel dags as they are selected"));
100 ViewSchedDAGs("view-sched-dags", cl::Hidden,
101 cl::desc("Pop up a window to show sched dags as they are processed"));
103 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
104 cl::desc("Pop up a window to show SUnit dags after they are processed"));
106 static const bool ViewDAGCombine1 = false,
107 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
108 ViewDAGCombine2 = false,
109 ViewDAGCombineLT = false,
110 ViewISelDAGs = false, ViewSchedDAGs = false,
111 ViewSUnitDAGs = false;
114 //===---------------------------------------------------------------------===//
116 /// RegisterScheduler class - Track the registration of instruction schedulers.
118 //===---------------------------------------------------------------------===//
119 MachinePassRegistry RegisterScheduler::Registry;
121 //===---------------------------------------------------------------------===//
123 /// ISHeuristic command line option for instruction schedulers.
125 //===---------------------------------------------------------------------===//
126 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
127 RegisterPassParser<RegisterScheduler> >
128 ISHeuristic("pre-RA-sched",
129 cl::init(&createDefaultScheduler),
130 cl::desc("Instruction schedulers available (before register"
133 static RegisterScheduler
134 defaultListDAGScheduler("default", "Best scheduler for the target",
135 createDefaultScheduler);
138 //===--------------------------------------------------------------------===//
139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
142 CodeGenOpt::Level OptLevel) {
143 const TargetLowering &TLI = IS->getTargetLowering();
145 if (OptLevel == CodeGenOpt::None)
146 return createSourceListDAGScheduler(IS, OptLevel);
147 if (TLI.getSchedulingPreference() == Sched::Latency)
148 return createTDListDAGScheduler(IS, OptLevel);
149 if (TLI.getSchedulingPreference() == Sched::RegPressure)
150 return createBURRListDAGScheduler(IS, OptLevel);
151 if (TLI.getSchedulingPreference() == Sched::Hybrid)
152 return createHybridListDAGScheduler(IS, OptLevel);
153 assert(TLI.getSchedulingPreference() == Sched::ILP &&
154 "Unknown sched type!");
155 return createILPListDAGScheduler(IS, OptLevel);
159 // EmitInstrWithCustomInserter - This method should be implemented by targets
160 // that mark instructions with the 'usesCustomInserter' flag. These
161 // instructions are special in various ways, which require special support to
162 // insert. The specified MachineInstr is created but not inserted into any
163 // basic blocks, and this method is called to expand it into a sequence of
164 // instructions, potentially also creating new basic blocks and control flow.
165 // When new basic blocks are inserted and the edges from MBB to its successors
166 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
169 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
170 MachineBasicBlock *MBB) const {
172 dbgs() << "If a target marks an instruction with "
173 "'usesCustomInserter', it must implement "
174 "TargetLowering::EmitInstrWithCustomInserter!";
180 //===----------------------------------------------------------------------===//
181 // SelectionDAGISel code
182 //===----------------------------------------------------------------------===//
184 SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm,
185 CodeGenOpt::Level OL) :
186 MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
187 FuncInfo(new FunctionLoweringInfo(TLI)),
188 CurDAG(new SelectionDAG(tm)),
189 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
193 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
194 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
197 SelectionDAGISel::~SelectionDAGISel() {
203 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.addRequired<AliasAnalysis>();
205 AU.addPreserved<AliasAnalysis>();
206 AU.addRequired<GCModuleInfo>();
207 AU.addPreserved<GCModuleInfo>();
208 MachineFunctionPass::getAnalysisUsage(AU);
211 /// FunctionCallsSetJmp - Return true if the function has a call to setjmp or
212 /// other function that gcc recognizes as "returning twice". This is used to
213 /// limit code-gen optimizations on the machine function.
215 /// FIXME: Remove after <rdar://problem/8031714> is fixed.
216 static bool FunctionCallsSetJmp(const Function *F) {
217 const Module *M = F->getParent();
218 static const char *ReturnsTwiceFns[] = {
228 #define NUM_RETURNS_TWICE_FNS sizeof(ReturnsTwiceFns) / sizeof(const char *)
230 for (unsigned I = 0; I < NUM_RETURNS_TWICE_FNS; ++I)
231 if (const Function *Callee = M->getFunction(ReturnsTwiceFns[I])) {
232 if (!Callee->use_empty())
233 for (Value::const_use_iterator
234 I = Callee->use_begin(), E = Callee->use_end();
236 if (const CallInst *CI = dyn_cast<CallInst>(*I))
237 if (CI->getParent()->getParent() == F)
242 #undef NUM_RETURNS_TWICE_FNS
245 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
246 /// may trap on it. In this case we have to split the edge so that the path
247 /// through the predecessor block that doesn't go to the phi block doesn't
248 /// execute the possibly trapping instruction.
250 /// This is required for correctness, so it must be done at -O0.
252 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
253 // Loop for blocks with phi nodes.
254 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
255 PHINode *PN = dyn_cast<PHINode>(BB->begin());
256 if (PN == 0) continue;
259 // For each block with a PHI node, check to see if any of the input values
260 // are potentially trapping constant expressions. Constant expressions are
261 // the only potentially trapping value that can occur as the argument to a
263 for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
264 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
265 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
266 if (CE == 0 || !CE->canTrap()) continue;
268 // The only case we have to worry about is when the edge is critical.
269 // Since this block has a PHI Node, we assume it has multiple input
270 // edges: check to see if the pred has multiple successors.
271 BasicBlock *Pred = PN->getIncomingBlock(i);
272 if (Pred->getTerminator()->getNumSuccessors() == 1)
275 // Okay, we have to split this edge.
276 SplitCriticalEdge(Pred->getTerminator(),
277 GetSuccessorNumber(Pred, BB), SDISel, true);
283 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
284 // Do some sanity-checking on the command-line options.
285 assert((!EnableFastISelVerbose || EnableFastISel) &&
286 "-fast-isel-verbose requires -fast-isel");
287 assert((!EnableFastISelAbort || EnableFastISel) &&
288 "-fast-isel-abort requires -fast-isel");
290 const Function &Fn = *mf.getFunction();
291 const TargetInstrInfo &TII = *TM.getInstrInfo();
292 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
295 RegInfo = &MF->getRegInfo();
296 AA = &getAnalysis<AliasAnalysis>();
297 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
299 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
301 SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
304 FuncInfo->set(Fn, *MF);
307 SelectAllBasicBlocks(Fn);
309 // If the first basic block in the function has live ins that need to be
310 // copied into vregs, emit the copies into the top of the block before
311 // emitting the code for the block.
312 MachineBasicBlock *EntryMBB = MF->begin();
313 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
315 DenseMap<unsigned, unsigned> LiveInMap;
316 if (!FuncInfo->ArgDbgValues.empty())
317 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
318 E = RegInfo->livein_end(); LI != E; ++LI)
320 LiveInMap.insert(std::make_pair(LI->first, LI->second));
322 // Insert DBG_VALUE instructions for function arguments to the entry block.
323 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
324 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
325 unsigned Reg = MI->getOperand(0).getReg();
326 if (TargetRegisterInfo::isPhysicalRegister(Reg))
327 EntryMBB->insert(EntryMBB->begin(), MI);
329 MachineInstr *Def = RegInfo->getVRegDef(Reg);
330 MachineBasicBlock::iterator InsertPos = Def;
331 // FIXME: VR def may not be in entry block.
332 Def->getParent()->insert(llvm::next(InsertPos), MI);
335 // If Reg is live-in then update debug info to track its copy in a vreg.
336 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
337 if (LDI != LiveInMap.end()) {
338 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
339 MachineBasicBlock::iterator InsertPos = Def;
340 const MDNode *Variable =
341 MI->getOperand(MI->getNumOperands()-1).getMetadata();
342 unsigned Offset = MI->getOperand(1).getImm();
343 // Def is never a terminator here, so it is ok to increment InsertPos.
344 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
345 TII.get(TargetOpcode::DBG_VALUE))
346 .addReg(LDI->second, RegState::Debug)
347 .addImm(Offset).addMetadata(Variable);
349 // If this vreg is directly copied into an exported register then
350 // that COPY instructions also need DBG_VALUE, if it is the only
351 // user of LDI->second.
352 MachineInstr *CopyUseMI = NULL;
353 for (MachineRegisterInfo::use_iterator
354 UI = RegInfo->use_begin(LDI->second);
355 MachineInstr *UseMI = UI.skipInstruction();) {
356 if (UseMI->isDebugValue()) continue;
357 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
358 CopyUseMI = UseMI; continue;
360 // Otherwise this is another use or second copy use.
361 CopyUseMI = NULL; break;
364 MachineInstr *NewMI =
365 BuildMI(*MF, CopyUseMI->getDebugLoc(),
366 TII.get(TargetOpcode::DBG_VALUE))
367 .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
368 .addImm(Offset).addMetadata(Variable);
369 EntryMBB->insertAfter(CopyUseMI, NewMI);
374 // Determine if there are any calls in this machine function.
375 MachineFrameInfo *MFI = MF->getFrameInfo();
376 if (!MFI->hasCalls()) {
377 for (MachineFunction::const_iterator
378 I = MF->begin(), E = MF->end(); I != E; ++I) {
379 const MachineBasicBlock *MBB = I;
380 for (MachineBasicBlock::const_iterator
381 II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
382 const TargetInstrDesc &TID = TM.getInstrInfo()->get(II->getOpcode());
384 if ((TID.isCall() && !TID.isReturn()) ||
385 II->isStackAligningInlineAsm()) {
386 MFI->setHasCalls(true);
394 // Determine if there is a call to setjmp in the machine function.
395 MF->setCallsSetJmp(FunctionCallsSetJmp(&Fn));
397 // Replace forward-declared registers with the registers containing
398 // the desired value.
399 MachineRegisterInfo &MRI = MF->getRegInfo();
400 for (DenseMap<unsigned, unsigned>::iterator
401 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
403 unsigned From = I->first;
404 unsigned To = I->second;
405 // If To is also scheduled to be replaced, find what its ultimate
408 DenseMap<unsigned, unsigned>::iterator J =
409 FuncInfo->RegFixups.find(To);
414 MRI.replaceRegWith(From, To);
417 // Release function-specific state. SDB and CurDAG are already cleared
425 SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
426 BasicBlock::const_iterator End,
428 // Lower all of the non-terminator instructions. If a call is emitted
429 // as a tail call, cease emitting nodes for this block. Terminators
430 // are handled below.
431 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
434 // Make sure the root of the DAG is up-to-date.
435 CurDAG->setRoot(SDB->getControlRoot());
436 HadTailCall = SDB->HasTailCall;
439 // Final step, emit the lowered DAG as machine code.
444 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
445 SmallPtrSet<SDNode*, 128> VisitedNodes;
446 SmallVector<SDNode*, 128> Worklist;
448 Worklist.push_back(CurDAG->getRoot().getNode());
455 SDNode *N = Worklist.pop_back_val();
457 // If we've already seen this node, ignore it.
458 if (!VisitedNodes.insert(N))
461 // Otherwise, add all chain operands to the worklist.
462 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
463 if (N->getOperand(i).getValueType() == MVT::Other)
464 Worklist.push_back(N->getOperand(i).getNode());
466 // If this is a CopyToReg with a vreg dest, process it.
467 if (N->getOpcode() != ISD::CopyToReg)
470 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
471 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
474 // Ignore non-scalar or non-integer values.
475 SDValue Src = N->getOperand(2);
476 EVT SrcVT = Src.getValueType();
477 if (!SrcVT.isInteger() || SrcVT.isVector())
480 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
481 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
482 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
484 // Only install this information if it tells us something.
485 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
486 FuncInfo->LiveOutRegInfo.grow(DestReg);
487 FunctionLoweringInfo::LiveOutInfo &LOI =
488 FuncInfo->LiveOutRegInfo[DestReg];
489 LOI.NumSignBits = NumSignBits;
490 LOI.KnownOne = KnownOne;
491 LOI.KnownZero = KnownZero;
493 } while (!Worklist.empty());
496 void SelectionDAGISel::CodeGenAndEmitDAG() {
497 std::string GroupName;
498 if (TimePassesIsEnabled)
499 GroupName = "Instruction Selection and Scheduling";
500 std::string BlockName;
501 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
502 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
504 BlockName = MF->getFunction()->getNameStr() + ":" +
505 FuncInfo->MBB->getBasicBlock()->getNameStr();
507 DEBUG(dbgs() << "Initial selection DAG:\n"; CurDAG->dump());
509 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
511 // Run the DAG combiner in pre-legalize mode.
513 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
514 CurDAG->Combine(Unrestricted, *AA, OptLevel);
517 DEBUG(dbgs() << "Optimized lowered selection DAG:\n"; CurDAG->dump());
519 // Second step, hack on the DAG until it only uses operations and types that
520 // the target supports.
521 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
526 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
527 Changed = CurDAG->LegalizeTypes();
530 DEBUG(dbgs() << "Type-legalized selection DAG:\n"; CurDAG->dump());
533 if (ViewDAGCombineLT)
534 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
536 // Run the DAG combiner in post-type-legalize mode.
538 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
539 TimePassesIsEnabled);
540 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
543 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n";
548 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
549 Changed = CurDAG->LegalizeVectors();
554 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
555 CurDAG->LegalizeTypes();
558 if (ViewDAGCombineLT)
559 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
561 // Run the DAG combiner in post-type-legalize mode.
563 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
564 TimePassesIsEnabled);
565 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
568 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n";
572 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
575 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
576 CurDAG->Legalize(OptLevel);
579 DEBUG(dbgs() << "Legalized selection DAG:\n"; CurDAG->dump());
581 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
583 // Run the DAG combiner in post-legalize mode.
585 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
586 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
589 DEBUG(dbgs() << "Optimized legalized selection DAG:\n"; CurDAG->dump());
591 if (OptLevel != CodeGenOpt::None)
592 ComputeLiveOutVRegInfo();
594 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
596 // Third, instruction select all of the operations to machine code, adding the
597 // code to the MachineBasicBlock.
599 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
600 DoInstructionSelection();
603 DEBUG(dbgs() << "Selected selection DAG:\n"; CurDAG->dump());
605 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
607 // Schedule machine code.
608 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
610 NamedRegionTimer T("Instruction Scheduling", GroupName,
611 TimePassesIsEnabled);
612 Scheduler->Run(CurDAG, FuncInfo->MBB, FuncInfo->InsertPt);
615 if (ViewSUnitDAGs) Scheduler->viewGraph();
617 // Emit machine code to BB. This can change 'BB' to the last block being
619 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
621 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
623 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule();
624 FuncInfo->InsertPt = Scheduler->InsertPos;
627 // If the block was split, make sure we update any references that are used to
628 // update PHI nodes later on.
629 if (FirstMBB != LastMBB)
630 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
632 // Free the scheduler state.
634 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
635 TimePassesIsEnabled);
639 // Free the SelectionDAG state, now that we're finished with it.
643 void SelectionDAGISel::DoInstructionSelection() {
644 DEBUG(errs() << "===== Instruction selection begins:\n");
648 // Select target instructions for the DAG.
650 // Number all nodes with a topological order and set DAGSize.
651 DAGSize = CurDAG->AssignTopologicalOrder();
653 // Create a dummy node (which is not added to allnodes), that adds
654 // a reference to the root node, preventing it from being deleted,
655 // and tracking any changes of the root.
656 HandleSDNode Dummy(CurDAG->getRoot());
657 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
660 // The AllNodes list is now topological-sorted. Visit the
661 // nodes by starting at the end of the list (the root of the
662 // graph) and preceding back toward the beginning (the entry
664 while (ISelPosition != CurDAG->allnodes_begin()) {
665 SDNode *Node = --ISelPosition;
666 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
667 // but there are currently some corner cases that it misses. Also, this
668 // makes it theoretically possible to disable the DAGCombiner.
669 if (Node->use_empty())
672 SDNode *ResNode = Select(Node);
674 // FIXME: This is pretty gross. 'Select' should be changed to not return
675 // anything at all and this code should be nuked with a tactical strike.
677 // If node should not be replaced, continue with the next one.
678 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
682 ReplaceUses(Node, ResNode);
684 // If after the replacement this node is not used any more,
685 // remove this dead node.
686 if (Node->use_empty()) { // Don't delete EntryToken, etc.
687 ISelUpdater ISU(ISelPosition);
688 CurDAG->RemoveDeadNode(Node, &ISU);
692 CurDAG->setRoot(Dummy.getValue());
695 DEBUG(errs() << "===== Instruction selection ends:\n");
697 PostprocessISelDAG();
700 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
701 /// do other setup for EH landing-pad blocks.
702 void SelectionDAGISel::PrepareEHLandingPad() {
703 // Add a label to mark the beginning of the landing pad. Deletion of the
704 // landing pad can thus be detected via the MachineModuleInfo.
705 MCSymbol *Label = MF->getMMI().addLandingPad(FuncInfo->MBB);
707 const TargetInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
708 BuildMI(*FuncInfo->MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
711 // Mark exception register as live in.
712 unsigned Reg = TLI.getExceptionAddressRegister();
713 if (Reg) FuncInfo->MBB->addLiveIn(Reg);
715 // Mark exception selector register as live in.
716 Reg = TLI.getExceptionSelectorRegister();
717 if (Reg) FuncInfo->MBB->addLiveIn(Reg);
719 // FIXME: Hack around an exception handling flaw (PR1508): the personality
720 // function and list of typeids logically belong to the invoke (or, if you
721 // like, the basic block containing the invoke), and need to be associated
722 // with it in the dwarf exception handling tables. Currently however the
723 // information is provided by an intrinsic (eh.selector) that can be moved
724 // to unexpected places by the optimizers: if the unwind edge is critical,
725 // then breaking it can result in the intrinsics being in the successor of
726 // the landing pad, not the landing pad itself. This results
727 // in exceptions not being caught because no typeids are associated with
728 // the invoke. This may not be the only way things can go wrong, but it
729 // is the only way we try to work around for the moment.
730 const BasicBlock *LLVMBB = FuncInfo->MBB->getBasicBlock();
731 const BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
733 if (Br && Br->isUnconditional()) { // Critical edge?
734 BasicBlock::const_iterator I, E;
735 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
736 if (isa<EHSelectorInst>(I))
740 // No catch info found - try to extract some from the successor.
741 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
748 bool SelectionDAGISel::TryToFoldFastISelLoad(const LoadInst *LI,
750 // Don't try to fold volatile loads. Target has to deal with alignment
752 if (LI->isVolatile()) return false;
754 // Figure out which vreg this is going into.
755 unsigned LoadReg = FastIS->getRegForValue(LI);
756 assert(LoadReg && "Load isn't already assigned a vreg? ");
758 // Check to see what the uses of this vreg are. If it has no uses, or more
759 // than one use (at the machine instr level) then we can't fold it.
760 MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(LoadReg);
761 if (RI == RegInfo->reg_end())
764 // See if there is exactly one use of the vreg. If there are multiple uses,
765 // then the instruction got lowered to multiple machine instructions or the
766 // use of the loaded value ended up being multiple operands of the result, in
767 // either case, we can't fold this.
768 MachineRegisterInfo::reg_iterator PostRI = RI; ++PostRI;
769 if (PostRI != RegInfo->reg_end())
772 assert(RI.getOperand().isUse() &&
773 "The only use of the vreg must be a use, we haven't emitted the def!");
775 MachineInstr *User = &*RI;
777 // Set the insertion point properly. Folding the load can cause generation of
778 // other random instructions (like sign extends) for addressing modes, make
779 // sure they get inserted in a logical place before the new instruction.
780 FuncInfo->InsertPt = User;
781 FuncInfo->MBB = User->getParent();
783 // Ask the target to try folding the load.
784 return FastIS->TryToFoldLoad(User, RI.getOperandNo(), LI);
788 /// CheckLineNumbers - Check if basic block instructions follow source order
790 static void CheckLineNumbers(const BasicBlock *BB) {
793 for (BasicBlock::const_iterator BI = BB->begin(),
794 BE = BB->end(); BI != BE; ++BI) {
795 const DebugLoc DL = BI->getDebugLoc();
796 if (DL.isUnknown()) continue;
797 unsigned L = DL.getLine();
798 unsigned C = DL.getCol();
799 if (L < Line || (L == Line && C < Col)) {
800 ++NumBBWithOutOfOrderLineInfo;
808 /// CheckLineNumbers - Check if machine basic block instructions follow source
810 static void CheckLineNumbers(const MachineBasicBlock *MBB) {
813 for (MachineBasicBlock::const_iterator MBI = MBB->begin(),
814 MBE = MBB->end(); MBI != MBE; ++MBI) {
815 const DebugLoc DL = MBI->getDebugLoc();
816 if (DL.isUnknown()) continue;
817 unsigned L = DL.getLine();
818 unsigned C = DL.getCol();
819 if (L < Line || (L == Line && C < Col)) {
820 ++NumMBBWithOutOfOrderLineInfo;
829 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
830 // Initialize the Fast-ISel state, if needed.
831 FastISel *FastIS = 0;
833 FastIS = TLI.createFastISel(*FuncInfo);
835 // Iterate over all basic blocks in the function.
836 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
837 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
838 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
839 const BasicBlock *LLVMBB = *I;
841 CheckLineNumbers(LLVMBB);
843 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
844 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
846 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
847 BasicBlock::const_iterator const End = LLVMBB->end();
848 BasicBlock::const_iterator BI = End;
850 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
852 // Setup an EH landing-pad block.
853 if (FuncInfo->MBB->isLandingPad())
854 PrepareEHLandingPad();
856 // Lower any arguments needed in this block if this is the entry block.
857 if (LLVMBB == &Fn.getEntryBlock())
858 LowerArguments(LLVMBB);
860 // Before doing SelectionDAG ISel, see if FastISel has been requested.
862 FastIS->startNewBlock();
864 // Emit code for any incoming arguments. This must happen before
865 // beginning FastISel on the entry block.
866 if (LLVMBB == &Fn.getEntryBlock()) {
867 CurDAG->setRoot(SDB->getControlRoot());
871 // If we inserted any instructions at the beginning, make a note of
872 // where they are, so we can be sure to emit subsequent instructions
874 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
875 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
877 FastIS->setLastLocalValue(0);
880 // Do FastISel on as many instructions as possible.
881 for (; BI != Begin; --BI) {
882 const Instruction *Inst = llvm::prior(BI);
884 // If we no longer require this instruction, skip it.
885 if (!Inst->mayWriteToMemory() &&
886 !isa<TerminatorInst>(Inst) &&
887 !isa<DbgInfoIntrinsic>(Inst) &&
888 !FuncInfo->isExportedInst(Inst))
891 // Bottom-up: reset the insert pos at the top, after any local-value
893 FastIS->recomputeInsertPt();
895 // Try to select the instruction with FastISel.
896 if (FastIS->SelectInstruction(Inst)) {
897 // If fast isel succeeded, check to see if there is a single-use
898 // non-volatile load right before the selected instruction, and see if
899 // the load is used by the instruction. If so, try to fold it.
900 const Instruction *BeforeInst = 0;
902 BeforeInst = llvm::prior(llvm::prior(BI));
903 if (BeforeInst && isa<LoadInst>(BeforeInst) &&
904 BeforeInst->hasOneUse() && *BeforeInst->use_begin() == Inst &&
905 TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), FastIS))
906 --BI; // If we succeeded, don't re-select the load.
910 // Then handle certain instructions as single-LLVM-Instruction blocks.
911 if (isa<CallInst>(Inst)) {
912 ++NumFastIselFailures;
913 if (EnableFastISelVerbose || EnableFastISelAbort) {
914 dbgs() << "FastISel missed call: ";
918 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
919 unsigned &R = FuncInfo->ValueMap[Inst];
921 R = FuncInfo->CreateRegs(Inst->getType());
924 bool HadTailCall = false;
925 SelectBasicBlock(Inst, BI, HadTailCall);
927 // If the call was emitted as a tail call, we're done with the block.
936 // Otherwise, give up on FastISel for the rest of the block.
937 // For now, be a little lenient about non-branch terminators.
938 if (!isa<TerminatorInst>(Inst) || isa<BranchInst>(Inst)) {
939 ++NumFastIselFailures;
940 if (EnableFastISelVerbose || EnableFastISelAbort) {
941 dbgs() << "FastISel miss: ";
944 if (EnableFastISelAbort)
945 // The "fast" selector couldn't handle something and bailed.
946 // For the purpose of debugging, just abort.
947 llvm_unreachable("FastISel didn't select the entire block");
952 FastIS->recomputeInsertPt();
960 // Run SelectionDAG instruction selection on the remainder of the block
961 // not handled by FastISel. If FastISel is not run, this is the entire
964 SelectBasicBlock(Begin, BI, HadTailCall);
967 FuncInfo->PHINodesToUpdate.clear();
972 for (MachineFunction::const_iterator MBI = MF->begin(), MBE = MF->end();
974 CheckLineNumbers(MBI);
979 SelectionDAGISel::FinishBasicBlock() {
981 DEBUG(dbgs() << "Total amount of phi nodes to update: "
982 << FuncInfo->PHINodesToUpdate.size() << "\n";
983 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
984 dbgs() << "Node " << i << " : ("
985 << FuncInfo->PHINodesToUpdate[i].first
986 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
988 // Next, now that we know what the last MBB the LLVM BB expanded is, update
989 // PHI nodes in successors.
990 if (SDB->SwitchCases.empty() &&
991 SDB->JTCases.empty() &&
992 SDB->BitTestCases.empty()) {
993 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
994 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
995 assert(PHI->isPHI() &&
996 "This is not a machine PHI node that we are updating!");
997 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1000 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
1001 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1006 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1007 // Lower header first, if it wasn't already lowered
1008 if (!SDB->BitTestCases[i].Emitted) {
1009 // Set the current basic block to the mbb we wish to insert the code into
1010 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1011 FuncInfo->InsertPt = FuncInfo->MBB->end();
1013 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1014 CurDAG->setRoot(SDB->getRoot());
1016 CodeGenAndEmitDAG();
1019 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1020 // Set the current basic block to the mbb we wish to insert the code into
1021 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1022 FuncInfo->InsertPt = FuncInfo->MBB->end();
1025 SDB->visitBitTestCase(SDB->BitTestCases[i],
1026 SDB->BitTestCases[i].Cases[j+1].ThisBB,
1027 SDB->BitTestCases[i].Reg,
1028 SDB->BitTestCases[i].Cases[j],
1031 SDB->visitBitTestCase(SDB->BitTestCases[i],
1032 SDB->BitTestCases[i].Default,
1033 SDB->BitTestCases[i].Reg,
1034 SDB->BitTestCases[i].Cases[j],
1038 CurDAG->setRoot(SDB->getRoot());
1040 CodeGenAndEmitDAG();
1044 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1046 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
1047 MachineBasicBlock *PHIBB = PHI->getParent();
1048 assert(PHI->isPHI() &&
1049 "This is not a machine PHI node that we are updating!");
1050 // This is "default" BB. We have two jumps to it. From "header" BB and
1051 // from last "case" BB.
1052 if (PHIBB == SDB->BitTestCases[i].Default) {
1053 PHI->addOperand(MachineOperand::
1054 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1056 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
1057 PHI->addOperand(MachineOperand::
1058 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1060 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
1063 // One of "cases" BB.
1064 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1066 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1067 if (cBB->isSuccessor(PHIBB)) {
1068 PHI->addOperand(MachineOperand::
1069 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1071 PHI->addOperand(MachineOperand::CreateMBB(cBB));
1076 SDB->BitTestCases.clear();
1078 // If the JumpTable record is filled in, then we need to emit a jump table.
1079 // Updating the PHI nodes is tricky in this case, since we need to determine
1080 // whether the PHI is a successor of the range check MBB or the jump table MBB
1081 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1082 // Lower header first, if it wasn't already lowered
1083 if (!SDB->JTCases[i].first.Emitted) {
1084 // Set the current basic block to the mbb we wish to insert the code into
1085 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1086 FuncInfo->InsertPt = FuncInfo->MBB->end();
1088 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1090 CurDAG->setRoot(SDB->getRoot());
1092 CodeGenAndEmitDAG();
1095 // Set the current basic block to the mbb we wish to insert the code into
1096 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1097 FuncInfo->InsertPt = FuncInfo->MBB->end();
1099 SDB->visitJumpTable(SDB->JTCases[i].second);
1100 CurDAG->setRoot(SDB->getRoot());
1102 CodeGenAndEmitDAG();
1105 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1107 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
1108 MachineBasicBlock *PHIBB = PHI->getParent();
1109 assert(PHI->isPHI() &&
1110 "This is not a machine PHI node that we are updating!");
1111 // "default" BB. We can go there only from header BB.
1112 if (PHIBB == SDB->JTCases[i].second.Default) {
1114 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1117 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
1119 // JT BB. Just iterate over successors here
1120 if (FuncInfo->MBB->isSuccessor(PHIBB)) {
1122 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1124 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1128 SDB->JTCases.clear();
1130 // If the switch block involved a branch to one of the actual successors, we
1131 // need to update PHI nodes in that block.
1132 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1133 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
1134 assert(PHI->isPHI() &&
1135 "This is not a machine PHI node that we are updating!");
1136 if (FuncInfo->MBB->isSuccessor(PHI->getParent())) {
1138 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
1139 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1143 // If we generated any switch lowering information, build and codegen any
1144 // additional DAGs necessary.
1145 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1146 // Set the current basic block to the mbb we wish to insert the code into
1147 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1148 FuncInfo->InsertPt = FuncInfo->MBB->end();
1150 // Determine the unique successors.
1151 SmallVector<MachineBasicBlock *, 2> Succs;
1152 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1153 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1154 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1156 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1157 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1158 CurDAG->setRoot(SDB->getRoot());
1160 CodeGenAndEmitDAG();
1162 // Remember the last block, now that any splitting is done, for use in
1163 // populating PHI nodes in successors.
1164 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1166 // Handle any PHI nodes in successors of this chunk, as if we were coming
1167 // from the original BB before switch expansion. Note that PHI nodes can
1168 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1169 // handle them the right number of times.
1170 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1171 FuncInfo->MBB = Succs[i];
1172 FuncInfo->InsertPt = FuncInfo->MBB->end();
1173 // FuncInfo->MBB may have been removed from the CFG if a branch was
1175 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1176 for (MachineBasicBlock::iterator Phi = FuncInfo->MBB->begin();
1177 Phi != FuncInfo->MBB->end() && Phi->isPHI();
1179 // This value for this PHI node is recorded in PHINodesToUpdate.
1180 for (unsigned pn = 0; ; ++pn) {
1181 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1182 "Didn't find PHI entry!");
1183 if (FuncInfo->PHINodesToUpdate[pn].first == Phi) {
1184 Phi->addOperand(MachineOperand::
1185 CreateReg(FuncInfo->PHINodesToUpdate[pn].second,
1187 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1195 SDB->SwitchCases.clear();
1199 /// Create the scheduler. If a specific scheduler was specified
1200 /// via the SchedulerRegistry, use it, otherwise select the
1201 /// one preferred by the target.
1203 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1204 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1208 RegisterScheduler::setDefault(Ctor);
1211 return Ctor(this, OptLevel);
1214 //===----------------------------------------------------------------------===//
1215 // Helper functions used by the generated instruction selector.
1216 //===----------------------------------------------------------------------===//
1217 // Calls to these methods are generated by tblgen.
1219 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1220 /// the dag combiner simplified the 255, we still want to match. RHS is the
1221 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1222 /// specified in the .td file (e.g. 255).
1223 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1224 int64_t DesiredMaskS) const {
1225 const APInt &ActualMask = RHS->getAPIntValue();
1226 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1228 // If the actual mask exactly matches, success!
1229 if (ActualMask == DesiredMask)
1232 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1233 if (ActualMask.intersects(~DesiredMask))
1236 // Otherwise, the DAG Combiner may have proven that the value coming in is
1237 // either already zero or is not demanded. Check for known zero input bits.
1238 APInt NeededMask = DesiredMask & ~ActualMask;
1239 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1242 // TODO: check to see if missing bits are just not demanded.
1244 // Otherwise, this pattern doesn't match.
1248 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1249 /// the dag combiner simplified the 255, we still want to match. RHS is the
1250 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1251 /// specified in the .td file (e.g. 255).
1252 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1253 int64_t DesiredMaskS) const {
1254 const APInt &ActualMask = RHS->getAPIntValue();
1255 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1257 // If the actual mask exactly matches, success!
1258 if (ActualMask == DesiredMask)
1261 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1262 if (ActualMask.intersects(~DesiredMask))
1265 // Otherwise, the DAG Combiner may have proven that the value coming in is
1266 // either already zero or is not demanded. Check for known zero input bits.
1267 APInt NeededMask = DesiredMask & ~ActualMask;
1269 APInt KnownZero, KnownOne;
1270 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1272 // If all the missing bits in the or are already known to be set, match!
1273 if ((NeededMask & KnownOne) == NeededMask)
1276 // TODO: check to see if missing bits are just not demanded.
1278 // Otherwise, this pattern doesn't match.
1283 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1284 /// by tblgen. Others should not call it.
1285 void SelectionDAGISel::
1286 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1287 std::vector<SDValue> InOps;
1288 std::swap(InOps, Ops);
1290 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1291 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1292 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1293 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1295 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1296 if (InOps[e-1].getValueType() == MVT::Glue)
1297 --e; // Don't process a glue operand if it is here.
1300 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1301 if (!InlineAsm::isMemKind(Flags)) {
1302 // Just skip over this operand, copying the operands verbatim.
1303 Ops.insert(Ops.end(), InOps.begin()+i,
1304 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1305 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1307 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1308 "Memory operand with multiple values?");
1309 // Otherwise, this is a memory operand. Ask the target to select it.
1310 std::vector<SDValue> SelOps;
1311 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1312 report_fatal_error("Could not match memory address. Inline asm"
1315 // Add this to the output node.
1317 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1318 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1319 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1324 // Add the glue input back if present.
1325 if (e != InOps.size())
1326 Ops.push_back(InOps.back());
1329 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1332 static SDNode *findGlueUse(SDNode *N) {
1333 unsigned FlagResNo = N->getNumValues()-1;
1334 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1335 SDUse &Use = I.getUse();
1336 if (Use.getResNo() == FlagResNo)
1337 return Use.getUser();
1342 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1343 /// This function recursively traverses up the operand chain, ignoring
1345 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1346 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1347 bool IgnoreChains) {
1348 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1349 // greater than all of its (recursive) operands. If we scan to a point where
1350 // 'use' is smaller than the node we're scanning for, then we know we will
1353 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1354 // happen because we scan down to newly selected nodes in the case of glue
1356 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1359 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1360 // won't fail if we scan it again.
1361 if (!Visited.insert(Use))
1364 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1365 // Ignore chain uses, they are validated by HandleMergeInputChains.
1366 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1369 SDNode *N = Use->getOperand(i).getNode();
1371 if (Use == ImmedUse || Use == Root)
1372 continue; // We are not looking for immediate use.
1377 // Traverse up the operand chain.
1378 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1384 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1385 /// operand node N of U during instruction selection that starts at Root.
1386 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1387 SDNode *Root) const {
1388 if (OptLevel == CodeGenOpt::None) return false;
1389 return N.hasOneUse();
1392 /// IsLegalToFold - Returns true if the specific operand node N of
1393 /// U can be folded during instruction selection that starts at Root.
1394 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1395 CodeGenOpt::Level OptLevel,
1396 bool IgnoreChains) {
1397 if (OptLevel == CodeGenOpt::None) return false;
1399 // If Root use can somehow reach N through a path that that doesn't contain
1400 // U then folding N would create a cycle. e.g. In the following
1401 // diagram, Root can reach N through X. If N is folded into into Root, then
1402 // X is both a predecessor and a successor of U.
1413 // * indicates nodes to be folded together.
1415 // If Root produces glue, then it gets (even more) interesting. Since it
1416 // will be "glued" together with its glue use in the scheduler, we need to
1417 // check if it might reach N.
1436 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1437 // (call it Fold), then X is a predecessor of GU and a successor of
1438 // Fold. But since Fold and GU are glued together, this will create
1439 // a cycle in the scheduling graph.
1441 // If the node has glue, walk down the graph to the "lowest" node in the
1443 EVT VT = Root->getValueType(Root->getNumValues()-1);
1444 while (VT == MVT::Glue) {
1445 SDNode *GU = findGlueUse(Root);
1449 VT = Root->getValueType(Root->getNumValues()-1);
1451 // If our query node has a glue result with a use, we've walked up it. If
1452 // the user (which has already been selected) has a chain or indirectly uses
1453 // the chain, our WalkChainUsers predicate will not consider it. Because of
1454 // this, we cannot ignore chains in this predicate.
1455 IgnoreChains = false;
1459 SmallPtrSet<SDNode*, 16> Visited;
1460 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1463 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1464 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1465 SelectInlineAsmMemoryOperands(Ops);
1467 std::vector<EVT> VTs;
1468 VTs.push_back(MVT::Other);
1469 VTs.push_back(MVT::Glue);
1470 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
1471 VTs, &Ops[0], Ops.size());
1473 return New.getNode();
1476 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1477 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1480 /// GetVBR - decode a vbr encoding whose top bit is set.
1481 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1482 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1483 assert(Val >= 128 && "Not a VBR");
1484 Val &= 127; // Remove first vbr bit.
1489 NextBits = MatcherTable[Idx++];
1490 Val |= (NextBits&127) << Shift;
1492 } while (NextBits & 128);
1498 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1499 /// interior glue and chain results to use the new glue and chain results.
1500 void SelectionDAGISel::
1501 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1502 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1504 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1505 bool isMorphNodeTo) {
1506 SmallVector<SDNode*, 4> NowDeadNodes;
1508 ISelUpdater ISU(ISelPosition);
1510 // Now that all the normal results are replaced, we replace the chain and
1511 // glue results if present.
1512 if (!ChainNodesMatched.empty()) {
1513 assert(InputChain.getNode() != 0 &&
1514 "Matched input chains but didn't produce a chain");
1515 // Loop over all of the nodes we matched that produced a chain result.
1516 // Replace all the chain results with the final chain we ended up with.
1517 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1518 SDNode *ChainNode = ChainNodesMatched[i];
1520 // If this node was already deleted, don't look at it.
1521 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1524 // Don't replace the results of the root node if we're doing a
1526 if (ChainNode == NodeToMatch && isMorphNodeTo)
1529 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1530 if (ChainVal.getValueType() == MVT::Glue)
1531 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1532 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1533 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1535 // If the node became dead and we haven't already seen it, delete it.
1536 if (ChainNode->use_empty() &&
1537 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1538 NowDeadNodes.push_back(ChainNode);
1542 // If the result produces glue, update any glue results in the matched
1543 // pattern with the glue result.
1544 if (InputGlue.getNode() != 0) {
1545 // Handle any interior nodes explicitly marked.
1546 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1547 SDNode *FRN = GlueResultNodesMatched[i];
1549 // If this node was already deleted, don't look at it.
1550 if (FRN->getOpcode() == ISD::DELETED_NODE)
1553 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1554 "Doesn't have a glue result");
1555 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1558 // If the node became dead and we haven't already seen it, delete it.
1559 if (FRN->use_empty() &&
1560 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1561 NowDeadNodes.push_back(FRN);
1565 if (!NowDeadNodes.empty())
1566 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1568 DEBUG(errs() << "ISEL: Match complete!\n");
1574 CR_LeadsToInteriorNode
1577 /// WalkChainUsers - Walk down the users of the specified chained node that is
1578 /// part of the pattern we're matching, looking at all of the users we find.
1579 /// This determines whether something is an interior node, whether we have a
1580 /// non-pattern node in between two pattern nodes (which prevent folding because
1581 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1582 /// between pattern nodes (in which case the TF becomes part of the pattern).
1584 /// The walk we do here is guaranteed to be small because we quickly get down to
1585 /// already selected nodes "below" us.
1587 WalkChainUsers(SDNode *ChainedNode,
1588 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1589 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1590 ChainResult Result = CR_Simple;
1592 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1593 E = ChainedNode->use_end(); UI != E; ++UI) {
1594 // Make sure the use is of the chain, not some other value we produce.
1595 if (UI.getUse().getValueType() != MVT::Other) continue;
1599 // If we see an already-selected machine node, then we've gone beyond the
1600 // pattern that we're selecting down into the already selected chunk of the
1602 if (User->isMachineOpcode() ||
1603 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1606 if (User->getOpcode() == ISD::CopyToReg ||
1607 User->getOpcode() == ISD::CopyFromReg ||
1608 User->getOpcode() == ISD::INLINEASM ||
1609 User->getOpcode() == ISD::EH_LABEL) {
1610 // If their node ID got reset to -1 then they've already been selected.
1611 // Treat them like a MachineOpcode.
1612 if (User->getNodeId() == -1)
1616 // If we have a TokenFactor, we handle it specially.
1617 if (User->getOpcode() != ISD::TokenFactor) {
1618 // If the node isn't a token factor and isn't part of our pattern, then it
1619 // must be a random chained node in between two nodes we're selecting.
1620 // This happens when we have something like:
1625 // Because we structurally match the load/store as a read/modify/write,
1626 // but the call is chained between them. We cannot fold in this case
1627 // because it would induce a cycle in the graph.
1628 if (!std::count(ChainedNodesInPattern.begin(),
1629 ChainedNodesInPattern.end(), User))
1630 return CR_InducesCycle;
1632 // Otherwise we found a node that is part of our pattern. For example in:
1636 // This would happen when we're scanning down from the load and see the
1637 // store as a user. Record that there is a use of ChainedNode that is
1638 // part of the pattern and keep scanning uses.
1639 Result = CR_LeadsToInteriorNode;
1640 InteriorChainedNodes.push_back(User);
1644 // If we found a TokenFactor, there are two cases to consider: first if the
1645 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1646 // uses of the TF are in our pattern) we just want to ignore it. Second,
1647 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1653 // | \ DAG's like cheese
1656 // [TokenFactor] [Op]
1663 // In this case, the TokenFactor becomes part of our match and we rewrite it
1664 // as a new TokenFactor.
1666 // To distinguish these two cases, do a recursive walk down the uses.
1667 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1669 // If the uses of the TokenFactor are just already-selected nodes, ignore
1670 // it, it is "below" our pattern.
1672 case CR_InducesCycle:
1673 // If the uses of the TokenFactor lead to nodes that are not part of our
1674 // pattern that are not selected, folding would turn this into a cycle,
1676 return CR_InducesCycle;
1677 case CR_LeadsToInteriorNode:
1678 break; // Otherwise, keep processing.
1681 // Okay, we know we're in the interesting interior case. The TokenFactor
1682 // is now going to be considered part of the pattern so that we rewrite its
1683 // uses (it may have uses that are not part of the pattern) with the
1684 // ultimate chain result of the generated code. We will also add its chain
1685 // inputs as inputs to the ultimate TokenFactor we create.
1686 Result = CR_LeadsToInteriorNode;
1687 ChainedNodesInPattern.push_back(User);
1688 InteriorChainedNodes.push_back(User);
1695 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1696 /// operation for when the pattern matched at least one node with a chains. The
1697 /// input vector contains a list of all of the chained nodes that we match. We
1698 /// must determine if this is a valid thing to cover (i.e. matching it won't
1699 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1700 /// be used as the input node chain for the generated nodes.
1702 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1703 SelectionDAG *CurDAG) {
1704 // Walk all of the chained nodes we've matched, recursively scanning down the
1705 // users of the chain result. This adds any TokenFactor nodes that are caught
1706 // in between chained nodes to the chained and interior nodes list.
1707 SmallVector<SDNode*, 3> InteriorChainedNodes;
1708 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1709 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1710 InteriorChainedNodes) == CR_InducesCycle)
1711 return SDValue(); // Would induce a cycle.
1714 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1715 // that we are interested in. Form our input TokenFactor node.
1716 SmallVector<SDValue, 3> InputChains;
1717 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1718 // Add the input chain of this node to the InputChains list (which will be
1719 // the operands of the generated TokenFactor) if it's not an interior node.
1720 SDNode *N = ChainNodesMatched[i];
1721 if (N->getOpcode() != ISD::TokenFactor) {
1722 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1725 // Otherwise, add the input chain.
1726 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1727 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1728 InputChains.push_back(InChain);
1732 // If we have a token factor, we want to add all inputs of the token factor
1733 // that are not part of the pattern we're matching.
1734 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1735 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1736 N->getOperand(op).getNode()))
1737 InputChains.push_back(N->getOperand(op));
1742 if (InputChains.size() == 1)
1743 return InputChains[0];
1744 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1745 MVT::Other, &InputChains[0], InputChains.size());
1748 /// MorphNode - Handle morphing a node in place for the selector.
1749 SDNode *SelectionDAGISel::
1750 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1751 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1752 // It is possible we're using MorphNodeTo to replace a node with no
1753 // normal results with one that has a normal result (or we could be
1754 // adding a chain) and the input could have glue and chains as well.
1755 // In this case we need to shift the operands down.
1756 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1757 // than the old isel though.
1758 int OldGlueResultNo = -1, OldChainResultNo = -1;
1760 unsigned NTMNumResults = Node->getNumValues();
1761 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
1762 OldGlueResultNo = NTMNumResults-1;
1763 if (NTMNumResults != 1 &&
1764 Node->getValueType(NTMNumResults-2) == MVT::Other)
1765 OldChainResultNo = NTMNumResults-2;
1766 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1767 OldChainResultNo = NTMNumResults-1;
1769 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1770 // that this deletes operands of the old node that become dead.
1771 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1773 // MorphNodeTo can operate in two ways: if an existing node with the
1774 // specified operands exists, it can just return it. Otherwise, it
1775 // updates the node in place to have the requested operands.
1777 // If we updated the node in place, reset the node ID. To the isel,
1778 // this should be just like a newly allocated machine node.
1782 unsigned ResNumResults = Res->getNumValues();
1783 // Move the glue if needed.
1784 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1785 (unsigned)OldGlueResultNo != ResNumResults-1)
1786 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
1787 SDValue(Res, ResNumResults-1));
1789 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
1792 // Move the chain reference if needed.
1793 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1794 (unsigned)OldChainResultNo != ResNumResults-1)
1795 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1796 SDValue(Res, ResNumResults-1));
1798 // Otherwise, no replacement happened because the node already exists. Replace
1799 // Uses of the old node with the new one.
1801 CurDAG->ReplaceAllUsesWith(Node, Res);
1806 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1807 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1808 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1810 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
1811 // Accept if it is exactly the same as a previously recorded node.
1812 unsigned RecNo = MatcherTable[MatcherIndex++];
1813 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1814 return N == RecordedNodes[RecNo].first;
1817 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1818 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1819 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1820 SelectionDAGISel &SDISel) {
1821 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1824 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
1825 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1826 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1827 SelectionDAGISel &SDISel, SDNode *N) {
1828 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1831 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1832 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1834 uint16_t Opc = MatcherTable[MatcherIndex++];
1835 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1836 return N->getOpcode() == Opc;
1839 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1840 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1841 SDValue N, const TargetLowering &TLI) {
1842 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1843 if (N.getValueType() == VT) return true;
1845 // Handle the case when VT is iPTR.
1846 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1849 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1850 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1851 SDValue N, const TargetLowering &TLI,
1853 if (ChildNo >= N.getNumOperands())
1854 return false; // Match fails if out of range child #.
1855 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1859 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1860 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1862 return cast<CondCodeSDNode>(N)->get() ==
1863 (ISD::CondCode)MatcherTable[MatcherIndex++];
1866 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1867 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1868 SDValue N, const TargetLowering &TLI) {
1869 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1870 if (cast<VTSDNode>(N)->getVT() == VT)
1873 // Handle the case when VT is iPTR.
1874 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1877 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1878 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1880 int64_t Val = MatcherTable[MatcherIndex++];
1882 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1885 return C != 0 && C->getSExtValue() == Val;
1888 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1889 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1890 SDValue N, SelectionDAGISel &SDISel) {
1891 int64_t Val = MatcherTable[MatcherIndex++];
1893 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1895 if (N->getOpcode() != ISD::AND) return false;
1897 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1898 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1901 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1902 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1903 SDValue N, SelectionDAGISel &SDISel) {
1904 int64_t Val = MatcherTable[MatcherIndex++];
1906 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1908 if (N->getOpcode() != ISD::OR) return false;
1910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1911 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1914 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
1915 /// scope, evaluate the current node. If the current predicate is known to
1916 /// fail, set Result=true and return anything. If the current predicate is
1917 /// known to pass, set Result=false and return the MatcherIndex to continue
1918 /// with. If the current predicate is unknown, set Result=false and return the
1919 /// MatcherIndex to continue with.
1920 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1921 unsigned Index, SDValue N,
1922 bool &Result, SelectionDAGISel &SDISel,
1923 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
1924 switch (Table[Index++]) {
1927 return Index-1; // Could not evaluate this predicate.
1928 case SelectionDAGISel::OPC_CheckSame:
1929 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1931 case SelectionDAGISel::OPC_CheckPatternPredicate:
1932 Result = !::CheckPatternPredicate(Table, Index, SDISel);
1934 case SelectionDAGISel::OPC_CheckPredicate:
1935 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
1937 case SelectionDAGISel::OPC_CheckOpcode:
1938 Result = !::CheckOpcode(Table, Index, N.getNode());
1940 case SelectionDAGISel::OPC_CheckType:
1941 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1943 case SelectionDAGISel::OPC_CheckChild0Type:
1944 case SelectionDAGISel::OPC_CheckChild1Type:
1945 case SelectionDAGISel::OPC_CheckChild2Type:
1946 case SelectionDAGISel::OPC_CheckChild3Type:
1947 case SelectionDAGISel::OPC_CheckChild4Type:
1948 case SelectionDAGISel::OPC_CheckChild5Type:
1949 case SelectionDAGISel::OPC_CheckChild6Type:
1950 case SelectionDAGISel::OPC_CheckChild7Type:
1951 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1952 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
1954 case SelectionDAGISel::OPC_CheckCondCode:
1955 Result = !::CheckCondCode(Table, Index, N);
1957 case SelectionDAGISel::OPC_CheckValueType:
1958 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1960 case SelectionDAGISel::OPC_CheckInteger:
1961 Result = !::CheckInteger(Table, Index, N);
1963 case SelectionDAGISel::OPC_CheckAndImm:
1964 Result = !::CheckAndImm(Table, Index, N, SDISel);
1966 case SelectionDAGISel::OPC_CheckOrImm:
1967 Result = !::CheckOrImm(Table, Index, N, SDISel);
1975 /// FailIndex - If this match fails, this is the index to continue with.
1978 /// NodeStack - The node stack when the scope was formed.
1979 SmallVector<SDValue, 4> NodeStack;
1981 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1982 unsigned NumRecordedNodes;
1984 /// NumMatchedMemRefs - The number of matched memref entries.
1985 unsigned NumMatchedMemRefs;
1987 /// InputChain/InputGlue - The current chain/glue
1988 SDValue InputChain, InputGlue;
1990 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1991 bool HasChainNodesMatched, HasGlueResultNodesMatched;
1996 SDNode *SelectionDAGISel::
1997 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1998 unsigned TableSize) {
1999 // FIXME: Should these even be selected? Handle these cases in the caller?
2000 switch (NodeToMatch->getOpcode()) {
2003 case ISD::EntryToken: // These nodes remain the same.
2004 case ISD::BasicBlock:
2006 //case ISD::VALUETYPE:
2007 //case ISD::CONDCODE:
2008 case ISD::HANDLENODE:
2009 case ISD::MDNODE_SDNODE:
2010 case ISD::TargetConstant:
2011 case ISD::TargetConstantFP:
2012 case ISD::TargetConstantPool:
2013 case ISD::TargetFrameIndex:
2014 case ISD::TargetExternalSymbol:
2015 case ISD::TargetBlockAddress:
2016 case ISD::TargetJumpTable:
2017 case ISD::TargetGlobalTLSAddress:
2018 case ISD::TargetGlobalAddress:
2019 case ISD::TokenFactor:
2020 case ISD::CopyFromReg:
2021 case ISD::CopyToReg:
2023 NodeToMatch->setNodeId(-1); // Mark selected.
2025 case ISD::AssertSext:
2026 case ISD::AssertZext:
2027 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2028 NodeToMatch->getOperand(0));
2030 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2031 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2034 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2036 // Set up the node stack with NodeToMatch as the only node on the stack.
2037 SmallVector<SDValue, 8> NodeStack;
2038 SDValue N = SDValue(NodeToMatch, 0);
2039 NodeStack.push_back(N);
2041 // MatchScopes - Scopes used when matching, if a match failure happens, this
2042 // indicates where to continue checking.
2043 SmallVector<MatchScope, 8> MatchScopes;
2045 // RecordedNodes - This is the set of nodes that have been recorded by the
2046 // state machine. The second value is the parent of the node, or null if the
2047 // root is recorded.
2048 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2050 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2052 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2054 // These are the current input chain and glue for use when generating nodes.
2055 // Various Emit operations change these. For example, emitting a copytoreg
2056 // uses and updates these.
2057 SDValue InputChain, InputGlue;
2059 // ChainNodesMatched - If a pattern matches nodes that have input/output
2060 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2061 // which ones they are. The result is captured into this list so that we can
2062 // update the chain results when the pattern is complete.
2063 SmallVector<SDNode*, 3> ChainNodesMatched;
2064 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2066 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
2067 NodeToMatch->dump(CurDAG);
2070 // Determine where to start the interpreter. Normally we start at opcode #0,
2071 // but if the state machine starts with an OPC_SwitchOpcode, then we
2072 // accelerate the first lookup (which is guaranteed to be hot) with the
2073 // OpcodeOffset table.
2074 unsigned MatcherIndex = 0;
2076 if (!OpcodeOffset.empty()) {
2077 // Already computed the OpcodeOffset table, just index into it.
2078 if (N.getOpcode() < OpcodeOffset.size())
2079 MatcherIndex = OpcodeOffset[N.getOpcode()];
2080 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
2082 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2083 // Otherwise, the table isn't computed, but the state machine does start
2084 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2085 // is the first time we're selecting an instruction.
2088 // Get the size of this case.
2089 unsigned CaseSize = MatcherTable[Idx++];
2091 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2092 if (CaseSize == 0) break;
2094 // Get the opcode, add the index to the table.
2095 uint16_t Opc = MatcherTable[Idx++];
2096 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2097 if (Opc >= OpcodeOffset.size())
2098 OpcodeOffset.resize((Opc+1)*2);
2099 OpcodeOffset[Opc] = Idx;
2103 // Okay, do the lookup for the first opcode.
2104 if (N.getOpcode() < OpcodeOffset.size())
2105 MatcherIndex = OpcodeOffset[N.getOpcode()];
2109 assert(MatcherIndex < TableSize && "Invalid index");
2111 unsigned CurrentOpcodeIndex = MatcherIndex;
2113 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2116 // Okay, the semantics of this operation are that we should push a scope
2117 // then evaluate the first child. However, pushing a scope only to have
2118 // the first check fail (which then pops it) is inefficient. If we can
2119 // determine immediately that the first check (or first several) will
2120 // immediately fail, don't even bother pushing a scope for them.
2124 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2125 if (NumToSkip & 128)
2126 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2127 // Found the end of the scope with no match.
2128 if (NumToSkip == 0) {
2133 FailIndex = MatcherIndex+NumToSkip;
2135 unsigned MatcherIndexOfPredicate = MatcherIndex;
2136 (void)MatcherIndexOfPredicate; // silence warning.
2138 // If we can't evaluate this predicate without pushing a scope (e.g. if
2139 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2140 // push the scope and evaluate the full predicate chain.
2142 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2143 Result, *this, RecordedNodes);
2147 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2148 << "index " << MatcherIndexOfPredicate
2149 << ", continuing at " << FailIndex << "\n");
2150 ++NumDAGIselRetries;
2152 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2153 // move to the next case.
2154 MatcherIndex = FailIndex;
2157 // If the whole scope failed to match, bail.
2158 if (FailIndex == 0) break;
2160 // Push a MatchScope which indicates where to go if the first child fails
2162 MatchScope NewEntry;
2163 NewEntry.FailIndex = FailIndex;
2164 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2165 NewEntry.NumRecordedNodes = RecordedNodes.size();
2166 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2167 NewEntry.InputChain = InputChain;
2168 NewEntry.InputGlue = InputGlue;
2169 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2170 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2171 MatchScopes.push_back(NewEntry);
2174 case OPC_RecordNode: {
2175 // Remember this node, it may end up being an operand in the pattern.
2177 if (NodeStack.size() > 1)
2178 Parent = NodeStack[NodeStack.size()-2].getNode();
2179 RecordedNodes.push_back(std::make_pair(N, Parent));
2183 case OPC_RecordChild0: case OPC_RecordChild1:
2184 case OPC_RecordChild2: case OPC_RecordChild3:
2185 case OPC_RecordChild4: case OPC_RecordChild5:
2186 case OPC_RecordChild6: case OPC_RecordChild7: {
2187 unsigned ChildNo = Opcode-OPC_RecordChild0;
2188 if (ChildNo >= N.getNumOperands())
2189 break; // Match fails if out of range child #.
2191 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2195 case OPC_RecordMemRef:
2196 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2199 case OPC_CaptureGlueInput:
2200 // If the current node has an input glue, capture it in InputGlue.
2201 if (N->getNumOperands() != 0 &&
2202 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2203 InputGlue = N->getOperand(N->getNumOperands()-1);
2206 case OPC_MoveChild: {
2207 unsigned ChildNo = MatcherTable[MatcherIndex++];
2208 if (ChildNo >= N.getNumOperands())
2209 break; // Match fails if out of range child #.
2210 N = N.getOperand(ChildNo);
2211 NodeStack.push_back(N);
2215 case OPC_MoveParent:
2216 // Pop the current node off the NodeStack.
2217 NodeStack.pop_back();
2218 assert(!NodeStack.empty() && "Node stack imbalance!");
2219 N = NodeStack.back();
2223 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2225 case OPC_CheckPatternPredicate:
2226 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2228 case OPC_CheckPredicate:
2229 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2233 case OPC_CheckComplexPat: {
2234 unsigned CPNum = MatcherTable[MatcherIndex++];
2235 unsigned RecNo = MatcherTable[MatcherIndex++];
2236 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2237 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2238 RecordedNodes[RecNo].first, CPNum,
2243 case OPC_CheckOpcode:
2244 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2248 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
2251 case OPC_SwitchOpcode: {
2252 unsigned CurNodeOpcode = N.getOpcode();
2253 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2256 // Get the size of this case.
2257 CaseSize = MatcherTable[MatcherIndex++];
2259 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2260 if (CaseSize == 0) break;
2262 uint16_t Opc = MatcherTable[MatcherIndex++];
2263 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2265 // If the opcode matches, then we will execute this case.
2266 if (CurNodeOpcode == Opc)
2269 // Otherwise, skip over this case.
2270 MatcherIndex += CaseSize;
2273 // If no cases matched, bail out.
2274 if (CaseSize == 0) break;
2276 // Otherwise, execute the case we found.
2277 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2278 << " to " << MatcherIndex << "\n");
2282 case OPC_SwitchType: {
2283 MVT CurNodeVT = N.getValueType().getSimpleVT();
2284 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2287 // Get the size of this case.
2288 CaseSize = MatcherTable[MatcherIndex++];
2290 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2291 if (CaseSize == 0) break;
2293 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2294 if (CaseVT == MVT::iPTR)
2295 CaseVT = TLI.getPointerTy();
2297 // If the VT matches, then we will execute this case.
2298 if (CurNodeVT == CaseVT)
2301 // Otherwise, skip over this case.
2302 MatcherIndex += CaseSize;
2305 // If no cases matched, bail out.
2306 if (CaseSize == 0) break;
2308 // Otherwise, execute the case we found.
2309 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2310 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2313 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2314 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2315 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2316 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2317 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2318 Opcode-OPC_CheckChild0Type))
2321 case OPC_CheckCondCode:
2322 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2324 case OPC_CheckValueType:
2325 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
2327 case OPC_CheckInteger:
2328 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2330 case OPC_CheckAndImm:
2331 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2333 case OPC_CheckOrImm:
2334 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2337 case OPC_CheckFoldableChainNode: {
2338 assert(NodeStack.size() != 1 && "No parent node");
2339 // Verify that all intermediate nodes between the root and this one have
2341 bool HasMultipleUses = false;
2342 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2343 if (!NodeStack[i].hasOneUse()) {
2344 HasMultipleUses = true;
2347 if (HasMultipleUses) break;
2349 // Check to see that the target thinks this is profitable to fold and that
2350 // we can fold it without inducing cycles in the graph.
2351 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2353 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2354 NodeToMatch, OptLevel,
2355 true/*We validate our own chains*/))
2360 case OPC_EmitInteger: {
2361 MVT::SimpleValueType VT =
2362 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2363 int64_t Val = MatcherTable[MatcherIndex++];
2365 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2366 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2367 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
2370 case OPC_EmitRegister: {
2371 MVT::SimpleValueType VT =
2372 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2373 unsigned RegNo = MatcherTable[MatcherIndex++];
2374 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2375 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2379 case OPC_EmitConvertToTarget: {
2380 // Convert from IMM/FPIMM to target version.
2381 unsigned RecNo = MatcherTable[MatcherIndex++];
2382 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2383 SDValue Imm = RecordedNodes[RecNo].first;
2385 if (Imm->getOpcode() == ISD::Constant) {
2386 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2387 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2388 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2389 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2390 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2393 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2397 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2398 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2399 // These are space-optimized forms of OPC_EmitMergeInputChains.
2400 assert(InputChain.getNode() == 0 &&
2401 "EmitMergeInputChains should be the first chain producing node");
2402 assert(ChainNodesMatched.empty() &&
2403 "Should only have one EmitMergeInputChains per match");
2405 // Read all of the chained nodes.
2406 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2407 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2408 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2410 // FIXME: What if other value results of the node have uses not matched
2412 if (ChainNodesMatched.back() != NodeToMatch &&
2413 !RecordedNodes[RecNo].first.hasOneUse()) {
2414 ChainNodesMatched.clear();
2418 // Merge the input chains if they are not intra-pattern references.
2419 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2421 if (InputChain.getNode() == 0)
2422 break; // Failed to merge.
2426 case OPC_EmitMergeInputChains: {
2427 assert(InputChain.getNode() == 0 &&
2428 "EmitMergeInputChains should be the first chain producing node");
2429 // This node gets a list of nodes we matched in the input that have
2430 // chains. We want to token factor all of the input chains to these nodes
2431 // together. However, if any of the input chains is actually one of the
2432 // nodes matched in this pattern, then we have an intra-match reference.
2433 // Ignore these because the newly token factored chain should not refer to
2435 unsigned NumChains = MatcherTable[MatcherIndex++];
2436 assert(NumChains != 0 && "Can't TF zero chains");
2438 assert(ChainNodesMatched.empty() &&
2439 "Should only have one EmitMergeInputChains per match");
2441 // Read all of the chained nodes.
2442 for (unsigned i = 0; i != NumChains; ++i) {
2443 unsigned RecNo = MatcherTable[MatcherIndex++];
2444 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2445 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2447 // FIXME: What if other value results of the node have uses not matched
2449 if (ChainNodesMatched.back() != NodeToMatch &&
2450 !RecordedNodes[RecNo].first.hasOneUse()) {
2451 ChainNodesMatched.clear();
2456 // If the inner loop broke out, the match fails.
2457 if (ChainNodesMatched.empty())
2460 // Merge the input chains if they are not intra-pattern references.
2461 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2463 if (InputChain.getNode() == 0)
2464 break; // Failed to merge.
2469 case OPC_EmitCopyToReg: {
2470 unsigned RecNo = MatcherTable[MatcherIndex++];
2471 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2472 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2474 if (InputChain.getNode() == 0)
2475 InputChain = CurDAG->getEntryNode();
2477 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2478 DestPhysReg, RecordedNodes[RecNo].first,
2481 InputGlue = InputChain.getValue(1);
2485 case OPC_EmitNodeXForm: {
2486 unsigned XFormNo = MatcherTable[MatcherIndex++];
2487 unsigned RecNo = MatcherTable[MatcherIndex++];
2488 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2489 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
2490 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
2495 case OPC_MorphNodeTo: {
2496 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2497 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2498 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2499 // Get the result VT list.
2500 unsigned NumVTs = MatcherTable[MatcherIndex++];
2501 SmallVector<EVT, 4> VTs;
2502 for (unsigned i = 0; i != NumVTs; ++i) {
2503 MVT::SimpleValueType VT =
2504 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2505 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2509 if (EmitNodeInfo & OPFL_Chain)
2510 VTs.push_back(MVT::Other);
2511 if (EmitNodeInfo & OPFL_GlueOutput)
2512 VTs.push_back(MVT::Glue);
2514 // This is hot code, so optimize the two most common cases of 1 and 2
2517 if (VTs.size() == 1)
2518 VTList = CurDAG->getVTList(VTs[0]);
2519 else if (VTs.size() == 2)
2520 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2522 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2524 // Get the operand list.
2525 unsigned NumOps = MatcherTable[MatcherIndex++];
2526 SmallVector<SDValue, 8> Ops;
2527 for (unsigned i = 0; i != NumOps; ++i) {
2528 unsigned RecNo = MatcherTable[MatcherIndex++];
2530 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2532 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2533 Ops.push_back(RecordedNodes[RecNo].first);
2536 // If there are variadic operands to add, handle them now.
2537 if (EmitNodeInfo & OPFL_VariadicInfo) {
2538 // Determine the start index to copy from.
2539 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2540 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2541 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2542 "Invalid variadic node");
2543 // Copy all of the variadic operands, not including a potential glue
2545 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2547 SDValue V = NodeToMatch->getOperand(i);
2548 if (V.getValueType() == MVT::Glue) break;
2553 // If this has chain/glue inputs, add them.
2554 if (EmitNodeInfo & OPFL_Chain)
2555 Ops.push_back(InputChain);
2556 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2557 Ops.push_back(InputGlue);
2561 if (Opcode != OPC_MorphNodeTo) {
2562 // If this is a normal EmitNode command, just create the new node and
2563 // add the results to the RecordedNodes list.
2564 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2565 VTList, Ops.data(), Ops.size());
2567 // Add all the non-glue/non-chain results to the RecordedNodes list.
2568 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2569 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
2570 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
2575 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2579 // If the node had chain/glue results, update our notion of the current
2581 if (EmitNodeInfo & OPFL_GlueOutput) {
2582 InputGlue = SDValue(Res, VTs.size()-1);
2583 if (EmitNodeInfo & OPFL_Chain)
2584 InputChain = SDValue(Res, VTs.size()-2);
2585 } else if (EmitNodeInfo & OPFL_Chain)
2586 InputChain = SDValue(Res, VTs.size()-1);
2588 // If the OPFL_MemRefs glue is set on this node, slap all of the
2589 // accumulated memrefs onto it.
2591 // FIXME: This is vastly incorrect for patterns with multiple outputs
2592 // instructions that access memory and for ComplexPatterns that match
2594 if (EmitNodeInfo & OPFL_MemRefs) {
2595 MachineSDNode::mmo_iterator MemRefs =
2596 MF->allocateMemRefsArray(MatchedMemRefs.size());
2597 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2598 cast<MachineSDNode>(Res)
2599 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2603 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2604 << " node: "; Res->dump(CurDAG); errs() << "\n");
2606 // If this was a MorphNodeTo then we're completely done!
2607 if (Opcode == OPC_MorphNodeTo) {
2608 // Update chain and glue uses.
2609 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2610 InputGlue, GlueResultNodesMatched, true);
2617 case OPC_MarkGlueResults: {
2618 unsigned NumNodes = MatcherTable[MatcherIndex++];
2620 // Read and remember all the glue-result nodes.
2621 for (unsigned i = 0; i != NumNodes; ++i) {
2622 unsigned RecNo = MatcherTable[MatcherIndex++];
2624 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2626 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2627 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2632 case OPC_CompleteMatch: {
2633 // The match has been completed, and any new nodes (if any) have been
2634 // created. Patch up references to the matched dag to use the newly
2636 unsigned NumResults = MatcherTable[MatcherIndex++];
2638 for (unsigned i = 0; i != NumResults; ++i) {
2639 unsigned ResSlot = MatcherTable[MatcherIndex++];
2641 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2643 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2644 SDValue Res = RecordedNodes[ResSlot].first;
2646 assert(i < NodeToMatch->getNumValues() &&
2647 NodeToMatch->getValueType(i) != MVT::Other &&
2648 NodeToMatch->getValueType(i) != MVT::Glue &&
2649 "Invalid number of results to complete!");
2650 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2651 NodeToMatch->getValueType(i) == MVT::iPTR ||
2652 Res.getValueType() == MVT::iPTR ||
2653 NodeToMatch->getValueType(i).getSizeInBits() ==
2654 Res.getValueType().getSizeInBits()) &&
2655 "invalid replacement");
2656 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2659 // If the root node defines glue, add it to the glue nodes to update list.
2660 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
2661 GlueResultNodesMatched.push_back(NodeToMatch);
2663 // Update chain and glue uses.
2664 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2665 InputGlue, GlueResultNodesMatched, false);
2667 assert(NodeToMatch->use_empty() &&
2668 "Didn't replace all uses of the node?");
2670 // FIXME: We just return here, which interacts correctly with SelectRoot
2671 // above. We should fix this to not return an SDNode* anymore.
2676 // If the code reached this point, then the match failed. See if there is
2677 // another child to try in the current 'Scope', otherwise pop it until we
2678 // find a case to check.
2679 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2680 ++NumDAGIselRetries;
2682 if (MatchScopes.empty()) {
2683 CannotYetSelect(NodeToMatch);
2687 // Restore the interpreter state back to the point where the scope was
2689 MatchScope &LastScope = MatchScopes.back();
2690 RecordedNodes.resize(LastScope.NumRecordedNodes);
2692 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2693 N = NodeStack.back();
2695 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2696 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2697 MatcherIndex = LastScope.FailIndex;
2699 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2701 InputChain = LastScope.InputChain;
2702 InputGlue = LastScope.InputGlue;
2703 if (!LastScope.HasChainNodesMatched)
2704 ChainNodesMatched.clear();
2705 if (!LastScope.HasGlueResultNodesMatched)
2706 GlueResultNodesMatched.clear();
2708 // Check to see what the offset is at the new MatcherIndex. If it is zero
2709 // we have reached the end of this scope, otherwise we have another child
2710 // in the current scope to try.
2711 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2712 if (NumToSkip & 128)
2713 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2715 // If we have another child in this scope to match, update FailIndex and
2717 if (NumToSkip != 0) {
2718 LastScope.FailIndex = MatcherIndex+NumToSkip;
2722 // End of this scope, pop it and try the next child in the containing
2724 MatchScopes.pop_back();
2731 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2733 raw_string_ostream Msg(msg);
2734 Msg << "Cannot select: ";
2736 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2737 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2738 N->getOpcode() != ISD::INTRINSIC_VOID) {
2739 N->printrFull(Msg, CurDAG);
2741 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2743 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2744 if (iid < Intrinsic::num_intrinsics)
2745 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2746 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2747 Msg << "target intrinsic %" << TII->getName(iid);
2749 Msg << "unknown intrinsic #" << iid;
2751 report_fatal_error(Msg.str());
2754 char SelectionDAGISel::ID = 0;