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