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