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