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