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