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