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