Enhance both TargetLibraryInfo and SelectionDAGBuilder so that the latter can use...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
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/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/Module.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/CodeGen/GCMetadata.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
39 #include "llvm/CodeGen/SchedulerRegistry.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetIntrinsicInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLibraryInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/ADT/PostOrderIterator.h"
55 #include "llvm/ADT/Statistic.h"
56 #include <algorithm>
57 using namespace llvm;
58
59 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
60 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
61 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
62 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
63 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
64
65 #ifndef NDEBUG
66   // Terminators
67 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
68 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
69 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
70 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
71 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
72 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
73 STATISTIC(NumFastIselFailUnwind,"Fast isel fails on Unwind");
74 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
75
76   // Standard binary operators...
77 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
78 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
79 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
80 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
81 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
82 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
83 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
84 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
85 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
86 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
87 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
88 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
89
90   // Logical operators...
91 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
92 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
93 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
94
95   // Memory instructions...
96 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
97 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
98 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
99 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
100 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
101 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
102 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
103
104   // Convert instructions...
105 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
106 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
107 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
108 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
109 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
110 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
111 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
112 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
113 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
114 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
115 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
116 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
117
118   // Other instructions...
119 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
120 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
121 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
122 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
123 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
124 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
125 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
126 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
127 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
128 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
129 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
130 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
131 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
132 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
133 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
134 #endif
135
136 static cl::opt<bool>
137 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
138           cl::desc("Enable verbose messages in the \"fast\" "
139                    "instruction selector"));
140 static cl::opt<bool>
141 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
142           cl::desc("Enable abort calls when \"fast\" instruction fails"));
143
144 static cl::opt<bool>
145 UseMBPI("use-mbpi",
146         cl::desc("use Machine Branch Probability Info"),
147         cl::init(true), cl::Hidden);
148
149 #ifndef NDEBUG
150 static cl::opt<bool>
151 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
152           cl::desc("Pop up a window to show dags before the first "
153                    "dag combine pass"));
154 static cl::opt<bool>
155 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
156           cl::desc("Pop up a window to show dags before legalize types"));
157 static cl::opt<bool>
158 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
159           cl::desc("Pop up a window to show dags before legalize"));
160 static cl::opt<bool>
161 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
162           cl::desc("Pop up a window to show dags before the second "
163                    "dag combine pass"));
164 static cl::opt<bool>
165 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
166           cl::desc("Pop up a window to show dags before the post legalize types"
167                    " dag combine pass"));
168 static cl::opt<bool>
169 ViewISelDAGs("view-isel-dags", cl::Hidden,
170           cl::desc("Pop up a window to show isel dags as they are selected"));
171 static cl::opt<bool>
172 ViewSchedDAGs("view-sched-dags", cl::Hidden,
173           cl::desc("Pop up a window to show sched dags as they are processed"));
174 static cl::opt<bool>
175 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
176       cl::desc("Pop up a window to show SUnit dags after they are processed"));
177 #else
178 static const bool ViewDAGCombine1 = false,
179                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
180                   ViewDAGCombine2 = false,
181                   ViewDAGCombineLT = false,
182                   ViewISelDAGs = false, ViewSchedDAGs = false,
183                   ViewSUnitDAGs = false;
184 #endif
185
186 //===---------------------------------------------------------------------===//
187 ///
188 /// RegisterScheduler class - Track the registration of instruction schedulers.
189 ///
190 //===---------------------------------------------------------------------===//
191 MachinePassRegistry RegisterScheduler::Registry;
192
193 //===---------------------------------------------------------------------===//
194 ///
195 /// ISHeuristic command line option for instruction schedulers.
196 ///
197 //===---------------------------------------------------------------------===//
198 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
199                RegisterPassParser<RegisterScheduler> >
200 ISHeuristic("pre-RA-sched",
201             cl::init(&createDefaultScheduler),
202             cl::desc("Instruction schedulers available (before register"
203                      " allocation):"));
204
205 static RegisterScheduler
206 defaultListDAGScheduler("default", "Best scheduler for the target",
207                         createDefaultScheduler);
208
209 namespace llvm {
210   //===--------------------------------------------------------------------===//
211   /// createDefaultScheduler - This creates an instruction scheduler appropriate
212   /// for the target.
213   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
214                                              CodeGenOpt::Level OptLevel) {
215     const TargetLowering &TLI = IS->getTargetLowering();
216
217     if (OptLevel == CodeGenOpt::None)
218       return createSourceListDAGScheduler(IS, OptLevel);
219     if (TLI.getSchedulingPreference() == Sched::RegPressure)
220       return createBURRListDAGScheduler(IS, OptLevel);
221     if (TLI.getSchedulingPreference() == Sched::Hybrid)
222       return createHybridListDAGScheduler(IS, OptLevel);
223     assert(TLI.getSchedulingPreference() == Sched::ILP &&
224            "Unknown sched type!");
225     return createILPListDAGScheduler(IS, OptLevel);
226   }
227 }
228
229 // EmitInstrWithCustomInserter - This method should be implemented by targets
230 // that mark instructions with the 'usesCustomInserter' flag.  These
231 // instructions are special in various ways, which require special support to
232 // insert.  The specified MachineInstr is created but not inserted into any
233 // basic blocks, and this method is called to expand it into a sequence of
234 // instructions, potentially also creating new basic blocks and control flow.
235 // When new basic blocks are inserted and the edges from MBB to its successors
236 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
237 // DenseMap.
238 MachineBasicBlock *
239 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
240                                             MachineBasicBlock *MBB) const {
241 #ifndef NDEBUG
242   dbgs() << "If a target marks an instruction with "
243           "'usesCustomInserter', it must implement "
244           "TargetLowering::EmitInstrWithCustomInserter!";
245 #endif
246   llvm_unreachable(0);
247   return 0;
248 }
249
250 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
251                                                    SDNode *Node) const {
252   assert(!MI->hasPostISelHook() &&
253          "If a target marks an instruction with 'hasPostISelHook', "
254          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
255 }
256
257 //===----------------------------------------------------------------------===//
258 // SelectionDAGISel code
259 //===----------------------------------------------------------------------===//
260
261 SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm,
262                                    CodeGenOpt::Level OL) :
263   MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
264   FuncInfo(new FunctionLoweringInfo(TLI)),
265   CurDAG(new SelectionDAG(tm)),
266   SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
267   GFI(),
268   OptLevel(OL),
269   DAGSize(0) {
270     initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
271     initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
272     initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
273     initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
274   }
275
276 SelectionDAGISel::~SelectionDAGISel() {
277   delete SDB;
278   delete CurDAG;
279   delete FuncInfo;
280 }
281
282 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
283   AU.addRequired<AliasAnalysis>();
284   AU.addPreserved<AliasAnalysis>();
285   AU.addRequired<GCModuleInfo>();
286   AU.addPreserved<GCModuleInfo>();
287   AU.addRequired<TargetLibraryInfo>();
288   if (UseMBPI && OptLevel != CodeGenOpt::None)
289     AU.addRequired<BranchProbabilityInfo>();
290   MachineFunctionPass::getAnalysisUsage(AU);
291 }
292
293 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
294 /// may trap on it.  In this case we have to split the edge so that the path
295 /// through the predecessor block that doesn't go to the phi block doesn't
296 /// execute the possibly trapping instruction.
297 ///
298 /// This is required for correctness, so it must be done at -O0.
299 ///
300 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
301   // Loop for blocks with phi nodes.
302   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
303     PHINode *PN = dyn_cast<PHINode>(BB->begin());
304     if (PN == 0) continue;
305
306   ReprocessBlock:
307     // For each block with a PHI node, check to see if any of the input values
308     // are potentially trapping constant expressions.  Constant expressions are
309     // the only potentially trapping value that can occur as the argument to a
310     // PHI.
311     for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
312       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
313         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
314         if (CE == 0 || !CE->canTrap()) continue;
315
316         // The only case we have to worry about is when the edge is critical.
317         // Since this block has a PHI Node, we assume it has multiple input
318         // edges: check to see if the pred has multiple successors.
319         BasicBlock *Pred = PN->getIncomingBlock(i);
320         if (Pred->getTerminator()->getNumSuccessors() == 1)
321           continue;
322
323         // Okay, we have to split this edge.
324         SplitCriticalEdge(Pred->getTerminator(),
325                           GetSuccessorNumber(Pred, BB), SDISel, true);
326         goto ReprocessBlock;
327       }
328   }
329 }
330
331 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
332   // Do some sanity-checking on the command-line options.
333   assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
334          "-fast-isel-verbose requires -fast-isel");
335   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
336          "-fast-isel-abort requires -fast-isel");
337
338   const Function &Fn = *mf.getFunction();
339   const TargetInstrInfo &TII = *TM.getInstrInfo();
340   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
341
342   MF = &mf;
343   RegInfo = &MF->getRegInfo();
344   AA = &getAnalysis<AliasAnalysis>();
345   LibInfo = &getAnalysis<TargetLibraryInfo>();
346   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
347
348   DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
349
350   SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
351
352   CurDAG->init(*MF);
353   FuncInfo->set(Fn, *MF);
354
355   if (UseMBPI && OptLevel != CodeGenOpt::None)
356     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
357   else
358     FuncInfo->BPI = 0;
359
360   SDB->init(GFI, *AA, LibInfo);
361
362   SelectAllBasicBlocks(Fn);
363
364   // If the first basic block in the function has live ins that need to be
365   // copied into vregs, emit the copies into the top of the block before
366   // emitting the code for the block.
367   MachineBasicBlock *EntryMBB = MF->begin();
368   RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
369
370   DenseMap<unsigned, unsigned> LiveInMap;
371   if (!FuncInfo->ArgDbgValues.empty())
372     for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
373            E = RegInfo->livein_end(); LI != E; ++LI)
374       if (LI->second)
375         LiveInMap.insert(std::make_pair(LI->first, LI->second));
376
377   // Insert DBG_VALUE instructions for function arguments to the entry block.
378   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
379     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
380     unsigned Reg = MI->getOperand(0).getReg();
381     if (TargetRegisterInfo::isPhysicalRegister(Reg))
382       EntryMBB->insert(EntryMBB->begin(), MI);
383     else {
384       MachineInstr *Def = RegInfo->getVRegDef(Reg);
385       MachineBasicBlock::iterator InsertPos = Def;
386       // FIXME: VR def may not be in entry block.
387       Def->getParent()->insert(llvm::next(InsertPos), MI);
388     }
389
390     // If Reg is live-in then update debug info to track its copy in a vreg.
391     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
392     if (LDI != LiveInMap.end()) {
393       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
394       MachineBasicBlock::iterator InsertPos = Def;
395       const MDNode *Variable =
396         MI->getOperand(MI->getNumOperands()-1).getMetadata();
397       unsigned Offset = MI->getOperand(1).getImm();
398       // Def is never a terminator here, so it is ok to increment InsertPos.
399       BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
400               TII.get(TargetOpcode::DBG_VALUE))
401         .addReg(LDI->second, RegState::Debug)
402         .addImm(Offset).addMetadata(Variable);
403
404       // If this vreg is directly copied into an exported register then
405       // that COPY instructions also need DBG_VALUE, if it is the only
406       // user of LDI->second.
407       MachineInstr *CopyUseMI = NULL;
408       for (MachineRegisterInfo::use_iterator
409              UI = RegInfo->use_begin(LDI->second);
410            MachineInstr *UseMI = UI.skipInstruction();) {
411         if (UseMI->isDebugValue()) continue;
412         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
413           CopyUseMI = UseMI; continue;
414         }
415         // Otherwise this is another use or second copy use.
416         CopyUseMI = NULL; break;
417       }
418       if (CopyUseMI) {
419         MachineInstr *NewMI =
420           BuildMI(*MF, CopyUseMI->getDebugLoc(),
421                   TII.get(TargetOpcode::DBG_VALUE))
422           .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
423           .addImm(Offset).addMetadata(Variable);
424         MachineBasicBlock::iterator Pos = CopyUseMI;
425         EntryMBB->insertAfter(Pos, NewMI);
426       }
427     }
428   }
429
430   // Determine if there are any calls in this machine function.
431   MachineFrameInfo *MFI = MF->getFrameInfo();
432   if (!MFI->hasCalls()) {
433     for (MachineFunction::const_iterator
434            I = MF->begin(), E = MF->end(); I != E; ++I) {
435       const MachineBasicBlock *MBB = I;
436       for (MachineBasicBlock::const_iterator
437              II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
438         const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
439
440         if ((MCID.isCall() && !MCID.isReturn()) ||
441             II->isStackAligningInlineAsm()) {
442           MFI->setHasCalls(true);
443           goto done;
444         }
445       }
446     }
447   done:;
448   }
449
450   // Determine if there is a call to setjmp in the machine function.
451   MF->setCallsSetJmp(Fn.callsFunctionThatReturnsTwice());
452
453   // Replace forward-declared registers with the registers containing
454   // the desired value.
455   MachineRegisterInfo &MRI = MF->getRegInfo();
456   for (DenseMap<unsigned, unsigned>::iterator
457        I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
458        I != E; ++I) {
459     unsigned From = I->first;
460     unsigned To = I->second;
461     // If To is also scheduled to be replaced, find what its ultimate
462     // replacement is.
463     for (;;) {
464       DenseMap<unsigned, unsigned>::iterator J =
465         FuncInfo->RegFixups.find(To);
466       if (J == E) break;
467       To = J->second;
468     }
469     // Replace it.
470     MRI.replaceRegWith(From, To);
471   }
472
473   // Release function-specific state. SDB and CurDAG are already cleared
474   // at this point.
475   FuncInfo->clear();
476
477   return true;
478 }
479
480 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
481                                         BasicBlock::const_iterator End,
482                                         bool &HadTailCall) {
483   // Lower all of the non-terminator instructions. If a call is emitted
484   // as a tail call, cease emitting nodes for this block. Terminators
485   // are handled below.
486   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
487     SDB->visit(*I);
488
489   // Make sure the root of the DAG is up-to-date.
490   CurDAG->setRoot(SDB->getControlRoot());
491   HadTailCall = SDB->HasTailCall;
492   SDB->clear();
493
494   // Final step, emit the lowered DAG as machine code.
495   CodeGenAndEmitDAG();
496 }
497
498 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
499   SmallPtrSet<SDNode*, 128> VisitedNodes;
500   SmallVector<SDNode*, 128> Worklist;
501
502   Worklist.push_back(CurDAG->getRoot().getNode());
503
504   APInt Mask;
505   APInt KnownZero;
506   APInt KnownOne;
507
508   do {
509     SDNode *N = Worklist.pop_back_val();
510
511     // If we've already seen this node, ignore it.
512     if (!VisitedNodes.insert(N))
513       continue;
514
515     // Otherwise, add all chain operands to the worklist.
516     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
517       if (N->getOperand(i).getValueType() == MVT::Other)
518         Worklist.push_back(N->getOperand(i).getNode());
519
520     // If this is a CopyToReg with a vreg dest, process it.
521     if (N->getOpcode() != ISD::CopyToReg)
522       continue;
523
524     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
525     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
526       continue;
527
528     // Ignore non-scalar or non-integer values.
529     SDValue Src = N->getOperand(2);
530     EVT SrcVT = Src.getValueType();
531     if (!SrcVT.isInteger() || SrcVT.isVector())
532       continue;
533
534     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
535     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
536     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
537     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
538   } while (!Worklist.empty());
539 }
540
541 void SelectionDAGISel::CodeGenAndEmitDAG() {
542   std::string GroupName;
543   if (TimePassesIsEnabled)
544     GroupName = "Instruction Selection and Scheduling";
545   std::string BlockName;
546   int BlockNumber = -1;
547   (void)BlockNumber;
548 #ifdef NDEBUG
549   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
550       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
551       ViewSUnitDAGs)
552 #endif
553   {
554     BlockNumber = FuncInfo->MBB->getNumber();
555     BlockName = MF->getFunction()->getName().str() + ":" +
556                 FuncInfo->MBB->getBasicBlock()->getName().str();
557   }
558   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
559         << " '" << BlockName << "'\n"; CurDAG->dump());
560
561   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
562
563   // Run the DAG combiner in pre-legalize mode.
564   {
565     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
566     CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
567   }
568
569   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
570         << " '" << BlockName << "'\n"; CurDAG->dump());
571
572   // Second step, hack on the DAG until it only uses operations and types that
573   // the target supports.
574   if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
575                                                BlockName);
576
577   bool Changed;
578   {
579     NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
580     Changed = CurDAG->LegalizeTypes();
581   }
582
583   DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
584         << " '" << BlockName << "'\n"; CurDAG->dump());
585
586   if (Changed) {
587     if (ViewDAGCombineLT)
588       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
589
590     // Run the DAG combiner in post-type-legalize mode.
591     {
592       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
593                          TimePassesIsEnabled);
594       CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
595     }
596
597     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
598           << " '" << BlockName << "'\n"; CurDAG->dump());
599   }
600
601   {
602     NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
603     Changed = CurDAG->LegalizeVectors();
604   }
605
606   if (Changed) {
607     {
608       NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
609       CurDAG->LegalizeTypes();
610     }
611
612     if (ViewDAGCombineLT)
613       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
614
615     // Run the DAG combiner in post-type-legalize mode.
616     {
617       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
618                          TimePassesIsEnabled);
619       CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
620     }
621
622     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
623           << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
624   }
625
626   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
627
628   {
629     NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
630     CurDAG->Legalize();
631   }
632
633   DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
634         << " '" << BlockName << "'\n"; CurDAG->dump());
635
636   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
637
638   // Run the DAG combiner in post-legalize mode.
639   {
640     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
641     CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
642   }
643
644   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
645         << " '" << BlockName << "'\n"; CurDAG->dump());
646
647   if (OptLevel != CodeGenOpt::None)
648     ComputeLiveOutVRegInfo();
649
650   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
651
652   // Third, instruction select all of the operations to machine code, adding the
653   // code to the MachineBasicBlock.
654   {
655     NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
656     DoInstructionSelection();
657   }
658
659   DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
660         << " '" << BlockName << "'\n"; CurDAG->dump());
661
662   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
663
664   // Schedule machine code.
665   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
666   {
667     NamedRegionTimer T("Instruction Scheduling", GroupName,
668                        TimePassesIsEnabled);
669     Scheduler->Run(CurDAG, FuncInfo->MBB, FuncInfo->InsertPt);
670   }
671
672   if (ViewSUnitDAGs) Scheduler->viewGraph();
673
674   // Emit machine code to BB.  This can change 'BB' to the last block being
675   // inserted into.
676   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
677   {
678     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
679
680     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule();
681     FuncInfo->InsertPt = Scheduler->InsertPos;
682   }
683
684   // If the block was split, make sure we update any references that are used to
685   // update PHI nodes later on.
686   if (FirstMBB != LastMBB)
687     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
688
689   // Free the scheduler state.
690   {
691     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
692                        TimePassesIsEnabled);
693     delete Scheduler;
694   }
695
696   // Free the SelectionDAG state, now that we're finished with it.
697   CurDAG->clear();
698 }
699
700 void SelectionDAGISel::DoInstructionSelection() {
701   DEBUG(errs() << "===== Instruction selection begins: BB#"
702         << FuncInfo->MBB->getNumber()
703         << " '" << FuncInfo->MBB->getName() << "'\n");
704
705   PreprocessISelDAG();
706
707   // Select target instructions for the DAG.
708   {
709     // Number all nodes with a topological order and set DAGSize.
710     DAGSize = CurDAG->AssignTopologicalOrder();
711
712     // Create a dummy node (which is not added to allnodes), that adds
713     // a reference to the root node, preventing it from being deleted,
714     // and tracking any changes of the root.
715     HandleSDNode Dummy(CurDAG->getRoot());
716     ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
717     ++ISelPosition;
718
719     // The AllNodes list is now topological-sorted. Visit the
720     // nodes by starting at the end of the list (the root of the
721     // graph) and preceding back toward the beginning (the entry
722     // node).
723     while (ISelPosition != CurDAG->allnodes_begin()) {
724       SDNode *Node = --ISelPosition;
725       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
726       // but there are currently some corner cases that it misses. Also, this
727       // makes it theoretically possible to disable the DAGCombiner.
728       if (Node->use_empty())
729         continue;
730
731       SDNode *ResNode = Select(Node);
732
733       // FIXME: This is pretty gross.  'Select' should be changed to not return
734       // anything at all and this code should be nuked with a tactical strike.
735
736       // If node should not be replaced, continue with the next one.
737       if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
738         continue;
739       // Replace node.
740       if (ResNode)
741         ReplaceUses(Node, ResNode);
742
743       // If after the replacement this node is not used any more,
744       // remove this dead node.
745       if (Node->use_empty()) { // Don't delete EntryToken, etc.
746         ISelUpdater ISU(ISelPosition);
747         CurDAG->RemoveDeadNode(Node, &ISU);
748       }
749     }
750
751     CurDAG->setRoot(Dummy.getValue());
752   }
753
754   DEBUG(errs() << "===== Instruction selection ends:\n");
755
756   PostprocessISelDAG();
757 }
758
759 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
760 /// do other setup for EH landing-pad blocks.
761 void SelectionDAGISel::PrepareEHLandingPad() {
762   MachineBasicBlock *MBB = FuncInfo->MBB;
763
764   // Add a label to mark the beginning of the landing pad.  Deletion of the
765   // landing pad can thus be detected via the MachineModuleInfo.
766   MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
767
768   // Assign the call site to the landing pad's begin label.
769   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
770     
771   const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
772   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
773     .addSym(Label);
774
775   // Mark exception register as live in.
776   unsigned Reg = TLI.getExceptionAddressRegister();
777   if (Reg) MBB->addLiveIn(Reg);
778
779   // Mark exception selector register as live in.
780   Reg = TLI.getExceptionSelectorRegister();
781   if (Reg) MBB->addLiveIn(Reg);
782
783   // FIXME: Hack around an exception handling flaw (PR1508): the personality
784   // function and list of typeids logically belong to the invoke (or, if you
785   // like, the basic block containing the invoke), and need to be associated
786   // with it in the dwarf exception handling tables.  Currently however the
787   // information is provided by an intrinsic (eh.selector) that can be moved
788   // to unexpected places by the optimizers: if the unwind edge is critical,
789   // then breaking it can result in the intrinsics being in the successor of
790   // the landing pad, not the landing pad itself.  This results
791   // in exceptions not being caught because no typeids are associated with
792   // the invoke.  This may not be the only way things can go wrong, but it
793   // is the only way we try to work around for the moment.
794   const BasicBlock *LLVMBB = MBB->getBasicBlock();
795   const BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
796
797   if (Br && Br->isUnconditional()) { // Critical edge?
798     BasicBlock::const_iterator I, E;
799     for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
800       if (isa<EHSelectorInst>(I))
801         break;
802
803     if (I == E)
804       // No catch info found - try to extract some from the successor.
805       CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
806   }
807 }
808
809 /// TryToFoldFastISelLoad - We're checking to see if we can fold the specified
810 /// load into the specified FoldInst.  Note that we could have a sequence where
811 /// multiple LLVM IR instructions are folded into the same machineinstr.  For
812 /// example we could have:
813 ///   A: x = load i32 *P
814 ///   B: y = icmp A, 42
815 ///   C: br y, ...
816 ///
817 /// In this scenario, LI is "A", and FoldInst is "C".  We know about "B" (and
818 /// any other folded instructions) because it is between A and C.
819 ///
820 /// If we succeed in folding the load into the operation, return true.
821 ///
822 bool SelectionDAGISel::TryToFoldFastISelLoad(const LoadInst *LI,
823                                              const Instruction *FoldInst,
824                                              FastISel *FastIS) {
825   // We know that the load has a single use, but don't know what it is.  If it
826   // isn't one of the folded instructions, then we can't succeed here.  Handle
827   // this by scanning the single-use users of the load until we get to FoldInst.
828   unsigned MaxUsers = 6;  // Don't scan down huge single-use chains of instrs.
829
830   const Instruction *TheUser = LI->use_back();
831   while (TheUser != FoldInst &&   // Scan up until we find FoldInst.
832          // Stay in the right block.
833          TheUser->getParent() == FoldInst->getParent() &&
834          --MaxUsers) {  // Don't scan too far.
835     // If there are multiple or no uses of this instruction, then bail out.
836     if (!TheUser->hasOneUse())
837       return false;
838
839     TheUser = TheUser->use_back();
840   }
841
842   // If we didn't find the fold instruction, then we failed to collapse the
843   // sequence.
844   if (TheUser != FoldInst)
845     return false;
846
847   // Don't try to fold volatile loads.  Target has to deal with alignment
848   // constraints.
849   if (LI->isVolatile()) return false;
850
851   // Figure out which vreg this is going into.  If there is no assigned vreg yet
852   // then there actually was no reference to it.  Perhaps the load is referenced
853   // by a dead instruction.
854   unsigned LoadReg = FastIS->getRegForValue(LI);
855   if (LoadReg == 0)
856     return false;
857
858   // Check to see what the uses of this vreg are.  If it has no uses, or more
859   // than one use (at the machine instr level) then we can't fold it.
860   MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(LoadReg);
861   if (RI == RegInfo->reg_end())
862     return false;
863
864   // See if there is exactly one use of the vreg.  If there are multiple uses,
865   // then the instruction got lowered to multiple machine instructions or the
866   // use of the loaded value ended up being multiple operands of the result, in
867   // either case, we can't fold this.
868   MachineRegisterInfo::reg_iterator PostRI = RI; ++PostRI;
869   if (PostRI != RegInfo->reg_end())
870     return false;
871
872   assert(RI.getOperand().isUse() &&
873          "The only use of the vreg must be a use, we haven't emitted the def!");
874
875   MachineInstr *User = &*RI;
876
877   // Set the insertion point properly.  Folding the load can cause generation of
878   // other random instructions (like sign extends) for addressing modes, make
879   // sure they get inserted in a logical place before the new instruction.
880   FuncInfo->InsertPt = User;
881   FuncInfo->MBB = User->getParent();
882
883   // Ask the target to try folding the load.
884   return FastIS->TryToFoldLoad(User, RI.getOperandNo(), LI);
885 }
886
887 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
888 /// side-effect free and is either dead or folded into a generated instruction.
889 /// Return false if it needs to be emitted.
890 static bool isFoldedOrDeadInstruction(const Instruction *I,
891                                       FunctionLoweringInfo *FuncInfo) {
892   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
893          !isa<TerminatorInst>(I) && // Terminators aren't folded.
894          !isa<DbgInfoIntrinsic>(I) &&  // Debug instructions aren't folded.
895          !isa<LandingPadInst>(I) &&    // Landingpad instructions aren't folded.
896          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
897 }
898
899 #ifndef NDEBUG
900 static void collectFailStats(const Instruction *I) {
901   switch (I->getOpcode()) {
902   default: assert (0 && "<Invalid operator> ");
903
904   // Terminators
905   case Instruction::Ret:         NumFastIselFailRet++; return;
906   case Instruction::Br:          NumFastIselFailBr++; return;
907   case Instruction::Switch:      NumFastIselFailSwitch++; return;
908   case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
909   case Instruction::Invoke:      NumFastIselFailInvoke++; return;
910   case Instruction::Resume:      NumFastIselFailResume++; return;
911   case Instruction::Unwind:      NumFastIselFailUnwind++; return;
912   case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
913
914   // Standard binary operators...
915   case Instruction::Add:  NumFastIselFailAdd++; return;
916   case Instruction::FAdd: NumFastIselFailFAdd++; return;
917   case Instruction::Sub:  NumFastIselFailSub++; return;
918   case Instruction::FSub: NumFastIselFailFSub++; return;
919   case Instruction::Mul:  NumFastIselFailMul++; return;
920   case Instruction::FMul: NumFastIselFailFMul++; return;
921   case Instruction::UDiv: NumFastIselFailUDiv++; return;
922   case Instruction::SDiv: NumFastIselFailSDiv++; return;
923   case Instruction::FDiv: NumFastIselFailFDiv++; return;
924   case Instruction::URem: NumFastIselFailURem++; return;
925   case Instruction::SRem: NumFastIselFailSRem++; return;
926   case Instruction::FRem: NumFastIselFailFRem++; return;
927
928   // Logical operators...
929   case Instruction::And: NumFastIselFailAnd++; return;
930   case Instruction::Or:  NumFastIselFailOr++; return;
931   case Instruction::Xor: NumFastIselFailXor++; return;
932
933   // Memory instructions...
934   case Instruction::Alloca:        NumFastIselFailAlloca++; return;
935   case Instruction::Load:          NumFastIselFailLoad++; return;
936   case Instruction::Store:         NumFastIselFailStore++; return;
937   case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
938   case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
939   case Instruction::Fence:         NumFastIselFailFence++; return;
940   case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
941
942   // Convert instructions...
943   case Instruction::Trunc:    NumFastIselFailTrunc++; return;
944   case Instruction::ZExt:     NumFastIselFailZExt++; return;
945   case Instruction::SExt:     NumFastIselFailSExt++; return;
946   case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
947   case Instruction::FPExt:    NumFastIselFailFPExt++; return;
948   case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
949   case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
950   case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
951   case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
952   case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return; 
953   case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
954   case Instruction::BitCast:  NumFastIselFailBitCast++; return; 
955
956   // Other instructions...
957   case Instruction::ICmp:           NumFastIselFailICmp++; return;
958   case Instruction::FCmp:           NumFastIselFailFCmp++; return;
959   case Instruction::PHI:            NumFastIselFailPHI++; return;
960   case Instruction::Select:         NumFastIselFailSelect++; return;
961   case Instruction::Call:           NumFastIselFailCall++; return;
962   case Instruction::Shl:            NumFastIselFailShl++; return;
963   case Instruction::LShr:           NumFastIselFailLShr++; return;
964   case Instruction::AShr:           NumFastIselFailAShr++; return;
965   case Instruction::VAArg:          NumFastIselFailVAArg++; return;
966   case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
967   case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
968   case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
969   case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
970   case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
971   case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
972   }
973   return;
974 }
975 #endif
976
977 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
978   // Initialize the Fast-ISel state, if needed.
979   FastISel *FastIS = 0;
980   if (TM.Options.EnableFastISel)
981     FastIS = TLI.createFastISel(*FuncInfo);
982
983   // Iterate over all basic blocks in the function.
984   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
985   for (ReversePostOrderTraversal<const Function*>::rpo_iterator
986        I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
987     const BasicBlock *LLVMBB = *I;
988
989     if (OptLevel != CodeGenOpt::None) {
990       bool AllPredsVisited = true;
991       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
992            PI != PE; ++PI) {
993         if (!FuncInfo->VisitedBBs.count(*PI)) {
994           AllPredsVisited = false;
995           break;
996         }
997       }
998
999       if (AllPredsVisited) {
1000         for (BasicBlock::const_iterator I = LLVMBB->begin();
1001              isa<PHINode>(I); ++I)
1002           FuncInfo->ComputePHILiveOutRegInfo(cast<PHINode>(I));
1003       } else {
1004         for (BasicBlock::const_iterator I = LLVMBB->begin();
1005              isa<PHINode>(I); ++I)
1006           FuncInfo->InvalidatePHILiveOutRegInfo(cast<PHINode>(I));
1007       }
1008
1009       FuncInfo->VisitedBBs.insert(LLVMBB);
1010     }
1011
1012     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1013     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1014
1015     BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
1016     BasicBlock::const_iterator const End = LLVMBB->end();
1017     BasicBlock::const_iterator BI = End;
1018
1019     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1020
1021     // Setup an EH landing-pad block.
1022     if (FuncInfo->MBB->isLandingPad())
1023       PrepareEHLandingPad();
1024
1025     // Lower any arguments needed in this block if this is the entry block.
1026     if (LLVMBB == &Fn.getEntryBlock())
1027       LowerArguments(LLVMBB);
1028
1029     // Before doing SelectionDAG ISel, see if FastISel has been requested.
1030     if (FastIS) {
1031       FastIS->startNewBlock();
1032
1033       // Emit code for any incoming arguments. This must happen before
1034       // beginning FastISel on the entry block.
1035       if (LLVMBB == &Fn.getEntryBlock()) {
1036         CurDAG->setRoot(SDB->getControlRoot());
1037         SDB->clear();
1038         CodeGenAndEmitDAG();
1039
1040         // If we inserted any instructions at the beginning, make a note of
1041         // where they are, so we can be sure to emit subsequent instructions
1042         // after them.
1043         if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1044           FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
1045         else
1046           FastIS->setLastLocalValue(0);
1047       }
1048
1049       unsigned NumFastIselRemaining = std::distance(Begin, End);
1050       // Do FastISel on as many instructions as possible.
1051       for (; BI != Begin; --BI) {
1052         const Instruction *Inst = llvm::prior(BI);
1053
1054         // If we no longer require this instruction, skip it.
1055         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1056           --NumFastIselRemaining;
1057           continue;
1058         }
1059
1060         // Bottom-up: reset the insert pos at the top, after any local-value
1061         // instructions.
1062         FastIS->recomputeInsertPt();
1063
1064         // Try to select the instruction with FastISel.
1065         if (FastIS->SelectInstruction(Inst)) {
1066           --NumFastIselRemaining;
1067           ++NumFastIselSuccess;
1068           // If fast isel succeeded, skip over all the folded instructions, and
1069           // then see if there is a load right before the selected instructions.
1070           // Try to fold the load if so.
1071           const Instruction *BeforeInst = Inst;
1072           while (BeforeInst != Begin) {
1073             BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
1074             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1075               break;
1076           }
1077           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1078               BeforeInst->hasOneUse() &&
1079               TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), Inst, FastIS)) {
1080             // If we succeeded, don't re-select the load.
1081             BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
1082             --NumFastIselRemaining;
1083             ++NumFastIselSuccess;
1084           }
1085           continue;
1086         }
1087
1088 #ifndef NDEBUG
1089         collectFailStats(Inst);
1090 #endif
1091
1092         // Then handle certain instructions as single-LLVM-Instruction blocks.
1093         if (isa<CallInst>(Inst)) {
1094
1095           if (EnableFastISelVerbose || EnableFastISelAbort) {
1096             dbgs() << "FastISel missed call: ";
1097             Inst->dump();
1098           }
1099
1100           if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1101             unsigned &R = FuncInfo->ValueMap[Inst];
1102             if (!R)
1103               R = FuncInfo->CreateRegs(Inst->getType());
1104           }
1105
1106           bool HadTailCall = false;
1107           SelectBasicBlock(Inst, BI, HadTailCall);
1108
1109           // Recompute NumFastIselRemaining as Selection DAG instruction
1110           // selection may have handled the call, input args, etc.
1111           unsigned RemainingNow = std::distance(Begin, BI);
1112           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1113
1114           // If the call was emitted as a tail call, we're done with the block.
1115           if (HadTailCall) {
1116             --BI;
1117             break;
1118           }
1119
1120           NumFastIselRemaining = RemainingNow;
1121           continue;
1122         }
1123
1124         if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1125           // Don't abort, and use a different message for terminator misses.
1126           NumFastIselFailures += NumFastIselRemaining;
1127           if (EnableFastISelVerbose || EnableFastISelAbort) {
1128             dbgs() << "FastISel missed terminator: ";
1129             Inst->dump();
1130           }
1131         } else {
1132           NumFastIselFailures += NumFastIselRemaining;
1133           if (EnableFastISelVerbose || EnableFastISelAbort) {
1134             dbgs() << "FastISel miss: ";
1135             Inst->dump();
1136           }
1137           if (EnableFastISelAbort)
1138             // The "fast" selector couldn't handle something and bailed.
1139             // For the purpose of debugging, just abort.
1140             llvm_unreachable("FastISel didn't select the entire block");
1141         }
1142         break;
1143       }
1144
1145       FastIS->recomputeInsertPt();
1146     }
1147
1148     if (Begin != BI)
1149       ++NumDAGBlocks;
1150     else
1151       ++NumFastIselBlocks;
1152
1153     if (Begin != BI) {
1154       // Run SelectionDAG instruction selection on the remainder of the block
1155       // not handled by FastISel. If FastISel is not run, this is the entire
1156       // block.
1157       bool HadTailCall;
1158       SelectBasicBlock(Begin, BI, HadTailCall);
1159     }
1160
1161     FinishBasicBlock();
1162     FuncInfo->PHINodesToUpdate.clear();
1163   }
1164
1165   delete FastIS;
1166   SDB->clearDanglingDebugInfo();
1167 }
1168
1169 void
1170 SelectionDAGISel::FinishBasicBlock() {
1171
1172   DEBUG(dbgs() << "Total amount of phi nodes to update: "
1173                << FuncInfo->PHINodesToUpdate.size() << "\n";
1174         for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1175           dbgs() << "Node " << i << " : ("
1176                  << FuncInfo->PHINodesToUpdate[i].first
1177                  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1178
1179   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1180   // PHI nodes in successors.
1181   if (SDB->SwitchCases.empty() &&
1182       SDB->JTCases.empty() &&
1183       SDB->BitTestCases.empty()) {
1184     for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1185       MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
1186       assert(PHI->isPHI() &&
1187              "This is not a machine PHI node that we are updating!");
1188       if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1189         continue;
1190       PHI->addOperand(
1191         MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
1192       PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1193     }
1194     return;
1195   }
1196
1197   for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1198     // Lower header first, if it wasn't already lowered
1199     if (!SDB->BitTestCases[i].Emitted) {
1200       // Set the current basic block to the mbb we wish to insert the code into
1201       FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1202       FuncInfo->InsertPt = FuncInfo->MBB->end();
1203       // Emit the code
1204       SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1205       CurDAG->setRoot(SDB->getRoot());
1206       SDB->clear();
1207       CodeGenAndEmitDAG();
1208     }
1209
1210     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1211       // Set the current basic block to the mbb we wish to insert the code into
1212       FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1213       FuncInfo->InsertPt = FuncInfo->MBB->end();
1214       // Emit the code
1215       if (j+1 != ej)
1216         SDB->visitBitTestCase(SDB->BitTestCases[i],
1217                               SDB->BitTestCases[i].Cases[j+1].ThisBB,
1218                               SDB->BitTestCases[i].Reg,
1219                               SDB->BitTestCases[i].Cases[j],
1220                               FuncInfo->MBB);
1221       else
1222         SDB->visitBitTestCase(SDB->BitTestCases[i],
1223                               SDB->BitTestCases[i].Default,
1224                               SDB->BitTestCases[i].Reg,
1225                               SDB->BitTestCases[i].Cases[j],
1226                               FuncInfo->MBB);
1227
1228
1229       CurDAG->setRoot(SDB->getRoot());
1230       SDB->clear();
1231       CodeGenAndEmitDAG();
1232     }
1233
1234     // Update PHI Nodes
1235     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1236          pi != pe; ++pi) {
1237       MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
1238       MachineBasicBlock *PHIBB = PHI->getParent();
1239       assert(PHI->isPHI() &&
1240              "This is not a machine PHI node that we are updating!");
1241       // This is "default" BB. We have two jumps to it. From "header" BB and
1242       // from last "case" BB.
1243       if (PHIBB == SDB->BitTestCases[i].Default) {
1244         PHI->addOperand(MachineOperand::
1245                         CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1246                                   false));
1247         PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
1248         PHI->addOperand(MachineOperand::
1249                         CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1250                                   false));
1251         PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
1252                                                   back().ThisBB));
1253       }
1254       // One of "cases" BB.
1255       for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1256            j != ej; ++j) {
1257         MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1258         if (cBB->isSuccessor(PHIBB)) {
1259           PHI->addOperand(MachineOperand::
1260                           CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1261                                     false));
1262           PHI->addOperand(MachineOperand::CreateMBB(cBB));
1263         }
1264       }
1265     }
1266   }
1267   SDB->BitTestCases.clear();
1268
1269   // If the JumpTable record is filled in, then we need to emit a jump table.
1270   // Updating the PHI nodes is tricky in this case, since we need to determine
1271   // whether the PHI is a successor of the range check MBB or the jump table MBB
1272   for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1273     // Lower header first, if it wasn't already lowered
1274     if (!SDB->JTCases[i].first.Emitted) {
1275       // Set the current basic block to the mbb we wish to insert the code into
1276       FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1277       FuncInfo->InsertPt = FuncInfo->MBB->end();
1278       // Emit the code
1279       SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1280                                 FuncInfo->MBB);
1281       CurDAG->setRoot(SDB->getRoot());
1282       SDB->clear();
1283       CodeGenAndEmitDAG();
1284     }
1285
1286     // Set the current basic block to the mbb we wish to insert the code into
1287     FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1288     FuncInfo->InsertPt = FuncInfo->MBB->end();
1289     // Emit the code
1290     SDB->visitJumpTable(SDB->JTCases[i].second);
1291     CurDAG->setRoot(SDB->getRoot());
1292     SDB->clear();
1293     CodeGenAndEmitDAG();
1294
1295     // Update PHI Nodes
1296     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1297          pi != pe; ++pi) {
1298       MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
1299       MachineBasicBlock *PHIBB = PHI->getParent();
1300       assert(PHI->isPHI() &&
1301              "This is not a machine PHI node that we are updating!");
1302       // "default" BB. We can go there only from header BB.
1303       if (PHIBB == SDB->JTCases[i].second.Default) {
1304         PHI->addOperand
1305           (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1306                                      false));
1307         PHI->addOperand
1308           (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
1309       }
1310       // JT BB. Just iterate over successors here
1311       if (FuncInfo->MBB->isSuccessor(PHIBB)) {
1312         PHI->addOperand
1313           (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1314                                      false));
1315         PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1316       }
1317     }
1318   }
1319   SDB->JTCases.clear();
1320
1321   // If the switch block involved a branch to one of the actual successors, we
1322   // need to update PHI nodes in that block.
1323   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1324     MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
1325     assert(PHI->isPHI() &&
1326            "This is not a machine PHI node that we are updating!");
1327     if (FuncInfo->MBB->isSuccessor(PHI->getParent())) {
1328       PHI->addOperand(
1329         MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
1330       PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
1331     }
1332   }
1333
1334   // If we generated any switch lowering information, build and codegen any
1335   // additional DAGs necessary.
1336   for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1337     // Set the current basic block to the mbb we wish to insert the code into
1338     FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1339     FuncInfo->InsertPt = FuncInfo->MBB->end();
1340
1341     // Determine the unique successors.
1342     SmallVector<MachineBasicBlock *, 2> Succs;
1343     Succs.push_back(SDB->SwitchCases[i].TrueBB);
1344     if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1345       Succs.push_back(SDB->SwitchCases[i].FalseBB);
1346
1347     // Emit the code. Note that this could result in FuncInfo->MBB being split.
1348     SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1349     CurDAG->setRoot(SDB->getRoot());
1350     SDB->clear();
1351     CodeGenAndEmitDAG();
1352
1353     // Remember the last block, now that any splitting is done, for use in
1354     // populating PHI nodes in successors.
1355     MachineBasicBlock *ThisBB = FuncInfo->MBB;
1356
1357     // Handle any PHI nodes in successors of this chunk, as if we were coming
1358     // from the original BB before switch expansion.  Note that PHI nodes can
1359     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1360     // handle them the right number of times.
1361     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1362       FuncInfo->MBB = Succs[i];
1363       FuncInfo->InsertPt = FuncInfo->MBB->end();
1364       // FuncInfo->MBB may have been removed from the CFG if a branch was
1365       // constant folded.
1366       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1367         for (MachineBasicBlock::iterator Phi = FuncInfo->MBB->begin();
1368              Phi != FuncInfo->MBB->end() && Phi->isPHI();
1369              ++Phi) {
1370           // This value for this PHI node is recorded in PHINodesToUpdate.
1371           for (unsigned pn = 0; ; ++pn) {
1372             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1373                    "Didn't find PHI entry!");
1374             if (FuncInfo->PHINodesToUpdate[pn].first == Phi) {
1375               Phi->addOperand(MachineOperand::
1376                               CreateReg(FuncInfo->PHINodesToUpdate[pn].second,
1377                                         false));
1378               Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1379               break;
1380             }
1381           }
1382         }
1383       }
1384     }
1385   }
1386   SDB->SwitchCases.clear();
1387 }
1388
1389
1390 /// Create the scheduler. If a specific scheduler was specified
1391 /// via the SchedulerRegistry, use it, otherwise select the
1392 /// one preferred by the target.
1393 ///
1394 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1395   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1396
1397   if (!Ctor) {
1398     Ctor = ISHeuristic;
1399     RegisterScheduler::setDefault(Ctor);
1400   }
1401
1402   return Ctor(this, OptLevel);
1403 }
1404
1405 //===----------------------------------------------------------------------===//
1406 // Helper functions used by the generated instruction selector.
1407 //===----------------------------------------------------------------------===//
1408 // Calls to these methods are generated by tblgen.
1409
1410 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1411 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1412 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1413 /// specified in the .td file (e.g. 255).
1414 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1415                                     int64_t DesiredMaskS) const {
1416   const APInt &ActualMask = RHS->getAPIntValue();
1417   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1418
1419   // If the actual mask exactly matches, success!
1420   if (ActualMask == DesiredMask)
1421     return true;
1422
1423   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1424   if (ActualMask.intersects(~DesiredMask))
1425     return false;
1426
1427   // Otherwise, the DAG Combiner may have proven that the value coming in is
1428   // either already zero or is not demanded.  Check for known zero input bits.
1429   APInt NeededMask = DesiredMask & ~ActualMask;
1430   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1431     return true;
1432
1433   // TODO: check to see if missing bits are just not demanded.
1434
1435   // Otherwise, this pattern doesn't match.
1436   return false;
1437 }
1438
1439 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1440 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1441 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1442 /// specified in the .td file (e.g. 255).
1443 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1444                                    int64_t DesiredMaskS) const {
1445   const APInt &ActualMask = RHS->getAPIntValue();
1446   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1447
1448   // If the actual mask exactly matches, success!
1449   if (ActualMask == DesiredMask)
1450     return true;
1451
1452   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1453   if (ActualMask.intersects(~DesiredMask))
1454     return false;
1455
1456   // Otherwise, the DAG Combiner may have proven that the value coming in is
1457   // either already zero or is not demanded.  Check for known zero input bits.
1458   APInt NeededMask = DesiredMask & ~ActualMask;
1459
1460   APInt KnownZero, KnownOne;
1461   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1462
1463   // If all the missing bits in the or are already known to be set, match!
1464   if ((NeededMask & KnownOne) == NeededMask)
1465     return true;
1466
1467   // TODO: check to see if missing bits are just not demanded.
1468
1469   // Otherwise, this pattern doesn't match.
1470   return false;
1471 }
1472
1473
1474 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1475 /// by tblgen.  Others should not call it.
1476 void SelectionDAGISel::
1477 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1478   std::vector<SDValue> InOps;
1479   std::swap(InOps, Ops);
1480
1481   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1482   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
1483   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
1484   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
1485
1486   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1487   if (InOps[e-1].getValueType() == MVT::Glue)
1488     --e;  // Don't process a glue operand if it is here.
1489
1490   while (i != e) {
1491     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1492     if (!InlineAsm::isMemKind(Flags)) {
1493       // Just skip over this operand, copying the operands verbatim.
1494       Ops.insert(Ops.end(), InOps.begin()+i,
1495                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1496       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1497     } else {
1498       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1499              "Memory operand with multiple values?");
1500       // Otherwise, this is a memory operand.  Ask the target to select it.
1501       std::vector<SDValue> SelOps;
1502       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1503         report_fatal_error("Could not match memory address.  Inline asm"
1504                            " failure!");
1505
1506       // Add this to the output node.
1507       unsigned NewFlags =
1508         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1509       Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1510       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1511       i += 2;
1512     }
1513   }
1514
1515   // Add the glue input back if present.
1516   if (e != InOps.size())
1517     Ops.push_back(InOps.back());
1518 }
1519
1520 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1521 /// SDNode.
1522 ///
1523 static SDNode *findGlueUse(SDNode *N) {
1524   unsigned FlagResNo = N->getNumValues()-1;
1525   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1526     SDUse &Use = I.getUse();
1527     if (Use.getResNo() == FlagResNo)
1528       return Use.getUser();
1529   }
1530   return NULL;
1531 }
1532
1533 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1534 /// This function recursively traverses up the operand chain, ignoring
1535 /// certain nodes.
1536 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1537                           SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1538                           bool IgnoreChains) {
1539   // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1540   // greater than all of its (recursive) operands.  If we scan to a point where
1541   // 'use' is smaller than the node we're scanning for, then we know we will
1542   // never find it.
1543   //
1544   // The Use may be -1 (unassigned) if it is a newly allocated node.  This can
1545   // happen because we scan down to newly selected nodes in the case of glue
1546   // uses.
1547   if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1548     return false;
1549
1550   // Don't revisit nodes if we already scanned it and didn't fail, we know we
1551   // won't fail if we scan it again.
1552   if (!Visited.insert(Use))
1553     return false;
1554
1555   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1556     // Ignore chain uses, they are validated by HandleMergeInputChains.
1557     if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1558       continue;
1559
1560     SDNode *N = Use->getOperand(i).getNode();
1561     if (N == Def) {
1562       if (Use == ImmedUse || Use == Root)
1563         continue;  // We are not looking for immediate use.
1564       assert(N != Root);
1565       return true;
1566     }
1567
1568     // Traverse up the operand chain.
1569     if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1570       return true;
1571   }
1572   return false;
1573 }
1574
1575 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1576 /// operand node N of U during instruction selection that starts at Root.
1577 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1578                                           SDNode *Root) const {
1579   if (OptLevel == CodeGenOpt::None) return false;
1580   return N.hasOneUse();
1581 }
1582
1583 /// IsLegalToFold - Returns true if the specific operand node N of
1584 /// U can be folded during instruction selection that starts at Root.
1585 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1586                                      CodeGenOpt::Level OptLevel,
1587                                      bool IgnoreChains) {
1588   if (OptLevel == CodeGenOpt::None) return false;
1589
1590   // If Root use can somehow reach N through a path that that doesn't contain
1591   // U then folding N would create a cycle. e.g. In the following
1592   // diagram, Root can reach N through X. If N is folded into into Root, then
1593   // X is both a predecessor and a successor of U.
1594   //
1595   //          [N*]           //
1596   //         ^   ^           //
1597   //        /     \          //
1598   //      [U*]    [X]?       //
1599   //        ^     ^          //
1600   //         \   /           //
1601   //          \ /            //
1602   //         [Root*]         //
1603   //
1604   // * indicates nodes to be folded together.
1605   //
1606   // If Root produces glue, then it gets (even more) interesting. Since it
1607   // will be "glued" together with its glue use in the scheduler, we need to
1608   // check if it might reach N.
1609   //
1610   //          [N*]           //
1611   //         ^   ^           //
1612   //        /     \          //
1613   //      [U*]    [X]?       //
1614   //        ^       ^        //
1615   //         \       \       //
1616   //          \      |       //
1617   //         [Root*] |       //
1618   //          ^      |       //
1619   //          f      |       //
1620   //          |      /       //
1621   //         [Y]    /        //
1622   //           ^   /         //
1623   //           f  /          //
1624   //           | /           //
1625   //          [GU]           //
1626   //
1627   // If GU (glue use) indirectly reaches N (the load), and Root folds N
1628   // (call it Fold), then X is a predecessor of GU and a successor of
1629   // Fold. But since Fold and GU are glued together, this will create
1630   // a cycle in the scheduling graph.
1631
1632   // If the node has glue, walk down the graph to the "lowest" node in the
1633   // glueged set.
1634   EVT VT = Root->getValueType(Root->getNumValues()-1);
1635   while (VT == MVT::Glue) {
1636     SDNode *GU = findGlueUse(Root);
1637     if (GU == NULL)
1638       break;
1639     Root = GU;
1640     VT = Root->getValueType(Root->getNumValues()-1);
1641
1642     // If our query node has a glue result with a use, we've walked up it.  If
1643     // the user (which has already been selected) has a chain or indirectly uses
1644     // the chain, our WalkChainUsers predicate will not consider it.  Because of
1645     // this, we cannot ignore chains in this predicate.
1646     IgnoreChains = false;
1647   }
1648
1649
1650   SmallPtrSet<SDNode*, 16> Visited;
1651   return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1652 }
1653
1654 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1655   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1656   SelectInlineAsmMemoryOperands(Ops);
1657
1658   std::vector<EVT> VTs;
1659   VTs.push_back(MVT::Other);
1660   VTs.push_back(MVT::Glue);
1661   SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
1662                                 VTs, &Ops[0], Ops.size());
1663   New->setNodeId(-1);
1664   return New.getNode();
1665 }
1666
1667 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1668   return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1669 }
1670
1671 /// GetVBR - decode a vbr encoding whose top bit is set.
1672 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1673 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1674   assert(Val >= 128 && "Not a VBR");
1675   Val &= 127;  // Remove first vbr bit.
1676
1677   unsigned Shift = 7;
1678   uint64_t NextBits;
1679   do {
1680     NextBits = MatcherTable[Idx++];
1681     Val |= (NextBits&127) << Shift;
1682     Shift += 7;
1683   } while (NextBits & 128);
1684
1685   return Val;
1686 }
1687
1688
1689 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1690 /// interior glue and chain results to use the new glue and chain results.
1691 void SelectionDAGISel::
1692 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1693                     const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1694                     SDValue InputGlue,
1695                     const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1696                     bool isMorphNodeTo) {
1697   SmallVector<SDNode*, 4> NowDeadNodes;
1698
1699   ISelUpdater ISU(ISelPosition);
1700
1701   // Now that all the normal results are replaced, we replace the chain and
1702   // glue results if present.
1703   if (!ChainNodesMatched.empty()) {
1704     assert(InputChain.getNode() != 0 &&
1705            "Matched input chains but didn't produce a chain");
1706     // Loop over all of the nodes we matched that produced a chain result.
1707     // Replace all the chain results with the final chain we ended up with.
1708     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1709       SDNode *ChainNode = ChainNodesMatched[i];
1710
1711       // If this node was already deleted, don't look at it.
1712       if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1713         continue;
1714
1715       // Don't replace the results of the root node if we're doing a
1716       // MorphNodeTo.
1717       if (ChainNode == NodeToMatch && isMorphNodeTo)
1718         continue;
1719
1720       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1721       if (ChainVal.getValueType() == MVT::Glue)
1722         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1723       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1724       CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1725
1726       // If the node became dead and we haven't already seen it, delete it.
1727       if (ChainNode->use_empty() &&
1728           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1729         NowDeadNodes.push_back(ChainNode);
1730     }
1731   }
1732
1733   // If the result produces glue, update any glue results in the matched
1734   // pattern with the glue result.
1735   if (InputGlue.getNode() != 0) {
1736     // Handle any interior nodes explicitly marked.
1737     for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1738       SDNode *FRN = GlueResultNodesMatched[i];
1739
1740       // If this node was already deleted, don't look at it.
1741       if (FRN->getOpcode() == ISD::DELETED_NODE)
1742         continue;
1743
1744       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1745              "Doesn't have a glue result");
1746       CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1747                                         InputGlue, &ISU);
1748
1749       // If the node became dead and we haven't already seen it, delete it.
1750       if (FRN->use_empty() &&
1751           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1752         NowDeadNodes.push_back(FRN);
1753     }
1754   }
1755
1756   if (!NowDeadNodes.empty())
1757     CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1758
1759   DEBUG(errs() << "ISEL: Match complete!\n");
1760 }
1761
1762 enum ChainResult {
1763   CR_Simple,
1764   CR_InducesCycle,
1765   CR_LeadsToInteriorNode
1766 };
1767
1768 /// WalkChainUsers - Walk down the users of the specified chained node that is
1769 /// part of the pattern we're matching, looking at all of the users we find.
1770 /// This determines whether something is an interior node, whether we have a
1771 /// non-pattern node in between two pattern nodes (which prevent folding because
1772 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1773 /// between pattern nodes (in which case the TF becomes part of the pattern).
1774 ///
1775 /// The walk we do here is guaranteed to be small because we quickly get down to
1776 /// already selected nodes "below" us.
1777 static ChainResult
1778 WalkChainUsers(SDNode *ChainedNode,
1779                SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1780                SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1781   ChainResult Result = CR_Simple;
1782
1783   for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1784          E = ChainedNode->use_end(); UI != E; ++UI) {
1785     // Make sure the use is of the chain, not some other value we produce.
1786     if (UI.getUse().getValueType() != MVT::Other) continue;
1787
1788     SDNode *User = *UI;
1789
1790     // If we see an already-selected machine node, then we've gone beyond the
1791     // pattern that we're selecting down into the already selected chunk of the
1792     // DAG.
1793     if (User->isMachineOpcode() ||
1794         User->getOpcode() == ISD::HANDLENODE)  // Root of the graph.
1795       continue;
1796
1797     if (User->getOpcode() == ISD::CopyToReg ||
1798         User->getOpcode() == ISD::CopyFromReg ||
1799         User->getOpcode() == ISD::INLINEASM ||
1800         User->getOpcode() == ISD::EH_LABEL) {
1801       // If their node ID got reset to -1 then they've already been selected.
1802       // Treat them like a MachineOpcode.
1803       if (User->getNodeId() == -1)
1804         continue;
1805     }
1806
1807     // If we have a TokenFactor, we handle it specially.
1808     if (User->getOpcode() != ISD::TokenFactor) {
1809       // If the node isn't a token factor and isn't part of our pattern, then it
1810       // must be a random chained node in between two nodes we're selecting.
1811       // This happens when we have something like:
1812       //   x = load ptr
1813       //   call
1814       //   y = x+4
1815       //   store y -> ptr
1816       // Because we structurally match the load/store as a read/modify/write,
1817       // but the call is chained between them.  We cannot fold in this case
1818       // because it would induce a cycle in the graph.
1819       if (!std::count(ChainedNodesInPattern.begin(),
1820                       ChainedNodesInPattern.end(), User))
1821         return CR_InducesCycle;
1822
1823       // Otherwise we found a node that is part of our pattern.  For example in:
1824       //   x = load ptr
1825       //   y = x+4
1826       //   store y -> ptr
1827       // This would happen when we're scanning down from the load and see the
1828       // store as a user.  Record that there is a use of ChainedNode that is
1829       // part of the pattern and keep scanning uses.
1830       Result = CR_LeadsToInteriorNode;
1831       InteriorChainedNodes.push_back(User);
1832       continue;
1833     }
1834
1835     // If we found a TokenFactor, there are two cases to consider: first if the
1836     // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1837     // uses of the TF are in our pattern) we just want to ignore it.  Second,
1838     // the TokenFactor can be sandwiched in between two chained nodes, like so:
1839     //     [Load chain]
1840     //         ^
1841     //         |
1842     //       [Load]
1843     //       ^    ^
1844     //       |    \                    DAG's like cheese
1845     //      /       \                       do you?
1846     //     /         |
1847     // [TokenFactor] [Op]
1848     //     ^          ^
1849     //     |          |
1850     //      \        /
1851     //       \      /
1852     //       [Store]
1853     //
1854     // In this case, the TokenFactor becomes part of our match and we rewrite it
1855     // as a new TokenFactor.
1856     //
1857     // To distinguish these two cases, do a recursive walk down the uses.
1858     switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1859     case CR_Simple:
1860       // If the uses of the TokenFactor are just already-selected nodes, ignore
1861       // it, it is "below" our pattern.
1862       continue;
1863     case CR_InducesCycle:
1864       // If the uses of the TokenFactor lead to nodes that are not part of our
1865       // pattern that are not selected, folding would turn this into a cycle,
1866       // bail out now.
1867       return CR_InducesCycle;
1868     case CR_LeadsToInteriorNode:
1869       break;  // Otherwise, keep processing.
1870     }
1871
1872     // Okay, we know we're in the interesting interior case.  The TokenFactor
1873     // is now going to be considered part of the pattern so that we rewrite its
1874     // uses (it may have uses that are not part of the pattern) with the
1875     // ultimate chain result of the generated code.  We will also add its chain
1876     // inputs as inputs to the ultimate TokenFactor we create.
1877     Result = CR_LeadsToInteriorNode;
1878     ChainedNodesInPattern.push_back(User);
1879     InteriorChainedNodes.push_back(User);
1880     continue;
1881   }
1882
1883   return Result;
1884 }
1885
1886 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1887 /// operation for when the pattern matched at least one node with a chains.  The
1888 /// input vector contains a list of all of the chained nodes that we match.  We
1889 /// must determine if this is a valid thing to cover (i.e. matching it won't
1890 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1891 /// be used as the input node chain for the generated nodes.
1892 static SDValue
1893 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1894                        SelectionDAG *CurDAG) {
1895   // Walk all of the chained nodes we've matched, recursively scanning down the
1896   // users of the chain result. This adds any TokenFactor nodes that are caught
1897   // in between chained nodes to the chained and interior nodes list.
1898   SmallVector<SDNode*, 3> InteriorChainedNodes;
1899   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1900     if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1901                        InteriorChainedNodes) == CR_InducesCycle)
1902       return SDValue(); // Would induce a cycle.
1903   }
1904
1905   // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1906   // that we are interested in.  Form our input TokenFactor node.
1907   SmallVector<SDValue, 3> InputChains;
1908   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1909     // Add the input chain of this node to the InputChains list (which will be
1910     // the operands of the generated TokenFactor) if it's not an interior node.
1911     SDNode *N = ChainNodesMatched[i];
1912     if (N->getOpcode() != ISD::TokenFactor) {
1913       if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1914         continue;
1915
1916       // Otherwise, add the input chain.
1917       SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1918       assert(InChain.getValueType() == MVT::Other && "Not a chain");
1919       InputChains.push_back(InChain);
1920       continue;
1921     }
1922
1923     // If we have a token factor, we want to add all inputs of the token factor
1924     // that are not part of the pattern we're matching.
1925     for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1926       if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1927                       N->getOperand(op).getNode()))
1928         InputChains.push_back(N->getOperand(op));
1929     }
1930   }
1931
1932   SDValue Res;
1933   if (InputChains.size() == 1)
1934     return InputChains[0];
1935   return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1936                          MVT::Other, &InputChains[0], InputChains.size());
1937 }
1938
1939 /// MorphNode - Handle morphing a node in place for the selector.
1940 SDNode *SelectionDAGISel::
1941 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1942           const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1943   // It is possible we're using MorphNodeTo to replace a node with no
1944   // normal results with one that has a normal result (or we could be
1945   // adding a chain) and the input could have glue and chains as well.
1946   // In this case we need to shift the operands down.
1947   // FIXME: This is a horrible hack and broken in obscure cases, no worse
1948   // than the old isel though.
1949   int OldGlueResultNo = -1, OldChainResultNo = -1;
1950
1951   unsigned NTMNumResults = Node->getNumValues();
1952   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
1953     OldGlueResultNo = NTMNumResults-1;
1954     if (NTMNumResults != 1 &&
1955         Node->getValueType(NTMNumResults-2) == MVT::Other)
1956       OldChainResultNo = NTMNumResults-2;
1957   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1958     OldChainResultNo = NTMNumResults-1;
1959
1960   // Call the underlying SelectionDAG routine to do the transmogrification. Note
1961   // that this deletes operands of the old node that become dead.
1962   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1963
1964   // MorphNodeTo can operate in two ways: if an existing node with the
1965   // specified operands exists, it can just return it.  Otherwise, it
1966   // updates the node in place to have the requested operands.
1967   if (Res == Node) {
1968     // If we updated the node in place, reset the node ID.  To the isel,
1969     // this should be just like a newly allocated machine node.
1970     Res->setNodeId(-1);
1971   }
1972
1973   unsigned ResNumResults = Res->getNumValues();
1974   // Move the glue if needed.
1975   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1976       (unsigned)OldGlueResultNo != ResNumResults-1)
1977     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
1978                                       SDValue(Res, ResNumResults-1));
1979
1980   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
1981     --ResNumResults;
1982
1983   // Move the chain reference if needed.
1984   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1985       (unsigned)OldChainResultNo != ResNumResults-1)
1986     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1987                                       SDValue(Res, ResNumResults-1));
1988
1989   // Otherwise, no replacement happened because the node already exists. Replace
1990   // Uses of the old node with the new one.
1991   if (Res != Node)
1992     CurDAG->ReplaceAllUsesWith(Node, Res);
1993
1994   return Res;
1995 }
1996
1997 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1998 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1999 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2000           SDValue N,
2001           const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2002   // Accept if it is exactly the same as a previously recorded node.
2003   unsigned RecNo = MatcherTable[MatcherIndex++];
2004   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2005   return N == RecordedNodes[RecNo].first;
2006 }
2007
2008 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2009 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2010 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2011                       SelectionDAGISel &SDISel) {
2012   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2013 }
2014
2015 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2016 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2017 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2018                    SelectionDAGISel &SDISel, SDNode *N) {
2019   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2020 }
2021
2022 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2023 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2024             SDNode *N) {
2025   uint16_t Opc = MatcherTable[MatcherIndex++];
2026   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2027   return N->getOpcode() == Opc;
2028 }
2029
2030 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2031 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2032           SDValue N, const TargetLowering &TLI) {
2033   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2034   if (N.getValueType() == VT) return true;
2035
2036   // Handle the case when VT is iPTR.
2037   return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
2038 }
2039
2040 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2041 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2042                SDValue N, const TargetLowering &TLI,
2043                unsigned ChildNo) {
2044   if (ChildNo >= N.getNumOperands())
2045     return false;  // Match fails if out of range child #.
2046   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2047 }
2048
2049
2050 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2051 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2052               SDValue N) {
2053   return cast<CondCodeSDNode>(N)->get() ==
2054       (ISD::CondCode)MatcherTable[MatcherIndex++];
2055 }
2056
2057 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2058 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2059                SDValue N, const TargetLowering &TLI) {
2060   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2061   if (cast<VTSDNode>(N)->getVT() == VT)
2062     return true;
2063
2064   // Handle the case when VT is iPTR.
2065   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
2066 }
2067
2068 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2069 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2070              SDValue N) {
2071   int64_t Val = MatcherTable[MatcherIndex++];
2072   if (Val & 128)
2073     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2074
2075   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2076   return C != 0 && C->getSExtValue() == Val;
2077 }
2078
2079 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2080 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2081             SDValue N, SelectionDAGISel &SDISel) {
2082   int64_t Val = MatcherTable[MatcherIndex++];
2083   if (Val & 128)
2084     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2085
2086   if (N->getOpcode() != ISD::AND) return false;
2087
2088   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2089   return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2090 }
2091
2092 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2093 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2094            SDValue N, SelectionDAGISel &SDISel) {
2095   int64_t Val = MatcherTable[MatcherIndex++];
2096   if (Val & 128)
2097     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2098
2099   if (N->getOpcode() != ISD::OR) return false;
2100
2101   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2102   return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2103 }
2104
2105 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2106 /// scope, evaluate the current node.  If the current predicate is known to
2107 /// fail, set Result=true and return anything.  If the current predicate is
2108 /// known to pass, set Result=false and return the MatcherIndex to continue
2109 /// with.  If the current predicate is unknown, set Result=false and return the
2110 /// MatcherIndex to continue with.
2111 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2112                                        unsigned Index, SDValue N,
2113                                        bool &Result, SelectionDAGISel &SDISel,
2114                  SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2115   switch (Table[Index++]) {
2116   default:
2117     Result = false;
2118     return Index-1;  // Could not evaluate this predicate.
2119   case SelectionDAGISel::OPC_CheckSame:
2120     Result = !::CheckSame(Table, Index, N, RecordedNodes);
2121     return Index;
2122   case SelectionDAGISel::OPC_CheckPatternPredicate:
2123     Result = !::CheckPatternPredicate(Table, Index, SDISel);
2124     return Index;
2125   case SelectionDAGISel::OPC_CheckPredicate:
2126     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2127     return Index;
2128   case SelectionDAGISel::OPC_CheckOpcode:
2129     Result = !::CheckOpcode(Table, Index, N.getNode());
2130     return Index;
2131   case SelectionDAGISel::OPC_CheckType:
2132     Result = !::CheckType(Table, Index, N, SDISel.TLI);
2133     return Index;
2134   case SelectionDAGISel::OPC_CheckChild0Type:
2135   case SelectionDAGISel::OPC_CheckChild1Type:
2136   case SelectionDAGISel::OPC_CheckChild2Type:
2137   case SelectionDAGISel::OPC_CheckChild3Type:
2138   case SelectionDAGISel::OPC_CheckChild4Type:
2139   case SelectionDAGISel::OPC_CheckChild5Type:
2140   case SelectionDAGISel::OPC_CheckChild6Type:
2141   case SelectionDAGISel::OPC_CheckChild7Type:
2142     Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
2143                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
2144     return Index;
2145   case SelectionDAGISel::OPC_CheckCondCode:
2146     Result = !::CheckCondCode(Table, Index, N);
2147     return Index;
2148   case SelectionDAGISel::OPC_CheckValueType:
2149     Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
2150     return Index;
2151   case SelectionDAGISel::OPC_CheckInteger:
2152     Result = !::CheckInteger(Table, Index, N);
2153     return Index;
2154   case SelectionDAGISel::OPC_CheckAndImm:
2155     Result = !::CheckAndImm(Table, Index, N, SDISel);
2156     return Index;
2157   case SelectionDAGISel::OPC_CheckOrImm:
2158     Result = !::CheckOrImm(Table, Index, N, SDISel);
2159     return Index;
2160   }
2161 }
2162
2163 namespace {
2164
2165 struct MatchScope {
2166   /// FailIndex - If this match fails, this is the index to continue with.
2167   unsigned FailIndex;
2168
2169   /// NodeStack - The node stack when the scope was formed.
2170   SmallVector<SDValue, 4> NodeStack;
2171
2172   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2173   unsigned NumRecordedNodes;
2174
2175   /// NumMatchedMemRefs - The number of matched memref entries.
2176   unsigned NumMatchedMemRefs;
2177
2178   /// InputChain/InputGlue - The current chain/glue
2179   SDValue InputChain, InputGlue;
2180
2181   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2182   bool HasChainNodesMatched, HasGlueResultNodesMatched;
2183 };
2184
2185 }
2186
2187 SDNode *SelectionDAGISel::
2188 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2189                  unsigned TableSize) {
2190   // FIXME: Should these even be selected?  Handle these cases in the caller?
2191   switch (NodeToMatch->getOpcode()) {
2192   default:
2193     break;
2194   case ISD::EntryToken:       // These nodes remain the same.
2195   case ISD::BasicBlock:
2196   case ISD::Register:
2197   //case ISD::VALUETYPE:
2198   //case ISD::CONDCODE:
2199   case ISD::HANDLENODE:
2200   case ISD::MDNODE_SDNODE:
2201   case ISD::TargetConstant:
2202   case ISD::TargetConstantFP:
2203   case ISD::TargetConstantPool:
2204   case ISD::TargetFrameIndex:
2205   case ISD::TargetExternalSymbol:
2206   case ISD::TargetBlockAddress:
2207   case ISD::TargetJumpTable:
2208   case ISD::TargetGlobalTLSAddress:
2209   case ISD::TargetGlobalAddress:
2210   case ISD::TokenFactor:
2211   case ISD::CopyFromReg:
2212   case ISD::CopyToReg:
2213   case ISD::EH_LABEL:
2214     NodeToMatch->setNodeId(-1); // Mark selected.
2215     return 0;
2216   case ISD::AssertSext:
2217   case ISD::AssertZext:
2218     CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2219                                       NodeToMatch->getOperand(0));
2220     return 0;
2221   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2222   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
2223   }
2224
2225   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2226
2227   // Set up the node stack with NodeToMatch as the only node on the stack.
2228   SmallVector<SDValue, 8> NodeStack;
2229   SDValue N = SDValue(NodeToMatch, 0);
2230   NodeStack.push_back(N);
2231
2232   // MatchScopes - Scopes used when matching, if a match failure happens, this
2233   // indicates where to continue checking.
2234   SmallVector<MatchScope, 8> MatchScopes;
2235
2236   // RecordedNodes - This is the set of nodes that have been recorded by the
2237   // state machine.  The second value is the parent of the node, or null if the
2238   // root is recorded.
2239   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2240
2241   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2242   // pattern.
2243   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2244
2245   // These are the current input chain and glue for use when generating nodes.
2246   // Various Emit operations change these.  For example, emitting a copytoreg
2247   // uses and updates these.
2248   SDValue InputChain, InputGlue;
2249
2250   // ChainNodesMatched - If a pattern matches nodes that have input/output
2251   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2252   // which ones they are.  The result is captured into this list so that we can
2253   // update the chain results when the pattern is complete.
2254   SmallVector<SDNode*, 3> ChainNodesMatched;
2255   SmallVector<SDNode*, 3> GlueResultNodesMatched;
2256
2257   DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
2258         NodeToMatch->dump(CurDAG);
2259         errs() << '\n');
2260
2261   // Determine where to start the interpreter.  Normally we start at opcode #0,
2262   // but if the state machine starts with an OPC_SwitchOpcode, then we
2263   // accelerate the first lookup (which is guaranteed to be hot) with the
2264   // OpcodeOffset table.
2265   unsigned MatcherIndex = 0;
2266
2267   if (!OpcodeOffset.empty()) {
2268     // Already computed the OpcodeOffset table, just index into it.
2269     if (N.getOpcode() < OpcodeOffset.size())
2270       MatcherIndex = OpcodeOffset[N.getOpcode()];
2271     DEBUG(errs() << "  Initial Opcode index to " << MatcherIndex << "\n");
2272
2273   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2274     // Otherwise, the table isn't computed, but the state machine does start
2275     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
2276     // is the first time we're selecting an instruction.
2277     unsigned Idx = 1;
2278     while (1) {
2279       // Get the size of this case.
2280       unsigned CaseSize = MatcherTable[Idx++];
2281       if (CaseSize & 128)
2282         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2283       if (CaseSize == 0) break;
2284
2285       // Get the opcode, add the index to the table.
2286       uint16_t Opc = MatcherTable[Idx++];
2287       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2288       if (Opc >= OpcodeOffset.size())
2289         OpcodeOffset.resize((Opc+1)*2);
2290       OpcodeOffset[Opc] = Idx;
2291       Idx += CaseSize;
2292     }
2293
2294     // Okay, do the lookup for the first opcode.
2295     if (N.getOpcode() < OpcodeOffset.size())
2296       MatcherIndex = OpcodeOffset[N.getOpcode()];
2297   }
2298
2299   while (1) {
2300     assert(MatcherIndex < TableSize && "Invalid index");
2301 #ifndef NDEBUG
2302     unsigned CurrentOpcodeIndex = MatcherIndex;
2303 #endif
2304     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2305     switch (Opcode) {
2306     case OPC_Scope: {
2307       // Okay, the semantics of this operation are that we should push a scope
2308       // then evaluate the first child.  However, pushing a scope only to have
2309       // the first check fail (which then pops it) is inefficient.  If we can
2310       // determine immediately that the first check (or first several) will
2311       // immediately fail, don't even bother pushing a scope for them.
2312       unsigned FailIndex;
2313
2314       while (1) {
2315         unsigned NumToSkip = MatcherTable[MatcherIndex++];
2316         if (NumToSkip & 128)
2317           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2318         // Found the end of the scope with no match.
2319         if (NumToSkip == 0) {
2320           FailIndex = 0;
2321           break;
2322         }
2323
2324         FailIndex = MatcherIndex+NumToSkip;
2325
2326         unsigned MatcherIndexOfPredicate = MatcherIndex;
2327         (void)MatcherIndexOfPredicate; // silence warning.
2328
2329         // If we can't evaluate this predicate without pushing a scope (e.g. if
2330         // it is a 'MoveParent') or if the predicate succeeds on this node, we
2331         // push the scope and evaluate the full predicate chain.
2332         bool Result;
2333         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2334                                               Result, *this, RecordedNodes);
2335         if (!Result)
2336           break;
2337
2338         DEBUG(errs() << "  Skipped scope entry (due to false predicate) at "
2339                      << "index " << MatcherIndexOfPredicate
2340                      << ", continuing at " << FailIndex << "\n");
2341         ++NumDAGIselRetries;
2342
2343         // Otherwise, we know that this case of the Scope is guaranteed to fail,
2344         // move to the next case.
2345         MatcherIndex = FailIndex;
2346       }
2347
2348       // If the whole scope failed to match, bail.
2349       if (FailIndex == 0) break;
2350
2351       // Push a MatchScope which indicates where to go if the first child fails
2352       // to match.
2353       MatchScope NewEntry;
2354       NewEntry.FailIndex = FailIndex;
2355       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2356       NewEntry.NumRecordedNodes = RecordedNodes.size();
2357       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2358       NewEntry.InputChain = InputChain;
2359       NewEntry.InputGlue = InputGlue;
2360       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2361       NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2362       MatchScopes.push_back(NewEntry);
2363       continue;
2364     }
2365     case OPC_RecordNode: {
2366       // Remember this node, it may end up being an operand in the pattern.
2367       SDNode *Parent = 0;
2368       if (NodeStack.size() > 1)
2369         Parent = NodeStack[NodeStack.size()-2].getNode();
2370       RecordedNodes.push_back(std::make_pair(N, Parent));
2371       continue;
2372     }
2373
2374     case OPC_RecordChild0: case OPC_RecordChild1:
2375     case OPC_RecordChild2: case OPC_RecordChild3:
2376     case OPC_RecordChild4: case OPC_RecordChild5:
2377     case OPC_RecordChild6: case OPC_RecordChild7: {
2378       unsigned ChildNo = Opcode-OPC_RecordChild0;
2379       if (ChildNo >= N.getNumOperands())
2380         break;  // Match fails if out of range child #.
2381
2382       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2383                                              N.getNode()));
2384       continue;
2385     }
2386     case OPC_RecordMemRef:
2387       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2388       continue;
2389
2390     case OPC_CaptureGlueInput:
2391       // If the current node has an input glue, capture it in InputGlue.
2392       if (N->getNumOperands() != 0 &&
2393           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2394         InputGlue = N->getOperand(N->getNumOperands()-1);
2395       continue;
2396
2397     case OPC_MoveChild: {
2398       unsigned ChildNo = MatcherTable[MatcherIndex++];
2399       if (ChildNo >= N.getNumOperands())
2400         break;  // Match fails if out of range child #.
2401       N = N.getOperand(ChildNo);
2402       NodeStack.push_back(N);
2403       continue;
2404     }
2405
2406     case OPC_MoveParent:
2407       // Pop the current node off the NodeStack.
2408       NodeStack.pop_back();
2409       assert(!NodeStack.empty() && "Node stack imbalance!");
2410       N = NodeStack.back();
2411       continue;
2412
2413     case OPC_CheckSame:
2414       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2415       continue;
2416     case OPC_CheckPatternPredicate:
2417       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2418       continue;
2419     case OPC_CheckPredicate:
2420       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2421                                 N.getNode()))
2422         break;
2423       continue;
2424     case OPC_CheckComplexPat: {
2425       unsigned CPNum = MatcherTable[MatcherIndex++];
2426       unsigned RecNo = MatcherTable[MatcherIndex++];
2427       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2428       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2429                                RecordedNodes[RecNo].first, CPNum,
2430                                RecordedNodes))
2431         break;
2432       continue;
2433     }
2434     case OPC_CheckOpcode:
2435       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2436       continue;
2437
2438     case OPC_CheckType:
2439       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
2440       continue;
2441
2442     case OPC_SwitchOpcode: {
2443       unsigned CurNodeOpcode = N.getOpcode();
2444       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2445       unsigned CaseSize;
2446       while (1) {
2447         // Get the size of this case.
2448         CaseSize = MatcherTable[MatcherIndex++];
2449         if (CaseSize & 128)
2450           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2451         if (CaseSize == 0) break;
2452
2453         uint16_t Opc = MatcherTable[MatcherIndex++];
2454         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2455
2456         // If the opcode matches, then we will execute this case.
2457         if (CurNodeOpcode == Opc)
2458           break;
2459
2460         // Otherwise, skip over this case.
2461         MatcherIndex += CaseSize;
2462       }
2463
2464       // If no cases matched, bail out.
2465       if (CaseSize == 0) break;
2466
2467       // Otherwise, execute the case we found.
2468       DEBUG(errs() << "  OpcodeSwitch from " << SwitchStart
2469                    << " to " << MatcherIndex << "\n");
2470       continue;
2471     }
2472
2473     case OPC_SwitchType: {
2474       MVT CurNodeVT = N.getValueType().getSimpleVT();
2475       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2476       unsigned CaseSize;
2477       while (1) {
2478         // Get the size of this case.
2479         CaseSize = MatcherTable[MatcherIndex++];
2480         if (CaseSize & 128)
2481           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2482         if (CaseSize == 0) break;
2483
2484         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2485         if (CaseVT == MVT::iPTR)
2486           CaseVT = TLI.getPointerTy();
2487
2488         // If the VT matches, then we will execute this case.
2489         if (CurNodeVT == CaseVT)
2490           break;
2491
2492         // Otherwise, skip over this case.
2493         MatcherIndex += CaseSize;
2494       }
2495
2496       // If no cases matched, bail out.
2497       if (CaseSize == 0) break;
2498
2499       // Otherwise, execute the case we found.
2500       DEBUG(errs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2501                    << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2502       continue;
2503     }
2504     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2505     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2506     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2507     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2508       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2509                             Opcode-OPC_CheckChild0Type))
2510         break;
2511       continue;
2512     case OPC_CheckCondCode:
2513       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2514       continue;
2515     case OPC_CheckValueType:
2516       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
2517       continue;
2518     case OPC_CheckInteger:
2519       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2520       continue;
2521     case OPC_CheckAndImm:
2522       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2523       continue;
2524     case OPC_CheckOrImm:
2525       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2526       continue;
2527
2528     case OPC_CheckFoldableChainNode: {
2529       assert(NodeStack.size() != 1 && "No parent node");
2530       // Verify that all intermediate nodes between the root and this one have
2531       // a single use.
2532       bool HasMultipleUses = false;
2533       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2534         if (!NodeStack[i].hasOneUse()) {
2535           HasMultipleUses = true;
2536           break;
2537         }
2538       if (HasMultipleUses) break;
2539
2540       // Check to see that the target thinks this is profitable to fold and that
2541       // we can fold it without inducing cycles in the graph.
2542       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2543                               NodeToMatch) ||
2544           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2545                          NodeToMatch, OptLevel,
2546                          true/*We validate our own chains*/))
2547         break;
2548
2549       continue;
2550     }
2551     case OPC_EmitInteger: {
2552       MVT::SimpleValueType VT =
2553         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2554       int64_t Val = MatcherTable[MatcherIndex++];
2555       if (Val & 128)
2556         Val = GetVBR(Val, MatcherTable, MatcherIndex);
2557       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2558                               CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
2559       continue;
2560     }
2561     case OPC_EmitRegister: {
2562       MVT::SimpleValueType VT =
2563         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2564       unsigned RegNo = MatcherTable[MatcherIndex++];
2565       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2566                               CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2567       continue;
2568     }
2569     case OPC_EmitRegister2: {
2570       // For targets w/ more than 256 register names, the register enum
2571       // values are stored in two bytes in the matcher table (just like
2572       // opcodes).
2573       MVT::SimpleValueType VT =
2574         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2575       unsigned RegNo = MatcherTable[MatcherIndex++];
2576       RegNo |= MatcherTable[MatcherIndex++] << 8;
2577       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2578                               CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2579       continue;
2580     }
2581
2582     case OPC_EmitConvertToTarget:  {
2583       // Convert from IMM/FPIMM to target version.
2584       unsigned RecNo = MatcherTable[MatcherIndex++];
2585       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2586       SDValue Imm = RecordedNodes[RecNo].first;
2587
2588       if (Imm->getOpcode() == ISD::Constant) {
2589         int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2590         Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2591       } else if (Imm->getOpcode() == ISD::ConstantFP) {
2592         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2593         Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2594       }
2595
2596       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2597       continue;
2598     }
2599
2600     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
2601     case OPC_EmitMergeInputChains1_1: {  // OPC_EmitMergeInputChains, 1, 1
2602       // These are space-optimized forms of OPC_EmitMergeInputChains.
2603       assert(InputChain.getNode() == 0 &&
2604              "EmitMergeInputChains should be the first chain producing node");
2605       assert(ChainNodesMatched.empty() &&
2606              "Should only have one EmitMergeInputChains per match");
2607
2608       // Read all of the chained nodes.
2609       unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2610       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2611       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2612
2613       // FIXME: What if other value results of the node have uses not matched
2614       // by this pattern?
2615       if (ChainNodesMatched.back() != NodeToMatch &&
2616           !RecordedNodes[RecNo].first.hasOneUse()) {
2617         ChainNodesMatched.clear();
2618         break;
2619       }
2620
2621       // Merge the input chains if they are not intra-pattern references.
2622       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2623
2624       if (InputChain.getNode() == 0)
2625         break;  // Failed to merge.
2626       continue;
2627     }
2628
2629     case OPC_EmitMergeInputChains: {
2630       assert(InputChain.getNode() == 0 &&
2631              "EmitMergeInputChains should be the first chain producing node");
2632       // This node gets a list of nodes we matched in the input that have
2633       // chains.  We want to token factor all of the input chains to these nodes
2634       // together.  However, if any of the input chains is actually one of the
2635       // nodes matched in this pattern, then we have an intra-match reference.
2636       // Ignore these because the newly token factored chain should not refer to
2637       // the old nodes.
2638       unsigned NumChains = MatcherTable[MatcherIndex++];
2639       assert(NumChains != 0 && "Can't TF zero chains");
2640
2641       assert(ChainNodesMatched.empty() &&
2642              "Should only have one EmitMergeInputChains per match");
2643
2644       // Read all of the chained nodes.
2645       for (unsigned i = 0; i != NumChains; ++i) {
2646         unsigned RecNo = MatcherTable[MatcherIndex++];
2647         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2648         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2649
2650         // FIXME: What if other value results of the node have uses not matched
2651         // by this pattern?
2652         if (ChainNodesMatched.back() != NodeToMatch &&
2653             !RecordedNodes[RecNo].first.hasOneUse()) {
2654           ChainNodesMatched.clear();
2655           break;
2656         }
2657       }
2658
2659       // If the inner loop broke out, the match fails.
2660       if (ChainNodesMatched.empty())
2661         break;
2662
2663       // Merge the input chains if they are not intra-pattern references.
2664       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2665
2666       if (InputChain.getNode() == 0)
2667         break;  // Failed to merge.
2668
2669       continue;
2670     }
2671
2672     case OPC_EmitCopyToReg: {
2673       unsigned RecNo = MatcherTable[MatcherIndex++];
2674       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2675       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2676
2677       if (InputChain.getNode() == 0)
2678         InputChain = CurDAG->getEntryNode();
2679
2680       InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2681                                         DestPhysReg, RecordedNodes[RecNo].first,
2682                                         InputGlue);
2683
2684       InputGlue = InputChain.getValue(1);
2685       continue;
2686     }
2687
2688     case OPC_EmitNodeXForm: {
2689       unsigned XFormNo = MatcherTable[MatcherIndex++];
2690       unsigned RecNo = MatcherTable[MatcherIndex++];
2691       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2692       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
2693       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
2694       continue;
2695     }
2696
2697     case OPC_EmitNode:
2698     case OPC_MorphNodeTo: {
2699       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2700       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2701       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2702       // Get the result VT list.
2703       unsigned NumVTs = MatcherTable[MatcherIndex++];
2704       SmallVector<EVT, 4> VTs;
2705       for (unsigned i = 0; i != NumVTs; ++i) {
2706         MVT::SimpleValueType VT =
2707           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2708         if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2709         VTs.push_back(VT);
2710       }
2711
2712       if (EmitNodeInfo & OPFL_Chain)
2713         VTs.push_back(MVT::Other);
2714       if (EmitNodeInfo & OPFL_GlueOutput)
2715         VTs.push_back(MVT::Glue);
2716
2717       // This is hot code, so optimize the two most common cases of 1 and 2
2718       // results.
2719       SDVTList VTList;
2720       if (VTs.size() == 1)
2721         VTList = CurDAG->getVTList(VTs[0]);
2722       else if (VTs.size() == 2)
2723         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2724       else
2725         VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2726
2727       // Get the operand list.
2728       unsigned NumOps = MatcherTable[MatcherIndex++];
2729       SmallVector<SDValue, 8> Ops;
2730       for (unsigned i = 0; i != NumOps; ++i) {
2731         unsigned RecNo = MatcherTable[MatcherIndex++];
2732         if (RecNo & 128)
2733           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2734
2735         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2736         Ops.push_back(RecordedNodes[RecNo].first);
2737       }
2738
2739       // If there are variadic operands to add, handle them now.
2740       if (EmitNodeInfo & OPFL_VariadicInfo) {
2741         // Determine the start index to copy from.
2742         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2743         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2744         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2745                "Invalid variadic node");
2746         // Copy all of the variadic operands, not including a potential glue
2747         // input.
2748         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2749              i != e; ++i) {
2750           SDValue V = NodeToMatch->getOperand(i);
2751           if (V.getValueType() == MVT::Glue) break;
2752           Ops.push_back(V);
2753         }
2754       }
2755
2756       // If this has chain/glue inputs, add them.
2757       if (EmitNodeInfo & OPFL_Chain)
2758         Ops.push_back(InputChain);
2759       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2760         Ops.push_back(InputGlue);
2761
2762       // Create the node.
2763       SDNode *Res = 0;
2764       if (Opcode != OPC_MorphNodeTo) {
2765         // If this is a normal EmitNode command, just create the new node and
2766         // add the results to the RecordedNodes list.
2767         Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2768                                      VTList, Ops.data(), Ops.size());
2769
2770         // Add all the non-glue/non-chain results to the RecordedNodes list.
2771         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2772           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
2773           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
2774                                                              (SDNode*) 0));
2775         }
2776
2777       } else {
2778         Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2779                         EmitNodeInfo);
2780       }
2781
2782       // If the node had chain/glue results, update our notion of the current
2783       // chain and glue.
2784       if (EmitNodeInfo & OPFL_GlueOutput) {
2785         InputGlue = SDValue(Res, VTs.size()-1);
2786         if (EmitNodeInfo & OPFL_Chain)
2787           InputChain = SDValue(Res, VTs.size()-2);
2788       } else if (EmitNodeInfo & OPFL_Chain)
2789         InputChain = SDValue(Res, VTs.size()-1);
2790
2791       // If the OPFL_MemRefs glue is set on this node, slap all of the
2792       // accumulated memrefs onto it.
2793       //
2794       // FIXME: This is vastly incorrect for patterns with multiple outputs
2795       // instructions that access memory and for ComplexPatterns that match
2796       // loads.
2797       if (EmitNodeInfo & OPFL_MemRefs) {
2798         // Only attach load or store memory operands if the generated
2799         // instruction may load or store.
2800         const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
2801         bool mayLoad = MCID.mayLoad();
2802         bool mayStore = MCID.mayStore();
2803
2804         unsigned NumMemRefs = 0;
2805         for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
2806              MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2807           if ((*I)->isLoad()) {
2808             if (mayLoad)
2809               ++NumMemRefs;
2810           } else if ((*I)->isStore()) {
2811             if (mayStore)
2812               ++NumMemRefs;
2813           } else {
2814             ++NumMemRefs;
2815           }
2816         }
2817
2818         MachineSDNode::mmo_iterator MemRefs =
2819           MF->allocateMemRefsArray(NumMemRefs);
2820
2821         MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
2822         for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
2823              MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2824           if ((*I)->isLoad()) {
2825             if (mayLoad)
2826               *MemRefsPos++ = *I;
2827           } else if ((*I)->isStore()) {
2828             if (mayStore)
2829               *MemRefsPos++ = *I;
2830           } else {
2831             *MemRefsPos++ = *I;
2832           }
2833         }
2834
2835         cast<MachineSDNode>(Res)
2836           ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
2837       }
2838
2839       DEBUG(errs() << "  "
2840                    << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2841                    << " node: "; Res->dump(CurDAG); errs() << "\n");
2842
2843       // If this was a MorphNodeTo then we're completely done!
2844       if (Opcode == OPC_MorphNodeTo) {
2845         // Update chain and glue uses.
2846         UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2847                             InputGlue, GlueResultNodesMatched, true);
2848         return Res;
2849       }
2850
2851       continue;
2852     }
2853
2854     case OPC_MarkGlueResults: {
2855       unsigned NumNodes = MatcherTable[MatcherIndex++];
2856
2857       // Read and remember all the glue-result nodes.
2858       for (unsigned i = 0; i != NumNodes; ++i) {
2859         unsigned RecNo = MatcherTable[MatcherIndex++];
2860         if (RecNo & 128)
2861           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2862
2863         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2864         GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2865       }
2866       continue;
2867     }
2868
2869     case OPC_CompleteMatch: {
2870       // The match has been completed, and any new nodes (if any) have been
2871       // created.  Patch up references to the matched dag to use the newly
2872       // created nodes.
2873       unsigned NumResults = MatcherTable[MatcherIndex++];
2874
2875       for (unsigned i = 0; i != NumResults; ++i) {
2876         unsigned ResSlot = MatcherTable[MatcherIndex++];
2877         if (ResSlot & 128)
2878           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2879
2880         assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2881         SDValue Res = RecordedNodes[ResSlot].first;
2882
2883         assert(i < NodeToMatch->getNumValues() &&
2884                NodeToMatch->getValueType(i) != MVT::Other &&
2885                NodeToMatch->getValueType(i) != MVT::Glue &&
2886                "Invalid number of results to complete!");
2887         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2888                 NodeToMatch->getValueType(i) == MVT::iPTR ||
2889                 Res.getValueType() == MVT::iPTR ||
2890                 NodeToMatch->getValueType(i).getSizeInBits() ==
2891                     Res.getValueType().getSizeInBits()) &&
2892                "invalid replacement");
2893         CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2894       }
2895
2896       // If the root node defines glue, add it to the glue nodes to update list.
2897       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
2898         GlueResultNodesMatched.push_back(NodeToMatch);
2899
2900       // Update chain and glue uses.
2901       UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2902                           InputGlue, GlueResultNodesMatched, false);
2903
2904       assert(NodeToMatch->use_empty() &&
2905              "Didn't replace all uses of the node?");
2906
2907       // FIXME: We just return here, which interacts correctly with SelectRoot
2908       // above.  We should fix this to not return an SDNode* anymore.
2909       return 0;
2910     }
2911     }
2912
2913     // If the code reached this point, then the match failed.  See if there is
2914     // another child to try in the current 'Scope', otherwise pop it until we
2915     // find a case to check.
2916     DEBUG(errs() << "  Match failed at index " << CurrentOpcodeIndex << "\n");
2917     ++NumDAGIselRetries;
2918     while (1) {
2919       if (MatchScopes.empty()) {
2920         CannotYetSelect(NodeToMatch);
2921         return 0;
2922       }
2923
2924       // Restore the interpreter state back to the point where the scope was
2925       // formed.
2926       MatchScope &LastScope = MatchScopes.back();
2927       RecordedNodes.resize(LastScope.NumRecordedNodes);
2928       NodeStack.clear();
2929       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2930       N = NodeStack.back();
2931
2932       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2933         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2934       MatcherIndex = LastScope.FailIndex;
2935
2936       DEBUG(errs() << "  Continuing at " << MatcherIndex << "\n");
2937
2938       InputChain = LastScope.InputChain;
2939       InputGlue = LastScope.InputGlue;
2940       if (!LastScope.HasChainNodesMatched)
2941         ChainNodesMatched.clear();
2942       if (!LastScope.HasGlueResultNodesMatched)
2943         GlueResultNodesMatched.clear();
2944
2945       // Check to see what the offset is at the new MatcherIndex.  If it is zero
2946       // we have reached the end of this scope, otherwise we have another child
2947       // in the current scope to try.
2948       unsigned NumToSkip = MatcherTable[MatcherIndex++];
2949       if (NumToSkip & 128)
2950         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2951
2952       // If we have another child in this scope to match, update FailIndex and
2953       // try it.
2954       if (NumToSkip != 0) {
2955         LastScope.FailIndex = MatcherIndex+NumToSkip;
2956         break;
2957       }
2958
2959       // End of this scope, pop it and try the next child in the containing
2960       // scope.
2961       MatchScopes.pop_back();
2962     }
2963   }
2964 }
2965
2966
2967
2968 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2969   std::string msg;
2970   raw_string_ostream Msg(msg);
2971   Msg << "Cannot select: ";
2972
2973   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2974       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2975       N->getOpcode() != ISD::INTRINSIC_VOID) {
2976     N->printrFull(Msg, CurDAG);
2977   } else {
2978     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2979     unsigned iid =
2980       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2981     if (iid < Intrinsic::num_intrinsics)
2982       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2983     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2984       Msg << "target intrinsic %" << TII->getName(iid);
2985     else
2986       Msg << "unknown intrinsic #" << iid;
2987   }
2988   report_fatal_error(Msg.str());
2989 }
2990
2991 char SelectionDAGISel::ID = 0;