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