blob: 98879649c81350de7a809e2d95f577f89f13e2c4 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/CodeGen/SelectionDAGISel.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000016#include "ScheduleDAGSDNodes.h"
Dan Gohman2048b852009-11-23 18:04:58 +000017#include "SelectionDAGBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/Statistic.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000020#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthbe049292013-01-07 03:08:10 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Dan Gohman78eca172008-08-19 22:33:34 +000023#include "llvm/CodeGen/FastISel.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000024#include "llvm/CodeGen/FunctionLoweringInfo.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000025#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/CodeGen/GCStrategy.h"
Bill Wendlingb92187a2010-05-14 21:14:32 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000030#include "llvm/CodeGen/MachineModuleInfo.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanfc54c552009-01-15 22:18:12 +000032#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Module.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000044#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000045#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000046#include "llvm/Support/ErrorHandling.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000047#include "llvm/Support/Timer.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000048#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000049#include "llvm/Target/TargetInstrInfo.h"
50#include "llvm/Target/TargetIntrinsicInfo.h"
51#include "llvm/Target/TargetLibraryInfo.h"
52#include "llvm/Target/TargetLowering.h"
53#include "llvm/Target/TargetMachine.h"
54#include "llvm/Target/TargetOptions.h"
55#include "llvm/Target/TargetRegisterInfo.h"
56#include "llvm/Target/TargetSubtargetInfo.h"
57#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000058#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000059using namespace llvm;
60
Nadav Rotem139f50a2013-02-27 22:52:54 +000061STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
62STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
Jan Wen Voungfa785cb2013-03-08 22:56:31 +000063STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
64STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
65STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
Eli Bendersky5bd07672013-04-19 01:04:40 +000066STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
67STATISTIC(NumFastIselFailLowerArguments,
68 "Number of entry blocks where fast isel failed to lower arguments");
Nadav Rotem139f50a2013-02-27 22:52:54 +000069
Jan Wen Voungfa785cb2013-03-08 22:56:31 +000070#ifndef NDEBUG
Chad Rosierf2a745e2011-12-13 00:05:11 +000071static cl::opt<bool>
72EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
73 cl::desc("Enable extra verbose messages in the \"fast\" "
74 "instruction selector"));
Eli Bendersky5bd07672013-04-19 01:04:40 +000075
Chad Rosier73e08d32011-12-08 21:37:10 +000076 // Terminators
77STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
78STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
79STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
80STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
81STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
82STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
Chad Rosier73e08d32011-12-08 21:37:10 +000083STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
84
85 // Standard binary operators...
86STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
87STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
88STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
89STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
90STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
91STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
92STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
93STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
94STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
95STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
96STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
97STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
98
99 // Logical operators...
100STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
101STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
102STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
103
104 // Memory instructions...
105STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
106STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
107STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
108STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
109STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
110STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
111STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
112
113 // Convert instructions...
114STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
115STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
116STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
117STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
118STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
119STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
120STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
121STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
122STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
123STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
124STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
125STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
126
127 // Other instructions...
128STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
129STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
130STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
131STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
132STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
133STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
134STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
135STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
136STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
137STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
138STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
139STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
140STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
141STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
142STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
143#endif
144
Chris Lattneread0d882008-06-17 06:09:18 +0000145static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +0000146EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +0000147 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +0000148 "instruction selector"));
149static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +0000150EnableFastISelAbort("fast-isel-abort", cl::Hidden,
Chad Rosierffa1dba2013-02-25 22:20:00 +0000151 cl::desc("Enable abort calls when \"fast\" instruction selection "
152 "fails to lower an instruction"));
Chad Rosierfd3417d2013-02-25 21:59:35 +0000153static cl::opt<bool>
154EnableFastISelAbortArgs("fast-isel-abort-args", cl::Hidden,
Chad Rosierffa1dba2013-02-25 22:20:00 +0000155 cl::desc("Enable abort calls when \"fast\" instruction selection "
156 "fails to lower a formal argument"));
Chris Lattneread0d882008-06-17 06:09:18 +0000157
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000158static cl::opt<bool>
159UseMBPI("use-mbpi",
160 cl::desc("use Machine Branch Probability Info"),
161 cl::init(true), cl::Hidden);
162
Chris Lattnerda8abb02005-09-01 18:44:10 +0000163#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +0000164static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +0000165ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
166 cl::desc("Pop up a window to show dags before the first "
167 "dag combine pass"));
168static cl::opt<bool>
169ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
170 cl::desc("Pop up a window to show dags before legalize types"));
171static cl::opt<bool>
172ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
173 cl::desc("Pop up a window to show dags before legalize"));
174static cl::opt<bool>
175ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
176 cl::desc("Pop up a window to show dags before the second "
177 "dag combine pass"));
178static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +0000179ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
180 cl::desc("Pop up a window to show dags before the post legalize types"
181 " dag combine pass"));
182static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +0000183ViewISelDAGs("view-isel-dags", cl::Hidden,
184 cl::desc("Pop up a window to show isel dags as they are selected"));
185static cl::opt<bool>
186ViewSchedDAGs("view-sched-dags", cl::Hidden,
187 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +0000188static cl::opt<bool>
189ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +0000190 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +0000191#else
Dan Gohman462dc7f2008-07-21 20:00:07 +0000192static const bool ViewDAGCombine1 = false,
193 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
194 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +0000195 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +0000196 ViewISelDAGs = false, ViewSchedDAGs = false,
197 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000198#endif
199
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000200//===---------------------------------------------------------------------===//
201///
202/// RegisterScheduler class - Track the registration of instruction schedulers.
203///
204//===---------------------------------------------------------------------===//
205MachinePassRegistry RegisterScheduler::Registry;
206
207//===---------------------------------------------------------------------===//
208///
209/// ISHeuristic command line option for instruction schedulers.
210///
211//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000212static cl::opt<RegisterScheduler::FunctionPassCtor, false,
213 RegisterPassParser<RegisterScheduler> >
214ISHeuristic("pre-RA-sched",
215 cl::init(&createDefaultScheduler),
216 cl::desc("Instruction schedulers available (before register"
217 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000218
Dan Gohman844731a2008-05-13 00:00:25 +0000219static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000220defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000221 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000222
Chris Lattner1c08c712005-01-07 07:47:53 +0000223namespace llvm {
224 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000225 /// createDefaultScheduler - This creates an instruction scheduler appropriate
226 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000227 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000228 CodeGenOpt::Level OptLevel) {
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000229 const TargetLowering *TLI = IS->getTargetLowering();
Andrew Trickad1cc1d2012-11-13 08:47:29 +0000230 const TargetSubtargetInfo &ST = IS->TM.getSubtarget<TargetSubtargetInfo>();
Dan Gohmane9530ec2009-01-15 16:58:17 +0000231
Andrew Trickad1cc1d2012-11-13 08:47:29 +0000232 if (OptLevel == CodeGenOpt::None || ST.enableMachineScheduler() ||
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000233 TLI->getSchedulingPreference() == Sched::Source)
Dan Gohmane667e012010-07-16 02:01:19 +0000234 return createSourceListDAGScheduler(IS, OptLevel);
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000235 if (TLI->getSchedulingPreference() == Sched::RegPressure)
Evan Cheng15a16de2010-05-20 06:13:19 +0000236 return createBURRListDAGScheduler(IS, OptLevel);
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000237 if (TLI->getSchedulingPreference() == Sched::Hybrid)
Evan Cheng70017e42010-07-24 00:39:05 +0000238 return createHybridListDAGScheduler(IS, OptLevel);
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000239 if (TLI->getSchedulingPreference() == Sched::VLIW)
Andrew Trickee498d32012-02-01 22:13:57 +0000240 return createVLIWDAGScheduler(IS, OptLevel);
Bill Wendling6a2e7ac2013-06-06 00:43:09 +0000241 assert(TLI->getSchedulingPreference() == Sched::ILP &&
Evan Cheng211ffa12010-05-19 20:19:50 +0000242 "Unknown sched type!");
Evan Cheng70017e42010-07-24 00:39:05 +0000243 return createILPListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000244 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000245}
246
Evan Chengff9b3732008-01-30 18:18:23 +0000247// EmitInstrWithCustomInserter - This method should be implemented by targets
Dan Gohman533297b2009-10-29 18:10:34 +0000248// that mark instructions with the 'usesCustomInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000249// instructions are special in various ways, which require special support to
250// insert. The specified MachineInstr is created but not inserted into any
Dan Gohman533297b2009-10-29 18:10:34 +0000251// basic blocks, and this method is called to expand it into a sequence of
252// instructions, potentially also creating new basic blocks and control flow.
253// When new basic blocks are inserted and the edges from MBB to its successors
254// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
255// DenseMap.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000256MachineBasicBlock *
257TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
258 MachineBasicBlock *MBB) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000259#ifndef NDEBUG
David Greene1a053232010-01-05 01:26:11 +0000260 dbgs() << "If a target marks an instruction with "
Dan Gohman533297b2009-10-29 18:10:34 +0000261 "'usesCustomInserter', it must implement "
Torok Edwinf3689232009-07-12 20:07:01 +0000262 "TargetLowering::EmitInstrWithCustomInserter!";
263#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000264 llvm_unreachable(0);
Chris Lattner025c39b2005-08-26 20:54:47 +0000265}
266
Evan Cheng37fefc22011-08-30 19:09:48 +0000267void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
268 SDNode *Node) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000269 assert(!MI->hasPostISelHook() &&
Andrew Trick3be654f2011-09-21 02:20:46 +0000270 "If a target marks an instruction with 'hasPostISelHook', "
271 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
Evan Cheng37fefc22011-08-30 19:09:48 +0000272}
273
Chris Lattner7041ee32005-01-11 05:56:49 +0000274//===----------------------------------------------------------------------===//
275// SelectionDAGISel code
276//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000277
Bill Wendlingba54bca2013-06-19 21:36:55 +0000278SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
Eric Christopher762a17a2011-01-05 21:45:56 +0000279 CodeGenOpt::Level OL) :
Bill Wendlingba54bca2013-06-19 21:36:55 +0000280 MachineFunctionPass(ID), TM(tm),
Bill Wendling384ceb82013-06-06 00:11:39 +0000281 FuncInfo(new FunctionLoweringInfo(TM)),
Devang Patel0508d042011-12-15 18:21:18 +0000282 CurDAG(new SelectionDAG(tm, OL)),
Dan Gohman55e59c12010-04-19 19:05:59 +0000283 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000284 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000285 OptLevel(OL),
Owen Anderson081c34b2010-10-19 17:21:58 +0000286 DAGSize(0) {
287 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
288 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000289 initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
Owen Anderson243eb9e2011-12-08 22:15:21 +0000290 initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +0000291 }
Dan Gohman7c3234c2008-08-27 23:52:12 +0000292
293SelectionDAGISel::~SelectionDAGISel() {
Dan Gohman2048b852009-11-23 18:04:58 +0000294 delete SDB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000295 delete CurDAG;
296 delete FuncInfo;
297}
298
Chris Lattner495a0b52005-08-17 06:37:43 +0000299void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000300 AU.addRequired<AliasAnalysis>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000301 AU.addPreserved<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000302 AU.addRequired<GCModuleInfo>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000303 AU.addPreserved<GCModuleInfo>();
Owen Anderson243eb9e2011-12-08 22:15:21 +0000304 AU.addRequired<TargetLibraryInfo>();
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000305 if (UseMBPI && OptLevel != CodeGenOpt::None)
306 AU.addRequired<BranchProbabilityInfo>();
Dan Gohmanad2afc22009-07-31 18:16:33 +0000307 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner495a0b52005-08-17 06:37:43 +0000308}
Chris Lattner1c08c712005-01-07 07:47:53 +0000309
Chris Lattner96ba57f2010-12-19 04:58:57 +0000310/// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
311/// may trap on it. In this case we have to split the edge so that the path
312/// through the predecessor block that doesn't go to the phi block doesn't
313/// execute the possibly trapping instruction.
314///
315/// This is required for correctness, so it must be done at -O0.
316///
317static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
318 // Loop for blocks with phi nodes.
319 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
320 PHINode *PN = dyn_cast<PHINode>(BB->begin());
321 if (PN == 0) continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000322
Chris Lattner96ba57f2010-12-19 04:58:57 +0000323 ReprocessBlock:
324 // For each block with a PHI node, check to see if any of the input values
325 // are potentially trapping constant expressions. Constant expressions are
326 // the only potentially trapping value that can occur as the argument to a
327 // PHI.
328 for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
330 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
331 if (CE == 0 || !CE->canTrap()) continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000332
Chris Lattner96ba57f2010-12-19 04:58:57 +0000333 // The only case we have to worry about is when the edge is critical.
334 // Since this block has a PHI Node, we assume it has multiple input
335 // edges: check to see if the pred has multiple successors.
336 BasicBlock *Pred = PN->getIncomingBlock(i);
337 if (Pred->getTerminator()->getNumSuccessors() == 1)
338 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000339
Chris Lattner96ba57f2010-12-19 04:58:57 +0000340 // Okay, we have to split this edge.
341 SplitCriticalEdge(Pred->getTerminator(),
342 GetSuccessorNumber(Pred, BB), SDISel, true);
343 goto ReprocessBlock;
344 }
345 }
346}
347
Dan Gohmanad2afc22009-07-31 18:16:33 +0000348bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
Dan Gohman4344a5d2008-09-09 23:05:00 +0000349 // Do some sanity-checking on the command-line options.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000350 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
Dan Gohman4344a5d2008-09-09 23:05:00 +0000351 "-fast-isel-verbose requires -fast-isel");
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000352 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
Dan Gohman4344a5d2008-09-09 23:05:00 +0000353 "-fast-isel-abort requires -fast-isel");
354
Dan Gohmanae541aa2010-04-15 04:33:49 +0000355 const Function &Fn = *mf.getFunction();
Dan Gohman8a110532008-09-05 22:59:21 +0000356 const TargetInstrInfo &TII = *TM.getInstrInfo();
357 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
358
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000359 MF = &mf;
Dan Gohman79ce2762009-01-15 19:20:50 +0000360 RegInfo = &MF->getRegInfo();
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000361 AA = &getAnalysis<AliasAnalysis>();
Owen Anderson243eb9e2011-12-08 22:15:21 +0000362 LibInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruthe4b4edd2013-01-05 12:32:17 +0000363 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000364 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
365
Bill Wendling789cb5d2013-02-15 22:31:27 +0000366 TargetSubtargetInfo &ST =
367 const_cast<TargetSubtargetInfo&>(TM.getSubtarget<TargetSubtargetInfo>());
368 ST.resetSubtargetFeatures(MF);
Bill Wendling4cb1f5f2013-03-13 22:26:59 +0000369 TM.resetTargetOptions(MF);
Bill Wendling789cb5d2013-02-15 22:31:27 +0000370
David Greene1a053232010-01-05 01:26:11 +0000371 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000372
Chris Lattner96ba57f2010-12-19 04:58:57 +0000373 SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000374
Chandler Carruthe4b4edd2013-01-05 12:32:17 +0000375 CurDAG->init(*MF, TTI);
Dan Gohman7451d3e2010-05-29 17:03:36 +0000376 FuncInfo->set(Fn, *MF);
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000377
378 if (UseMBPI && OptLevel != CodeGenOpt::None)
379 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
380 else
381 FuncInfo->BPI = 0;
382
Owen Anderson243eb9e2011-12-08 22:15:21 +0000383 SDB->init(GFI, *AA, LibInfo);
Chris Lattner1c08c712005-01-07 07:47:53 +0000384
Chad Rosierb875acd2013-02-18 20:13:59 +0000385 MF->setHasMSInlineAsm(false);
Dan Gohman6a732b52010-04-14 20:05:00 +0000386 SelectAllBasicBlocks(Fn);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000387
Dan Gohman1b79a2f2010-05-01 00:33:28 +0000388 // If the first basic block in the function has live ins that need to be
Dan Gohman8a110532008-09-05 22:59:21 +0000389 // copied into vregs, emit the copies into the top of the block before
390 // emitting the code for the block.
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000391 MachineBasicBlock *EntryMBB = MF->begin();
392 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
393
Devang Patel394427b2010-05-26 20:18:50 +0000394 DenseMap<unsigned, unsigned> LiveInMap;
395 if (!FuncInfo->ArgDbgValues.empty())
396 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
397 E = RegInfo->livein_end(); LI != E; ++LI)
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000398 if (LI->second)
Devang Patel394427b2010-05-26 20:18:50 +0000399 LiveInMap.insert(std::make_pair(LI->first, LI->second));
400
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000401 // Insert DBG_VALUE instructions for function arguments to the entry block.
402 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
403 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
David Blaikie6d9dbd52013-06-16 20:34:15 +0000404 bool hasFI = MI->getOperand(0).isFI();
405 unsigned Reg = hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000406 if (TargetRegisterInfo::isPhysicalRegister(Reg))
407 EntryMBB->insert(EntryMBB->begin(), MI);
408 else {
409 MachineInstr *Def = RegInfo->getVRegDef(Reg);
410 MachineBasicBlock::iterator InsertPos = Def;
Evan Chengf1ced252010-05-04 00:58:39 +0000411 // FIXME: VR def may not be in entry block.
412 Def->getParent()->insert(llvm::next(InsertPos), MI);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000413 }
Devang Patel394427b2010-05-26 20:18:50 +0000414
415 // If Reg is live-in then update debug info to track its copy in a vreg.
416 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
417 if (LDI != LiveInMap.end()) {
David Blaikie6d9dbd52013-06-16 20:34:15 +0000418 assert(!hasFI && "There's no handling of frame pointer updating here yet "
419 "- add if needed");
Devang Patel394427b2010-05-26 20:18:50 +0000420 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
421 MachineBasicBlock::iterator InsertPos = Def;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000422 const MDNode *Variable =
Devang Patel394427b2010-05-26 20:18:50 +0000423 MI->getOperand(MI->getNumOperands()-1).getMetadata();
Adrian Prantl35176402013-07-09 20:28:37 +0000424 bool IsIndirect = MI->getOperand(1).isImm();
425 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
Devang Patel394427b2010-05-26 20:18:50 +0000426 // Def is never a terminator here, so it is ok to increment InsertPos.
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000427 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
Adrian Prantl35176402013-07-09 20:28:37 +0000428 TII.get(TargetOpcode::DBG_VALUE),
429 IsIndirect,
430 LDI->second, Offset, Variable);
Devang Patel44cfe142010-09-21 20:56:33 +0000431
432 // If this vreg is directly copied into an exported register then
433 // that COPY instructions also need DBG_VALUE, if it is the only
434 // user of LDI->second.
435 MachineInstr *CopyUseMI = NULL;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000436 for (MachineRegisterInfo::use_iterator
437 UI = RegInfo->use_begin(LDI->second);
Devang Patel44cfe142010-09-21 20:56:33 +0000438 MachineInstr *UseMI = UI.skipInstruction();) {
439 if (UseMI->isDebugValue()) continue;
440 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
441 CopyUseMI = UseMI; continue;
442 }
443 // Otherwise this is another use or second copy use.
444 CopyUseMI = NULL; break;
445 }
446 if (CopyUseMI) {
447 MachineInstr *NewMI =
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000448 BuildMI(*MF, CopyUseMI->getDebugLoc(),
Adrian Prantl35176402013-07-09 20:28:37 +0000449 TII.get(TargetOpcode::DBG_VALUE),
450 IsIndirect,
451 CopyUseMI->getOperand(0).getReg(),
452 Offset, Variable);
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000453 MachineBasicBlock::iterator Pos = CopyUseMI;
454 EntryMBB->insertAfter(Pos, NewMI);
Devang Patel44cfe142010-09-21 20:56:33 +0000455 }
Devang Patel394427b2010-05-26 20:18:50 +0000456 }
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000457 }
458
Bill Wendling53f76022010-05-17 23:09:50 +0000459 // Determine if there are any calls in this machine function.
460 MachineFrameInfo *MFI = MF->getFrameInfo();
Chad Rosierb5660622013-02-16 01:25:28 +0000461 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
462 ++I) {
Bill Wendling8886c492010-07-09 19:44:12 +0000463
Chad Rosierb5660622013-02-16 01:25:28 +0000464 if (MFI->hasCalls() && MF->hasMSInlineAsm())
465 break;
466
467 const MachineBasicBlock *MBB = I;
468 for (MachineBasicBlock::const_iterator II = MBB->begin(), IE = MBB->end();
469 II != IE; ++II) {
470 const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
471 if ((MCID.isCall() && !MCID.isReturn()) ||
472 II->isStackAligningInlineAsm()) {
473 MFI->setHasCalls(true);
474 }
475 if (II->isMSInlineAsm()) {
476 MF->setHasMSInlineAsm(true);
Bill Wendling53f76022010-05-17 23:09:50 +0000477 }
478 }
Bill Wendling53f76022010-05-17 23:09:50 +0000479 }
480
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000481 // Determine if there is a call to setjmp in the machine function.
Joerg Sonnenberger34706932011-12-18 20:35:43 +0000482 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000483
Dan Gohman84023e02010-07-10 09:00:22 +0000484 // Replace forward-declared registers with the registers containing
485 // the desired value.
486 MachineRegisterInfo &MRI = MF->getRegInfo();
487 for (DenseMap<unsigned, unsigned>::iterator
488 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
489 I != E; ++I) {
490 unsigned From = I->first;
491 unsigned To = I->second;
492 // If To is also scheduled to be replaced, find what its ultimate
493 // replacement is.
494 for (;;) {
Jakub Staszak39379c52012-04-30 23:41:30 +0000495 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
Dan Gohman84023e02010-07-10 09:00:22 +0000496 if (J == E) break;
497 To = J->second;
498 }
499 // Replace it.
500 MRI.replaceRegWith(From, To);
501 }
502
Jakob Stoklund Olesene4f27392012-10-15 21:33:06 +0000503 // Freeze the set of reserved registers now that MachineFrameInfo has been
504 // set up. All the information required by getReservedRegs() should be
505 // available now.
506 MRI.freezeReservedRegs(*MF);
507
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000508 // Release function-specific state. SDB and CurDAG are already cleared
509 // at this point.
510 FuncInfo->clear();
Dan Gohman8a110532008-09-05 22:59:21 +0000511
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 return true;
513}
514
Chris Lattner685090f2011-04-17 17:12:08 +0000515void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
516 BasicBlock::const_iterator End,
517 bool &HadTailCall) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000518 // Lower all of the non-terminator instructions. If a call is emitted
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000519 // as a tail call, cease emitting nodes for this block. Terminators
520 // are handled below.
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000521 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000522 SDB->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000523
Chris Lattnera651cf62005-01-17 19:43:36 +0000524 // Make sure the root of the DAG is up-to-date.
Dan Gohman2048b852009-11-23 18:04:58 +0000525 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000526 HadTailCall = SDB->HasTailCall;
527 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000528
529 // Final step, emit the lowered DAG as machine code.
Dan Gohman84023e02010-07-10 09:00:22 +0000530 CodeGenAndEmitDAG();
Chris Lattner1c08c712005-01-07 07:47:53 +0000531}
532
Dan Gohmanf350b272008-08-23 02:25:05 +0000533void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000534 SmallPtrSet<SDNode*, 128> VisitedNodes;
535 SmallVector<SDNode*, 128> Worklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000536
Gabor Greifba36cb52008-08-28 21:40:38 +0000537 Worklist.push_back(CurDAG->getRoot().getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538
Chris Lattneread0d882008-06-17 06:09:18 +0000539 APInt KnownZero;
540 APInt KnownOne;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000541
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000542 do {
543 SDNode *N = Worklist.pop_back_val();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000544
Chris Lattneread0d882008-06-17 06:09:18 +0000545 // If we've already seen this node, ignore it.
546 if (!VisitedNodes.insert(N))
547 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000548
Chris Lattneread0d882008-06-17 06:09:18 +0000549 // Otherwise, add all chain operands to the worklist.
550 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +0000551 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000552 Worklist.push_back(N->getOperand(i).getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000553
Chris Lattneread0d882008-06-17 06:09:18 +0000554 // If this is a CopyToReg with a vreg dest, process it.
555 if (N->getOpcode() != ISD::CopyToReg)
556 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000557
Chris Lattneread0d882008-06-17 06:09:18 +0000558 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
559 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
560 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561
Chris Lattneread0d882008-06-17 06:09:18 +0000562 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000563 SDValue Src = N->getOperand(2);
Owen Andersone50ed302009-08-10 22:56:29 +0000564 EVT SrcVT = Src.getValueType();
Chris Lattneread0d882008-06-17 06:09:18 +0000565 if (!SrcVT.isInteger() || SrcVT.isVector())
566 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000567
Dan Gohmanf350b272008-08-23 02:25:05 +0000568 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000569 CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
Cameron Zwariche1497b92011-02-24 10:00:08 +0000570 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000571 } while (!Worklist.empty());
Chris Lattneread0d882008-06-17 06:09:18 +0000572}
573
Dan Gohman84023e02010-07-10 09:00:22 +0000574void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000575 std::string GroupName;
576 if (TimePassesIsEnabled)
577 GroupName = "Instruction Selection and Scheduling";
578 std::string BlockName;
Andrew Tricka2f45292011-03-23 01:38:28 +0000579 int BlockNumber = -1;
Duncan Sands1f6a3292011-08-12 14:54:45 +0000580 (void)BlockNumber;
Andrew Tricka2f45292011-03-23 01:38:28 +0000581#ifdef NDEBUG
Dan Gohman462dc7f2008-07-21 20:00:07 +0000582 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000583 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
584 ViewSUnitDAGs)
Andrew Tricka2f45292011-03-23 01:38:28 +0000585#endif
586 {
587 BlockNumber = FuncInfo->MBB->getNumber();
Craig Topper96601ca2012-08-22 06:07:19 +0000588 BlockName = MF->getName().str() + ":" +
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000589 FuncInfo->MBB->getBasicBlock()->getName().str();
Andrew Tricka2f45292011-03-23 01:38:28 +0000590 }
591 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
592 << " '" << BlockName << "'\n"; CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000593
Dan Gohmanf350b272008-08-23 02:25:05 +0000594 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000595
Chris Lattneraf21d552005-10-10 16:47:10 +0000596 // Run the DAG combiner in pre-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000597 {
598 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
Eli Friedman50185242011-11-12 00:35:34 +0000599 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000600 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000601
Andrew Tricka2f45292011-03-23 01:38:28 +0000602 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
603 << " '" << BlockName << "'\n"; CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000604
Chris Lattner1c08c712005-01-07 07:47:53 +0000605 // Second step, hack on the DAG until it only uses operations and types that
606 // the target supports.
Dan Gohman714efc62009-12-05 17:51:33 +0000607 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
608 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000609
Dan Gohman714efc62009-12-05 17:51:33 +0000610 bool Changed;
Dan Gohman03c3dc72010-06-18 15:56:31 +0000611 {
612 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000613 Changed = CurDAG->LegalizeTypes();
614 }
615
Andrew Tricka2f45292011-03-23 01:38:28 +0000616 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
617 << " '" << BlockName << "'\n"; CurDAG->dump());
Dan Gohman714efc62009-12-05 17:51:33 +0000618
619 if (Changed) {
620 if (ViewDAGCombineLT)
621 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
622
623 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000624 {
625 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
626 TimePassesIsEnabled);
Eli Friedman50185242011-11-12 00:35:34 +0000627 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000628 }
629
Andrew Tricka2f45292011-03-23 01:38:28 +0000630 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
631 << " '" << BlockName << "'\n"; CurDAG->dump());
Andrew Trickdd0fb012013-05-25 03:08:10 +0000632
Dan Gohman714efc62009-12-05 17:51:33 +0000633 }
Dan Gohman462dc7f2008-07-21 20:00:07 +0000634
Dan Gohman03c3dc72010-06-18 15:56:31 +0000635 {
636 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000637 Changed = CurDAG->LegalizeVectors();
638 }
Duncan Sands25cf2272008-11-24 14:53:14 +0000639
Dan Gohman714efc62009-12-05 17:51:33 +0000640 if (Changed) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000641 {
642 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
Bill Wendling98820072009-12-28 01:51:30 +0000643 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000644 }
645
Dan Gohman714efc62009-12-05 17:51:33 +0000646 if (ViewDAGCombineLT)
647 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
Eli Friedman5c22c802009-05-23 12:35:30 +0000648
Dan Gohman714efc62009-12-05 17:51:33 +0000649 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000650 {
651 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
652 TimePassesIsEnabled);
Eli Friedman50185242011-11-12 00:35:34 +0000653 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
Eli Friedman5c22c802009-05-23 12:35:30 +0000654 }
Dan Gohman714efc62009-12-05 17:51:33 +0000655
Andrew Tricka2f45292011-03-23 01:38:28 +0000656 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
657 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
Chris Lattner70587ea2008-07-10 23:37:50 +0000658 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000659
Dan Gohmanf350b272008-08-23 02:25:05 +0000660 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000661
Dan Gohman03c3dc72010-06-18 15:56:31 +0000662 {
663 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman975716a2011-05-16 22:19:54 +0000664 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +0000665 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000666
Andrew Tricka2f45292011-03-23 01:38:28 +0000667 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
668 << " '" << BlockName << "'\n"; CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Dan Gohmanf350b272008-08-23 02:25:05 +0000670 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000671
Chris Lattneraf21d552005-10-10 16:47:10 +0000672 // Run the DAG combiner in post-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000673 {
674 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
Eli Friedman50185242011-11-12 00:35:34 +0000675 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000676 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000677
Andrew Tricka2f45292011-03-23 01:38:28 +0000678 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
679 << " '" << BlockName << "'\n"; CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000680
Dan Gohman4e39e9d2010-06-24 14:30:44 +0000681 if (OptLevel != CodeGenOpt::None)
Dan Gohmanf350b272008-08-23 02:25:05 +0000682 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +0000683
Chris Lattner552186d2010-03-14 19:27:55 +0000684 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
685
Chris Lattnera33ef482005-03-30 01:10:47 +0000686 // Third, instruction select all of the operations to machine code, adding the
687 // code to the MachineBasicBlock.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000688 {
689 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
Chris Lattner7c306da2010-03-02 06:34:30 +0000690 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000691 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000692
Andrew Tricka2f45292011-03-23 01:38:28 +0000693 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
694 << " '" << BlockName << "'\n"; CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000695
Dan Gohmanf350b272008-08-23 02:25:05 +0000696 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000697
Dan Gohman5e843682008-07-14 18:19:29 +0000698 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000699 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman03c3dc72010-06-18 15:56:31 +0000700 {
701 NamedRegionTimer T("Instruction Scheduling", GroupName,
702 TimePassesIsEnabled);
Andrew Trick47c14452012-03-07 05:21:52 +0000703 Scheduler->Run(CurDAG, FuncInfo->MBB);
Dan Gohman5e843682008-07-14 18:19:29 +0000704 }
705
Dan Gohman462dc7f2008-07-21 20:00:07 +0000706 if (ViewSUnitDAGs) Scheduler->viewGraph();
707
Daniel Dunbara279bc32009-09-20 02:20:51 +0000708 // Emit machine code to BB. This can change 'BB' to the last block being
Evan Chengdb8d56b2008-06-30 20:45:06 +0000709 // inserted into.
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +0000710 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
Dan Gohman03c3dc72010-06-18 15:56:31 +0000711 {
712 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
Dan Gohman84023e02010-07-10 09:00:22 +0000713
Andrew Trick47c14452012-03-07 05:21:52 +0000714 // FuncInfo->InsertPt is passed by reference and set to the end of the
715 // scheduled instructions.
716 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
Dan Gohman5e843682008-07-14 18:19:29 +0000717 }
718
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +0000719 // If the block was split, make sure we update any references that are used to
720 // update PHI nodes later on.
721 if (FirstMBB != LastMBB)
722 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
723
Dan Gohman5e843682008-07-14 18:19:29 +0000724 // Free the scheduler state.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000725 {
726 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
727 TimePassesIsEnabled);
Dan Gohman5e843682008-07-14 18:19:29 +0000728 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000729 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000730
Dan Gohman95140a42010-05-01 00:25:44 +0000731 // Free the SelectionDAG state, now that we're finished with it.
732 CurDAG->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000733}
Chris Lattner1c08c712005-01-07 07:47:53 +0000734
Jakob Stoklund Olesen8c48e4f2012-04-20 22:08:50 +0000735namespace {
736/// ISelUpdater - helper class to handle updates of the instruction selection
737/// graph.
738class ISelUpdater : public SelectionDAG::DAGUpdateListener {
739 SelectionDAG::allnodes_iterator &ISelPosition;
740public:
741 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
742 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
743
744 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
745 /// deleted is the current ISelPosition node, update ISelPosition.
746 ///
747 virtual void NodeDeleted(SDNode *N, SDNode *E) {
748 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
749 ++ISelPosition;
750 }
751};
752} // end anonymous namespace
753
Chris Lattner7c306da2010-03-02 06:34:30 +0000754void SelectionDAGISel::DoInstructionSelection() {
Eli Bendersky03494e02013-04-19 21:37:07 +0000755 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
Andrew Tricka2f45292011-03-23 01:38:28 +0000756 << FuncInfo->MBB->getNumber()
757 << " '" << FuncInfo->MBB->getName() << "'\n");
Chris Lattner7c306da2010-03-02 06:34:30 +0000758
759 PreprocessISelDAG();
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000760
Chris Lattner7c306da2010-03-02 06:34:30 +0000761 // Select target instructions for the DAG.
762 {
763 // Number all nodes with a topological order and set DAGSize.
764 DAGSize = CurDAG->AssignTopologicalOrder();
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000765
Chris Lattner7c306da2010-03-02 06:34:30 +0000766 // Create a dummy node (which is not added to allnodes), that adds
767 // a reference to the root node, preventing it from being deleted,
768 // and tracking any changes of the root.
769 HandleSDNode Dummy(CurDAG->getRoot());
Jakob Stoklund Olesen8c48e4f2012-04-20 22:08:50 +0000770 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
Chris Lattner7c306da2010-03-02 06:34:30 +0000771 ++ISelPosition;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000772
Jakob Stoklund Olesen8c48e4f2012-04-20 22:08:50 +0000773 // Make sure that ISelPosition gets properly updated when nodes are deleted
774 // in calls made from this function.
775 ISelUpdater ISU(*CurDAG, ISelPosition);
776
Chris Lattner7c306da2010-03-02 06:34:30 +0000777 // The AllNodes list is now topological-sorted. Visit the
778 // nodes by starting at the end of the list (the root of the
779 // graph) and preceding back toward the beginning (the entry
780 // node).
781 while (ISelPosition != CurDAG->allnodes_begin()) {
782 SDNode *Node = --ISelPosition;
783 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
784 // but there are currently some corner cases that it misses. Also, this
785 // makes it theoretically possible to disable the DAGCombiner.
786 if (Node->use_empty())
787 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000788
Chris Lattner7c306da2010-03-02 06:34:30 +0000789 SDNode *ResNode = Select(Node);
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000790
Chris Lattner82dd3d32010-03-02 07:50:03 +0000791 // FIXME: This is pretty gross. 'Select' should be changed to not return
792 // anything at all and this code should be nuked with a tactical strike.
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000793
Chris Lattner7c306da2010-03-02 06:34:30 +0000794 // If node should not be replaced, continue with the next one.
Chris Lattner82dd3d32010-03-02 07:50:03 +0000795 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
Chris Lattner7c306da2010-03-02 06:34:30 +0000796 continue;
797 // Replace node.
Justin Holewinskid73dc542013-03-20 00:10:32 +0000798 if (ResNode) {
Chris Lattner7c306da2010-03-02 06:34:30 +0000799 ReplaceUses(Node, ResNode);
Justin Holewinskid73dc542013-03-20 00:10:32 +0000800 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000801
Chris Lattner7c306da2010-03-02 06:34:30 +0000802 // If after the replacement this node is not used any more,
803 // remove this dead node.
Jakob Stoklund Olesen8c48e4f2012-04-20 22:08:50 +0000804 if (Node->use_empty()) // Don't delete EntryToken, etc.
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000805 CurDAG->RemoveDeadNode(Node);
Chris Lattner7c306da2010-03-02 06:34:30 +0000806 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000807
Chris Lattner7c306da2010-03-02 06:34:30 +0000808 CurDAG->setRoot(Dummy.getValue());
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000809 }
Bill Wendling53f76022010-05-17 23:09:50 +0000810
Eli Bendersky03494e02013-04-19 21:37:07 +0000811 DEBUG(dbgs() << "===== Instruction selection ends:\n");
Chris Lattner7c306da2010-03-02 06:34:30 +0000812
813 PostprocessISelDAG();
Chris Lattner7c306da2010-03-02 06:34:30 +0000814}
815
Dan Gohman25208642010-04-14 19:53:31 +0000816/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
817/// do other setup for EH landing-pad blocks.
Dan Gohman84023e02010-07-10 09:00:22 +0000818void SelectionDAGISel::PrepareEHLandingPad() {
Bill Wendling6f500542011-10-05 22:16:11 +0000819 MachineBasicBlock *MBB = FuncInfo->MBB;
820
Dan Gohman25208642010-04-14 19:53:31 +0000821 // Add a label to mark the beginning of the landing pad. Deletion of the
822 // landing pad can thus be detected via the MachineModuleInfo.
Bill Wendling6f500542011-10-05 22:16:11 +0000823 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
Dan Gohman25208642010-04-14 19:53:31 +0000824
Bill Wendling30e67402011-10-05 22:24:35 +0000825 // Assign the call site to the landing pad's begin label.
826 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
Andrew Trickacddd492012-03-07 00:18:15 +0000827
Evan Chenge837dea2011-06-28 19:10:37 +0000828 const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
Bill Wendling6f500542011-10-05 22:16:11 +0000829 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
Dan Gohman84023e02010-07-10 09:00:22 +0000830 .addSym(Label);
Dan Gohman25208642010-04-14 19:53:31 +0000831
832 // Mark exception register as live in.
Bill Wendlingba54bca2013-06-19 21:36:55 +0000833 const TargetLowering *TLI = getTargetLowering();
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +0000834 const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
835 if (unsigned Reg = TLI->getExceptionPointerRegister())
836 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
Dan Gohman25208642010-04-14 19:53:31 +0000837
838 // Mark exception selector register as live in.
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +0000839 if (unsigned Reg = TLI->getExceptionSelectorRegister())
840 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
Dan Gohman25208642010-04-14 19:53:31 +0000841}
Chris Lattner7c306da2010-03-02 06:34:30 +0000842
Chris Lattner8bdc2512011-04-17 06:03:19 +0000843/// isFoldedOrDeadInstruction - Return true if the specified instruction is
844/// side-effect free and is either dead or folded into a generated instruction.
845/// Return false if it needs to be emitted.
846static bool isFoldedOrDeadInstruction(const Instruction *I,
847 FunctionLoweringInfo *FuncInfo) {
Chris Lattnerb686af02011-04-22 21:59:37 +0000848 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
849 !isa<TerminatorInst>(I) && // Terminators aren't folded.
850 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
Bill Wendling4477d692011-08-23 21:33:05 +0000851 !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
Chris Lattnerb686af02011-04-22 21:59:37 +0000852 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
Chris Lattner8bdc2512011-04-17 06:03:19 +0000853}
854
Chad Rosier73e08d32011-12-08 21:37:10 +0000855#ifndef NDEBUG
Chad Rosier4bf76e02012-01-06 23:45:47 +0000856// Collect per Instruction statistics for fast-isel misses. Only those
857// instructions that cause the bail are accounted for. It does not account for
858// instructions higher in the block. Thus, summing the per instructions stats
859// will not add up to what is reported by NumFastIselFailures.
Chad Rosier73e08d32011-12-08 21:37:10 +0000860static void collectFailStats(const Instruction *I) {
861 switch (I->getOpcode()) {
862 default: assert (0 && "<Invalid operator> ");
863
864 // Terminators
865 case Instruction::Ret: NumFastIselFailRet++; return;
866 case Instruction::Br: NumFastIselFailBr++; return;
867 case Instruction::Switch: NumFastIselFailSwitch++; return;
868 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
869 case Instruction::Invoke: NumFastIselFailInvoke++; return;
870 case Instruction::Resume: NumFastIselFailResume++; return;
Chad Rosier73e08d32011-12-08 21:37:10 +0000871 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
872
873 // Standard binary operators...
874 case Instruction::Add: NumFastIselFailAdd++; return;
875 case Instruction::FAdd: NumFastIselFailFAdd++; return;
876 case Instruction::Sub: NumFastIselFailSub++; return;
877 case Instruction::FSub: NumFastIselFailFSub++; return;
878 case Instruction::Mul: NumFastIselFailMul++; return;
879 case Instruction::FMul: NumFastIselFailFMul++; return;
880 case Instruction::UDiv: NumFastIselFailUDiv++; return;
881 case Instruction::SDiv: NumFastIselFailSDiv++; return;
882 case Instruction::FDiv: NumFastIselFailFDiv++; return;
883 case Instruction::URem: NumFastIselFailURem++; return;
884 case Instruction::SRem: NumFastIselFailSRem++; return;
885 case Instruction::FRem: NumFastIselFailFRem++; return;
886
887 // Logical operators...
888 case Instruction::And: NumFastIselFailAnd++; return;
889 case Instruction::Or: NumFastIselFailOr++; return;
890 case Instruction::Xor: NumFastIselFailXor++; return;
891
892 // Memory instructions...
893 case Instruction::Alloca: NumFastIselFailAlloca++; return;
894 case Instruction::Load: NumFastIselFailLoad++; return;
895 case Instruction::Store: NumFastIselFailStore++; return;
896 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
897 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
898 case Instruction::Fence: NumFastIselFailFence++; return;
899 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
900
901 // Convert instructions...
902 case Instruction::Trunc: NumFastIselFailTrunc++; return;
903 case Instruction::ZExt: NumFastIselFailZExt++; return;
904 case Instruction::SExt: NumFastIselFailSExt++; return;
905 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
906 case Instruction::FPExt: NumFastIselFailFPExt++; return;
907 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
908 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
909 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
910 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
Andrew Trickacddd492012-03-07 00:18:15 +0000911 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
Chad Rosier73e08d32011-12-08 21:37:10 +0000912 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
Andrew Trickacddd492012-03-07 00:18:15 +0000913 case Instruction::BitCast: NumFastIselFailBitCast++; return;
Chad Rosier73e08d32011-12-08 21:37:10 +0000914
915 // Other instructions...
916 case Instruction::ICmp: NumFastIselFailICmp++; return;
917 case Instruction::FCmp: NumFastIselFailFCmp++; return;
918 case Instruction::PHI: NumFastIselFailPHI++; return;
919 case Instruction::Select: NumFastIselFailSelect++; return;
920 case Instruction::Call: NumFastIselFailCall++; return;
921 case Instruction::Shl: NumFastIselFailShl++; return;
922 case Instruction::LShr: NumFastIselFailLShr++; return;
923 case Instruction::AShr: NumFastIselFailAShr++; return;
924 case Instruction::VAArg: NumFastIselFailVAArg++; return;
925 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
926 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
927 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
928 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
929 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
930 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
931 }
Chad Rosier73e08d32011-12-08 21:37:10 +0000932}
933#endif
934
Dan Gohman46510a72010-04-15 01:51:59 +0000935void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000936 // Initialize the Fast-ISel state, if needed.
937 FastISel *FastIS = 0;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000938 if (TM.Options.EnableFastISel)
Bill Wendlingba54bca2013-06-19 21:36:55 +0000939 FastIS = getTargetLowering()->createFastISel(*FuncInfo, LibInfo);
Dan Gohmana43abd12008-09-29 21:55:50 +0000940
941 // Iterate over all basic blocks in the function.
Cameron Zwarich2dbe2852011-02-24 10:00:04 +0000942 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
943 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
944 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
945 const BasicBlock *LLVMBB = *I;
Cameron Zwaricha46cd972011-02-24 10:00:13 +0000946
Cameron Zwarich324a24f2011-02-24 10:00:16 +0000947 if (OptLevel != CodeGenOpt::None) {
948 bool AllPredsVisited = true;
949 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
950 PI != PE; ++PI) {
951 if (!FuncInfo->VisitedBBs.count(*PI)) {
952 AllPredsVisited = false;
953 break;
954 }
955 }
956
Cameron Zwarich8ca814c2011-02-24 10:00:25 +0000957 if (AllPredsVisited) {
Chris Lattner8bdc2512011-04-17 06:03:19 +0000958 for (BasicBlock::const_iterator I = LLVMBB->begin();
Jakub Staszak46608c02012-12-04 00:50:06 +0000959 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
960 FuncInfo->ComputePHILiveOutRegInfo(PN);
Cameron Zwarich8ca814c2011-02-24 10:00:25 +0000961 } else {
Chris Lattner8bdc2512011-04-17 06:03:19 +0000962 for (BasicBlock::const_iterator I = LLVMBB->begin();
Jakub Staszak46608c02012-12-04 00:50:06 +0000963 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
964 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
Cameron Zwarich324a24f2011-02-24 10:00:16 +0000965 }
966
Cameron Zwaricha46cd972011-02-24 10:00:13 +0000967 FuncInfo->VisitedBBs.insert(LLVMBB);
Cameron Zwarich324a24f2011-02-24 10:00:16 +0000968 }
Cameron Zwaricha46cd972011-02-24 10:00:13 +0000969
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000970 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
Dan Gohman46510a72010-04-15 01:51:59 +0000971 BasicBlock::const_iterator const End = LLVMBB->end();
Dan Gohman84023e02010-07-10 09:00:22 +0000972 BasicBlock::const_iterator BI = End;
Dan Gohman5edd3612008-08-28 20:28:56 +0000973
Eli Benderskyb804a1b2013-03-01 23:32:40 +0000974 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
Dan Gohman84023e02010-07-10 09:00:22 +0000975 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
976
977 // Setup an EH landing-pad block.
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +0000978 FuncInfo->ExceptionPointerVirtReg = 0;
979 FuncInfo->ExceptionSelectorVirtReg = 0;
Dan Gohman84023e02010-07-10 09:00:22 +0000980 if (FuncInfo->MBB->isLandingPad())
981 PrepareEHLandingPad();
Andrew Trick6e8f4c42010-12-24 04:28:06 +0000982
Dan Gohmanf350b272008-08-23 02:25:05 +0000983 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmand725f042010-05-01 02:44:23 +0000984 if (FastIS) {
Dan Gohman84023e02010-07-10 09:00:22 +0000985 FastIS->startNewBlock();
986
Dan Gohmanf5951412010-07-08 01:00:56 +0000987 // Emit code for any incoming arguments. This must happen before
988 // beginning FastISel on the entry block.
989 if (LLVMBB == &Fn.getEntryBlock()) {
Eli Bendersky5bd07672013-04-19 01:04:40 +0000990 ++NumEntryBlocks;
991
Evan Cheng092e5e72013-02-11 01:27:15 +0000992 // Lower any arguments needed in this block if this is the entry block.
993 if (!FastIS->LowerArguments()) {
Eli Bendersky6437d382013-02-28 23:09:18 +0000994 // Fast isel failed to lower these arguments
Eli Bendersky5bd07672013-04-19 01:04:40 +0000995 ++NumFastIselFailLowerArguments;
Chad Rosierfd3417d2013-02-25 21:59:35 +0000996 if (EnableFastISelAbortArgs)
Chad Rosierfd3417d2013-02-25 21:59:35 +0000997 llvm_unreachable("FastISel didn't lower all arguments");
998
Eli Bendersky6437d382013-02-28 23:09:18 +0000999 // Use SelectionDAG argument lowering
1000 LowerArguments(Fn);
Evan Cheng092e5e72013-02-11 01:27:15 +00001001 CurDAG->setRoot(SDB->getControlRoot());
1002 SDB->clear();
1003 CodeGenAndEmitDAG();
1004 }
Dan Gohman84023e02010-07-10 09:00:22 +00001005
1006 // If we inserted any instructions at the beginning, make a note of
1007 // where they are, so we can be sure to emit subsequent instructions
1008 // after them.
1009 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1010 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
1011 else
1012 FastIS->setLastLocalValue(0);
Dan Gohmanf5951412010-07-08 01:00:56 +00001013 }
Dan Gohman84023e02010-07-10 09:00:22 +00001014
Nadav Rotem139f50a2013-02-27 22:52:54 +00001015 unsigned NumFastIselRemaining = std::distance(Begin, End);
Dan Gohmana43abd12008-09-29 21:55:50 +00001016 // Do FastISel on as many instructions as possible.
Dan Gohman84023e02010-07-10 09:00:22 +00001017 for (; BI != Begin; --BI) {
1018 const Instruction *Inst = llvm::prior(BI);
1019
1020 // If we no longer require this instruction, skip it.
Chad Rosierf91488c2011-11-16 21:02:08 +00001021 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1022 --NumFastIselRemaining;
Dan Gohman20d4be12010-07-01 02:58:57 +00001023 continue;
Chad Rosierf91488c2011-11-16 21:02:08 +00001024 }
Dan Gohman84023e02010-07-10 09:00:22 +00001025
1026 // Bottom-up: reset the insert pos at the top, after any local-value
1027 // instructions.
1028 FastIS->recomputeInsertPt();
Dan Gohman20d4be12010-07-01 02:58:57 +00001029
Dan Gohman21c14e32010-01-12 04:32:35 +00001030 // Try to select the instruction with FastISel.
Chris Lattnerbeac75d2010-09-05 02:18:34 +00001031 if (FastIS->SelectInstruction(Inst)) {
Chad Rosierf91488c2011-11-16 21:02:08 +00001032 --NumFastIselRemaining;
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00001033 ++NumFastIselSuccess;
Chris Lattnerb686af02011-04-22 21:59:37 +00001034 // If fast isel succeeded, skip over all the folded instructions, and
1035 // then see if there is a load right before the selected instructions.
1036 // Try to fold the load if so.
1037 const Instruction *BeforeInst = Inst;
1038 while (BeforeInst != Begin) {
1039 BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
1040 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1041 break;
1042 }
1043 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1044 BeforeInst->hasOneUse() &&
Eli Bendersky75299e32013-04-19 22:29:18 +00001045 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
Chris Lattnerb686af02011-04-22 21:59:37 +00001046 // If we succeeded, don't re-select the load.
1047 BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
Chad Rosierf91488c2011-11-16 21:02:08 +00001048 --NumFastIselRemaining;
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00001049 ++NumFastIselSuccess;
Chad Rosierf91488c2011-11-16 21:02:08 +00001050 }
Dan Gohmana43abd12008-09-29 21:55:50 +00001051 continue;
Chris Lattnerbeac75d2010-09-05 02:18:34 +00001052 }
Dan Gohmana43abd12008-09-29 21:55:50 +00001053
Chad Rosier73e08d32011-12-08 21:37:10 +00001054#ifndef NDEBUG
Chad Rosierf2a745e2011-12-13 00:05:11 +00001055 if (EnableFastISelVerbose2)
1056 collectFailStats(Inst);
Chad Rosier73e08d32011-12-08 21:37:10 +00001057#endif
1058
Dan Gohmana43abd12008-09-29 21:55:50 +00001059 // Then handle certain instructions as single-LLVM-Instruction blocks.
Dan Gohman84023e02010-07-10 09:00:22 +00001060 if (isa<CallInst>(Inst)) {
Chad Rosierf91488c2011-11-16 21:02:08 +00001061
Dan Gohmana43abd12008-09-29 21:55:50 +00001062 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +00001063 dbgs() << "FastISel missed call: ";
Dan Gohman84023e02010-07-10 09:00:22 +00001064 Inst->dump();
Dan Gohmana43abd12008-09-29 21:55:50 +00001065 }
1066
Dan Gohman84023e02010-07-10 09:00:22 +00001067 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1068 unsigned &R = FuncInfo->ValueMap[Inst];
Dan Gohmana43abd12008-09-29 21:55:50 +00001069 if (!R)
Dan Gohman84023e02010-07-10 09:00:22 +00001070 R = FuncInfo->CreateRegs(Inst->getType());
Dan Gohmana43abd12008-09-29 21:55:50 +00001071 }
1072
Dan Gohmanb4afb132009-11-20 02:51:26 +00001073 bool HadTailCall = false;
Chad Rosier425e9512012-12-11 00:18:02 +00001074 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
Devang Pateldf8370b2010-10-25 21:31:46 +00001075 SelectBasicBlock(Inst, BI, HadTailCall);
Dan Gohmanb4afb132009-11-20 02:51:26 +00001076
Chad Rosier425e9512012-12-11 00:18:02 +00001077 // If the call was emitted as a tail call, we're done with the block.
1078 // We also need to delete any previously emitted instructions.
1079 if (HadTailCall) {
1080 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1081 --BI;
1082 break;
1083 }
1084
Chad Rosierf91488c2011-11-16 21:02:08 +00001085 // Recompute NumFastIselRemaining as Selection DAG instruction
1086 // selection may have handled the call, input args, etc.
1087 unsigned RemainingNow = std::distance(Begin, BI);
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00001088 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1089 NumFastIselRemaining = RemainingNow;
Dan Gohmana43abd12008-09-29 21:55:50 +00001090 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +00001091 }
Dan Gohmana43abd12008-09-29 21:55:50 +00001092
Eli Friedman9c4dae62011-05-17 23:02:10 +00001093 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1094 // Don't abort, and use a different message for terminator misses.
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00001095 NumFastIselFailures += NumFastIselRemaining;
Eli Friedman9c4dae62011-05-17 23:02:10 +00001096 if (EnableFastISelVerbose || EnableFastISelAbort) {
1097 dbgs() << "FastISel missed terminator: ";
1098 Inst->dump();
1099 }
1100 } else {
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00001101 NumFastIselFailures += NumFastIselRemaining;
Dan Gohmana43abd12008-09-29 21:55:50 +00001102 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +00001103 dbgs() << "FastISel miss: ";
Dan Gohman84023e02010-07-10 09:00:22 +00001104 Inst->dump();
Dan Gohmana43abd12008-09-29 21:55:50 +00001105 }
1106 if (EnableFastISelAbort)
1107 // The "fast" selector couldn't handle something and bailed.
1108 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +00001109 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +00001110 }
1111 break;
Dan Gohmanf350b272008-08-23 02:25:05 +00001112 }
Dan Gohman84023e02010-07-10 09:00:22 +00001113
1114 FastIS->recomputeInsertPt();
Evan Cheng092e5e72013-02-11 01:27:15 +00001115 } else {
1116 // Lower any arguments needed in this block if this is the entry block.
Eli Bendersky5bd07672013-04-19 01:04:40 +00001117 if (LLVMBB == &Fn.getEntryBlock()) {
1118 ++NumEntryBlocks;
Eli Bendersky6437d382013-02-28 23:09:18 +00001119 LowerArguments(Fn);
Eli Bendersky5bd07672013-04-19 01:04:40 +00001120 }
Dan Gohmanf350b272008-08-23 02:25:05 +00001121 }
1122
Devang Pateldf8370b2010-10-25 21:31:46 +00001123 if (Begin != BI)
1124 ++NumDAGBlocks;
1125 else
1126 ++NumFastIselBlocks;
1127
Eli Friedman37d38bf2011-04-19 17:01:08 +00001128 if (Begin != BI) {
1129 // Run SelectionDAG instruction selection on the remainder of the block
1130 // not handled by FastISel. If FastISel is not run, this is the entire
1131 // block.
1132 bool HadTailCall;
1133 SelectBasicBlock(Begin, BI, HadTailCall);
1134 }
Dan Gohmanf350b272008-08-23 02:25:05 +00001135
Dan Gohman84023e02010-07-10 09:00:22 +00001136 FinishBasicBlock();
Dan Gohman620427d2010-04-22 19:55:20 +00001137 FuncInfo->PHINodesToUpdate.clear();
Evan Cheng39fd6e82008-08-07 00:43:25 +00001138 }
Dan Gohmana43abd12008-09-29 21:55:50 +00001139
1140 delete FastIS;
Devang Patel23385752011-05-23 17:44:13 +00001141 SDB->clearDanglingDebugInfo();
Dan Gohman0e5f1302008-07-07 23:02:41 +00001142}
1143
Dan Gohmanfed90b62008-07-28 21:51:04 +00001144void
Dan Gohman84023e02010-07-10 09:00:22 +00001145SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +00001146
David Greene1a053232010-01-05 01:26:11 +00001147 DEBUG(dbgs() << "Total amount of phi nodes to update: "
Dan Gohman927f8662010-06-18 16:00:29 +00001148 << FuncInfo->PHINodesToUpdate.size() << "\n";
1149 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
David Greene1a053232010-01-05 01:26:11 +00001150 dbgs() << "Node " << i << " : ("
Dan Gohman620427d2010-04-22 19:55:20 +00001151 << FuncInfo->PHINodesToUpdate[i].first
1152 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001153
Chris Lattnera33ef482005-03-30 01:10:47 +00001154 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001155 // PHI nodes in successors.
Dan Gohman2048b852009-11-23 18:04:58 +00001156 if (SDB->SwitchCases.empty() &&
1157 SDB->JTCases.empty() &&
1158 SDB->BitTestCases.empty()) {
Dan Gohman620427d2010-04-22 19:55:20 +00001159 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001160 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
Chris Lattner518bb532010-02-09 19:54:29 +00001161 assert(PHI->isPHI() &&
Nate Begemanf15485a2006-03-27 01:32:24 +00001162 "This is not a machine PHI node that we are updating!");
Dan Gohman84023e02010-07-10 09:00:22 +00001163 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
Jakob Stoklund Olesen580bba22010-03-05 21:49:10 +00001164 continue;
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001165 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001166 }
1167 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001168 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001169
Dan Gohman2048b852009-11-23 18:04:58 +00001170 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001171 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +00001172 if (!SDB->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001173 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001174 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1175 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001176 // Emit the code
Dan Gohman84023e02010-07-10 09:00:22 +00001177 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +00001178 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001179 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001180 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001182
Manman Ren1a710fd2012-08-24 18:14:27 +00001183 uint32_t UnhandledWeight = 0;
1184 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
1185 UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
1186
Dan Gohman2048b852009-11-23 18:04:58 +00001187 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
Manman Ren1a710fd2012-08-24 18:14:27 +00001188 UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001189 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001190 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1191 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001192 // Emit the code
1193 if (j+1 != ej)
Evan Chengd08e5b42011-01-06 01:02:44 +00001194 SDB->visitBitTestCase(SDB->BitTestCases[i],
1195 SDB->BitTestCases[i].Cases[j+1].ThisBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00001196 UnhandledWeight,
Dan Gohman2048b852009-11-23 18:04:58 +00001197 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001198 SDB->BitTestCases[i].Cases[j],
Dan Gohman84023e02010-07-10 09:00:22 +00001199 FuncInfo->MBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001200 else
Evan Chengd08e5b42011-01-06 01:02:44 +00001201 SDB->visitBitTestCase(SDB->BitTestCases[i],
1202 SDB->BitTestCases[i].Default,
Manman Ren1a710fd2012-08-24 18:14:27 +00001203 UnhandledWeight,
Dan Gohman2048b852009-11-23 18:04:58 +00001204 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001205 SDB->BitTestCases[i].Cases[j],
Dan Gohman84023e02010-07-10 09:00:22 +00001206 FuncInfo->MBB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001207
1208
Dan Gohman2048b852009-11-23 18:04:58 +00001209 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001210 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001211 CodeGenAndEmitDAG();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001212 }
1213
1214 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +00001215 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1216 pi != pe; ++pi) {
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001217 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001218 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +00001219 assert(PHI->isPHI() &&
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001220 "This is not a machine PHI node that we are updating!");
1221 // This is "default" BB. We have two jumps to it. From "header" BB and
1222 // from last "case" BB.
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001223 if (PHIBB == SDB->BitTestCases[i].Default)
1224 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1225 .addMBB(SDB->BitTestCases[i].Parent)
1226 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1227 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001228 // One of "cases" BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001229 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001230 j != ej; ++j) {
Dan Gohman2048b852009-11-23 18:04:58 +00001231 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001232 if (cBB->isSuccessor(PHIBB))
1233 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001234 }
1235 }
1236 }
Dan Gohman2048b852009-11-23 18:04:58 +00001237 SDB->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001238
Nate Begeman9453eea2006-04-23 06:26:20 +00001239 // If the JumpTable record is filled in, then we need to emit a jump table.
1240 // Updating the PHI nodes is tricky in this case, since we need to determine
1241 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001242 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001243 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +00001244 if (!SDB->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001245 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001246 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1247 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001248 // Emit the code
Dan Gohman99be8ae2010-04-19 22:41:47 +00001249 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
Dan Gohman84023e02010-07-10 09:00:22 +00001250 FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +00001251 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001252 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001253 CodeGenAndEmitDAG();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001254 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001255
Nate Begeman37efe672006-04-22 18:53:45 +00001256 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001257 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1258 FuncInfo->InsertPt = FuncInfo->MBB->end();
Nate Begeman37efe672006-04-22 18:53:45 +00001259 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001260 SDB->visitJumpTable(SDB->JTCases[i].second);
1261 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001262 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001263 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Nate Begeman37efe672006-04-22 18:53:45 +00001265 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +00001266 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1267 pi != pe; ++pi) {
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001268 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
Nate Begeman37efe672006-04-22 18:53:45 +00001269 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +00001270 assert(PHI->isPHI() &&
Nate Begeman37efe672006-04-22 18:53:45 +00001271 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001272 // "default" BB. We can go there only from header BB.
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001273 if (PHIBB == SDB->JTCases[i].second.Default)
1274 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1275 .addMBB(SDB->JTCases[i].first.HeaderBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001276 // JT BB. Just iterate over successors here
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001277 if (FuncInfo->MBB->isSuccessor(PHIBB))
1278 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
Nate Begeman37efe672006-04-22 18:53:45 +00001279 }
Nate Begeman37efe672006-04-22 18:53:45 +00001280 }
Dan Gohman2048b852009-11-23 18:04:58 +00001281 SDB->JTCases.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001283 // If the switch block involved a branch to one of the actual successors, we
1284 // need to update PHI nodes in that block.
Dan Gohman620427d2010-04-22 19:55:20 +00001285 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001286 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
Chris Lattner518bb532010-02-09 19:54:29 +00001287 assert(PHI->isPHI() &&
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001288 "This is not a machine PHI node that we are updating!");
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001289 if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
1290 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001291 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001292
Nate Begemanf15485a2006-03-27 01:32:24 +00001293 // If we generated any switch lowering information, build and codegen any
1294 // additional DAGs necessary.
Dan Gohman2048b852009-11-23 18:04:58 +00001295 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001296 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohmanca5f6162011-01-14 22:26:16 +00001297 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
Dan Gohman84023e02010-07-10 09:00:22 +00001298 FuncInfo->InsertPt = FuncInfo->MBB->end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001299
Dan Gohman95140a42010-05-01 00:25:44 +00001300 // Determine the unique successors.
1301 SmallVector<MachineBasicBlock *, 2> Succs;
1302 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1303 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1304 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1305
Dan Gohmanca5f6162011-01-14 22:26:16 +00001306 // Emit the code. Note that this could result in FuncInfo->MBB being split.
Dan Gohman84023e02010-07-10 09:00:22 +00001307 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +00001308 CurDAG->setRoot(SDB->getRoot());
Dan Gohman95140a42010-05-01 00:25:44 +00001309 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001310 CodeGenAndEmitDAG();
Dan Gohmanca5f6162011-01-14 22:26:16 +00001311
1312 // Remember the last block, now that any splitting is done, for use in
1313 // populating PHI nodes in successors.
1314 MachineBasicBlock *ThisBB = FuncInfo->MBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001315
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001316 // Handle any PHI nodes in successors of this chunk, as if we were coming
1317 // from the original BB before switch expansion. Note that PHI nodes can
1318 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1319 // handle them the right number of times.
Dan Gohman95140a42010-05-01 00:25:44 +00001320 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
Dan Gohman84023e02010-07-10 09:00:22 +00001321 FuncInfo->MBB = Succs[i];
1322 FuncInfo->InsertPt = FuncInfo->MBB->end();
1323 // FuncInfo->MBB may have been removed from the CFG if a branch was
1324 // constant folded.
1325 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001326 for (MachineBasicBlock::iterator
1327 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1328 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1329 MachineInstrBuilder PHI(*MF, MBBI);
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001330 // This value for this PHI node is recorded in PHINodesToUpdate.
1331 for (unsigned pn = 0; ; ++pn) {
Dan Gohman620427d2010-04-22 19:55:20 +00001332 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001333 "Didn't find PHI entry!");
Jakob Stoklund Olesen5d3cfa62012-12-20 18:46:29 +00001334 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1335 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001336 break;
1337 }
Evan Cheng8be58a12009-09-18 08:26:06 +00001338 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001339 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001340 }
1341 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001342 }
Dan Gohman2048b852009-11-23 18:04:58 +00001343 SDB->SwitchCases.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001344}
Evan Chenga9c20912006-01-21 02:32:06 +00001345
Jim Laskey13ec7022006-08-01 14:21:23 +00001346
Dan Gohman0a3776d2009-02-06 18:26:51 +00001347/// Create the scheduler. If a specific scheduler was specified
1348/// via the SchedulerRegistry, use it, otherwise select the
1349/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001350///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001351ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001352 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Jim Laskey13ec7022006-08-01 14:21:23 +00001354 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001355 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001356 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001358
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001359 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001360}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001361
Chris Lattner75548062006-10-11 03:58:02 +00001362//===----------------------------------------------------------------------===//
1363// Helper functions used by the generated instruction selector.
1364//===----------------------------------------------------------------------===//
1365// Calls to these methods are generated by tblgen.
1366
1367/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1368/// the dag combiner simplified the 255, we still want to match. RHS is the
1369/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1370/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001371bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001372 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001373 const APInt &ActualMask = RHS->getAPIntValue();
1374 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001375
Chris Lattner75548062006-10-11 03:58:02 +00001376 // If the actual mask exactly matches, success!
1377 if (ActualMask == DesiredMask)
1378 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001379
Chris Lattner75548062006-10-11 03:58:02 +00001380 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001381 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001382 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001383
Chris Lattner75548062006-10-11 03:58:02 +00001384 // Otherwise, the DAG Combiner may have proven that the value coming in is
1385 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001386 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001387 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001388 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001389
Chris Lattner75548062006-10-11 03:58:02 +00001390 // TODO: check to see if missing bits are just not demanded.
1391
1392 // Otherwise, this pattern doesn't match.
1393 return false;
1394}
1395
1396/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1397/// the dag combiner simplified the 255, we still want to match. RHS is the
1398/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1399/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001401 int64_t DesiredMaskS) const {
1402 const APInt &ActualMask = RHS->getAPIntValue();
1403 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattner75548062006-10-11 03:58:02 +00001405 // If the actual mask exactly matches, success!
1406 if (ActualMask == DesiredMask)
1407 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001408
Chris Lattner75548062006-10-11 03:58:02 +00001409 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001410 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001411 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001412
Chris Lattner75548062006-10-11 03:58:02 +00001413 // Otherwise, the DAG Combiner may have proven that the value coming in is
1414 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001415 APInt NeededMask = DesiredMask & ~ActualMask;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001417 APInt KnownZero, KnownOne;
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001418 CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001419
Chris Lattner75548062006-10-11 03:58:02 +00001420 // If all the missing bits in the or are already known to be set, match!
1421 if ((NeededMask & KnownOne) == NeededMask)
1422 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001423
Chris Lattner75548062006-10-11 03:58:02 +00001424 // TODO: check to see if missing bits are just not demanded.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001425
Chris Lattner75548062006-10-11 03:58:02 +00001426 // Otherwise, this pattern doesn't match.
1427 return false;
1428}
1429
Jim Laskey9ff542f2006-08-01 18:29:48 +00001430
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001431/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1432/// by tblgen. Others should not call it.
1433void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001434SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001435 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001436 std::swap(InOps, Ops);
1437
Chris Lattnerdecc2672010-04-07 05:20:54 +00001438 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1439 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1440 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
Evan Chengc36b7062011-01-07 23:50:32 +00001441 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001442
Chris Lattnerdecc2672010-04-07 05:20:54 +00001443 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00001444 if (InOps[e-1].getValueType() == MVT::Glue)
Chris Lattnera4359be2010-12-23 17:13:18 +00001445 --e; // Don't process a glue operand if it is here.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001447 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001448 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00001449 if (!InlineAsm::isMemKind(Flags)) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001450 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001451 Ops.insert(Ops.end(), InOps.begin()+i,
1452 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1453 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001454 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001455 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1456 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001457 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001458 std::vector<SDValue> SelOps;
Chris Lattnerdecc2672010-04-07 05:20:54 +00001459 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
Chris Lattner75361b62010-04-07 22:58:41 +00001460 report_fatal_error("Could not match memory address. Inline asm"
Chris Lattner87d677c2010-04-07 23:50:38 +00001461 " failure!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001462
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001463 // Add this to the output node.
Chris Lattnerdecc2672010-04-07 05:20:54 +00001464 unsigned NewFlags =
1465 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1466 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001467 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1468 i += 2;
1469 }
1470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattnera4359be2010-12-23 17:13:18 +00001472 // Add the glue input back if present.
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001473 if (e != InOps.size())
1474 Ops.push_back(InOps.back());
1475}
Devang Patel794fd752007-05-01 21:15:47 +00001476
Chris Lattnera4359be2010-12-23 17:13:18 +00001477/// findGlueUse - Return use of MVT::Glue value produced by the specified
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001478/// SDNode.
1479///
Chris Lattnera4359be2010-12-23 17:13:18 +00001480static SDNode *findGlueUse(SDNode *N) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001481 unsigned FlagResNo = N->getNumValues()-1;
1482 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1483 SDUse &Use = I.getUse();
1484 if (Use.getResNo() == FlagResNo)
1485 return Use.getUser();
1486 }
1487 return NULL;
1488}
1489
1490/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1491/// This function recursively traverses up the operand chain, ignoring
1492/// certain nodes.
1493static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
Chris Lattnerd1b73822010-03-02 22:20:06 +00001494 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1495 bool IgnoreChains) {
Chris Lattnerda244a02010-02-23 19:32:27 +00001496 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1497 // greater than all of its (recursive) operands. If we scan to a point where
1498 // 'use' is smaller than the node we're scanning for, then we know we will
1499 // never find it.
1500 //
1501 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
Chris Lattnera4359be2010-12-23 17:13:18 +00001502 // happen because we scan down to newly selected nodes in the case of glue
Chris Lattnerda244a02010-02-23 19:32:27 +00001503 // uses.
1504 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1505 return false;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001506
Chris Lattnerda244a02010-02-23 19:32:27 +00001507 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1508 // won't fail if we scan it again.
1509 if (!Visited.insert(Use))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001510 return false;
1511
1512 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001513 // Ignore chain uses, they are validated by HandleMergeInputChains.
1514 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1515 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001516
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001517 SDNode *N = Use->getOperand(i).getNode();
1518 if (N == Def) {
1519 if (Use == ImmedUse || Use == Root)
1520 continue; // We are not looking for immediate use.
1521 assert(N != Root);
1522 return true;
1523 }
1524
1525 // Traverse up the operand chain.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001526 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001527 return true;
1528 }
1529 return false;
1530}
1531
Evan Cheng014bf212010-02-15 19:41:07 +00001532/// IsProfitableToFold - Returns true if it's profitable to fold the specific
1533/// operand node N of U during instruction selection that starts at Root.
1534bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1535 SDNode *Root) const {
1536 if (OptLevel == CodeGenOpt::None) return false;
1537 return N.hasOneUse();
1538}
1539
1540/// IsLegalToFold - Returns true if the specific operand node N of
1541/// U can be folded during instruction selection that starts at Root.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001542bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
Dan Gohmand858e902010-04-17 15:26:15 +00001543 CodeGenOpt::Level OptLevel,
1544 bool IgnoreChains) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001545 if (OptLevel == CodeGenOpt::None) return false;
1546
1547 // If Root use can somehow reach N through a path that that doesn't contain
1548 // U then folding N would create a cycle. e.g. In the following
1549 // diagram, Root can reach N through X. If N is folded into into Root, then
1550 // X is both a predecessor and a successor of U.
1551 //
1552 // [N*] //
1553 // ^ ^ //
1554 // / \ //
1555 // [U*] [X]? //
1556 // ^ ^ //
1557 // \ / //
1558 // \ / //
1559 // [Root*] //
1560 //
1561 // * indicates nodes to be folded together.
1562 //
Chris Lattnera4359be2010-12-23 17:13:18 +00001563 // If Root produces glue, then it gets (even more) interesting. Since it
1564 // will be "glued" together with its glue use in the scheduler, we need to
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001565 // check if it might reach N.
1566 //
1567 // [N*] //
1568 // ^ ^ //
1569 // / \ //
1570 // [U*] [X]? //
1571 // ^ ^ //
1572 // \ \ //
1573 // \ | //
1574 // [Root*] | //
1575 // ^ | //
1576 // f | //
1577 // | / //
1578 // [Y] / //
1579 // ^ / //
1580 // f / //
1581 // | / //
Chris Lattnera4359be2010-12-23 17:13:18 +00001582 // [GU] //
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001583 //
Chris Lattnera4359be2010-12-23 17:13:18 +00001584 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1585 // (call it Fold), then X is a predecessor of GU and a successor of
1586 // Fold. But since Fold and GU are glued together, this will create
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001587 // a cycle in the scheduling graph.
1588
Chris Lattnera4359be2010-12-23 17:13:18 +00001589 // If the node has glue, walk down the graph to the "lowest" node in the
1590 // glueged set.
Owen Andersone50ed302009-08-10 22:56:29 +00001591 EVT VT = Root->getValueType(Root->getNumValues()-1);
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00001592 while (VT == MVT::Glue) {
Chris Lattnera4359be2010-12-23 17:13:18 +00001593 SDNode *GU = findGlueUse(Root);
1594 if (GU == NULL)
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001595 break;
Chris Lattnera4359be2010-12-23 17:13:18 +00001596 Root = GU;
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001597 VT = Root->getValueType(Root->getNumValues()-1);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001598
Chris Lattnera4359be2010-12-23 17:13:18 +00001599 // If our query node has a glue result with a use, we've walked up it. If
Chris Lattner18fdaba2010-03-05 06:19:13 +00001600 // the user (which has already been selected) has a chain or indirectly uses
1601 // the chain, our WalkChainUsers predicate will not consider it. Because of
1602 // this, we cannot ignore chains in this predicate.
1603 IgnoreChains = false;
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001604 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001605
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001606
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001607 SmallPtrSet<SDNode*, 16> Visited;
1608 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001609}
1610
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001611SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1612 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
Dan Gohmane1f188f2009-10-29 22:30:23 +00001613 SelectInlineAsmMemoryOperands(Ops);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001614
Benjamin Kramer3853f742013-03-07 20:33:29 +00001615 EVT VTs[] = { MVT::Other, MVT::Glue };
Andrew Trickac6d9be2013-05-25 02:42:55 +00001616 SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N),
Dan Gohmane1f188f2009-10-29 22:30:23 +00001617 VTs, &Ops[0], Ops.size());
Chris Lattnerd1b73822010-03-02 22:20:06 +00001618 New->setNodeId(-1);
Dan Gohmane1f188f2009-10-29 22:30:23 +00001619 return New.getNode();
1620}
1621
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001622SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
Chris Lattner518bb532010-02-09 19:54:29 +00001623 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
Dan Gohmane1f188f2009-10-29 22:30:23 +00001624}
1625
Chris Lattner2a49d572010-02-28 22:37:22 +00001626/// GetVBR - decode a vbr encoding whose top bit is set.
Chandler Carruth19e57022010-10-23 08:40:19 +00001627LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
Chris Lattner2a49d572010-02-28 22:37:22 +00001628GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1629 assert(Val >= 128 && "Not a VBR");
1630 Val &= 127; // Remove first vbr bit.
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001631
Chris Lattner2a49d572010-02-28 22:37:22 +00001632 unsigned Shift = 7;
1633 uint64_t NextBits;
1634 do {
Chris Lattner14df8dc2010-02-28 22:38:43 +00001635 NextBits = MatcherTable[Idx++];
Chris Lattner2a49d572010-02-28 22:37:22 +00001636 Val |= (NextBits&127) << Shift;
1637 Shift += 7;
1638 } while (NextBits & 128);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001639
Chris Lattner2a49d572010-02-28 22:37:22 +00001640 return Val;
1641}
1642
Chris Lattner2a49d572010-02-28 22:37:22 +00001643
Chris Lattnera4359be2010-12-23 17:13:18 +00001644/// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1645/// interior glue and chain results to use the new glue and chain results.
Chris Lattner82dd3d32010-03-02 07:50:03 +00001646void SelectionDAGISel::
Chris Lattnera4359be2010-12-23 17:13:18 +00001647UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1648 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1649 SDValue InputGlue,
1650 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1651 bool isMorphNodeTo) {
Chris Lattner82dd3d32010-03-02 07:50:03 +00001652 SmallVector<SDNode*, 4> NowDeadNodes;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001653
Chris Lattner2a49d572010-02-28 22:37:22 +00001654 // Now that all the normal results are replaced, we replace the chain and
Chris Lattnera4359be2010-12-23 17:13:18 +00001655 // glue results if present.
Chris Lattner2a49d572010-02-28 22:37:22 +00001656 if (!ChainNodesMatched.empty()) {
1657 assert(InputChain.getNode() != 0 &&
1658 "Matched input chains but didn't produce a chain");
1659 // Loop over all of the nodes we matched that produced a chain result.
1660 // Replace all the chain results with the final chain we ended up with.
1661 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1662 SDNode *ChainNode = ChainNodesMatched[i];
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001663
Chris Lattner82dd3d32010-03-02 07:50:03 +00001664 // If this node was already deleted, don't look at it.
1665 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1666 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001667
Chris Lattner2a49d572010-02-28 22:37:22 +00001668 // Don't replace the results of the root node if we're doing a
1669 // MorphNodeTo.
1670 if (ChainNode == NodeToMatch && isMorphNodeTo)
1671 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001672
Chris Lattner2a49d572010-02-28 22:37:22 +00001673 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00001674 if (ChainVal.getValueType() == MVT::Glue)
Chris Lattner2a49d572010-02-28 22:37:22 +00001675 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1676 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001677 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001678
Chris Lattner856fb392010-03-28 05:28:31 +00001679 // If the node became dead and we haven't already seen it, delete it.
1680 if (ChainNode->use_empty() &&
1681 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001682 NowDeadNodes.push_back(ChainNode);
Chris Lattner2a49d572010-02-28 22:37:22 +00001683 }
1684 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001685
Chris Lattnera4359be2010-12-23 17:13:18 +00001686 // If the result produces glue, update any glue results in the matched
1687 // pattern with the glue result.
1688 if (InputGlue.getNode() != 0) {
Chris Lattner2a49d572010-02-28 22:37:22 +00001689 // Handle any interior nodes explicitly marked.
Chris Lattnera4359be2010-12-23 17:13:18 +00001690 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1691 SDNode *FRN = GlueResultNodesMatched[i];
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001692
Chris Lattner82dd3d32010-03-02 07:50:03 +00001693 // If this node was already deleted, don't look at it.
1694 if (FRN->getOpcode() == ISD::DELETED_NODE)
1695 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001696
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00001697 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
Chris Lattnera4359be2010-12-23 17:13:18 +00001698 "Doesn't have a glue result");
Chris Lattner2a49d572010-02-28 22:37:22 +00001699 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001700 InputGlue);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001701
Chris Lattner19e37cb2010-03-28 04:54:33 +00001702 // If the node became dead and we haven't already seen it, delete it.
1703 if (FRN->use_empty() &&
1704 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001705 NowDeadNodes.push_back(FRN);
Chris Lattner2a49d572010-02-28 22:37:22 +00001706 }
1707 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001708
Chris Lattner82dd3d32010-03-02 07:50:03 +00001709 if (!NowDeadNodes.empty())
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001710 CurDAG->RemoveDeadNodes(NowDeadNodes);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001711
Eli Bendersky03494e02013-04-19 21:37:07 +00001712 DEBUG(dbgs() << "ISEL: Match complete!\n");
Chris Lattner2a49d572010-02-28 22:37:22 +00001713}
1714
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001715enum ChainResult {
1716 CR_Simple,
1717 CR_InducesCycle,
1718 CR_LeadsToInteriorNode
1719};
1720
1721/// WalkChainUsers - Walk down the users of the specified chained node that is
1722/// part of the pattern we're matching, looking at all of the users we find.
1723/// This determines whether something is an interior node, whether we have a
1724/// non-pattern node in between two pattern nodes (which prevent folding because
1725/// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1726/// between pattern nodes (in which case the TF becomes part of the pattern).
1727///
1728/// The walk we do here is guaranteed to be small because we quickly get down to
1729/// already selected nodes "below" us.
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001730static ChainResult
Jakub Staszak39379c52012-04-30 23:41:30 +00001731WalkChainUsers(const SDNode *ChainedNode,
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001732 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1733 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1734 ChainResult Result = CR_Simple;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001735
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001736 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1737 E = ChainedNode->use_end(); UI != E; ++UI) {
1738 // Make sure the use is of the chain, not some other value we produce.
1739 if (UI.getUse().getValueType() != MVT::Other) continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001740
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001741 SDNode *User = *UI;
1742
1743 // If we see an already-selected machine node, then we've gone beyond the
1744 // pattern that we're selecting down into the already selected chunk of the
1745 // DAG.
1746 if (User->isMachineOpcode() ||
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001747 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1748 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001749
Nadav Rotemc05d3062012-09-06 09:17:37 +00001750 unsigned UserOpcode = User->getOpcode();
1751 if (UserOpcode == ISD::CopyToReg ||
1752 UserOpcode == ISD::CopyFromReg ||
1753 UserOpcode == ISD::INLINEASM ||
1754 UserOpcode == ISD::EH_LABEL ||
1755 UserOpcode == ISD::LIFETIME_START ||
1756 UserOpcode == ISD::LIFETIME_END) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001757 // If their node ID got reset to -1 then they've already been selected.
1758 // Treat them like a MachineOpcode.
1759 if (User->getNodeId() == -1)
1760 continue;
1761 }
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001762
1763 // If we have a TokenFactor, we handle it specially.
1764 if (User->getOpcode() != ISD::TokenFactor) {
1765 // If the node isn't a token factor and isn't part of our pattern, then it
1766 // must be a random chained node in between two nodes we're selecting.
1767 // This happens when we have something like:
1768 // x = load ptr
1769 // call
1770 // y = x+4
1771 // store y -> ptr
1772 // Because we structurally match the load/store as a read/modify/write,
1773 // but the call is chained between them. We cannot fold in this case
1774 // because it would induce a cycle in the graph.
1775 if (!std::count(ChainedNodesInPattern.begin(),
1776 ChainedNodesInPattern.end(), User))
1777 return CR_InducesCycle;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001778
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001779 // Otherwise we found a node that is part of our pattern. For example in:
1780 // x = load ptr
1781 // y = x+4
1782 // store y -> ptr
1783 // This would happen when we're scanning down from the load and see the
1784 // store as a user. Record that there is a use of ChainedNode that is
1785 // part of the pattern and keep scanning uses.
1786 Result = CR_LeadsToInteriorNode;
1787 InteriorChainedNodes.push_back(User);
1788 continue;
1789 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001790
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001791 // If we found a TokenFactor, there are two cases to consider: first if the
1792 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1793 // uses of the TF are in our pattern) we just want to ignore it. Second,
1794 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1795 // [Load chain]
1796 // ^
1797 // |
1798 // [Load]
1799 // ^ ^
1800 // | \ DAG's like cheese
1801 // / \ do you?
1802 // / |
1803 // [TokenFactor] [Op]
1804 // ^ ^
1805 // | |
1806 // \ /
1807 // \ /
1808 // [Store]
1809 //
1810 // In this case, the TokenFactor becomes part of our match and we rewrite it
1811 // as a new TokenFactor.
1812 //
1813 // To distinguish these two cases, do a recursive walk down the uses.
1814 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1815 case CR_Simple:
1816 // If the uses of the TokenFactor are just already-selected nodes, ignore
1817 // it, it is "below" our pattern.
1818 continue;
1819 case CR_InducesCycle:
1820 // If the uses of the TokenFactor lead to nodes that are not part of our
1821 // pattern that are not selected, folding would turn this into a cycle,
1822 // bail out now.
1823 return CR_InducesCycle;
1824 case CR_LeadsToInteriorNode:
1825 break; // Otherwise, keep processing.
1826 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001827
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001828 // Okay, we know we're in the interesting interior case. The TokenFactor
1829 // is now going to be considered part of the pattern so that we rewrite its
1830 // uses (it may have uses that are not part of the pattern) with the
1831 // ultimate chain result of the generated code. We will also add its chain
1832 // inputs as inputs to the ultimate TokenFactor we create.
1833 Result = CR_LeadsToInteriorNode;
1834 ChainedNodesInPattern.push_back(User);
1835 InteriorChainedNodes.push_back(User);
1836 continue;
1837 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001838
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001839 return Result;
1840}
1841
Chris Lattner6b307922010-03-02 00:00:03 +00001842/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
Chris Lattner00592ec2010-03-02 19:34:59 +00001843/// operation for when the pattern matched at least one node with a chains. The
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001844/// input vector contains a list of all of the chained nodes that we match. We
1845/// must determine if this is a valid thing to cover (i.e. matching it won't
1846/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1847/// be used as the input node chain for the generated nodes.
Chris Lattner6b307922010-03-02 00:00:03 +00001848static SDValue
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001849HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
Chris Lattner6b307922010-03-02 00:00:03 +00001850 SelectionDAG *CurDAG) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001851 // Walk all of the chained nodes we've matched, recursively scanning down the
1852 // users of the chain result. This adds any TokenFactor nodes that are caught
1853 // in between chained nodes to the chained and interior nodes list.
1854 SmallVector<SDNode*, 3> InteriorChainedNodes;
1855 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1856 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1857 InteriorChainedNodes) == CR_InducesCycle)
1858 return SDValue(); // Would induce a cycle.
1859 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001860
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001861 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1862 // that we are interested in. Form our input TokenFactor node.
Chris Lattner6b307922010-03-02 00:00:03 +00001863 SmallVector<SDValue, 3> InputChains;
1864 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001865 // Add the input chain of this node to the InputChains list (which will be
1866 // the operands of the generated TokenFactor) if it's not an interior node.
1867 SDNode *N = ChainNodesMatched[i];
1868 if (N->getOpcode() != ISD::TokenFactor) {
1869 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1870 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001871
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001872 // Otherwise, add the input chain.
1873 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1874 assert(InChain.getValueType() == MVT::Other && "Not a chain");
Chris Lattner6b307922010-03-02 00:00:03 +00001875 InputChains.push_back(InChain);
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001876 continue;
1877 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001878
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001879 // If we have a token factor, we want to add all inputs of the token factor
1880 // that are not part of the pattern we're matching.
1881 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1882 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
Chris Lattner6183fbd2010-03-02 02:37:23 +00001883 N->getOperand(op).getNode()))
1884 InputChains.push_back(N->getOperand(op));
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001885 }
Chris Lattner6b307922010-03-02 00:00:03 +00001886 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001887
Chris Lattner6b307922010-03-02 00:00:03 +00001888 SDValue Res;
1889 if (InputChains.size() == 1)
1890 return InputChains[0];
Andrew Trickac6d9be2013-05-25 02:42:55 +00001891 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
Chris Lattner6b307922010-03-02 00:00:03 +00001892 MVT::Other, &InputChains[0], InputChains.size());
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001893}
Chris Lattner2a49d572010-02-28 22:37:22 +00001894
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001895/// MorphNode - Handle morphing a node in place for the selector.
1896SDNode *SelectionDAGISel::
1897MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1898 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1899 // It is possible we're using MorphNodeTo to replace a node with no
1900 // normal results with one that has a normal result (or we could be
Chris Lattnera4359be2010-12-23 17:13:18 +00001901 // adding a chain) and the input could have glue and chains as well.
Chris Lattnercaa88702010-03-28 08:43:23 +00001902 // In this case we need to shift the operands down.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001903 // FIXME: This is a horrible hack and broken in obscure cases, no worse
Chris Lattnera6f86932010-03-27 18:54:50 +00001904 // than the old isel though.
Chris Lattnera4359be2010-12-23 17:13:18 +00001905 int OldGlueResultNo = -1, OldChainResultNo = -1;
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001906
1907 unsigned NTMNumResults = Node->getNumValues();
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00001908 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
Chris Lattnera4359be2010-12-23 17:13:18 +00001909 OldGlueResultNo = NTMNumResults-1;
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001910 if (NTMNumResults != 1 &&
1911 Node->getValueType(NTMNumResults-2) == MVT::Other)
1912 OldChainResultNo = NTMNumResults-2;
1913 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1914 OldChainResultNo = NTMNumResults-1;
1915
Chris Lattner61c97f62010-03-02 07:14:49 +00001916 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1917 // that this deletes operands of the old node that become dead.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001918 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1919
1920 // MorphNodeTo can operate in two ways: if an existing node with the
1921 // specified operands exists, it can just return it. Otherwise, it
1922 // updates the node in place to have the requested operands.
1923 if (Res == Node) {
1924 // If we updated the node in place, reset the node ID. To the isel,
1925 // this should be just like a newly allocated machine node.
1926 Res->setNodeId(-1);
1927 }
1928
1929 unsigned ResNumResults = Res->getNumValues();
Chris Lattnera4359be2010-12-23 17:13:18 +00001930 // Move the glue if needed.
1931 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1932 (unsigned)OldGlueResultNo != ResNumResults-1)
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001933 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001934 SDValue(Res, ResNumResults-1));
1935
Chris Lattnera4359be2010-12-23 17:13:18 +00001936 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
Bill Wendlingd9cb7ca2010-07-04 08:58:43 +00001937 --ResNumResults;
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001938
1939 // Move the chain reference if needed.
1940 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1941 (unsigned)OldChainResultNo != ResNumResults-1)
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001942 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001943 SDValue(Res, ResNumResults-1));
1944
1945 // Otherwise, no replacement happened because the node already exists. Replace
1946 // Uses of the old node with the new one.
1947 if (Res != Node)
1948 CurDAG->ReplaceAllUsesWith(Node, Res);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001949
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001950 return Res;
1951}
1952
Craig Topper1d2b45f2012-09-16 16:48:25 +00001953/// CheckSame - Implements OP_CheckSame.
Chandler Carruth19e57022010-10-23 08:40:19 +00001954LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001955CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Chris Lattnerd847bc22010-09-21 22:00:25 +00001956 SDValue N,
1957 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
Chris Lattnerda828e32010-03-03 07:46:25 +00001958 // Accept if it is exactly the same as a previously recorded node.
1959 unsigned RecNo = MatcherTable[MatcherIndex++];
1960 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00001961 return N == RecordedNodes[RecNo].first;
Chris Lattnerda828e32010-03-03 07:46:25 +00001962}
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001963
Chris Lattnerda828e32010-03-03 07:46:25 +00001964/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
Chandler Carruth19e57022010-10-23 08:40:19 +00001965LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001966CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Jakub Staszak39379c52012-04-30 23:41:30 +00001967 const SelectionDAGISel &SDISel) {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001968 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1969}
1970
1971/// CheckNodePredicate - Implements OP_CheckNodePredicate.
Chandler Carruth19e57022010-10-23 08:40:19 +00001972LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001973CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Jakub Staszak39379c52012-04-30 23:41:30 +00001974 const SelectionDAGISel &SDISel, SDNode *N) {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001975 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1976}
1977
Chandler Carruth19e57022010-10-23 08:40:19 +00001978LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001979CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1980 SDNode *N) {
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00001981 uint16_t Opc = MatcherTable[MatcherIndex++];
1982 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1983 return N->getOpcode() == Opc;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001984}
1985
Chandler Carruth19e57022010-10-23 08:40:19 +00001986LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001987CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00001988 SDValue N, const TargetLowering *TLI) {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001989 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1990 if (N.getValueType() == VT) return true;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00001991
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001992 // Handle the case when VT is iPTR.
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00001993 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001994}
1995
Chandler Carruth19e57022010-10-23 08:40:19 +00001996LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001997CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00001998 SDValue N, const TargetLowering *TLI,
Chris Lattnerda828e32010-03-03 07:46:25 +00001999 unsigned ChildNo) {
2000 if (ChildNo >= N.getNumOperands())
2001 return false; // Match fails if out of range child #.
2002 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2003}
2004
Chandler Carruth19e57022010-10-23 08:40:19 +00002005LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00002006CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2007 SDValue N) {
2008 return cast<CondCodeSDNode>(N)->get() ==
2009 (ISD::CondCode)MatcherTable[MatcherIndex++];
2010}
2011
Chandler Carruth19e57022010-10-23 08:40:19 +00002012LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00002013CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00002014 SDValue N, const TargetLowering *TLI) {
Chris Lattnerda828e32010-03-03 07:46:25 +00002015 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2016 if (cast<VTSDNode>(N)->getVT() == VT)
2017 return true;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002018
Chris Lattnerda828e32010-03-03 07:46:25 +00002019 // Handle the case when VT is iPTR.
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00002020 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
Chris Lattnerda828e32010-03-03 07:46:25 +00002021}
2022
Chandler Carruth19e57022010-10-23 08:40:19 +00002023LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002024CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2025 SDValue N) {
2026 int64_t Val = MatcherTable[MatcherIndex++];
2027 if (Val & 128)
2028 Val = GetVBR(Val, MatcherTable, MatcherIndex);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002029
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002030 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2031 return C != 0 && C->getSExtValue() == Val;
2032}
2033
Chandler Carruth19e57022010-10-23 08:40:19 +00002034LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00002035CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Jakub Staszak39379c52012-04-30 23:41:30 +00002036 SDValue N, const SelectionDAGISel &SDISel) {
Chris Lattnerda828e32010-03-03 07:46:25 +00002037 int64_t Val = MatcherTable[MatcherIndex++];
2038 if (Val & 128)
2039 Val = GetVBR(Val, MatcherTable, MatcherIndex);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002040
Chris Lattnerda828e32010-03-03 07:46:25 +00002041 if (N->getOpcode() != ISD::AND) return false;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002042
Chris Lattnerda828e32010-03-03 07:46:25 +00002043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2044 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2045}
2046
Chandler Carruth19e57022010-10-23 08:40:19 +00002047LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00002048CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Jakub Staszak39379c52012-04-30 23:41:30 +00002049 SDValue N, const SelectionDAGISel &SDISel) {
Chris Lattnerda828e32010-03-03 07:46:25 +00002050 int64_t Val = MatcherTable[MatcherIndex++];
2051 if (Val & 128)
2052 Val = GetVBR(Val, MatcherTable, MatcherIndex);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002053
Chris Lattnerda828e32010-03-03 07:46:25 +00002054 if (N->getOpcode() != ISD::OR) return false;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002055
Chris Lattnerda828e32010-03-03 07:46:25 +00002056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2057 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2058}
2059
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002060/// IsPredicateKnownToFail - If we know how and can do so without pushing a
2061/// scope, evaluate the current node. If the current predicate is known to
2062/// fail, set Result=true and return anything. If the current predicate is
2063/// known to pass, set Result=false and return the MatcherIndex to continue
2064/// with. If the current predicate is unknown, set Result=false and return the
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002065/// MatcherIndex to continue with.
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002066static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2067 unsigned Index, SDValue N,
Jakub Staszak39379c52012-04-30 23:41:30 +00002068 bool &Result,
2069 const SelectionDAGISel &SDISel,
Chris Lattnerd847bc22010-09-21 22:00:25 +00002070 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002071 switch (Table[Index++]) {
2072 default:
2073 Result = false;
2074 return Index-1; // Could not evaluate this predicate.
Chris Lattnerda828e32010-03-03 07:46:25 +00002075 case SelectionDAGISel::OPC_CheckSame:
2076 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2077 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002078 case SelectionDAGISel::OPC_CheckPatternPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00002079 Result = !::CheckPatternPredicate(Table, Index, SDISel);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002080 return Index;
2081 case SelectionDAGISel::OPC_CheckPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00002082 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002083 return Index;
2084 case SelectionDAGISel::OPC_CheckOpcode:
2085 Result = !::CheckOpcode(Table, Index, N.getNode());
2086 return Index;
2087 case SelectionDAGISel::OPC_CheckType:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002088 Result = !::CheckType(Table, Index, N, SDISel.getTargetLowering());
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002089 return Index;
2090 case SelectionDAGISel::OPC_CheckChild0Type:
2091 case SelectionDAGISel::OPC_CheckChild1Type:
2092 case SelectionDAGISel::OPC_CheckChild2Type:
2093 case SelectionDAGISel::OPC_CheckChild3Type:
2094 case SelectionDAGISel::OPC_CheckChild4Type:
2095 case SelectionDAGISel::OPC_CheckChild5Type:
2096 case SelectionDAGISel::OPC_CheckChild6Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00002097 case SelectionDAGISel::OPC_CheckChild7Type:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002098 Result = !::CheckChildType(Table, Index, N, SDISel.getTargetLowering(),
Chris Lattnerda828e32010-03-03 07:46:25 +00002099 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002100 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00002101 case SelectionDAGISel::OPC_CheckCondCode:
2102 Result = !::CheckCondCode(Table, Index, N);
2103 return Index;
2104 case SelectionDAGISel::OPC_CheckValueType:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002105 Result = !::CheckValueType(Table, Index, N, SDISel.getTargetLowering());
Chris Lattnerda828e32010-03-03 07:46:25 +00002106 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002107 case SelectionDAGISel::OPC_CheckInteger:
2108 Result = !::CheckInteger(Table, Index, N);
2109 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00002110 case SelectionDAGISel::OPC_CheckAndImm:
2111 Result = !::CheckAndImm(Table, Index, N, SDISel);
2112 return Index;
2113 case SelectionDAGISel::OPC_CheckOrImm:
2114 Result = !::CheckOrImm(Table, Index, N, SDISel);
2115 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002116 }
2117}
2118
Dan Gohmanb3579832010-04-15 17:08:50 +00002119namespace {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00002120
Chris Lattner2a49d572010-02-28 22:37:22 +00002121struct MatchScope {
2122 /// FailIndex - If this match fails, this is the index to continue with.
2123 unsigned FailIndex;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002124
Chris Lattner2a49d572010-02-28 22:37:22 +00002125 /// NodeStack - The node stack when the scope was formed.
2126 SmallVector<SDValue, 4> NodeStack;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002127
Chris Lattner2a49d572010-02-28 22:37:22 +00002128 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2129 unsigned NumRecordedNodes;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002130
Chris Lattner2a49d572010-02-28 22:37:22 +00002131 /// NumMatchedMemRefs - The number of matched memref entries.
2132 unsigned NumMatchedMemRefs;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002133
2134 /// InputChain/InputGlue - The current chain/glue
Chris Lattnera4359be2010-12-23 17:13:18 +00002135 SDValue InputChain, InputGlue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002136
2137 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
Chris Lattnera4359be2010-12-23 17:13:18 +00002138 bool HasChainNodesMatched, HasGlueResultNodesMatched;
Chris Lattner2a49d572010-02-28 22:37:22 +00002139};
2140
Dan Gohmanb3579832010-04-15 17:08:50 +00002141}
2142
Chris Lattner2a49d572010-02-28 22:37:22 +00002143SDNode *SelectionDAGISel::
2144SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2145 unsigned TableSize) {
2146 // FIXME: Should these even be selected? Handle these cases in the caller?
2147 switch (NodeToMatch->getOpcode()) {
2148 default:
2149 break;
2150 case ISD::EntryToken: // These nodes remain the same.
2151 case ISD::BasicBlock:
2152 case ISD::Register:
Jakob Stoklund Olesen9cf37e82012-01-18 23:52:12 +00002153 case ISD::RegisterMask:
Chris Lattner3b9d6212010-03-14 17:53:23 +00002154 //case ISD::VALUETYPE:
2155 //case ISD::CONDCODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00002156 case ISD::HANDLENODE:
Chris Lattnerdecc2672010-04-07 05:20:54 +00002157 case ISD::MDNODE_SDNODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00002158 case ISD::TargetConstant:
2159 case ISD::TargetConstantFP:
2160 case ISD::TargetConstantPool:
2161 case ISD::TargetFrameIndex:
2162 case ISD::TargetExternalSymbol:
2163 case ISD::TargetBlockAddress:
2164 case ISD::TargetJumpTable:
2165 case ISD::TargetGlobalTLSAddress:
2166 case ISD::TargetGlobalAddress:
2167 case ISD::TokenFactor:
2168 case ISD::CopyFromReg:
2169 case ISD::CopyToReg:
Chris Lattner7561d482010-03-14 02:33:54 +00002170 case ISD::EH_LABEL:
Nadav Rotemc05d3062012-09-06 09:17:37 +00002171 case ISD::LIFETIME_START:
2172 case ISD::LIFETIME_END:
Chris Lattnerd1b73822010-03-02 22:20:06 +00002173 NodeToMatch->setNodeId(-1); // Mark selected.
Chris Lattner2a49d572010-02-28 22:37:22 +00002174 return 0;
2175 case ISD::AssertSext:
2176 case ISD::AssertZext:
2177 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2178 NodeToMatch->getOperand(0));
2179 return 0;
2180 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
Chris Lattner2a49d572010-02-28 22:37:22 +00002181 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2182 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002183
Chris Lattner2a49d572010-02-28 22:37:22 +00002184 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2185
2186 // Set up the node stack with NodeToMatch as the only node on the stack.
2187 SmallVector<SDValue, 8> NodeStack;
2188 SDValue N = SDValue(NodeToMatch, 0);
2189 NodeStack.push_back(N);
2190
2191 // MatchScopes - Scopes used when matching, if a match failure happens, this
2192 // indicates where to continue checking.
2193 SmallVector<MatchScope, 8> MatchScopes;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002194
Chris Lattner2a49d572010-02-28 22:37:22 +00002195 // RecordedNodes - This is the set of nodes that have been recorded by the
Chris Lattnerd847bc22010-09-21 22:00:25 +00002196 // state machine. The second value is the parent of the node, or null if the
2197 // root is recorded.
2198 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002199
Chris Lattner2a49d572010-02-28 22:37:22 +00002200 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2201 // pattern.
2202 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002203
Chris Lattnera4359be2010-12-23 17:13:18 +00002204 // These are the current input chain and glue for use when generating nodes.
Chris Lattner2a49d572010-02-28 22:37:22 +00002205 // Various Emit operations change these. For example, emitting a copytoreg
2206 // uses and updates these.
Chris Lattnera4359be2010-12-23 17:13:18 +00002207 SDValue InputChain, InputGlue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002208
Chris Lattner2a49d572010-02-28 22:37:22 +00002209 // ChainNodesMatched - If a pattern matches nodes that have input/output
2210 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2211 // which ones they are. The result is captured into this list so that we can
2212 // update the chain results when the pattern is complete.
2213 SmallVector<SDNode*, 3> ChainNodesMatched;
Chris Lattnera4359be2010-12-23 17:13:18 +00002214 SmallVector<SDNode*, 3> GlueResultNodesMatched;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002215
Eli Bendersky03494e02013-04-19 21:37:07 +00002216 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
Chris Lattner2a49d572010-02-28 22:37:22 +00002217 NodeToMatch->dump(CurDAG);
Eli Bendersky03494e02013-04-19 21:37:07 +00002218 dbgs() << '\n');
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002219
Chris Lattner7390eeb2010-03-01 18:47:11 +00002220 // Determine where to start the interpreter. Normally we start at opcode #0,
2221 // but if the state machine starts with an OPC_SwitchOpcode, then we
2222 // accelerate the first lookup (which is guaranteed to be hot) with the
2223 // OpcodeOffset table.
Chris Lattner2a49d572010-02-28 22:37:22 +00002224 unsigned MatcherIndex = 0;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002225
Chris Lattner7390eeb2010-03-01 18:47:11 +00002226 if (!OpcodeOffset.empty()) {
2227 // Already computed the OpcodeOffset table, just index into it.
2228 if (N.getOpcode() < OpcodeOffset.size())
2229 MatcherIndex = OpcodeOffset[N.getOpcode()];
Eli Bendersky03494e02013-04-19 21:37:07 +00002230 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
Chris Lattner7390eeb2010-03-01 18:47:11 +00002231
2232 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2233 // Otherwise, the table isn't computed, but the state machine does start
2234 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2235 // is the first time we're selecting an instruction.
2236 unsigned Idx = 1;
2237 while (1) {
2238 // Get the size of this case.
2239 unsigned CaseSize = MatcherTable[Idx++];
2240 if (CaseSize & 128)
2241 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2242 if (CaseSize == 0) break;
2243
2244 // Get the opcode, add the index to the table.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002245 uint16_t Opc = MatcherTable[Idx++];
2246 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
Chris Lattner7390eeb2010-03-01 18:47:11 +00002247 if (Opc >= OpcodeOffset.size())
2248 OpcodeOffset.resize((Opc+1)*2);
2249 OpcodeOffset[Opc] = Idx;
2250 Idx += CaseSize;
2251 }
2252
2253 // Okay, do the lookup for the first opcode.
2254 if (N.getOpcode() < OpcodeOffset.size())
2255 MatcherIndex = OpcodeOffset[N.getOpcode()];
2256 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002257
Chris Lattner2a49d572010-02-28 22:37:22 +00002258 while (1) {
2259 assert(MatcherIndex < TableSize && "Invalid index");
Dan Gohman19b38262010-03-09 02:15:05 +00002260#ifndef NDEBUG
2261 unsigned CurrentOpcodeIndex = MatcherIndex;
2262#endif
Chris Lattner2a49d572010-02-28 22:37:22 +00002263 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2264 switch (Opcode) {
2265 case OPC_Scope: {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002266 // Okay, the semantics of this operation are that we should push a scope
2267 // then evaluate the first child. However, pushing a scope only to have
2268 // the first check fail (which then pops it) is inefficient. If we can
2269 // determine immediately that the first check (or first several) will
2270 // immediately fail, don't even bother pushing a scope for them.
2271 unsigned FailIndex;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002272
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002273 while (1) {
2274 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2275 if (NumToSkip & 128)
2276 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2277 // Found the end of the scope with no match.
2278 if (NumToSkip == 0) {
2279 FailIndex = 0;
2280 break;
2281 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002282
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002283 FailIndex = MatcherIndex+NumToSkip;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002284
Chris Lattnera6f86932010-03-27 18:54:50 +00002285 unsigned MatcherIndexOfPredicate = MatcherIndex;
2286 (void)MatcherIndexOfPredicate; // silence warning.
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002287
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002288 // If we can't evaluate this predicate without pushing a scope (e.g. if
2289 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2290 // push the scope and evaluate the full predicate chain.
2291 bool Result;
2292 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
Chris Lattnerda828e32010-03-03 07:46:25 +00002293 Result, *this, RecordedNodes);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002294 if (!Result)
2295 break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002296
Eli Bendersky03494e02013-04-19 21:37:07 +00002297 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
Chris Lattnera6f86932010-03-27 18:54:50 +00002298 << "index " << MatcherIndexOfPredicate
2299 << ", continuing at " << FailIndex << "\n");
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00002300 ++NumDAGIselRetries;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002301
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002302 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2303 // move to the next case.
2304 MatcherIndex = FailIndex;
2305 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002306
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002307 // If the whole scope failed to match, bail.
2308 if (FailIndex == 0) break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002309
Chris Lattner2a49d572010-02-28 22:37:22 +00002310 // Push a MatchScope which indicates where to go if the first child fails
2311 // to match.
2312 MatchScope NewEntry;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002313 NewEntry.FailIndex = FailIndex;
Chris Lattner2a49d572010-02-28 22:37:22 +00002314 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2315 NewEntry.NumRecordedNodes = RecordedNodes.size();
2316 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2317 NewEntry.InputChain = InputChain;
Chris Lattnera4359be2010-12-23 17:13:18 +00002318 NewEntry.InputGlue = InputGlue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002319 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
Chris Lattnera4359be2010-12-23 17:13:18 +00002320 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
Chris Lattner2a49d572010-02-28 22:37:22 +00002321 MatchScopes.push_back(NewEntry);
2322 continue;
2323 }
Chris Lattnerd847bc22010-09-21 22:00:25 +00002324 case OPC_RecordNode: {
Chris Lattner2a49d572010-02-28 22:37:22 +00002325 // Remember this node, it may end up being an operand in the pattern.
Chris Lattnerd847bc22010-09-21 22:00:25 +00002326 SDNode *Parent = 0;
2327 if (NodeStack.size() > 1)
2328 Parent = NodeStack[NodeStack.size()-2].getNode();
2329 RecordedNodes.push_back(std::make_pair(N, Parent));
Chris Lattner2a49d572010-02-28 22:37:22 +00002330 continue;
Chris Lattnerd847bc22010-09-21 22:00:25 +00002331 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002332
Chris Lattner2a49d572010-02-28 22:37:22 +00002333 case OPC_RecordChild0: case OPC_RecordChild1:
2334 case OPC_RecordChild2: case OPC_RecordChild3:
2335 case OPC_RecordChild4: case OPC_RecordChild5:
2336 case OPC_RecordChild6: case OPC_RecordChild7: {
2337 unsigned ChildNo = Opcode-OPC_RecordChild0;
2338 if (ChildNo >= N.getNumOperands())
2339 break; // Match fails if out of range child #.
2340
Chris Lattnerd847bc22010-09-21 22:00:25 +00002341 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2342 N.getNode()));
Chris Lattner2a49d572010-02-28 22:37:22 +00002343 continue;
2344 }
2345 case OPC_RecordMemRef:
2346 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2347 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002348
Chris Lattner29d8f0c2010-12-23 17:24:32 +00002349 case OPC_CaptureGlueInput:
Chris Lattnera4359be2010-12-23 17:13:18 +00002350 // If the current node has an input glue, capture it in InputGlue.
Chris Lattner2a49d572010-02-28 22:37:22 +00002351 if (N->getNumOperands() != 0 &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002352 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
Chris Lattnera4359be2010-12-23 17:13:18 +00002353 InputGlue = N->getOperand(N->getNumOperands()-1);
Chris Lattner2a49d572010-02-28 22:37:22 +00002354 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002355
Chris Lattner2a49d572010-02-28 22:37:22 +00002356 case OPC_MoveChild: {
2357 unsigned ChildNo = MatcherTable[MatcherIndex++];
2358 if (ChildNo >= N.getNumOperands())
2359 break; // Match fails if out of range child #.
2360 N = N.getOperand(ChildNo);
2361 NodeStack.push_back(N);
2362 continue;
2363 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002364
Chris Lattner2a49d572010-02-28 22:37:22 +00002365 case OPC_MoveParent:
2366 // Pop the current node off the NodeStack.
2367 NodeStack.pop_back();
2368 assert(!NodeStack.empty() && "Node stack imbalance!");
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002369 N = NodeStack.back();
Chris Lattner2a49d572010-02-28 22:37:22 +00002370 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002371
Chris Lattnerda828e32010-03-03 07:46:25 +00002372 case OPC_CheckSame:
2373 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002374 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002375 case OPC_CheckPatternPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002376 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002377 continue;
2378 case OPC_CheckPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002379 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2380 N.getNode()))
2381 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002382 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002383 case OPC_CheckComplexPat: {
2384 unsigned CPNum = MatcherTable[MatcherIndex++];
2385 unsigned RecNo = MatcherTable[MatcherIndex++];
2386 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002387 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2388 RecordedNodes[RecNo].first, CPNum,
Chris Lattner57bf8a42010-03-04 01:23:08 +00002389 RecordedNodes))
Chris Lattner2a49d572010-02-28 22:37:22 +00002390 break;
2391 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002392 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002393 case OPC_CheckOpcode:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002394 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2395 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002396
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002397 case OPC_CheckType:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002398 if (!::CheckType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2399 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002400 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002401
Chris Lattnereb669212010-03-01 06:59:22 +00002402 case OPC_SwitchOpcode: {
2403 unsigned CurNodeOpcode = N.getOpcode();
Chris Lattner7d892d62010-03-01 07:43:08 +00002404 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
Chris Lattnereb669212010-03-01 06:59:22 +00002405 unsigned CaseSize;
2406 while (1) {
2407 // Get the size of this case.
2408 CaseSize = MatcherTable[MatcherIndex++];
2409 if (CaseSize & 128)
2410 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2411 if (CaseSize == 0) break;
2412
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002413 uint16_t Opc = MatcherTable[MatcherIndex++];
2414 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2415
Chris Lattnereb669212010-03-01 06:59:22 +00002416 // If the opcode matches, then we will execute this case.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002417 if (CurNodeOpcode == Opc)
Chris Lattnereb669212010-03-01 06:59:22 +00002418 break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002419
Chris Lattnereb669212010-03-01 06:59:22 +00002420 // Otherwise, skip over this case.
2421 MatcherIndex += CaseSize;
2422 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002423
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002424 // If no cases matched, bail out.
Chris Lattnereb669212010-03-01 06:59:22 +00002425 if (CaseSize == 0) break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002426
Chris Lattnereb669212010-03-01 06:59:22 +00002427 // Otherwise, execute the case we found.
Eli Bendersky03494e02013-04-19 21:37:07 +00002428 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
Chris Lattnereb669212010-03-01 06:59:22 +00002429 << " to " << MatcherIndex << "\n");
2430 continue;
2431 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002432
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002433 case OPC_SwitchType: {
Duncan Sandscdfad362010-11-03 12:17:33 +00002434 MVT CurNodeVT = N.getValueType().getSimpleVT();
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002435 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2436 unsigned CaseSize;
2437 while (1) {
2438 // Get the size of this case.
2439 CaseSize = MatcherTable[MatcherIndex++];
2440 if (CaseSize & 128)
2441 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2442 if (CaseSize == 0) break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002443
Duncan Sandscdfad362010-11-03 12:17:33 +00002444 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002445 if (CaseVT == MVT::iPTR)
Bill Wendlingba54bca2013-06-19 21:36:55 +00002446 CaseVT = getTargetLowering()->getPointerTy();
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002447
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002448 // If the VT matches, then we will execute this case.
2449 if (CurNodeVT == CaseVT)
2450 break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002451
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002452 // Otherwise, skip over this case.
2453 MatcherIndex += CaseSize;
2454 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002455
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002456 // If no cases matched, bail out.
2457 if (CaseSize == 0) break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002458
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002459 // Otherwise, execute the case we found.
Eli Bendersky03494e02013-04-19 21:37:07 +00002460 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002461 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2462 continue;
2463 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002464 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2465 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2466 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00002467 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002468 if (!::CheckChildType(MatcherTable, MatcherIndex, N, getTargetLowering(),
Chris Lattnerda828e32010-03-03 07:46:25 +00002469 Opcode-OPC_CheckChild0Type))
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002470 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002471 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002472 case OPC_CheckCondCode:
Chris Lattnerda828e32010-03-03 07:46:25 +00002473 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002474 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002475 case OPC_CheckValueType:
Bill Wendlingba54bca2013-06-19 21:36:55 +00002476 if (!::CheckValueType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2477 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002478 continue;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002479 case OPC_CheckInteger:
2480 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002481 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002482 case OPC_CheckAndImm:
2483 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002484 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002485 case OPC_CheckOrImm:
2486 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002487 continue;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002488
Chris Lattner2a49d572010-02-28 22:37:22 +00002489 case OPC_CheckFoldableChainNode: {
2490 assert(NodeStack.size() != 1 && "No parent node");
2491 // Verify that all intermediate nodes between the root and this one have
2492 // a single use.
2493 bool HasMultipleUses = false;
2494 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2495 if (!NodeStack[i].hasOneUse()) {
2496 HasMultipleUses = true;
2497 break;
2498 }
2499 if (HasMultipleUses) break;
2500
2501 // Check to see that the target thinks this is profitable to fold and that
2502 // we can fold it without inducing cycles in the graph.
2503 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2504 NodeToMatch) ||
2505 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
Dan Gohmand858e902010-04-17 15:26:15 +00002506 NodeToMatch, OptLevel,
2507 true/*We validate our own chains*/))
Chris Lattner2a49d572010-02-28 22:37:22 +00002508 break;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002509
Chris Lattner2a49d572010-02-28 22:37:22 +00002510 continue;
2511 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002512 case OPC_EmitInteger: {
2513 MVT::SimpleValueType VT =
2514 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2515 int64_t Val = MatcherTable[MatcherIndex++];
2516 if (Val & 128)
2517 Val = GetVBR(Val, MatcherTable, MatcherIndex);
Chris Lattnerd847bc22010-09-21 22:00:25 +00002518 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002519 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002520 continue;
2521 }
2522 case OPC_EmitRegister: {
2523 MVT::SimpleValueType VT =
2524 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2525 unsigned RegNo = MatcherTable[MatcherIndex++];
Chris Lattnerd847bc22010-09-21 22:00:25 +00002526 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002527 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002528 continue;
2529 }
Jim Grosbach2d76c842011-03-01 01:37:19 +00002530 case OPC_EmitRegister2: {
2531 // For targets w/ more than 256 register names, the register enum
2532 // values are stored in two bytes in the matcher table (just like
2533 // opcodes).
2534 MVT::SimpleValueType VT =
2535 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2536 unsigned RegNo = MatcherTable[MatcherIndex++];
2537 RegNo |= MatcherTable[MatcherIndex++] << 8;
2538 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2539 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2540 continue;
2541 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002542
Chris Lattner2a49d572010-02-28 22:37:22 +00002543 case OPC_EmitConvertToTarget: {
2544 // Convert from IMM/FPIMM to target version.
2545 unsigned RecNo = MatcherTable[MatcherIndex++];
2546 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002547 SDValue Imm = RecordedNodes[RecNo].first;
Chris Lattner2a49d572010-02-28 22:37:22 +00002548
2549 if (Imm->getOpcode() == ISD::Constant) {
Nadav Rotem4d895452013-03-07 06:34:49 +00002550 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
2551 Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
Chris Lattner2a49d572010-02-28 22:37:22 +00002552 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2553 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
Nadav Rotem4d895452013-03-07 06:34:49 +00002554 Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
Chris Lattner2a49d572010-02-28 22:37:22 +00002555 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002556
Chris Lattnerd847bc22010-09-21 22:00:25 +00002557 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
Chris Lattner2a49d572010-02-28 22:37:22 +00002558 continue;
2559 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002560
Chris Lattneraa4e3392010-03-28 05:50:16 +00002561 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2562 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2563 // These are space-optimized forms of OPC_EmitMergeInputChains.
2564 assert(InputChain.getNode() == 0 &&
2565 "EmitMergeInputChains should be the first chain producing node");
2566 assert(ChainNodesMatched.empty() &&
2567 "Should only have one EmitMergeInputChains per match");
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002568
Chris Lattneraa4e3392010-03-28 05:50:16 +00002569 // Read all of the chained nodes.
2570 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2571 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002572 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002573
Chris Lattneraa4e3392010-03-28 05:50:16 +00002574 // FIXME: What if other value results of the node have uses not matched
2575 // by this pattern?
2576 if (ChainNodesMatched.back() != NodeToMatch &&
Chris Lattnerd847bc22010-09-21 22:00:25 +00002577 !RecordedNodes[RecNo].first.hasOneUse()) {
Chris Lattneraa4e3392010-03-28 05:50:16 +00002578 ChainNodesMatched.clear();
2579 break;
2580 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002581
Chris Lattneraa4e3392010-03-28 05:50:16 +00002582 // Merge the input chains if they are not intra-pattern references.
2583 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002584
Chris Lattneraa4e3392010-03-28 05:50:16 +00002585 if (InputChain.getNode() == 0)
2586 break; // Failed to merge.
2587 continue;
2588 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002589
Chris Lattner2a49d572010-02-28 22:37:22 +00002590 case OPC_EmitMergeInputChains: {
2591 assert(InputChain.getNode() == 0 &&
2592 "EmitMergeInputChains should be the first chain producing node");
2593 // This node gets a list of nodes we matched in the input that have
2594 // chains. We want to token factor all of the input chains to these nodes
2595 // together. However, if any of the input chains is actually one of the
2596 // nodes matched in this pattern, then we have an intra-match reference.
2597 // Ignore these because the newly token factored chain should not refer to
2598 // the old nodes.
2599 unsigned NumChains = MatcherTable[MatcherIndex++];
2600 assert(NumChains != 0 && "Can't TF zero chains");
2601
2602 assert(ChainNodesMatched.empty() &&
2603 "Should only have one EmitMergeInputChains per match");
2604
Chris Lattner2a49d572010-02-28 22:37:22 +00002605 // Read all of the chained nodes.
Chris Lattner00592ec2010-03-02 19:34:59 +00002606 for (unsigned i = 0; i != NumChains; ++i) {
2607 unsigned RecNo = MatcherTable[MatcherIndex++];
Chris Lattner2a49d572010-02-28 22:37:22 +00002608 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002609 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002610
Chris Lattner2a49d572010-02-28 22:37:22 +00002611 // FIXME: What if other value results of the node have uses not matched
2612 // by this pattern?
2613 if (ChainNodesMatched.back() != NodeToMatch &&
Chris Lattnerd847bc22010-09-21 22:00:25 +00002614 !RecordedNodes[RecNo].first.hasOneUse()) {
Chris Lattner2a49d572010-02-28 22:37:22 +00002615 ChainNodesMatched.clear();
2616 break;
2617 }
2618 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002619
Chris Lattner6b307922010-03-02 00:00:03 +00002620 // If the inner loop broke out, the match fails.
2621 if (ChainNodesMatched.empty())
2622 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002623
Chris Lattner6b307922010-03-02 00:00:03 +00002624 // Merge the input chains if they are not intra-pattern references.
2625 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002626
Chris Lattner6b307922010-03-02 00:00:03 +00002627 if (InputChain.getNode() == 0)
2628 break; // Failed to merge.
Chris Lattner2a49d572010-02-28 22:37:22 +00002629
Chris Lattner2a49d572010-02-28 22:37:22 +00002630 continue;
2631 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002632
Chris Lattner2a49d572010-02-28 22:37:22 +00002633 case OPC_EmitCopyToReg: {
2634 unsigned RecNo = MatcherTable[MatcherIndex++];
2635 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2636 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002637
Chris Lattner2a49d572010-02-28 22:37:22 +00002638 if (InputChain.getNode() == 0)
2639 InputChain = CurDAG->getEntryNode();
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002640
Andrew Trickac6d9be2013-05-25 02:42:55 +00002641 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
Chris Lattnerd847bc22010-09-21 22:00:25 +00002642 DestPhysReg, RecordedNodes[RecNo].first,
Chris Lattnera4359be2010-12-23 17:13:18 +00002643 InputGlue);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002644
Chris Lattnera4359be2010-12-23 17:13:18 +00002645 InputGlue = InputChain.getValue(1);
Chris Lattner2a49d572010-02-28 22:37:22 +00002646 continue;
2647 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002648
Chris Lattner2a49d572010-02-28 22:37:22 +00002649 case OPC_EmitNodeXForm: {
2650 unsigned XFormNo = MatcherTable[MatcherIndex++];
2651 unsigned RecNo = MatcherTable[MatcherIndex++];
2652 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002653 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002654 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002655 continue;
2656 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002657
Chris Lattner2a49d572010-02-28 22:37:22 +00002658 case OPC_EmitNode:
2659 case OPC_MorphNodeTo: {
Chris Lattner14df8dc2010-02-28 22:38:43 +00002660 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2661 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
Chris Lattner2a49d572010-02-28 22:37:22 +00002662 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2663 // Get the result VT list.
2664 unsigned NumVTs = MatcherTable[MatcherIndex++];
2665 SmallVector<EVT, 4> VTs;
2666 for (unsigned i = 0; i != NumVTs; ++i) {
2667 MVT::SimpleValueType VT =
2668 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
Bill Wendlingba54bca2013-06-19 21:36:55 +00002669 if (VT == MVT::iPTR) VT = getTargetLowering()->getPointerTy().SimpleTy;
Chris Lattner2a49d572010-02-28 22:37:22 +00002670 VTs.push_back(VT);
2671 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002672
Chris Lattner2a49d572010-02-28 22:37:22 +00002673 if (EmitNodeInfo & OPFL_Chain)
2674 VTs.push_back(MVT::Other);
Chris Lattnera4359be2010-12-23 17:13:18 +00002675 if (EmitNodeInfo & OPFL_GlueOutput)
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002676 VTs.push_back(MVT::Glue);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002677
Chris Lattner7d892d62010-03-01 07:43:08 +00002678 // This is hot code, so optimize the two most common cases of 1 and 2
2679 // results.
2680 SDVTList VTList;
2681 if (VTs.size() == 1)
2682 VTList = CurDAG->getVTList(VTs[0]);
2683 else if (VTs.size() == 2)
2684 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2685 else
2686 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
Chris Lattner2a49d572010-02-28 22:37:22 +00002687
2688 // Get the operand list.
2689 unsigned NumOps = MatcherTable[MatcherIndex++];
2690 SmallVector<SDValue, 8> Ops;
2691 for (unsigned i = 0; i != NumOps; ++i) {
2692 unsigned RecNo = MatcherTable[MatcherIndex++];
2693 if (RecNo & 128)
2694 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002695
Chris Lattner2a49d572010-02-28 22:37:22 +00002696 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002697 Ops.push_back(RecordedNodes[RecNo].first);
Chris Lattner2a49d572010-02-28 22:37:22 +00002698 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002699
Chris Lattner2a49d572010-02-28 22:37:22 +00002700 // If there are variadic operands to add, handle them now.
2701 if (EmitNodeInfo & OPFL_VariadicInfo) {
2702 // Determine the start index to copy from.
2703 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2704 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2705 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2706 "Invalid variadic node");
Chris Lattnera4359be2010-12-23 17:13:18 +00002707 // Copy all of the variadic operands, not including a potential glue
Chris Lattner2a49d572010-02-28 22:37:22 +00002708 // input.
2709 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2710 i != e; ++i) {
2711 SDValue V = NodeToMatch->getOperand(i);
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002712 if (V.getValueType() == MVT::Glue) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002713 Ops.push_back(V);
2714 }
2715 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002716
Chris Lattnera4359be2010-12-23 17:13:18 +00002717 // If this has chain/glue inputs, add them.
Chris Lattner2a49d572010-02-28 22:37:22 +00002718 if (EmitNodeInfo & OPFL_Chain)
2719 Ops.push_back(InputChain);
Chris Lattnera4359be2010-12-23 17:13:18 +00002720 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2721 Ops.push_back(InputGlue);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002722
Chris Lattner2a49d572010-02-28 22:37:22 +00002723 // Create the node.
2724 SDNode *Res = 0;
2725 if (Opcode != OPC_MorphNodeTo) {
2726 // If this is a normal EmitNode command, just create the new node and
2727 // add the results to the RecordedNodes list.
Andrew Trickac6d9be2013-05-25 02:42:55 +00002728 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
Michael Liao2a8bea72013-04-19 22:22:57 +00002729 VTList, Ops);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002730
Chris Lattnera4359be2010-12-23 17:13:18 +00002731 // Add all the non-glue/non-chain results to the RecordedNodes list.
Chris Lattner2a49d572010-02-28 22:37:22 +00002732 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002733 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
Chris Lattnerd847bc22010-09-21 22:00:25 +00002734 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002735 (SDNode*) 0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002736 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002737
Jakob Stoklund Olesen0b35c352012-04-20 23:36:09 +00002738 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00002739 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2740 EmitNodeInfo);
Jakob Stoklund Olesen0b35c352012-04-20 23:36:09 +00002741 } else {
2742 // NodeToMatch was eliminated by CSE when the target changed the DAG.
2743 // We will visit the equivalent node later.
2744 DEBUG(dbgs() << "Node was eliminated by CSE\n");
2745 return 0;
Chris Lattner2a49d572010-02-28 22:37:22 +00002746 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002747
Chris Lattnera4359be2010-12-23 17:13:18 +00002748 // If the node had chain/glue results, update our notion of the current
2749 // chain and glue.
2750 if (EmitNodeInfo & OPFL_GlueOutput) {
2751 InputGlue = SDValue(Res, VTs.size()-1);
Chris Lattner2a49d572010-02-28 22:37:22 +00002752 if (EmitNodeInfo & OPFL_Chain)
2753 InputChain = SDValue(Res, VTs.size()-2);
2754 } else if (EmitNodeInfo & OPFL_Chain)
2755 InputChain = SDValue(Res, VTs.size()-1);
2756
Chris Lattnera4359be2010-12-23 17:13:18 +00002757 // If the OPFL_MemRefs glue is set on this node, slap all of the
Chris Lattner2a49d572010-02-28 22:37:22 +00002758 // accumulated memrefs onto it.
2759 //
2760 // FIXME: This is vastly incorrect for patterns with multiple outputs
2761 // instructions that access memory and for ComplexPatterns that match
2762 // loads.
2763 if (EmitNodeInfo & OPFL_MemRefs) {
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002764 // Only attach load or store memory operands if the generated
2765 // instruction may load or store.
Evan Chenge837dea2011-06-28 19:10:37 +00002766 const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
2767 bool mayLoad = MCID.mayLoad();
2768 bool mayStore = MCID.mayStore();
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002769
2770 unsigned NumMemRefs = 0;
Craig Topper32bdf822013-07-03 05:18:47 +00002771 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2772 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002773 if ((*I)->isLoad()) {
2774 if (mayLoad)
2775 ++NumMemRefs;
2776 } else if ((*I)->isStore()) {
2777 if (mayStore)
2778 ++NumMemRefs;
2779 } else {
2780 ++NumMemRefs;
2781 }
2782 }
2783
Chris Lattner2a49d572010-02-28 22:37:22 +00002784 MachineSDNode::mmo_iterator MemRefs =
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002785 MF->allocateMemRefsArray(NumMemRefs);
2786
2787 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
Craig Topper32bdf822013-07-03 05:18:47 +00002788 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2789 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002790 if ((*I)->isLoad()) {
2791 if (mayLoad)
2792 *MemRefsPos++ = *I;
2793 } else if ((*I)->isStore()) {
2794 if (mayStore)
2795 *MemRefsPos++ = *I;
2796 } else {
2797 *MemRefsPos++ = *I;
2798 }
2799 }
2800
Chris Lattner2a49d572010-02-28 22:37:22 +00002801 cast<MachineSDNode>(Res)
Cameron Zwarich5a4b3d82011-05-19 23:44:34 +00002802 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
Chris Lattner2a49d572010-02-28 22:37:22 +00002803 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002804
Eli Bendersky03494e02013-04-19 21:37:07 +00002805 DEBUG(dbgs() << " "
Chris Lattner2a49d572010-02-28 22:37:22 +00002806 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
Eli Bendersky03494e02013-04-19 21:37:07 +00002807 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002808
Chris Lattner2a49d572010-02-28 22:37:22 +00002809 // If this was a MorphNodeTo then we're completely done!
2810 if (Opcode == OPC_MorphNodeTo) {
Chris Lattnera4359be2010-12-23 17:13:18 +00002811 // Update chain and glue uses.
2812 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2813 InputGlue, GlueResultNodesMatched, true);
Chris Lattner82dd3d32010-03-02 07:50:03 +00002814 return Res;
Chris Lattner2a49d572010-02-28 22:37:22 +00002815 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002816
Chris Lattner2a49d572010-02-28 22:37:22 +00002817 continue;
2818 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002819
Chris Lattner29d8f0c2010-12-23 17:24:32 +00002820 case OPC_MarkGlueResults: {
Chris Lattner2a49d572010-02-28 22:37:22 +00002821 unsigned NumNodes = MatcherTable[MatcherIndex++];
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002822
Chris Lattnera4359be2010-12-23 17:13:18 +00002823 // Read and remember all the glue-result nodes.
Chris Lattner2a49d572010-02-28 22:37:22 +00002824 for (unsigned i = 0; i != NumNodes; ++i) {
2825 unsigned RecNo = MatcherTable[MatcherIndex++];
2826 if (RecNo & 128)
2827 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2828
2829 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnera4359be2010-12-23 17:13:18 +00002830 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Chris Lattner2a49d572010-02-28 22:37:22 +00002831 }
2832 continue;
2833 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002834
Chris Lattner2a49d572010-02-28 22:37:22 +00002835 case OPC_CompleteMatch: {
2836 // The match has been completed, and any new nodes (if any) have been
2837 // created. Patch up references to the matched dag to use the newly
2838 // created nodes.
2839 unsigned NumResults = MatcherTable[MatcherIndex++];
2840
2841 for (unsigned i = 0; i != NumResults; ++i) {
2842 unsigned ResSlot = MatcherTable[MatcherIndex++];
2843 if (ResSlot & 128)
2844 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002845
Chris Lattner2a49d572010-02-28 22:37:22 +00002846 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002847 SDValue Res = RecordedNodes[ResSlot].first;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002848
Chris Lattnerb0e483e2010-03-28 05:54:03 +00002849 assert(i < NodeToMatch->getNumValues() &&
2850 NodeToMatch->getValueType(i) != MVT::Other &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002851 NodeToMatch->getValueType(i) != MVT::Glue &&
Chris Lattnerb0e483e2010-03-28 05:54:03 +00002852 "Invalid number of results to complete!");
Chris Lattner2a49d572010-02-28 22:37:22 +00002853 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2854 NodeToMatch->getValueType(i) == MVT::iPTR ||
2855 Res.getValueType() == MVT::iPTR ||
2856 NodeToMatch->getValueType(i).getSizeInBits() ==
2857 Res.getValueType().getSizeInBits()) &&
2858 "invalid replacement");
2859 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2860 }
2861
Chris Lattner29d8f0c2010-12-23 17:24:32 +00002862 // If the root node defines glue, add it to the glue nodes to update list.
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00002863 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
Chris Lattnera4359be2010-12-23 17:13:18 +00002864 GlueResultNodesMatched.push_back(NodeToMatch);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002865
Chris Lattnera4359be2010-12-23 17:13:18 +00002866 // Update chain and glue uses.
2867 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2868 InputGlue, GlueResultNodesMatched, false);
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002869
Chris Lattner2a49d572010-02-28 22:37:22 +00002870 assert(NodeToMatch->use_empty() &&
2871 "Didn't replace all uses of the node?");
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002872
Chris Lattner2a49d572010-02-28 22:37:22 +00002873 // FIXME: We just return here, which interacts correctly with SelectRoot
2874 // above. We should fix this to not return an SDNode* anymore.
2875 return 0;
2876 }
2877 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002878
Chris Lattner2a49d572010-02-28 22:37:22 +00002879 // If the code reached this point, then the match failed. See if there is
2880 // another child to try in the current 'Scope', otherwise pop it until we
2881 // find a case to check.
Eli Bendersky03494e02013-04-19 21:37:07 +00002882 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
Jan Wen Voungfa785cb2013-03-08 22:56:31 +00002883 ++NumDAGIselRetries;
Chris Lattner2a49d572010-02-28 22:37:22 +00002884 while (1) {
2885 if (MatchScopes.empty()) {
2886 CannotYetSelect(NodeToMatch);
2887 return 0;
2888 }
2889
2890 // Restore the interpreter state back to the point where the scope was
2891 // formed.
2892 MatchScope &LastScope = MatchScopes.back();
2893 RecordedNodes.resize(LastScope.NumRecordedNodes);
2894 NodeStack.clear();
2895 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2896 N = NodeStack.back();
2897
Chris Lattner2a49d572010-02-28 22:37:22 +00002898 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2899 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2900 MatcherIndex = LastScope.FailIndex;
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002901
Eli Bendersky03494e02013-04-19 21:37:07 +00002902 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002903
Chris Lattner2a49d572010-02-28 22:37:22 +00002904 InputChain = LastScope.InputChain;
Chris Lattnera4359be2010-12-23 17:13:18 +00002905 InputGlue = LastScope.InputGlue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002906 if (!LastScope.HasChainNodesMatched)
2907 ChainNodesMatched.clear();
Chris Lattnera4359be2010-12-23 17:13:18 +00002908 if (!LastScope.HasGlueResultNodesMatched)
2909 GlueResultNodesMatched.clear();
Chris Lattner2a49d572010-02-28 22:37:22 +00002910
2911 // Check to see what the offset is at the new MatcherIndex. If it is zero
2912 // we have reached the end of this scope, otherwise we have another child
2913 // in the current scope to try.
2914 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2915 if (NumToSkip & 128)
2916 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2917
2918 // If we have another child in this scope to match, update FailIndex and
2919 // try it.
2920 if (NumToSkip != 0) {
2921 LastScope.FailIndex = MatcherIndex+NumToSkip;
2922 break;
2923 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002924
Chris Lattner2a49d572010-02-28 22:37:22 +00002925 // End of this scope, pop it and try the next child in the containing
2926 // scope.
2927 MatchScopes.pop_back();
2928 }
2929 }
2930}
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002931
Chris Lattner2a49d572010-02-28 22:37:22 +00002932
2933
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002934void SelectionDAGISel::CannotYetSelect(SDNode *N) {
Dan Gohmane1f188f2009-10-29 22:30:23 +00002935 std::string msg;
2936 raw_string_ostream Msg(msg);
Chris Lattner5df15782010-12-21 02:07:03 +00002937 Msg << "Cannot select: ";
Andrew Trick6e8f4c42010-12-24 04:28:06 +00002938
Chris Lattner2c4afd12010-03-04 00:21:16 +00002939 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2940 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2941 N->getOpcode() != ISD::INTRINSIC_VOID) {
2942 N->printrFull(Msg, CurDAG);
Craig Topper96601ca2012-08-22 06:07:19 +00002943 Msg << "\nIn function: " << MF->getName();
Chris Lattner2c4afd12010-03-04 00:21:16 +00002944 } else {
2945 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2946 unsigned iid =
2947 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2948 if (iid < Intrinsic::num_intrinsics)
2949 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2950 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2951 Msg << "target intrinsic %" << TII->getName(iid);
2952 else
2953 Msg << "unknown intrinsic #" << iid;
2954 }
Chris Lattner75361b62010-04-07 22:58:41 +00002955 report_fatal_error(Msg.str());
Dan Gohmane1f188f2009-10-29 22:30:23 +00002956}
2957
Devang Patel19974732007-05-03 01:11:54 +00002958char SelectionDAGISel::ID = 0;