blob: 394ef82d72101daa4d22dd2a06bff4a24744d60f [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"
Dan Gohman84fbac52009-02-06 17:22:58 +000015#include "ScheduleDAGSDNodes.h"
Dan Gohman2048b852009-11-23 18:04:58 +000016#include "SelectionDAGBuilder.h"
Dan Gohman6277eb22009-11-23 17:16:22 +000017#include "FunctionLoweringInfo.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000018#include "llvm/CodeGen/SelectionDAGISel.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000019#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel713f0432009-09-16 21:09:07 +000020#include "llvm/Analysis/DebugInfo.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000021#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000022#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000025#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000026#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000027#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000029#include "llvm/IntrinsicInst.h"
Chris Lattner75c478a2009-10-27 17:02:08 +000030#include "llvm/LLVMContext.h"
Dan Gohman78eca172008-08-19 22:33:34 +000031#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000032#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000033#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/MachineFunction.h"
Dan Gohmanad2afc22009-07-31 18:16:33 +000035#include "llvm/CodeGen/MachineFunctionAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000036#include "llvm/CodeGen/MachineFrameInfo.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000038#include "llvm/CodeGen/MachineJumpTableInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanfc54c552009-01-15 22:18:12 +000041#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000042#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000043#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000044#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Target/TargetFrameInfo.h"
Dan Gohmane1f188f2009-10-29 22:30:23 +000047#include "llvm/Target/TargetIntrinsicInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000048#include "llvm/Target/TargetInstrInfo.h"
49#include "llvm/Target/TargetLowering.h"
50#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000051#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000055#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/Timer.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000057#include "llvm/Support/raw_ostream.h"
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000058#include "llvm/ADT/Statistic.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000059#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000060using namespace llvm;
61
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000062STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
Chris Lattnerbed993d2010-03-28 19:46:56 +000063STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000064
Chris Lattneread0d882008-06-17 06:09:18 +000065static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +000066EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +000067 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +000068 "instruction selector"));
69static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +000070EnableFastISelAbort("fast-isel-abort", cl::Hidden,
71 cl::desc("Enable abort calls when \"fast\" instruction fails"));
Chris Lattneread0d882008-06-17 06:09:18 +000072
Chris Lattnerda8abb02005-09-01 18:44:10 +000073#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000074static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000075ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
76 cl::desc("Pop up a window to show dags before the first "
77 "dag combine pass"));
78static cl::opt<bool>
79ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before legalize types"));
81static cl::opt<bool>
82ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before legalize"));
84static cl::opt<bool>
85ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
86 cl::desc("Pop up a window to show dags before the second "
87 "dag combine pass"));
88static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +000089ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
90 cl::desc("Pop up a window to show dags before the post legalize types"
91 " dag combine pass"));
92static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000093ViewISelDAGs("view-isel-dags", cl::Hidden,
94 cl::desc("Pop up a window to show isel dags as they are selected"));
95static cl::opt<bool>
96ViewSchedDAGs("view-sched-dags", cl::Hidden,
97 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000098static cl::opt<bool>
99ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +0000100 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +0000101#else
Dan Gohman462dc7f2008-07-21 20:00:07 +0000102static const bool ViewDAGCombine1 = false,
103 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
104 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +0000105 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +0000106 ViewISelDAGs = false, ViewSchedDAGs = false,
107 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000108#endif
109
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000110//===---------------------------------------------------------------------===//
111///
112/// RegisterScheduler class - Track the registration of instruction schedulers.
113///
114//===---------------------------------------------------------------------===//
115MachinePassRegistry RegisterScheduler::Registry;
116
117//===---------------------------------------------------------------------===//
118///
119/// ISHeuristic command line option for instruction schedulers.
120///
121//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000122static cl::opt<RegisterScheduler::FunctionPassCtor, false,
123 RegisterPassParser<RegisterScheduler> >
124ISHeuristic("pre-RA-sched",
125 cl::init(&createDefaultScheduler),
126 cl::desc("Instruction schedulers available (before register"
127 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000128
Dan Gohman844731a2008-05-13 00:00:25 +0000129static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000130defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000131 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000132
Chris Lattner1c08c712005-01-07 07:47:53 +0000133namespace llvm {
134 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000135 /// createDefaultScheduler - This creates an instruction scheduler appropriate
136 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000137 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000138 CodeGenOpt::Level OptLevel) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000139 const TargetLowering &TLI = IS->getTargetLowering();
140
Bill Wendling98a366d2009-04-29 23:29:43 +0000141 if (OptLevel == CodeGenOpt::None)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000142 return createFastDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000143 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000144 return createTDListDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000145 assert(TLI.getSchedulingPreference() ==
Bill Wendling187361b2010-01-23 10:26:57 +0000146 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000147 return createBURRListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000148 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000149}
150
Evan Chengff9b3732008-01-30 18:18:23 +0000151// EmitInstrWithCustomInserter - This method should be implemented by targets
Dan Gohman533297b2009-10-29 18:10:34 +0000152// that mark instructions with the 'usesCustomInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000153// instructions are special in various ways, which require special support to
154// insert. The specified MachineInstr is created but not inserted into any
Dan Gohman533297b2009-10-29 18:10:34 +0000155// basic blocks, and this method is called to expand it into a sequence of
156// instructions, potentially also creating new basic blocks and control flow.
157// When new basic blocks are inserted and the edges from MBB to its successors
158// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
159// DenseMap.
Evan Chengff9b3732008-01-30 18:18:23 +0000160MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Evan Chengfb2e7522009-09-18 21:02:19 +0000161 MachineBasicBlock *MBB,
162 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000163#ifndef NDEBUG
David Greene1a053232010-01-05 01:26:11 +0000164 dbgs() << "If a target marks an instruction with "
Dan Gohman533297b2009-10-29 18:10:34 +0000165 "'usesCustomInserter', it must implement "
Torok Edwinf3689232009-07-12 20:07:01 +0000166 "TargetLowering::EmitInstrWithCustomInserter!";
167#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000168 llvm_unreachable(0);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000169 return 0;
Chris Lattner025c39b2005-08-26 20:54:47 +0000170}
171
Chris Lattner7041ee32005-01-11 05:56:49 +0000172//===----------------------------------------------------------------------===//
173// SelectionDAGISel code
174//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000175
Bill Wendling98a366d2009-04-29 23:29:43 +0000176SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
Dan Gohmanad2afc22009-07-31 18:16:33 +0000177 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000178 FuncInfo(new FunctionLoweringInfo(TLI)),
179 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
Dan Gohman2048b852009-11-23 18:04:58 +0000180 SDB(new SelectionDAGBuilder(*CurDAG, TLI, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000181 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000182 OptLevel(OL),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000183 DAGSize(0)
184{}
185
186SelectionDAGISel::~SelectionDAGISel() {
Dan Gohman2048b852009-11-23 18:04:58 +0000187 delete SDB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000188 delete CurDAG;
189 delete FuncInfo;
190}
191
Owen Andersone50ed302009-08-10 22:56:29 +0000192unsigned SelectionDAGISel::MakeReg(EVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000193 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000194}
195
Chris Lattner495a0b52005-08-17 06:37:43 +0000196void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000197 AU.addRequired<AliasAnalysis>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000198 AU.addPreserved<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000199 AU.addRequired<GCModuleInfo>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000200 AU.addPreserved<GCModuleInfo>();
Dan Gohmanad2afc22009-07-31 18:16:33 +0000201 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner495a0b52005-08-17 06:37:43 +0000202}
Chris Lattner1c08c712005-01-07 07:47:53 +0000203
Dan Gohmanad2afc22009-07-31 18:16:33 +0000204bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
205 Function &Fn = *mf.getFunction();
206
Dan Gohman4344a5d2008-09-09 23:05:00 +0000207 // Do some sanity-checking on the command-line options.
208 assert((!EnableFastISelVerbose || EnableFastISel) &&
209 "-fast-isel-verbose requires -fast-isel");
210 assert((!EnableFastISelAbort || EnableFastISel) &&
211 "-fast-isel-abort requires -fast-isel");
212
Dan Gohman5f43f922007-08-27 16:26:13 +0000213 // Get alias analysis for load/store combining.
214 AA = &getAnalysis<AliasAnalysis>();
215
Dan Gohmanad2afc22009-07-31 18:16:33 +0000216 MF = &mf;
Dan Gohman8a110532008-09-05 22:59:21 +0000217 const TargetInstrInfo &TII = *TM.getInstrInfo();
218 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
219
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000220 if (Fn.hasGC())
221 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn);
Gordon Henriksence224772008-01-07 01:30:38 +0000222 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000223 GFI = 0;
Dan Gohman79ce2762009-01-15 19:20:50 +0000224 RegInfo = &MF->getRegInfo();
David Greene1a053232010-01-05 01:26:11 +0000225 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000226
Chris Lattnerde6e7832010-04-05 06:10:13 +0000227 CurDAG->init(*MF);
Dan Gohman6277eb22009-11-23 17:16:22 +0000228 FuncInfo->set(Fn, *MF, EnableFastISel);
Dan Gohman2048b852009-11-23 18:04:58 +0000229 SDB->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000230
Chris Lattnerde6e7832010-04-05 06:10:13 +0000231 SelectAllBasicBlocks(Fn, *MF, TII);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000232
Dan Gohman8a110532008-09-05 22:59:21 +0000233 // If the first basic block in the function has live ins that need to be
234 // copied into vregs, emit the copies into the top of the block before
235 // emitting the code for the block.
Dan Gohman98708262010-04-14 16:51:49 +0000236 RegInfo->EmitLiveInCopies(MF->begin(), TRI, TII);
Dan Gohman8a110532008-09-05 22:59:21 +0000237
Evan Chengad2070c2007-02-10 02:43:39 +0000238 // Add function live-ins to entry block live-in set.
Dan Gohman8a110532008-09-05 22:59:21 +0000239 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
240 E = RegInfo->livein_end(); I != E; ++I)
Dan Gohman79ce2762009-01-15 19:20:50 +0000241 MF->begin()->addLiveIn(I->first);
Evan Chengad2070c2007-02-10 02:43:39 +0000242
Duncan Sandsf4070822007-06-15 19:04:19 +0000243#ifndef NDEBUG
Dan Gohman7c3234c2008-08-27 23:52:12 +0000244 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
Duncan Sandsf4070822007-06-15 19:04:19 +0000245 "Not all catch info was assigned to a landing pad!");
246#endif
247
Dan Gohman7c3234c2008-08-27 23:52:12 +0000248 FuncInfo->clear();
249
Chris Lattner1c08c712005-01-07 07:47:53 +0000250 return true;
251}
252
Dan Gohman07f111e2009-12-05 00:27:08 +0000253/// SetDebugLoc - Update MF's and SDB's DebugLocs if debug information is
254/// attached with this instruction.
Chris Lattner23dbf662010-03-31 04:24:50 +0000255static void SetDebugLoc(Instruction *I, SelectionDAGBuilder *SDB,
Chris Lattner0eb41982009-12-28 20:45:51 +0000256 FastISel *FastIS, MachineFunction *MF) {
Chris Lattnerde4845c2010-04-02 19:42:39 +0000257 DebugLoc DL = I->getDebugLoc();
258 if (DL.isUnknown()) return;
Chris Lattner23dbf662010-03-31 04:24:50 +0000259
Chris Lattnerde4845c2010-04-02 19:42:39 +0000260 SDB->setCurDebugLoc(DL);
Dan Gohman07f111e2009-12-05 00:27:08 +0000261
Chris Lattner23dbf662010-03-31 04:24:50 +0000262 if (FastIS)
Chris Lattnerde4845c2010-04-02 19:42:39 +0000263 FastIS->setCurDebugLoc(DL);
Dan Gohman07f111e2009-12-05 00:27:08 +0000264
Chris Lattner23dbf662010-03-31 04:24:50 +0000265 // If the function doesn't have a default debug location yet, set
266 // it. This is kind of a hack.
267 if (MF->getDefaultDebugLoc().isUnknown())
Chris Lattnerde4845c2010-04-02 19:42:39 +0000268 MF->setDefaultDebugLoc(DL);
Dan Gohman07f111e2009-12-05 00:27:08 +0000269}
270
271/// ResetDebugLoc - Set MF's and SDB's DebugLocs to Unknown.
Chris Lattner3990b122009-12-28 23:41:32 +0000272static void ResetDebugLoc(SelectionDAGBuilder *SDB, FastISel *FastIS) {
Chris Lattnera4f2bb02010-04-02 20:17:23 +0000273 SDB->setCurDebugLoc(DebugLoc());
Dan Gohman07f111e2009-12-05 00:27:08 +0000274 if (FastIS)
Chris Lattnera4f2bb02010-04-02 20:17:23 +0000275 FastIS->setCurDebugLoc(DebugLoc());
Dan Gohman07f111e2009-12-05 00:27:08 +0000276}
277
Dan Gohmanf350b272008-08-23 02:25:05 +0000278void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
279 BasicBlock::iterator Begin,
Dan Gohmanb4afb132009-11-20 02:51:26 +0000280 BasicBlock::iterator End,
281 bool &HadTailCall) {
Dan Gohman2048b852009-11-23 18:04:58 +0000282 SDB->setCurrentBasicBlock(BB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000283
Dan Gohman98ca4f22009-08-05 01:29:28 +0000284 // Lower all of the non-terminator instructions. If a call is emitted
285 // as a tail call, cease emitting nodes for this block.
Dan Gohman2048b852009-11-23 18:04:58 +0000286 for (BasicBlock::iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
Chris Lattner23dbf662010-03-31 04:24:50 +0000287 SetDebugLoc(I, SDB, 0, MF);
Dan Gohman07f111e2009-12-05 00:27:08 +0000288
289 if (!isa<TerminatorInst>(I)) {
Dan Gohman2048b852009-11-23 18:04:58 +0000290 SDB->visit(*I);
Dan Gohman07f111e2009-12-05 00:27:08 +0000291
292 // Set the current debug location back to "unknown" so that it doesn't
293 // spuriously apply to subsequent instructions.
294 ResetDebugLoc(SDB, 0);
295 }
Devang Patel123eaa72009-09-16 20:39:11 +0000296 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000297
Dan Gohman2048b852009-11-23 18:04:58 +0000298 if (!SDB->HasTailCall) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000299 // Ensure that all instructions which are used outside of their defining
300 // blocks are available as virtual registers. Invoke is handled elsewhere.
301 for (BasicBlock::iterator I = Begin; I != End; ++I)
302 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
Dan Gohman2048b852009-11-23 18:04:58 +0000303 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000304
Dan Gohman98ca4f22009-08-05 01:29:28 +0000305 // Handle PHI nodes in successor blocks.
306 if (End == LLVMBB->end()) {
307 HandlePHINodesInSuccessorBlocks(LLVMBB);
Dan Gohman3df24e62008-09-03 23:12:08 +0000308
Dan Gohman98ca4f22009-08-05 01:29:28 +0000309 // Lower the terminator after the copies are emitted.
Chris Lattner23dbf662010-03-31 04:24:50 +0000310 SetDebugLoc(LLVMBB->getTerminator(), SDB, 0, MF);
Dan Gohman2048b852009-11-23 18:04:58 +0000311 SDB->visit(*LLVMBB->getTerminator());
Dan Gohman07f111e2009-12-05 00:27:08 +0000312 ResetDebugLoc(SDB, 0);
Dan Gohman98ca4f22009-08-05 01:29:28 +0000313 }
Dan Gohman3df24e62008-09-03 23:12:08 +0000314 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnera651cf62005-01-17 19:43:36 +0000316 // Make sure the root of the DAG is up-to-date.
Dan Gohman2048b852009-11-23 18:04:58 +0000317 CurDAG->setRoot(SDB->getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000318
Dan Gohmanf350b272008-08-23 02:25:05 +0000319 // Final step, emit the lowered DAG as machine code.
320 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000321 HadTailCall = SDB->HasTailCall;
322 SDB->clear();
Chris Lattner1c08c712005-01-07 07:47:53 +0000323}
324
Evan Cheng54e146b2010-01-09 00:21:08 +0000325namespace {
326/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
327/// nodes from the worklist.
328class SDOPsWorkListRemover : public SelectionDAG::DAGUpdateListener {
329 SmallVector<SDNode*, 128> &Worklist;
Chris Lattner25e0ab92010-03-14 19:43:04 +0000330 SmallPtrSet<SDNode*, 128> &InWorklist;
Evan Cheng54e146b2010-01-09 00:21:08 +0000331public:
Chris Lattner25e0ab92010-03-14 19:43:04 +0000332 SDOPsWorkListRemover(SmallVector<SDNode*, 128> &wl,
333 SmallPtrSet<SDNode*, 128> &inwl)
334 : Worklist(wl), InWorklist(inwl) {}
Evan Cheng54e146b2010-01-09 00:21:08 +0000335
Chris Lattner25e0ab92010-03-14 19:43:04 +0000336 void RemoveFromWorklist(SDNode *N) {
337 if (!InWorklist.erase(N)) return;
338
339 SmallVector<SDNode*, 128>::iterator I =
340 std::find(Worklist.begin(), Worklist.end(), N);
341 assert(I != Worklist.end() && "Not in worklist");
342
343 *I = Worklist.back();
344 Worklist.pop_back();
345 }
346
Evan Cheng54e146b2010-01-09 00:21:08 +0000347 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattner25e0ab92010-03-14 19:43:04 +0000348 RemoveFromWorklist(N);
Evan Cheng54e146b2010-01-09 00:21:08 +0000349 }
350
351 virtual void NodeUpdated(SDNode *N) {
352 // Ignore updates.
353 }
354};
355}
356
Evan Cheng046632f2010-02-10 02:17:34 +0000357/// TrivialTruncElim - Eliminate some trivial nops that can result from
358/// ShrinkDemandedOps: (trunc (ext n)) -> n.
359static bool TrivialTruncElim(SDValue Op,
360 TargetLowering::TargetLoweringOpt &TLO) {
361 SDValue N0 = Op.getOperand(0);
362 EVT VT = Op.getValueType();
363 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
364 N0.getOpcode() == ISD::SIGN_EXTEND ||
365 N0.getOpcode() == ISD::ANY_EXTEND) &&
366 N0.getOperand(0).getValueType() == VT) {
367 return TLO.CombineTo(Op, N0.getOperand(0));
368 }
369 return false;
370}
371
Evan Cheng54eb4c22010-01-06 19:43:21 +0000372/// ShrinkDemandedOps - A late transformation pass that shrink expressions
373/// using TargetLowering::TargetLoweringOpt::ShrinkDemandedOp. It converts
374/// x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
Evan Chengd40d03e2010-01-06 19:38:29 +0000375void SelectionDAGISel::ShrinkDemandedOps() {
376 SmallVector<SDNode*, 128> Worklist;
Chris Lattner25e0ab92010-03-14 19:43:04 +0000377 SmallPtrSet<SDNode*, 128> InWorklist;
Evan Chengd40d03e2010-01-06 19:38:29 +0000378
379 // Add all the dag nodes to the worklist.
380 Worklist.reserve(CurDAG->allnodes_size());
381 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
Chris Lattner25e0ab92010-03-14 19:43:04 +0000382 E = CurDAG->allnodes_end(); I != E; ++I) {
Evan Chengd40d03e2010-01-06 19:38:29 +0000383 Worklist.push_back(I);
Chris Lattner25e0ab92010-03-14 19:43:04 +0000384 InWorklist.insert(I);
385 }
Evan Chengd40d03e2010-01-06 19:38:29 +0000386
387 TargetLowering::TargetLoweringOpt TLO(*CurDAG, true);
388 while (!Worklist.empty()) {
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000389 SDNode *N = Worklist.pop_back_val();
Chris Lattner25e0ab92010-03-14 19:43:04 +0000390 InWorklist.erase(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000391
392 if (N->use_empty() && N != CurDAG->getRoot().getNode()) {
Chris Lattnerc4a3f232010-03-14 19:46:02 +0000393 // Deleting this node may make its operands dead, add them to the worklist
394 // if they aren't already there.
395 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
396 if (InWorklist.insert(N->getOperand(i).getNode()))
397 Worklist.push_back(N->getOperand(i).getNode());
398
Evan Cheng54e146b2010-01-09 00:21:08 +0000399 CurDAG->DeleteNode(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000400 continue;
401 }
402
403 // Run ShrinkDemandedOp on scalar binary operations.
Chris Lattner25e0ab92010-03-14 19:43:04 +0000404 if (N->getNumValues() != 1 ||
405 !N->getValueType(0).isSimple() || !N->getValueType(0).isInteger())
406 continue;
407
408 unsigned BitWidth = N->getValueType(0).getScalarType().getSizeInBits();
409 APInt Demanded = APInt::getAllOnesValue(BitWidth);
410 APInt KnownZero, KnownOne;
411 if (!TLI.SimplifyDemandedBits(SDValue(N, 0), Demanded,
412 KnownZero, KnownOne, TLO) &&
413 (N->getOpcode() != ISD::TRUNCATE ||
414 !TrivialTruncElim(SDValue(N, 0), TLO)))
415 continue;
416
417 // Revisit the node.
418 assert(!InWorklist.count(N) && "Already in worklist");
419 Worklist.push_back(N);
420 InWorklist.insert(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000421
Chris Lattner25e0ab92010-03-14 19:43:04 +0000422 // Replace the old value with the new one.
423 DEBUG(errs() << "\nShrinkDemandedOps replacing ";
424 TLO.Old.getNode()->dump(CurDAG);
425 errs() << "\nWith: ";
426 TLO.New.getNode()->dump(CurDAG);
427 errs() << '\n');
Evan Chengd40d03e2010-01-06 19:38:29 +0000428
Chris Lattner25e0ab92010-03-14 19:43:04 +0000429 if (InWorklist.insert(TLO.New.getNode()))
430 Worklist.push_back(TLO.New.getNode());
Evan Cheng54e146b2010-01-09 00:21:08 +0000431
Chris Lattner25e0ab92010-03-14 19:43:04 +0000432 SDOPsWorkListRemover DeadNodes(Worklist, InWorklist);
433 CurDAG->ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
Evan Chengd40d03e2010-01-06 19:38:29 +0000434
Chris Lattner25e0ab92010-03-14 19:43:04 +0000435 if (!TLO.Old.getNode()->use_empty()) continue;
436
437 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands();
438 i != e; ++i) {
439 SDNode *OpNode = TLO.Old.getNode()->getOperand(i).getNode();
440 if (OpNode->hasOneUse()) {
441 // Add OpNode to the end of the list to revisit.
442 DeadNodes.RemoveFromWorklist(OpNode);
443 Worklist.push_back(OpNode);
444 InWorklist.insert(OpNode);
Evan Chengd40d03e2010-01-06 19:38:29 +0000445 }
446 }
Chris Lattner25e0ab92010-03-14 19:43:04 +0000447
448 DeadNodes.RemoveFromWorklist(TLO.Old.getNode());
449 CurDAG->DeleteNode(TLO.Old.getNode());
Evan Chengd40d03e2010-01-06 19:38:29 +0000450 }
451}
452
Dan Gohmanf350b272008-08-23 02:25:05 +0000453void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000454 SmallPtrSet<SDNode*, 128> VisitedNodes;
455 SmallVector<SDNode*, 128> Worklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000456
Gabor Greifba36cb52008-08-28 21:40:38 +0000457 Worklist.push_back(CurDAG->getRoot().getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattneread0d882008-06-17 06:09:18 +0000459 APInt Mask;
460 APInt KnownZero;
461 APInt KnownOne;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000462
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000463 do {
464 SDNode *N = Worklist.pop_back_val();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000465
Chris Lattneread0d882008-06-17 06:09:18 +0000466 // If we've already seen this node, ignore it.
467 if (!VisitedNodes.insert(N))
468 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000469
Chris Lattneread0d882008-06-17 06:09:18 +0000470 // Otherwise, add all chain operands to the worklist.
471 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +0000472 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000473 Worklist.push_back(N->getOperand(i).getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000474
Chris Lattneread0d882008-06-17 06:09:18 +0000475 // If this is a CopyToReg with a vreg dest, process it.
476 if (N->getOpcode() != ISD::CopyToReg)
477 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000478
Chris Lattneread0d882008-06-17 06:09:18 +0000479 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
480 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
481 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000482
Chris Lattneread0d882008-06-17 06:09:18 +0000483 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000484 SDValue Src = N->getOperand(2);
Owen Andersone50ed302009-08-10 22:56:29 +0000485 EVT SrcVT = Src.getValueType();
Chris Lattneread0d882008-06-17 06:09:18 +0000486 if (!SrcVT.isInteger() || SrcVT.isVector())
487 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000488
Dan Gohmanf350b272008-08-23 02:25:05 +0000489 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +0000490 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +0000491 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000492
Chris Lattneread0d882008-06-17 06:09:18 +0000493 // Only install this information if it tells us something.
494 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
495 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000496 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
497 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
498 FunctionLoweringInfo::LiveOutInfo &LOI =
499 FuncInfo->LiveOutRegInfo[DestReg];
Chris Lattneread0d882008-06-17 06:09:18 +0000500 LOI.NumSignBits = NumSignBits;
Dan Gohmana80efce2009-03-27 23:55:04 +0000501 LOI.KnownOne = KnownOne;
502 LOI.KnownZero = KnownZero;
Chris Lattneread0d882008-06-17 06:09:18 +0000503 }
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000504 } while (!Worklist.empty());
Chris Lattneread0d882008-06-17 06:09:18 +0000505}
506
Dan Gohmanf350b272008-08-23 02:25:05 +0000507void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000508 std::string GroupName;
509 if (TimePassesIsEnabled)
510 GroupName = "Instruction Selection and Scheduling";
511 std::string BlockName;
512 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000513 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
514 ViewSUnitDAGs)
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000515 BlockName = MF->getFunction()->getNameStr() + ":" +
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000516 BB->getBasicBlock()->getNameStr();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000517
David Greene1a053232010-01-05 01:26:11 +0000518 DEBUG(dbgs() << "Initial selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000519 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000520
Dan Gohmanf350b272008-08-23 02:25:05 +0000521 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000522
Chris Lattneraf21d552005-10-10 16:47:10 +0000523 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000524 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000525 NamedRegionTimer T("DAG Combining 1", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000526 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000527 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000528 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000529 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000530
David Greene1a053232010-01-05 01:26:11 +0000531 DEBUG(dbgs() << "Optimized lowered selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000532 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000533
Chris Lattner1c08c712005-01-07 07:47:53 +0000534 // Second step, hack on the DAG until it only uses operations and types that
535 // the target supports.
Dan Gohman714efc62009-12-05 17:51:33 +0000536 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
537 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000538
Dan Gohman714efc62009-12-05 17:51:33 +0000539 bool Changed;
540 if (TimePassesIsEnabled) {
541 NamedRegionTimer T("Type Legalization", GroupName);
542 Changed = CurDAG->LegalizeTypes();
543 } else {
544 Changed = CurDAG->LegalizeTypes();
545 }
546
David Greene1a053232010-01-05 01:26:11 +0000547 DEBUG(dbgs() << "Type-legalized selection DAG:\n");
Dan Gohman714efc62009-12-05 17:51:33 +0000548 DEBUG(CurDAG->dump());
549
550 if (Changed) {
551 if (ViewDAGCombineLT)
552 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
553
554 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman462dc7f2008-07-21 20:00:07 +0000555 if (TimePassesIsEnabled) {
Dan Gohman714efc62009-12-05 17:51:33 +0000556 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
557 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000558 } else {
Dan Gohman714efc62009-12-05 17:51:33 +0000559 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000560 }
561
David Greene1a053232010-01-05 01:26:11 +0000562 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000563 DEBUG(CurDAG->dump());
Dan Gohman714efc62009-12-05 17:51:33 +0000564 }
Dan Gohman462dc7f2008-07-21 20:00:07 +0000565
Dan Gohman714efc62009-12-05 17:51:33 +0000566 if (TimePassesIsEnabled) {
567 NamedRegionTimer T("Vector Legalization", GroupName);
568 Changed = CurDAG->LegalizeVectors();
569 } else {
570 Changed = CurDAG->LegalizeVectors();
571 }
Duncan Sands25cf2272008-11-24 14:53:14 +0000572
Dan Gohman714efc62009-12-05 17:51:33 +0000573 if (Changed) {
Eli Friedman5c22c802009-05-23 12:35:30 +0000574 if (TimePassesIsEnabled) {
Dan Gohman714efc62009-12-05 17:51:33 +0000575 NamedRegionTimer T("Type Legalization 2", GroupName);
Bill Wendling98820072009-12-28 01:51:30 +0000576 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000577 } else {
Bill Wendling98820072009-12-28 01:51:30 +0000578 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000579 }
580
Dan Gohman714efc62009-12-05 17:51:33 +0000581 if (ViewDAGCombineLT)
582 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
Eli Friedman5c22c802009-05-23 12:35:30 +0000583
Dan Gohman714efc62009-12-05 17:51:33 +0000584 // Run the DAG combiner in post-type-legalize mode.
585 if (TimePassesIsEnabled) {
586 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
587 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
588 } else {
589 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Eli Friedman5c22c802009-05-23 12:35:30 +0000590 }
Dan Gohman714efc62009-12-05 17:51:33 +0000591
David Greene1a053232010-01-05 01:26:11 +0000592 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n");
Dan Gohman714efc62009-12-05 17:51:33 +0000593 DEBUG(CurDAG->dump());
Chris Lattner70587ea2008-07-10 23:37:50 +0000594 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000595
Dan Gohmanf350b272008-08-23 02:25:05 +0000596 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000597
Evan Chengebffb662008-07-01 17:59:20 +0000598 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000599 NamedRegionTimer T("DAG Legalization", GroupName);
Dan Gohman714efc62009-12-05 17:51:33 +0000600 CurDAG->Legalize(OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000601 } else {
Dan Gohman714efc62009-12-05 17:51:33 +0000602 CurDAG->Legalize(OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000603 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000604
David Greene1a053232010-01-05 01:26:11 +0000605 DEBUG(dbgs() << "Legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000606 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000607
Dan Gohmanf350b272008-08-23 02:25:05 +0000608 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000609
Chris Lattneraf21d552005-10-10 16:47:10 +0000610 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000611 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000612 NamedRegionTimer T("DAG Combining 2", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000613 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000614 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000615 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000616 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000617
David Greene1a053232010-01-05 01:26:11 +0000618 DEBUG(dbgs() << "Optimized legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000619 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000620
Evan Chengd40d03e2010-01-06 19:38:29 +0000621 if (OptLevel != CodeGenOpt::None) {
622 ShrinkDemandedOps();
Dan Gohmanf350b272008-08-23 02:25:05 +0000623 ComputeLiveOutVRegInfo();
Evan Chengd40d03e2010-01-06 19:38:29 +0000624 }
Evan Cheng552c4a82006-04-28 02:09:19 +0000625
Chris Lattner552186d2010-03-14 19:27:55 +0000626 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
627
Chris Lattnera33ef482005-03-30 01:10:47 +0000628 // Third, instruction select all of the operations to machine code, adding the
629 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +0000630 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000631 NamedRegionTimer T("Instruction Selection", GroupName);
Chris Lattner7c306da2010-03-02 06:34:30 +0000632 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000633 } else {
Chris Lattner7c306da2010-03-02 06:34:30 +0000634 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000635 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000636
David Greene1a053232010-01-05 01:26:11 +0000637 DEBUG(dbgs() << "Selected selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000638 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000639
Dan Gohmanf350b272008-08-23 02:25:05 +0000640 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000641
Dan Gohman5e843682008-07-14 18:19:29 +0000642 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000643 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman5e843682008-07-14 18:19:29 +0000644 if (TimePassesIsEnabled) {
645 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000646 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000647 } else {
Dan Gohman47ac0f02009-02-11 04:27:20 +0000648 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000649 }
650
Dan Gohman462dc7f2008-07-21 20:00:07 +0000651 if (ViewSUnitDAGs) Scheduler->viewGraph();
652
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653 // Emit machine code to BB. This can change 'BB' to the last block being
Evan Chengdb8d56b2008-06-30 20:45:06 +0000654 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +0000655 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000656 NamedRegionTimer T("Instruction Creation", GroupName);
Dan Gohman2048b852009-11-23 18:04:58 +0000657 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
Evan Chengebffb662008-07-01 17:59:20 +0000658 } else {
Dan Gohman2048b852009-11-23 18:04:58 +0000659 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
Dan Gohman5e843682008-07-14 18:19:29 +0000660 }
661
662 // Free the scheduler state.
663 if (TimePassesIsEnabled) {
664 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
665 delete Scheduler;
666 } else {
667 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000668 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000669
David Greene1a053232010-01-05 01:26:11 +0000670 DEBUG(dbgs() << "Selected machine code:\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000671 DEBUG(BB->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000672}
Chris Lattner1c08c712005-01-07 07:47:53 +0000673
Chris Lattner7c306da2010-03-02 06:34:30 +0000674void SelectionDAGISel::DoInstructionSelection() {
675 DEBUG(errs() << "===== Instruction selection begins:\n");
676
677 PreprocessISelDAG();
678
679 // Select target instructions for the DAG.
680 {
681 // Number all nodes with a topological order and set DAGSize.
682 DAGSize = CurDAG->AssignTopologicalOrder();
683
684 // Create a dummy node (which is not added to allnodes), that adds
685 // a reference to the root node, preventing it from being deleted,
686 // and tracking any changes of the root.
687 HandleSDNode Dummy(CurDAG->getRoot());
688 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
689 ++ISelPosition;
690
691 // The AllNodes list is now topological-sorted. Visit the
692 // nodes by starting at the end of the list (the root of the
693 // graph) and preceding back toward the beginning (the entry
694 // node).
695 while (ISelPosition != CurDAG->allnodes_begin()) {
696 SDNode *Node = --ISelPosition;
697 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
698 // but there are currently some corner cases that it misses. Also, this
699 // makes it theoretically possible to disable the DAGCombiner.
700 if (Node->use_empty())
701 continue;
702
703 SDNode *ResNode = Select(Node);
704
Chris Lattner82dd3d32010-03-02 07:50:03 +0000705 // FIXME: This is pretty gross. 'Select' should be changed to not return
706 // anything at all and this code should be nuked with a tactical strike.
707
Chris Lattner7c306da2010-03-02 06:34:30 +0000708 // If node should not be replaced, continue with the next one.
Chris Lattner82dd3d32010-03-02 07:50:03 +0000709 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
Chris Lattner7c306da2010-03-02 06:34:30 +0000710 continue;
711 // Replace node.
712 if (ResNode)
713 ReplaceUses(Node, ResNode);
714
715 // If after the replacement this node is not used any more,
716 // remove this dead node.
717 if (Node->use_empty()) { // Don't delete EntryToken, etc.
718 ISelUpdater ISU(ISelPosition);
719 CurDAG->RemoveDeadNode(Node, &ISU);
720 }
721 }
722
723 CurDAG->setRoot(Dummy.getValue());
724 }
725 DEBUG(errs() << "===== Instruction selection ends:\n");
726
727 PostprocessISelDAG();
Chris Lattner7c306da2010-03-02 06:34:30 +0000728}
729
730
Dan Gohman79ce2762009-01-15 19:20:50 +0000731void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
732 MachineFunction &MF,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000733 const TargetInstrInfo &TII) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000734 // Initialize the Fast-ISel state, if needed.
735 FastISel *FastIS = 0;
736 if (EnableFastISel)
Chris Lattnered3a8062010-04-05 06:05:26 +0000737 FastIS = TLI.createFastISel(MF, FuncInfo->ValueMap, FuncInfo->MBBMap,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000738 FuncInfo->StaticAllocaMap
739#ifndef NDEBUG
740 , FuncInfo->CatchInfoLost
741#endif
742 );
Dan Gohmana43abd12008-09-29 21:55:50 +0000743
744 // Iterate over all basic blocks in the function.
Evan Cheng39fd6e82008-08-07 00:43:25 +0000745 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
746 BasicBlock *LLVMBB = &*I;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000747 BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +0000748
Dan Gohman3df24e62008-09-03 23:12:08 +0000749 BasicBlock::iterator const Begin = LLVMBB->begin();
750 BasicBlock::iterator const End = LLVMBB->end();
Evan Cheng9f118502008-09-08 16:01:27 +0000751 BasicBlock::iterator BI = Begin;
Dan Gohman5edd3612008-08-28 20:28:56 +0000752
753 // Lower any arguments needed in this block if this is the entry block.
Dan Gohman33134c42008-09-25 17:05:24 +0000754 bool SuppressFastISel = false;
755 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman5edd3612008-08-28 20:28:56 +0000756 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000757
Dan Gohman33134c42008-09-25 17:05:24 +0000758 // If any of the arguments has the byval attribute, forgo
759 // fast-isel in the entry block.
Dan Gohmana43abd12008-09-29 21:55:50 +0000760 if (FastIS) {
Dan Gohman33134c42008-09-25 17:05:24 +0000761 unsigned j = 1;
762 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
763 I != E; ++I, ++j)
Devang Patel05988662008-09-25 21:00:45 +0000764 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohman77ca41e2008-09-25 17:21:42 +0000765 if (EnableFastISelVerbose || EnableFastISelAbort)
David Greene1a053232010-01-05 01:26:11 +0000766 dbgs() << "FastISel skips entry block due to byval argument\n";
Dan Gohman33134c42008-09-25 17:05:24 +0000767 SuppressFastISel = true;
768 break;
769 }
770 }
771 }
772
Chris Lattnerde6e7832010-04-05 06:10:13 +0000773 if (BB->isLandingPad()) {
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000774 // Add a label to mark the beginning of the landing pad. Deletion of the
775 // landing pad can thus be detected via the MachineModuleInfo.
Chris Lattnerde6e7832010-04-05 06:10:13 +0000776 MCSymbol *Label = MF.getMMI().addLandingPad(BB);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000777
Chris Lattner518bb532010-02-09 19:54:29 +0000778 const TargetInstrDesc &II = TII.get(TargetOpcode::EH_LABEL);
Chris Lattner7561d482010-03-14 02:33:54 +0000779 BuildMI(BB, SDB->getCurDebugLoc(), II).addSym(Label);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000780
781 // Mark exception register as live in.
782 unsigned Reg = TLI.getExceptionAddressRegister();
783 if (Reg) BB->addLiveIn(Reg);
784
785 // Mark exception selector register as live in.
786 Reg = TLI.getExceptionSelectorRegister();
787 if (Reg) BB->addLiveIn(Reg);
788
789 // FIXME: Hack around an exception handling flaw (PR1508): the personality
790 // function and list of typeids logically belong to the invoke (or, if you
791 // like, the basic block containing the invoke), and need to be associated
792 // with it in the dwarf exception handling tables. Currently however the
793 // information is provided by an intrinsic (eh.selector) that can be moved
794 // to unexpected places by the optimizers: if the unwind edge is critical,
795 // then breaking it can result in the intrinsics being in the successor of
Jim Grosbachf4549b02010-01-15 00:36:15 +0000796 // the landing pad, not the landing pad itself. This results
797 // in exceptions not being caught because no typeids are associated with
798 // the invoke. This may not be the only way things can go wrong, but it
799 // is the only way we try to work around for the moment.
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000800 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
801
802 if (Br && Br->isUnconditional()) { // Critical edge?
803 BasicBlock::iterator I, E;
804 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
805 if (isa<EHSelectorInst>(I))
806 break;
807
808 if (I == E)
809 // No catch info found - try to extract some from the successor.
Chris Lattnerde6e7832010-04-05 06:10:13 +0000810 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF.getMMI(), *FuncInfo);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000811 }
812 }
813
Dan Gohmanf350b272008-08-23 02:25:05 +0000814 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000815 if (FastIS && !SuppressFastISel) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000816 // Emit code for any incoming arguments. This must happen before
817 // beginning FastISel on the entry block.
818 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman2048b852009-11-23 18:04:58 +0000819 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohmana43abd12008-09-29 21:55:50 +0000820 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000821 SDB->clear();
Dan Gohmana43abd12008-09-29 21:55:50 +0000822 }
Dan Gohman241f4642008-10-04 00:56:36 +0000823 FastIS->startNewBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000824 // Do FastISel on as many instructions as possible.
825 for (; BI != End; ++BI) {
826 // Just before the terminator instruction, insert instructions to
827 // feed PHI nodes in successor blocks.
828 if (isa<TerminatorInst>(BI))
829 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000830 ++NumFastIselFailures;
Dan Gohman07f111e2009-12-05 00:27:08 +0000831 ResetDebugLoc(SDB, FastIS);
Dan Gohman4344a5d2008-09-09 23:05:00 +0000832 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000833 dbgs() << "FastISel miss: ";
Dan Gohman293d5f82008-09-09 22:06:46 +0000834 BI->dump();
835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000836 assert(!EnableFastISelAbort &&
Torok Edwinf3689232009-07-12 20:07:01 +0000837 "FastISel didn't handle a PHI in a successor");
Dan Gohmana43abd12008-09-29 21:55:50 +0000838 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000839 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000840
Chris Lattner23dbf662010-03-31 04:24:50 +0000841 SetDebugLoc(BI, SDB, FastIS, &MF);
Dan Gohman381ca552009-12-05 01:29:04 +0000842
Dan Gohman21c14e32010-01-12 04:32:35 +0000843 // Try to select the instruction with FastISel.
Dan Gohman07f111e2009-12-05 00:27:08 +0000844 if (FastIS->SelectInstruction(BI)) {
845 ResetDebugLoc(SDB, FastIS);
Dan Gohmana43abd12008-09-29 21:55:50 +0000846 continue;
Dan Gohman07f111e2009-12-05 00:27:08 +0000847 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000848
Dan Gohman07f111e2009-12-05 00:27:08 +0000849 // Clear out the debug location so that it doesn't carry over to
850 // unrelated instructions.
851 ResetDebugLoc(SDB, FastIS);
Dan Gohmana43abd12008-09-29 21:55:50 +0000852
853 // Then handle certain instructions as single-LLVM-Instruction blocks.
854 if (isa<CallInst>(BI)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000855 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000856 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000857 dbgs() << "FastISel missed call: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000858 BI->dump();
859 }
860
Benjamin Kramerf0127052010-01-05 13:12:22 +0000861 if (!BI->getType()->isVoidTy()) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000862 unsigned &R = FuncInfo->ValueMap[BI];
863 if (!R)
864 R = FuncInfo->CreateRegForValue(BI);
865 }
866
Dan Gohmanb4afb132009-11-20 02:51:26 +0000867 bool HadTailCall = false;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000868 SelectBasicBlock(LLVMBB, BI, llvm::next(BI), HadTailCall);
Dan Gohmanb4afb132009-11-20 02:51:26 +0000869
870 // If the call was emitted as a tail call, we're done with the block.
871 if (HadTailCall) {
872 BI = End;
873 break;
874 }
875
Dan Gohman241f4642008-10-04 00:56:36 +0000876 // If the instruction was codegen'd with multiple blocks,
877 // inform the FastISel object where to resume inserting.
878 FastIS->setCurrentBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000879 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +0000880 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000881
882 // Otherwise, give up on FastISel for the rest of the block.
883 // For now, be a little lenient about non-branch terminators.
884 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000885 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000886 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000887 dbgs() << "FastISel miss: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000888 BI->dump();
889 }
890 if (EnableFastISelAbort)
891 // The "fast" selector couldn't handle something and bailed.
892 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +0000893 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +0000894 }
895 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000896 }
897 }
898
Dan Gohmand2ff6472008-09-02 20:17:56 +0000899 // Run SelectionDAG instruction selection on the remainder of the block
900 // not handled by FastISel. If FastISel is not run, this is the entire
Dan Gohman3df24e62008-09-03 23:12:08 +0000901 // block.
Devang Patel390f3ac2009-04-16 01:33:10 +0000902 if (BI != End) {
Dan Gohmanb4afb132009-11-20 02:51:26 +0000903 bool HadTailCall;
904 SelectBasicBlock(LLVMBB, BI, End, HadTailCall);
Devang Patel390f3ac2009-04-16 01:33:10 +0000905 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000906
Dan Gohman7c3234c2008-08-27 23:52:12 +0000907 FinishBasicBlock();
Evan Cheng39fd6e82008-08-07 00:43:25 +0000908 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000909
910 delete FastIS;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000911}
912
Dan Gohmanfed90b62008-07-28 21:51:04 +0000913void
Dan Gohman7c3234c2008-08-27 23:52:12 +0000914SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +0000915
David Greene1a053232010-01-05 01:26:11 +0000916 DEBUG(dbgs() << "Target-post-processed machine code:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000917 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +0000918
David Greene1a053232010-01-05 01:26:11 +0000919 DEBUG(dbgs() << "Total amount of phi nodes to update: "
Dan Gohman2048b852009-11-23 18:04:58 +0000920 << SDB->PHINodesToUpdate.size() << "\n");
921 DEBUG(for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i)
David Greene1a053232010-01-05 01:26:11 +0000922 dbgs() << "Node " << i << " : ("
Dan Gohman2048b852009-11-23 18:04:58 +0000923 << SDB->PHINodesToUpdate[i].first
924 << ", " << SDB->PHINodesToUpdate[i].second << ")\n");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925
Chris Lattnera33ef482005-03-30 01:10:47 +0000926 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +0000927 // PHI nodes in successors.
Dan Gohman2048b852009-11-23 18:04:58 +0000928 if (SDB->SwitchCases.empty() &&
929 SDB->JTCases.empty() &&
930 SDB->BitTestCases.empty()) {
931 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
932 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +0000933 assert(PHI->isPHI() &&
Nate Begemanf15485a2006-03-27 01:32:24 +0000934 "This is not a machine PHI node that we are updating!");
Jakob Stoklund Olesen580bba22010-03-05 21:49:10 +0000935 if (!BB->isSuccessor(PHI->getParent()))
936 continue;
Dan Gohman2048b852009-11-23 18:04:58 +0000937 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000938 false));
939 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +0000940 }
Dan Gohman2048b852009-11-23 18:04:58 +0000941 SDB->PHINodesToUpdate.clear();
Nate Begemanf15485a2006-03-27 01:32:24 +0000942 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000943 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000944
Dan Gohman2048b852009-11-23 18:04:58 +0000945 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000946 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000947 if (!SDB->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000948 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000949 BB = SDB->BitTestCases[i].Parent;
950 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000951 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +0000952 SDB->visitBitTestHeader(SDB->BitTestCases[i]);
953 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000954 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000955 SDB->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000956 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000957
Dan Gohman2048b852009-11-23 18:04:58 +0000958 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000959 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000960 BB = SDB->BitTestCases[i].Cases[j].ThisBB;
961 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000962 // Emit the code
963 if (j+1 != ej)
Dan Gohman2048b852009-11-23 18:04:58 +0000964 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
965 SDB->BitTestCases[i].Reg,
966 SDB->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000967 else
Dan Gohman2048b852009-11-23 18:04:58 +0000968 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
969 SDB->BitTestCases[i].Reg,
970 SDB->BitTestCases[i].Cases[j]);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000971
972
Dan Gohman2048b852009-11-23 18:04:58 +0000973 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000974 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000975 SDB->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000976 }
977
978 // Update PHI Nodes
Dan Gohman2048b852009-11-23 18:04:58 +0000979 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
980 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000981 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000982 assert(PHI->isPHI() &&
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000983 "This is not a machine PHI node that we are updating!");
984 // This is "default" BB. We have two jumps to it. From "header" BB and
985 // from last "case" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000986 if (PHIBB == SDB->BitTestCases[i].Default) {
Jim Grosbachf4549b02010-01-15 00:36:15 +0000987 PHI->addOperand(MachineOperand::
988 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Dan Gohman2048b852009-11-23 18:04:58 +0000989 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
Jim Grosbachf4549b02010-01-15 00:36:15 +0000990 PHI->addOperand(MachineOperand::
991 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Dan Gohman2048b852009-11-23 18:04:58 +0000992 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000993 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000994 }
995 // One of "cases" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000996 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000997 j != ej; ++j) {
Dan Gohman2048b852009-11-23 18:04:58 +0000998 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +0000999 if (cBB->isSuccessor(PHIBB)) {
Jim Grosbachf4549b02010-01-15 00:36:15 +00001000 PHI->addOperand(MachineOperand::
1001 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001002 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001003 }
1004 }
1005 }
1006 }
Dan Gohman2048b852009-11-23 18:04:58 +00001007 SDB->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001008
Nate Begeman9453eea2006-04-23 06:26:20 +00001009 // If the JumpTable record is filled in, then we need to emit a jump table.
1010 // Updating the PHI nodes is tricky in this case, since we need to determine
1011 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001012 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001013 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +00001014 if (!SDB->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001015 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +00001016 BB = SDB->JTCases[i].first.HeaderBB;
1017 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001018 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001019 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first);
1020 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001021 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +00001022 SDB->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001023 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001024
Nate Begeman37efe672006-04-22 18:53:45 +00001025 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +00001026 BB = SDB->JTCases[i].second.MBB;
1027 SDB->setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00001028 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001029 SDB->visitJumpTable(SDB->JTCases[i].second);
1030 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001031 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +00001032 SDB->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001033
Nate Begeman37efe672006-04-22 18:53:45 +00001034 // Update PHI Nodes
Dan Gohman2048b852009-11-23 18:04:58 +00001035 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
1036 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +00001037 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +00001038 assert(PHI->isPHI() &&
Nate Begeman37efe672006-04-22 18:53:45 +00001039 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001040 // "default" BB. We can go there only from header BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001041 if (PHIBB == SDB->JTCases[i].second.Default) {
Evan Chengce319102009-09-19 09:51:03 +00001042 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +00001043 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Evan Chengce319102009-09-19 09:51:03 +00001044 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +00001045 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00001046 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001047 // JT BB. Just iterate over successors here
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001048 if (BB->isSuccessor(PHIBB)) {
Evan Chengce319102009-09-19 09:51:03 +00001049 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +00001050 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001051 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00001052 }
1053 }
Nate Begeman37efe672006-04-22 18:53:45 +00001054 }
Dan Gohman2048b852009-11-23 18:04:58 +00001055 SDB->JTCases.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001056
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001057 // If the switch block involved a branch to one of the actual successors, we
1058 // need to update PHI nodes in that block.
Dan Gohman2048b852009-11-23 18:04:58 +00001059 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
1060 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +00001061 assert(PHI->isPHI() &&
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001062 "This is not a machine PHI node that we are updating!");
1063 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman2048b852009-11-23 18:04:58 +00001064 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001065 false));
1066 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001067 }
1068 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001069
Nate Begemanf15485a2006-03-27 01:32:24 +00001070 // If we generated any switch lowering information, build and codegen any
1071 // additional DAGs necessary.
Dan Gohman2048b852009-11-23 18:04:58 +00001072 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001073 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +00001074 MachineBasicBlock *ThisBB = BB = SDB->SwitchCases[i].ThisBB;
1075 SDB->setCurrentBasicBlock(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001076
Nate Begemanf15485a2006-03-27 01:32:24 +00001077 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001078 SDB->visitSwitchCase(SDB->SwitchCases[i]);
1079 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001080 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001082 // Handle any PHI nodes in successors of this chunk, as if we were coming
1083 // from the original BB before switch expansion. Note that PHI nodes can
1084 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1085 // handle them the right number of times.
Dan Gohman2048b852009-11-23 18:04:58 +00001086 while ((BB = SDB->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Evan Chengfb2e7522009-09-18 21:02:19 +00001087 // If new BB's are created during scheduling, the edges may have been
Evan Chengce319102009-09-19 09:51:03 +00001088 // updated. That is, the edge from ThisBB to BB may have been split and
1089 // BB's predecessor is now another block.
Evan Chengfb2e7522009-09-18 21:02:19 +00001090 DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
Dan Gohman2048b852009-11-23 18:04:58 +00001091 SDB->EdgeMapping.find(BB);
1092 if (EI != SDB->EdgeMapping.end())
Evan Chengfb2e7522009-09-18 21:02:19 +00001093 ThisBB = EI->second;
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001094
1095 // BB may have been removed from the CFG if a branch was constant folded.
1096 if (ThisBB->isSuccessor(BB)) {
1097 for (MachineBasicBlock::iterator Phi = BB->begin();
Chris Lattner518bb532010-02-09 19:54:29 +00001098 Phi != BB->end() && Phi->isPHI();
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001099 ++Phi) {
1100 // This value for this PHI node is recorded in PHINodesToUpdate.
1101 for (unsigned pn = 0; ; ++pn) {
1102 assert(pn != SDB->PHINodesToUpdate.size() &&
1103 "Didn't find PHI entry!");
1104 if (SDB->PHINodesToUpdate[pn].first == Phi) {
1105 Phi->addOperand(MachineOperand::
1106 CreateReg(SDB->PHINodesToUpdate[pn].second,
1107 false));
1108 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1109 break;
1110 }
Evan Cheng8be58a12009-09-18 08:26:06 +00001111 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001112 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001113 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001114
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001115 // Don't process RHS if same block as LHS.
Dan Gohman2048b852009-11-23 18:04:58 +00001116 if (BB == SDB->SwitchCases[i].FalseBB)
1117 SDB->SwitchCases[i].FalseBB = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001118
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001119 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Dan Gohman2048b852009-11-23 18:04:58 +00001120 SDB->SwitchCases[i].TrueBB = SDB->SwitchCases[i].FalseBB;
1121 SDB->SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00001122 }
Dan Gohman2048b852009-11-23 18:04:58 +00001123 assert(SDB->SwitchCases[i].TrueBB == 0 && SDB->SwitchCases[i].FalseBB == 0);
1124 SDB->clear();
Chris Lattnera33ef482005-03-30 01:10:47 +00001125 }
Dan Gohman2048b852009-11-23 18:04:58 +00001126 SDB->SwitchCases.clear();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001127
Dan Gohman2048b852009-11-23 18:04:58 +00001128 SDB->PHINodesToUpdate.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001129}
Evan Chenga9c20912006-01-21 02:32:06 +00001130
Jim Laskey13ec7022006-08-01 14:21:23 +00001131
Dan Gohman0a3776d2009-02-06 18:26:51 +00001132/// Create the scheduler. If a specific scheduler was specified
1133/// via the SchedulerRegistry, use it, otherwise select the
1134/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001135///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001136ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001137 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001138
Jim Laskey13ec7022006-08-01 14:21:23 +00001139 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001140 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001141 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001143
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001144 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001145}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001146
Dan Gohmanfc54c552009-01-15 22:18:12 +00001147ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1148 return new ScheduleHazardRecognizer();
Jim Laskey9ff542f2006-08-01 18:29:48 +00001149}
1150
Chris Lattner75548062006-10-11 03:58:02 +00001151//===----------------------------------------------------------------------===//
1152// Helper functions used by the generated instruction selector.
1153//===----------------------------------------------------------------------===//
1154// Calls to these methods are generated by tblgen.
1155
1156/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1157/// the dag combiner simplified the 255, we still want to match. RHS is the
1158/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1159/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001160bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001161 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001162 const APInt &ActualMask = RHS->getAPIntValue();
1163 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001164
Chris Lattner75548062006-10-11 03:58:02 +00001165 // If the actual mask exactly matches, success!
1166 if (ActualMask == DesiredMask)
1167 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168
Chris Lattner75548062006-10-11 03:58:02 +00001169 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001170 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001171 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001172
Chris Lattner75548062006-10-11 03:58:02 +00001173 // Otherwise, the DAG Combiner may have proven that the value coming in is
1174 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001175 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001176 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001177 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001178
Chris Lattner75548062006-10-11 03:58:02 +00001179 // TODO: check to see if missing bits are just not demanded.
1180
1181 // Otherwise, this pattern doesn't match.
1182 return false;
1183}
1184
1185/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1186/// the dag combiner simplified the 255, we still want to match. RHS is the
1187/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1188/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001189bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001190 int64_t DesiredMaskS) const {
1191 const APInt &ActualMask = RHS->getAPIntValue();
1192 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattner75548062006-10-11 03:58:02 +00001194 // If the actual mask exactly matches, success!
1195 if (ActualMask == DesiredMask)
1196 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001197
Chris Lattner75548062006-10-11 03:58:02 +00001198 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001199 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001200 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001201
Chris Lattner75548062006-10-11 03:58:02 +00001202 // Otherwise, the DAG Combiner may have proven that the value coming in is
1203 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001204 APInt NeededMask = DesiredMask & ~ActualMask;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001205
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001206 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00001207 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001208
Chris Lattner75548062006-10-11 03:58:02 +00001209 // If all the missing bits in the or are already known to be set, match!
1210 if ((NeededMask & KnownOne) == NeededMask)
1211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001212
Chris Lattner75548062006-10-11 03:58:02 +00001213 // TODO: check to see if missing bits are just not demanded.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001214
Chris Lattner75548062006-10-11 03:58:02 +00001215 // Otherwise, this pattern doesn't match.
1216 return false;
1217}
1218
Jim Laskey9ff542f2006-08-01 18:29:48 +00001219
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001220/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1221/// by tblgen. Others should not call it.
1222void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001223SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001224 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001225 std::swap(InOps, Ops);
1226
Chris Lattnerdecc2672010-04-07 05:20:54 +00001227 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1228 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1229 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001230
Chris Lattnerdecc2672010-04-07 05:20:54 +00001231 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
Owen Anderson825b72b2009-08-11 20:47:22 +00001232 if (InOps[e-1].getValueType() == MVT::Flag)
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001233 --e; // Don't process a flag operand if it is here.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001234
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001235 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001236 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00001237 if (!InlineAsm::isMemKind(Flags)) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001238 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001239 Ops.insert(Ops.end(), InOps.begin()+i,
1240 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1241 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001242 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001243 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1244 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001245 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001246 std::vector<SDValue> SelOps;
Chris Lattnerdecc2672010-04-07 05:20:54 +00001247 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
Chris Lattner75361b62010-04-07 22:58:41 +00001248 report_fatal_error("Could not match memory address. Inline asm"
Chris Lattner87d677c2010-04-07 23:50:38 +00001249 " failure!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001250
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001251 // Add this to the output node.
Chris Lattnerdecc2672010-04-07 05:20:54 +00001252 unsigned NewFlags =
1253 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1254 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001255 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1256 i += 2;
1257 }
1258 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001260 // Add the flag input back if present.
1261 if (e != InOps.size())
1262 Ops.push_back(InOps.back());
1263}
Devang Patel794fd752007-05-01 21:15:47 +00001264
Owen Andersone50ed302009-08-10 22:56:29 +00001265/// findFlagUse - Return use of EVT::Flag value produced by the specified
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001266/// SDNode.
1267///
1268static SDNode *findFlagUse(SDNode *N) {
1269 unsigned FlagResNo = N->getNumValues()-1;
1270 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1271 SDUse &Use = I.getUse();
1272 if (Use.getResNo() == FlagResNo)
1273 return Use.getUser();
1274 }
1275 return NULL;
1276}
1277
1278/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1279/// This function recursively traverses up the operand chain, ignoring
1280/// certain nodes.
1281static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
Chris Lattnerd1b73822010-03-02 22:20:06 +00001282 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1283 bool IgnoreChains) {
Chris Lattnerda244a02010-02-23 19:32:27 +00001284 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1285 // greater than all of its (recursive) operands. If we scan to a point where
1286 // 'use' is smaller than the node we're scanning for, then we know we will
1287 // never find it.
1288 //
1289 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1290 // happen because we scan down to newly selected nodes in the case of flag
1291 // uses.
1292 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1293 return false;
1294
1295 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1296 // won't fail if we scan it again.
1297 if (!Visited.insert(Use))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001298 return false;
1299
1300 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001301 // Ignore chain uses, they are validated by HandleMergeInputChains.
1302 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1303 continue;
1304
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001305 SDNode *N = Use->getOperand(i).getNode();
1306 if (N == Def) {
1307 if (Use == ImmedUse || Use == Root)
1308 continue; // We are not looking for immediate use.
1309 assert(N != Root);
1310 return true;
1311 }
1312
1313 // Traverse up the operand chain.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001314 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001315 return true;
1316 }
1317 return false;
1318}
1319
Evan Cheng014bf212010-02-15 19:41:07 +00001320/// IsProfitableToFold - Returns true if it's profitable to fold the specific
1321/// operand node N of U during instruction selection that starts at Root.
1322bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1323 SDNode *Root) const {
1324 if (OptLevel == CodeGenOpt::None) return false;
1325 return N.hasOneUse();
1326}
1327
1328/// IsLegalToFold - Returns true if the specific operand node N of
1329/// U can be folded during instruction selection that starts at Root.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001330bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1331 bool IgnoreChains) const {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001332 if (OptLevel == CodeGenOpt::None) return false;
1333
1334 // If Root use can somehow reach N through a path that that doesn't contain
1335 // U then folding N would create a cycle. e.g. In the following
1336 // diagram, Root can reach N through X. If N is folded into into Root, then
1337 // X is both a predecessor and a successor of U.
1338 //
1339 // [N*] //
1340 // ^ ^ //
1341 // / \ //
1342 // [U*] [X]? //
1343 // ^ ^ //
1344 // \ / //
1345 // \ / //
1346 // [Root*] //
1347 //
1348 // * indicates nodes to be folded together.
1349 //
1350 // If Root produces a flag, then it gets (even more) interesting. Since it
1351 // will be "glued" together with its flag use in the scheduler, we need to
1352 // check if it might reach N.
1353 //
1354 // [N*] //
1355 // ^ ^ //
1356 // / \ //
1357 // [U*] [X]? //
1358 // ^ ^ //
1359 // \ \ //
1360 // \ | //
1361 // [Root*] | //
1362 // ^ | //
1363 // f | //
1364 // | / //
1365 // [Y] / //
1366 // ^ / //
1367 // f / //
1368 // | / //
1369 // [FU] //
1370 //
1371 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1372 // (call it Fold), then X is a predecessor of FU and a successor of
1373 // Fold. But since Fold and FU are flagged together, this will create
1374 // a cycle in the scheduling graph.
1375
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001376 // If the node has flags, walk down the graph to the "lowest" node in the
1377 // flagged set.
Owen Andersone50ed302009-08-10 22:56:29 +00001378 EVT VT = Root->getValueType(Root->getNumValues()-1);
Owen Anderson825b72b2009-08-11 20:47:22 +00001379 while (VT == MVT::Flag) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001380 SDNode *FU = findFlagUse(Root);
1381 if (FU == NULL)
1382 break;
1383 Root = FU;
1384 VT = Root->getValueType(Root->getNumValues()-1);
Chris Lattner18fdaba2010-03-05 06:19:13 +00001385
1386 // If our query node has a flag result with a use, we've walked up it. If
1387 // the user (which has already been selected) has a chain or indirectly uses
1388 // the chain, our WalkChainUsers predicate will not consider it. Because of
1389 // this, we cannot ignore chains in this predicate.
1390 IgnoreChains = false;
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001391 }
Chris Lattner18fdaba2010-03-05 06:19:13 +00001392
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001393
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001394 SmallPtrSet<SDNode*, 16> Visited;
1395 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001396}
1397
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001398SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1399 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
Dan Gohmane1f188f2009-10-29 22:30:23 +00001400 SelectInlineAsmMemoryOperands(Ops);
1401
1402 std::vector<EVT> VTs;
1403 VTs.push_back(MVT::Other);
1404 VTs.push_back(MVT::Flag);
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001405 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
Dan Gohmane1f188f2009-10-29 22:30:23 +00001406 VTs, &Ops[0], Ops.size());
Chris Lattnerd1b73822010-03-02 22:20:06 +00001407 New->setNodeId(-1);
Dan Gohmane1f188f2009-10-29 22:30:23 +00001408 return New.getNode();
1409}
1410
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001411SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
Chris Lattner518bb532010-02-09 19:54:29 +00001412 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
Dan Gohmane1f188f2009-10-29 22:30:23 +00001413}
1414
Chris Lattner2a49d572010-02-28 22:37:22 +00001415/// GetVBR - decode a vbr encoding whose top bit is set.
1416ALWAYS_INLINE static uint64_t
1417GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1418 assert(Val >= 128 && "Not a VBR");
1419 Val &= 127; // Remove first vbr bit.
1420
1421 unsigned Shift = 7;
1422 uint64_t NextBits;
1423 do {
Chris Lattner14df8dc2010-02-28 22:38:43 +00001424 NextBits = MatcherTable[Idx++];
Chris Lattner2a49d572010-02-28 22:37:22 +00001425 Val |= (NextBits&127) << Shift;
1426 Shift += 7;
1427 } while (NextBits & 128);
1428
1429 return Val;
1430}
1431
Chris Lattner2a49d572010-02-28 22:37:22 +00001432
1433/// UpdateChainsAndFlags - When a match is complete, this method updates uses of
1434/// interior flag and chain results to use the new flag and chain results.
Chris Lattner82dd3d32010-03-02 07:50:03 +00001435void SelectionDAGISel::
1436UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
1437 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1438 SDValue InputFlag,
1439 const SmallVectorImpl<SDNode*> &FlagResultNodesMatched,
1440 bool isMorphNodeTo) {
1441 SmallVector<SDNode*, 4> NowDeadNodes;
1442
1443 ISelUpdater ISU(ISelPosition);
1444
Chris Lattner2a49d572010-02-28 22:37:22 +00001445 // Now that all the normal results are replaced, we replace the chain and
1446 // flag results if present.
1447 if (!ChainNodesMatched.empty()) {
1448 assert(InputChain.getNode() != 0 &&
1449 "Matched input chains but didn't produce a chain");
1450 // Loop over all of the nodes we matched that produced a chain result.
1451 // Replace all the chain results with the final chain we ended up with.
1452 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1453 SDNode *ChainNode = ChainNodesMatched[i];
1454
Chris Lattner82dd3d32010-03-02 07:50:03 +00001455 // If this node was already deleted, don't look at it.
1456 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1457 continue;
1458
Chris Lattner2a49d572010-02-28 22:37:22 +00001459 // Don't replace the results of the root node if we're doing a
1460 // MorphNodeTo.
1461 if (ChainNode == NodeToMatch && isMorphNodeTo)
1462 continue;
1463
1464 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1465 if (ChainVal.getValueType() == MVT::Flag)
1466 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1467 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
Chris Lattner82dd3d32010-03-02 07:50:03 +00001468 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1469
Chris Lattner856fb392010-03-28 05:28:31 +00001470 // If the node became dead and we haven't already seen it, delete it.
1471 if (ChainNode->use_empty() &&
1472 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001473 NowDeadNodes.push_back(ChainNode);
Chris Lattner2a49d572010-02-28 22:37:22 +00001474 }
1475 }
1476
1477 // If the result produces a flag, update any flag results in the matched
1478 // pattern with the flag result.
1479 if (InputFlag.getNode() != 0) {
1480 // Handle any interior nodes explicitly marked.
1481 for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
1482 SDNode *FRN = FlagResultNodesMatched[i];
Chris Lattner82dd3d32010-03-02 07:50:03 +00001483
1484 // If this node was already deleted, don't look at it.
1485 if (FRN->getOpcode() == ISD::DELETED_NODE)
1486 continue;
1487
Chris Lattner2a49d572010-02-28 22:37:22 +00001488 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
1489 "Doesn't have a flag result");
1490 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
Chris Lattner82dd3d32010-03-02 07:50:03 +00001491 InputFlag, &ISU);
1492
Chris Lattner19e37cb2010-03-28 04:54:33 +00001493 // If the node became dead and we haven't already seen it, delete it.
1494 if (FRN->use_empty() &&
1495 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001496 NowDeadNodes.push_back(FRN);
Chris Lattner2a49d572010-02-28 22:37:22 +00001497 }
1498 }
1499
Chris Lattner82dd3d32010-03-02 07:50:03 +00001500 if (!NowDeadNodes.empty())
1501 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1502
Chris Lattner2a49d572010-02-28 22:37:22 +00001503 DEBUG(errs() << "ISEL: Match complete!\n");
1504}
1505
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001506enum ChainResult {
1507 CR_Simple,
1508 CR_InducesCycle,
1509 CR_LeadsToInteriorNode
1510};
1511
1512/// WalkChainUsers - Walk down the users of the specified chained node that is
1513/// part of the pattern we're matching, looking at all of the users we find.
1514/// This determines whether something is an interior node, whether we have a
1515/// non-pattern node in between two pattern nodes (which prevent folding because
1516/// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1517/// between pattern nodes (in which case the TF becomes part of the pattern).
1518///
1519/// The walk we do here is guaranteed to be small because we quickly get down to
1520/// already selected nodes "below" us.
1521static ChainResult
1522WalkChainUsers(SDNode *ChainedNode,
1523 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1524 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1525 ChainResult Result = CR_Simple;
1526
1527 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1528 E = ChainedNode->use_end(); UI != E; ++UI) {
1529 // Make sure the use is of the chain, not some other value we produce.
1530 if (UI.getUse().getValueType() != MVT::Other) continue;
1531
1532 SDNode *User = *UI;
1533
1534 // If we see an already-selected machine node, then we've gone beyond the
1535 // pattern that we're selecting down into the already selected chunk of the
1536 // DAG.
1537 if (User->isMachineOpcode() ||
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001538 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1539 continue;
Chris Lattnerd1b73822010-03-02 22:20:06 +00001540
1541 if (User->getOpcode() == ISD::CopyToReg ||
1542 User->getOpcode() == ISD::CopyFromReg ||
Chris Lattner7561d482010-03-14 02:33:54 +00001543 User->getOpcode() == ISD::INLINEASM ||
1544 User->getOpcode() == ISD::EH_LABEL) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001545 // If their node ID got reset to -1 then they've already been selected.
1546 // Treat them like a MachineOpcode.
1547 if (User->getNodeId() == -1)
1548 continue;
1549 }
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001550
1551 // If we have a TokenFactor, we handle it specially.
1552 if (User->getOpcode() != ISD::TokenFactor) {
1553 // If the node isn't a token factor and isn't part of our pattern, then it
1554 // must be a random chained node in between two nodes we're selecting.
1555 // This happens when we have something like:
1556 // x = load ptr
1557 // call
1558 // y = x+4
1559 // store y -> ptr
1560 // Because we structurally match the load/store as a read/modify/write,
1561 // but the call is chained between them. We cannot fold in this case
1562 // because it would induce a cycle in the graph.
1563 if (!std::count(ChainedNodesInPattern.begin(),
1564 ChainedNodesInPattern.end(), User))
1565 return CR_InducesCycle;
1566
1567 // Otherwise we found a node that is part of our pattern. For example in:
1568 // x = load ptr
1569 // y = x+4
1570 // store y -> ptr
1571 // This would happen when we're scanning down from the load and see the
1572 // store as a user. Record that there is a use of ChainedNode that is
1573 // part of the pattern and keep scanning uses.
1574 Result = CR_LeadsToInteriorNode;
1575 InteriorChainedNodes.push_back(User);
1576 continue;
1577 }
1578
1579 // If we found a TokenFactor, there are two cases to consider: first if the
1580 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1581 // uses of the TF are in our pattern) we just want to ignore it. Second,
1582 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1583 // [Load chain]
1584 // ^
1585 // |
1586 // [Load]
1587 // ^ ^
1588 // | \ DAG's like cheese
1589 // / \ do you?
1590 // / |
1591 // [TokenFactor] [Op]
1592 // ^ ^
1593 // | |
1594 // \ /
1595 // \ /
1596 // [Store]
1597 //
1598 // In this case, the TokenFactor becomes part of our match and we rewrite it
1599 // as a new TokenFactor.
1600 //
1601 // To distinguish these two cases, do a recursive walk down the uses.
1602 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1603 case CR_Simple:
1604 // If the uses of the TokenFactor are just already-selected nodes, ignore
1605 // it, it is "below" our pattern.
1606 continue;
1607 case CR_InducesCycle:
1608 // If the uses of the TokenFactor lead to nodes that are not part of our
1609 // pattern that are not selected, folding would turn this into a cycle,
1610 // bail out now.
1611 return CR_InducesCycle;
1612 case CR_LeadsToInteriorNode:
1613 break; // Otherwise, keep processing.
1614 }
1615
1616 // Okay, we know we're in the interesting interior case. The TokenFactor
1617 // is now going to be considered part of the pattern so that we rewrite its
1618 // uses (it may have uses that are not part of the pattern) with the
1619 // ultimate chain result of the generated code. We will also add its chain
1620 // inputs as inputs to the ultimate TokenFactor we create.
1621 Result = CR_LeadsToInteriorNode;
1622 ChainedNodesInPattern.push_back(User);
1623 InteriorChainedNodes.push_back(User);
1624 continue;
1625 }
1626
1627 return Result;
1628}
1629
Chris Lattner6b307922010-03-02 00:00:03 +00001630/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
Chris Lattner00592ec2010-03-02 19:34:59 +00001631/// operation for when the pattern matched at least one node with a chains. The
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001632/// input vector contains a list of all of the chained nodes that we match. We
1633/// must determine if this is a valid thing to cover (i.e. matching it won't
1634/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1635/// be used as the input node chain for the generated nodes.
Chris Lattner6b307922010-03-02 00:00:03 +00001636static SDValue
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001637HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
Chris Lattner6b307922010-03-02 00:00:03 +00001638 SelectionDAG *CurDAG) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001639 // Walk all of the chained nodes we've matched, recursively scanning down the
1640 // users of the chain result. This adds any TokenFactor nodes that are caught
1641 // in between chained nodes to the chained and interior nodes list.
1642 SmallVector<SDNode*, 3> InteriorChainedNodes;
1643 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1644 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1645 InteriorChainedNodes) == CR_InducesCycle)
1646 return SDValue(); // Would induce a cycle.
1647 }
Chris Lattner6b307922010-03-02 00:00:03 +00001648
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001649 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1650 // that we are interested in. Form our input TokenFactor node.
Chris Lattner6b307922010-03-02 00:00:03 +00001651 SmallVector<SDValue, 3> InputChains;
1652 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001653 // Add the input chain of this node to the InputChains list (which will be
1654 // the operands of the generated TokenFactor) if it's not an interior node.
1655 SDNode *N = ChainNodesMatched[i];
1656 if (N->getOpcode() != ISD::TokenFactor) {
1657 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1658 continue;
1659
1660 // Otherwise, add the input chain.
1661 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1662 assert(InChain.getValueType() == MVT::Other && "Not a chain");
Chris Lattner6b307922010-03-02 00:00:03 +00001663 InputChains.push_back(InChain);
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001664 continue;
1665 }
1666
1667 // If we have a token factor, we want to add all inputs of the token factor
1668 // that are not part of the pattern we're matching.
1669 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1670 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
Chris Lattner6183fbd2010-03-02 02:37:23 +00001671 N->getOperand(op).getNode()))
1672 InputChains.push_back(N->getOperand(op));
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001673 }
Chris Lattner6b307922010-03-02 00:00:03 +00001674 }
1675
1676 SDValue Res;
1677 if (InputChains.size() == 1)
1678 return InputChains[0];
1679 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1680 MVT::Other, &InputChains[0], InputChains.size());
1681}
Chris Lattner2a49d572010-02-28 22:37:22 +00001682
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001683/// MorphNode - Handle morphing a node in place for the selector.
1684SDNode *SelectionDAGISel::
1685MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1686 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1687 // It is possible we're using MorphNodeTo to replace a node with no
1688 // normal results with one that has a normal result (or we could be
1689 // adding a chain) and the input could have flags and chains as well.
Chris Lattnercaa88702010-03-28 08:43:23 +00001690 // In this case we need to shift the operands down.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001691 // FIXME: This is a horrible hack and broken in obscure cases, no worse
Chris Lattnera6f86932010-03-27 18:54:50 +00001692 // than the old isel though.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001693 int OldFlagResultNo = -1, OldChainResultNo = -1;
1694
1695 unsigned NTMNumResults = Node->getNumValues();
1696 if (Node->getValueType(NTMNumResults-1) == MVT::Flag) {
1697 OldFlagResultNo = NTMNumResults-1;
1698 if (NTMNumResults != 1 &&
1699 Node->getValueType(NTMNumResults-2) == MVT::Other)
1700 OldChainResultNo = NTMNumResults-2;
1701 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1702 OldChainResultNo = NTMNumResults-1;
1703
Chris Lattner61c97f62010-03-02 07:14:49 +00001704 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1705 // that this deletes operands of the old node that become dead.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001706 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1707
1708 // MorphNodeTo can operate in two ways: if an existing node with the
1709 // specified operands exists, it can just return it. Otherwise, it
1710 // updates the node in place to have the requested operands.
1711 if (Res == Node) {
1712 // If we updated the node in place, reset the node ID. To the isel,
1713 // this should be just like a newly allocated machine node.
1714 Res->setNodeId(-1);
1715 }
1716
1717 unsigned ResNumResults = Res->getNumValues();
1718 // Move the flag if needed.
1719 if ((EmitNodeInfo & OPFL_FlagOutput) && OldFlagResultNo != -1 &&
1720 (unsigned)OldFlagResultNo != ResNumResults-1)
1721 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldFlagResultNo),
1722 SDValue(Res, ResNumResults-1));
1723
1724 if ((EmitNodeInfo & OPFL_FlagOutput) != 0)
1725 --ResNumResults;
1726
1727 // Move the chain reference if needed.
1728 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1729 (unsigned)OldChainResultNo != ResNumResults-1)
1730 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1731 SDValue(Res, ResNumResults-1));
1732
1733 // Otherwise, no replacement happened because the node already exists. Replace
1734 // Uses of the old node with the new one.
1735 if (Res != Node)
1736 CurDAG->ReplaceAllUsesWith(Node, Res);
1737
1738 return Res;
1739}
1740
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001741/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1742ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001743CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1744 SDValue N, const SmallVectorImpl<SDValue> &RecordedNodes) {
1745 // Accept if it is exactly the same as a previously recorded node.
1746 unsigned RecNo = MatcherTable[MatcherIndex++];
1747 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1748 return N == RecordedNodes[RecNo];
1749}
1750
1751/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1752ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001753CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1754 SelectionDAGISel &SDISel) {
1755 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1756}
1757
1758/// CheckNodePredicate - Implements OP_CheckNodePredicate.
1759ALWAYS_INLINE static bool
1760CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1761 SelectionDAGISel &SDISel, SDNode *N) {
1762 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1763}
1764
1765ALWAYS_INLINE static bool
1766CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1767 SDNode *N) {
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00001768 uint16_t Opc = MatcherTable[MatcherIndex++];
1769 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1770 return N->getOpcode() == Opc;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001771}
1772
1773ALWAYS_INLINE static bool
1774CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1775 SDValue N, const TargetLowering &TLI) {
1776 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1777 if (N.getValueType() == VT) return true;
1778
1779 // Handle the case when VT is iPTR.
1780 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1781}
1782
1783ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001784CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1785 SDValue N, const TargetLowering &TLI,
1786 unsigned ChildNo) {
1787 if (ChildNo >= N.getNumOperands())
1788 return false; // Match fails if out of range child #.
1789 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1790}
1791
1792
1793ALWAYS_INLINE static bool
1794CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1795 SDValue N) {
1796 return cast<CondCodeSDNode>(N)->get() ==
1797 (ISD::CondCode)MatcherTable[MatcherIndex++];
1798}
1799
1800ALWAYS_INLINE static bool
1801CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1802 SDValue N, const TargetLowering &TLI) {
1803 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1804 if (cast<VTSDNode>(N)->getVT() == VT)
1805 return true;
1806
1807 // Handle the case when VT is iPTR.
1808 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1809}
1810
1811ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001812CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1813 SDValue N) {
1814 int64_t Val = MatcherTable[MatcherIndex++];
1815 if (Val & 128)
1816 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1817
1818 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1819 return C != 0 && C->getSExtValue() == Val;
1820}
1821
Chris Lattnerda828e32010-03-03 07:46:25 +00001822ALWAYS_INLINE static bool
1823CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1824 SDValue N, SelectionDAGISel &SDISel) {
1825 int64_t Val = MatcherTable[MatcherIndex++];
1826 if (Val & 128)
1827 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1828
1829 if (N->getOpcode() != ISD::AND) return false;
1830
1831 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1832 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1833}
1834
1835ALWAYS_INLINE static bool
1836CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1837 SDValue N, SelectionDAGISel &SDISel) {
1838 int64_t Val = MatcherTable[MatcherIndex++];
1839 if (Val & 128)
1840 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1841
1842 if (N->getOpcode() != ISD::OR) return false;
1843
1844 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1845 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1846}
1847
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001848/// IsPredicateKnownToFail - If we know how and can do so without pushing a
1849/// scope, evaluate the current node. If the current predicate is known to
1850/// fail, set Result=true and return anything. If the current predicate is
1851/// known to pass, set Result=false and return the MatcherIndex to continue
1852/// with. If the current predicate is unknown, set Result=false and return the
1853/// MatcherIndex to continue with.
1854static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1855 unsigned Index, SDValue N,
Chris Lattnerda828e32010-03-03 07:46:25 +00001856 bool &Result, SelectionDAGISel &SDISel,
1857 SmallVectorImpl<SDValue> &RecordedNodes){
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001858 switch (Table[Index++]) {
1859 default:
1860 Result = false;
1861 return Index-1; // Could not evaluate this predicate.
Chris Lattnerda828e32010-03-03 07:46:25 +00001862 case SelectionDAGISel::OPC_CheckSame:
1863 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1864 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001865 case SelectionDAGISel::OPC_CheckPatternPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001866 Result = !::CheckPatternPredicate(Table, Index, SDISel);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001867 return Index;
1868 case SelectionDAGISel::OPC_CheckPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001869 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001870 return Index;
1871 case SelectionDAGISel::OPC_CheckOpcode:
1872 Result = !::CheckOpcode(Table, Index, N.getNode());
1873 return Index;
1874 case SelectionDAGISel::OPC_CheckType:
1875 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1876 return Index;
1877 case SelectionDAGISel::OPC_CheckChild0Type:
1878 case SelectionDAGISel::OPC_CheckChild1Type:
1879 case SelectionDAGISel::OPC_CheckChild2Type:
1880 case SelectionDAGISel::OPC_CheckChild3Type:
1881 case SelectionDAGISel::OPC_CheckChild4Type:
1882 case SelectionDAGISel::OPC_CheckChild5Type:
1883 case SelectionDAGISel::OPC_CheckChild6Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00001884 case SelectionDAGISel::OPC_CheckChild7Type:
1885 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1886 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001887 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001888 case SelectionDAGISel::OPC_CheckCondCode:
1889 Result = !::CheckCondCode(Table, Index, N);
1890 return Index;
1891 case SelectionDAGISel::OPC_CheckValueType:
1892 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1893 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001894 case SelectionDAGISel::OPC_CheckInteger:
1895 Result = !::CheckInteger(Table, Index, N);
1896 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001897 case SelectionDAGISel::OPC_CheckAndImm:
1898 Result = !::CheckAndImm(Table, Index, N, SDISel);
1899 return Index;
1900 case SelectionDAGISel::OPC_CheckOrImm:
1901 Result = !::CheckOrImm(Table, Index, N, SDISel);
1902 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001903 }
1904}
1905
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001906
Chris Lattner2a49d572010-02-28 22:37:22 +00001907struct MatchScope {
1908 /// FailIndex - If this match fails, this is the index to continue with.
1909 unsigned FailIndex;
1910
1911 /// NodeStack - The node stack when the scope was formed.
1912 SmallVector<SDValue, 4> NodeStack;
1913
1914 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1915 unsigned NumRecordedNodes;
1916
1917 /// NumMatchedMemRefs - The number of matched memref entries.
1918 unsigned NumMatchedMemRefs;
1919
1920 /// InputChain/InputFlag - The current chain/flag
1921 SDValue InputChain, InputFlag;
1922
1923 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1924 bool HasChainNodesMatched, HasFlagResultNodesMatched;
1925};
1926
1927SDNode *SelectionDAGISel::
1928SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1929 unsigned TableSize) {
1930 // FIXME: Should these even be selected? Handle these cases in the caller?
1931 switch (NodeToMatch->getOpcode()) {
1932 default:
1933 break;
1934 case ISD::EntryToken: // These nodes remain the same.
1935 case ISD::BasicBlock:
1936 case ISD::Register:
Chris Lattner3b9d6212010-03-14 17:53:23 +00001937 //case ISD::VALUETYPE:
1938 //case ISD::CONDCODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001939 case ISD::HANDLENODE:
Chris Lattnerdecc2672010-04-07 05:20:54 +00001940 case ISD::MDNODE_SDNODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001941 case ISD::TargetConstant:
1942 case ISD::TargetConstantFP:
1943 case ISD::TargetConstantPool:
1944 case ISD::TargetFrameIndex:
1945 case ISD::TargetExternalSymbol:
1946 case ISD::TargetBlockAddress:
1947 case ISD::TargetJumpTable:
1948 case ISD::TargetGlobalTLSAddress:
1949 case ISD::TargetGlobalAddress:
1950 case ISD::TokenFactor:
1951 case ISD::CopyFromReg:
1952 case ISD::CopyToReg:
Chris Lattner7561d482010-03-14 02:33:54 +00001953 case ISD::EH_LABEL:
Chris Lattnerd1b73822010-03-02 22:20:06 +00001954 NodeToMatch->setNodeId(-1); // Mark selected.
Chris Lattner2a49d572010-02-28 22:37:22 +00001955 return 0;
1956 case ISD::AssertSext:
1957 case ISD::AssertZext:
1958 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
1959 NodeToMatch->getOperand(0));
1960 return 0;
1961 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
Chris Lattner2a49d572010-02-28 22:37:22 +00001962 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
1963 }
1964
1965 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
1966
1967 // Set up the node stack with NodeToMatch as the only node on the stack.
1968 SmallVector<SDValue, 8> NodeStack;
1969 SDValue N = SDValue(NodeToMatch, 0);
1970 NodeStack.push_back(N);
1971
1972 // MatchScopes - Scopes used when matching, if a match failure happens, this
1973 // indicates where to continue checking.
1974 SmallVector<MatchScope, 8> MatchScopes;
1975
1976 // RecordedNodes - This is the set of nodes that have been recorded by the
1977 // state machine.
1978 SmallVector<SDValue, 8> RecordedNodes;
1979
1980 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
1981 // pattern.
1982 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
1983
1984 // These are the current input chain and flag for use when generating nodes.
1985 // Various Emit operations change these. For example, emitting a copytoreg
1986 // uses and updates these.
1987 SDValue InputChain, InputFlag;
1988
1989 // ChainNodesMatched - If a pattern matches nodes that have input/output
1990 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
1991 // which ones they are. The result is captured into this list so that we can
1992 // update the chain results when the pattern is complete.
1993 SmallVector<SDNode*, 3> ChainNodesMatched;
1994 SmallVector<SDNode*, 3> FlagResultNodesMatched;
1995
1996 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
1997 NodeToMatch->dump(CurDAG);
1998 errs() << '\n');
1999
Chris Lattner7390eeb2010-03-01 18:47:11 +00002000 // Determine where to start the interpreter. Normally we start at opcode #0,
2001 // but if the state machine starts with an OPC_SwitchOpcode, then we
2002 // accelerate the first lookup (which is guaranteed to be hot) with the
2003 // OpcodeOffset table.
Chris Lattner2a49d572010-02-28 22:37:22 +00002004 unsigned MatcherIndex = 0;
Chris Lattner7390eeb2010-03-01 18:47:11 +00002005
2006 if (!OpcodeOffset.empty()) {
2007 // Already computed the OpcodeOffset table, just index into it.
2008 if (N.getOpcode() < OpcodeOffset.size())
2009 MatcherIndex = OpcodeOffset[N.getOpcode()];
2010 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
2011
2012 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2013 // Otherwise, the table isn't computed, but the state machine does start
2014 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2015 // is the first time we're selecting an instruction.
2016 unsigned Idx = 1;
2017 while (1) {
2018 // Get the size of this case.
2019 unsigned CaseSize = MatcherTable[Idx++];
2020 if (CaseSize & 128)
2021 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2022 if (CaseSize == 0) break;
2023
2024 // Get the opcode, add the index to the table.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002025 uint16_t Opc = MatcherTable[Idx++];
2026 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
Chris Lattner7390eeb2010-03-01 18:47:11 +00002027 if (Opc >= OpcodeOffset.size())
2028 OpcodeOffset.resize((Opc+1)*2);
2029 OpcodeOffset[Opc] = Idx;
2030 Idx += CaseSize;
2031 }
2032
2033 // Okay, do the lookup for the first opcode.
2034 if (N.getOpcode() < OpcodeOffset.size())
2035 MatcherIndex = OpcodeOffset[N.getOpcode()];
2036 }
2037
Chris Lattner2a49d572010-02-28 22:37:22 +00002038 while (1) {
2039 assert(MatcherIndex < TableSize && "Invalid index");
Dan Gohman19b38262010-03-09 02:15:05 +00002040#ifndef NDEBUG
2041 unsigned CurrentOpcodeIndex = MatcherIndex;
2042#endif
Chris Lattner2a49d572010-02-28 22:37:22 +00002043 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2044 switch (Opcode) {
2045 case OPC_Scope: {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002046 // Okay, the semantics of this operation are that we should push a scope
2047 // then evaluate the first child. However, pushing a scope only to have
2048 // the first check fail (which then pops it) is inefficient. If we can
2049 // determine immediately that the first check (or first several) will
2050 // immediately fail, don't even bother pushing a scope for them.
2051 unsigned FailIndex;
2052
2053 while (1) {
2054 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2055 if (NumToSkip & 128)
2056 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2057 // Found the end of the scope with no match.
2058 if (NumToSkip == 0) {
2059 FailIndex = 0;
2060 break;
2061 }
2062
2063 FailIndex = MatcherIndex+NumToSkip;
2064
Chris Lattnera6f86932010-03-27 18:54:50 +00002065 unsigned MatcherIndexOfPredicate = MatcherIndex;
2066 (void)MatcherIndexOfPredicate; // silence warning.
2067
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002068 // If we can't evaluate this predicate without pushing a scope (e.g. if
2069 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2070 // push the scope and evaluate the full predicate chain.
2071 bool Result;
2072 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
Chris Lattnerda828e32010-03-03 07:46:25 +00002073 Result, *this, RecordedNodes);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002074 if (!Result)
2075 break;
2076
Chris Lattnera6f86932010-03-27 18:54:50 +00002077 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2078 << "index " << MatcherIndexOfPredicate
2079 << ", continuing at " << FailIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002080 ++NumDAGIselRetries;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002081
2082 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2083 // move to the next case.
2084 MatcherIndex = FailIndex;
2085 }
2086
2087 // If the whole scope failed to match, bail.
2088 if (FailIndex == 0) break;
2089
Chris Lattner2a49d572010-02-28 22:37:22 +00002090 // Push a MatchScope which indicates where to go if the first child fails
2091 // to match.
2092 MatchScope NewEntry;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002093 NewEntry.FailIndex = FailIndex;
Chris Lattner2a49d572010-02-28 22:37:22 +00002094 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2095 NewEntry.NumRecordedNodes = RecordedNodes.size();
2096 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2097 NewEntry.InputChain = InputChain;
2098 NewEntry.InputFlag = InputFlag;
2099 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2100 NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
2101 MatchScopes.push_back(NewEntry);
2102 continue;
2103 }
2104 case OPC_RecordNode:
2105 // Remember this node, it may end up being an operand in the pattern.
2106 RecordedNodes.push_back(N);
2107 continue;
2108
2109 case OPC_RecordChild0: case OPC_RecordChild1:
2110 case OPC_RecordChild2: case OPC_RecordChild3:
2111 case OPC_RecordChild4: case OPC_RecordChild5:
2112 case OPC_RecordChild6: case OPC_RecordChild7: {
2113 unsigned ChildNo = Opcode-OPC_RecordChild0;
2114 if (ChildNo >= N.getNumOperands())
2115 break; // Match fails if out of range child #.
2116
2117 RecordedNodes.push_back(N->getOperand(ChildNo));
2118 continue;
2119 }
2120 case OPC_RecordMemRef:
2121 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2122 continue;
2123
2124 case OPC_CaptureFlagInput:
2125 // If the current node has an input flag, capture it in InputFlag.
2126 if (N->getNumOperands() != 0 &&
2127 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
2128 InputFlag = N->getOperand(N->getNumOperands()-1);
2129 continue;
2130
2131 case OPC_MoveChild: {
2132 unsigned ChildNo = MatcherTable[MatcherIndex++];
2133 if (ChildNo >= N.getNumOperands())
2134 break; // Match fails if out of range child #.
2135 N = N.getOperand(ChildNo);
2136 NodeStack.push_back(N);
2137 continue;
2138 }
2139
2140 case OPC_MoveParent:
2141 // Pop the current node off the NodeStack.
2142 NodeStack.pop_back();
2143 assert(!NodeStack.empty() && "Node stack imbalance!");
2144 N = NodeStack.back();
2145 continue;
2146
Chris Lattnerda828e32010-03-03 07:46:25 +00002147 case OPC_CheckSame:
2148 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002149 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002150 case OPC_CheckPatternPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002151 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002152 continue;
2153 case OPC_CheckPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002154 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2155 N.getNode()))
2156 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002157 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002158 case OPC_CheckComplexPat: {
2159 unsigned CPNum = MatcherTable[MatcherIndex++];
2160 unsigned RecNo = MatcherTable[MatcherIndex++];
2161 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2162 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo], CPNum,
2163 RecordedNodes))
Chris Lattner2a49d572010-02-28 22:37:22 +00002164 break;
2165 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002166 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002167 case OPC_CheckOpcode:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002168 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2169 continue;
2170
2171 case OPC_CheckType:
2172 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002173 continue;
2174
Chris Lattnereb669212010-03-01 06:59:22 +00002175 case OPC_SwitchOpcode: {
2176 unsigned CurNodeOpcode = N.getOpcode();
Chris Lattner7d892d62010-03-01 07:43:08 +00002177 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
Chris Lattnereb669212010-03-01 06:59:22 +00002178 unsigned CaseSize;
2179 while (1) {
2180 // Get the size of this case.
2181 CaseSize = MatcherTable[MatcherIndex++];
2182 if (CaseSize & 128)
2183 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2184 if (CaseSize == 0) break;
2185
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002186 uint16_t Opc = MatcherTable[MatcherIndex++];
2187 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2188
Chris Lattnereb669212010-03-01 06:59:22 +00002189 // If the opcode matches, then we will execute this case.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002190 if (CurNodeOpcode == Opc)
Chris Lattnereb669212010-03-01 06:59:22 +00002191 break;
2192
2193 // Otherwise, skip over this case.
2194 MatcherIndex += CaseSize;
2195 }
2196
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002197 // If no cases matched, bail out.
Chris Lattnereb669212010-03-01 06:59:22 +00002198 if (CaseSize == 0) break;
2199
2200 // Otherwise, execute the case we found.
2201 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2202 << " to " << MatcherIndex << "\n");
2203 continue;
2204 }
2205
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002206 case OPC_SwitchType: {
2207 MVT::SimpleValueType CurNodeVT = N.getValueType().getSimpleVT().SimpleTy;
2208 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2209 unsigned CaseSize;
2210 while (1) {
2211 // Get the size of this case.
2212 CaseSize = MatcherTable[MatcherIndex++];
2213 if (CaseSize & 128)
2214 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2215 if (CaseSize == 0) break;
2216
2217 MVT::SimpleValueType CaseVT =
2218 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2219 if (CaseVT == MVT::iPTR)
2220 CaseVT = TLI.getPointerTy().SimpleTy;
2221
2222 // If the VT matches, then we will execute this case.
2223 if (CurNodeVT == CaseVT)
2224 break;
2225
2226 // Otherwise, skip over this case.
2227 MatcherIndex += CaseSize;
2228 }
2229
2230 // If no cases matched, bail out.
2231 if (CaseSize == 0) break;
2232
2233 // Otherwise, execute the case we found.
2234 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2235 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2236 continue;
2237 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002238 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2239 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2240 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00002241 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2242 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2243 Opcode-OPC_CheckChild0Type))
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002244 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002245 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002246 case OPC_CheckCondCode:
Chris Lattnerda828e32010-03-03 07:46:25 +00002247 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002248 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002249 case OPC_CheckValueType:
2250 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002251 continue;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002252 case OPC_CheckInteger:
2253 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002254 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002255 case OPC_CheckAndImm:
2256 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002257 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002258 case OPC_CheckOrImm:
2259 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002260 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002261
2262 case OPC_CheckFoldableChainNode: {
2263 assert(NodeStack.size() != 1 && "No parent node");
2264 // Verify that all intermediate nodes between the root and this one have
2265 // a single use.
2266 bool HasMultipleUses = false;
2267 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2268 if (!NodeStack[i].hasOneUse()) {
2269 HasMultipleUses = true;
2270 break;
2271 }
2272 if (HasMultipleUses) break;
2273
2274 // Check to see that the target thinks this is profitable to fold and that
2275 // we can fold it without inducing cycles in the graph.
2276 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2277 NodeToMatch) ||
2278 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
Chris Lattnerd1b73822010-03-02 22:20:06 +00002279 NodeToMatch, true/*We validate our own chains*/))
Chris Lattner2a49d572010-02-28 22:37:22 +00002280 break;
2281
2282 continue;
2283 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002284 case OPC_EmitInteger: {
2285 MVT::SimpleValueType VT =
2286 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2287 int64_t Val = MatcherTable[MatcherIndex++];
2288 if (Val & 128)
2289 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2290 RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
2291 continue;
2292 }
2293 case OPC_EmitRegister: {
2294 MVT::SimpleValueType VT =
2295 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2296 unsigned RegNo = MatcherTable[MatcherIndex++];
2297 RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
2298 continue;
2299 }
2300
2301 case OPC_EmitConvertToTarget: {
2302 // Convert from IMM/FPIMM to target version.
2303 unsigned RecNo = MatcherTable[MatcherIndex++];
2304 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2305 SDValue Imm = RecordedNodes[RecNo];
2306
2307 if (Imm->getOpcode() == ISD::Constant) {
2308 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2309 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2310 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2311 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2312 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2313 }
2314
2315 RecordedNodes.push_back(Imm);
2316 continue;
2317 }
2318
Chris Lattneraa4e3392010-03-28 05:50:16 +00002319 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2320 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2321 // These are space-optimized forms of OPC_EmitMergeInputChains.
2322 assert(InputChain.getNode() == 0 &&
2323 "EmitMergeInputChains should be the first chain producing node");
2324 assert(ChainNodesMatched.empty() &&
2325 "Should only have one EmitMergeInputChains per match");
2326
2327 // Read all of the chained nodes.
2328 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2329 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2330 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2331
2332 // FIXME: What if other value results of the node have uses not matched
2333 // by this pattern?
2334 if (ChainNodesMatched.back() != NodeToMatch &&
2335 !RecordedNodes[RecNo].hasOneUse()) {
2336 ChainNodesMatched.clear();
2337 break;
2338 }
2339
2340 // Merge the input chains if they are not intra-pattern references.
2341 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2342
2343 if (InputChain.getNode() == 0)
2344 break; // Failed to merge.
2345 continue;
2346 }
2347
Chris Lattner2a49d572010-02-28 22:37:22 +00002348 case OPC_EmitMergeInputChains: {
2349 assert(InputChain.getNode() == 0 &&
2350 "EmitMergeInputChains should be the first chain producing node");
2351 // This node gets a list of nodes we matched in the input that have
2352 // chains. We want to token factor all of the input chains to these nodes
2353 // together. However, if any of the input chains is actually one of the
2354 // nodes matched in this pattern, then we have an intra-match reference.
2355 // Ignore these because the newly token factored chain should not refer to
2356 // the old nodes.
2357 unsigned NumChains = MatcherTable[MatcherIndex++];
2358 assert(NumChains != 0 && "Can't TF zero chains");
2359
2360 assert(ChainNodesMatched.empty() &&
2361 "Should only have one EmitMergeInputChains per match");
2362
Chris Lattner2a49d572010-02-28 22:37:22 +00002363 // Read all of the chained nodes.
Chris Lattner00592ec2010-03-02 19:34:59 +00002364 for (unsigned i = 0; i != NumChains; ++i) {
2365 unsigned RecNo = MatcherTable[MatcherIndex++];
Chris Lattner2a49d572010-02-28 22:37:22 +00002366 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2367 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2368
2369 // FIXME: What if other value results of the node have uses not matched
2370 // by this pattern?
2371 if (ChainNodesMatched.back() != NodeToMatch &&
2372 !RecordedNodes[RecNo].hasOneUse()) {
2373 ChainNodesMatched.clear();
2374 break;
2375 }
2376 }
Chris Lattner6b307922010-03-02 00:00:03 +00002377
2378 // If the inner loop broke out, the match fails.
2379 if (ChainNodesMatched.empty())
2380 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002381
Chris Lattner6b307922010-03-02 00:00:03 +00002382 // Merge the input chains if they are not intra-pattern references.
2383 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2384
2385 if (InputChain.getNode() == 0)
2386 break; // Failed to merge.
Chris Lattner2a49d572010-02-28 22:37:22 +00002387
Chris Lattner2a49d572010-02-28 22:37:22 +00002388 continue;
2389 }
2390
2391 case OPC_EmitCopyToReg: {
2392 unsigned RecNo = MatcherTable[MatcherIndex++];
2393 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2394 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2395
2396 if (InputChain.getNode() == 0)
2397 InputChain = CurDAG->getEntryNode();
2398
2399 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2400 DestPhysReg, RecordedNodes[RecNo],
2401 InputFlag);
2402
2403 InputFlag = InputChain.getValue(1);
2404 continue;
2405 }
2406
2407 case OPC_EmitNodeXForm: {
2408 unsigned XFormNo = MatcherTable[MatcherIndex++];
2409 unsigned RecNo = MatcherTable[MatcherIndex++];
2410 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2411 RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
2412 continue;
2413 }
2414
2415 case OPC_EmitNode:
2416 case OPC_MorphNodeTo: {
Chris Lattner14df8dc2010-02-28 22:38:43 +00002417 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2418 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
Chris Lattner2a49d572010-02-28 22:37:22 +00002419 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2420 // Get the result VT list.
2421 unsigned NumVTs = MatcherTable[MatcherIndex++];
2422 SmallVector<EVT, 4> VTs;
2423 for (unsigned i = 0; i != NumVTs; ++i) {
2424 MVT::SimpleValueType VT =
2425 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2426 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2427 VTs.push_back(VT);
2428 }
2429
2430 if (EmitNodeInfo & OPFL_Chain)
2431 VTs.push_back(MVT::Other);
2432 if (EmitNodeInfo & OPFL_FlagOutput)
2433 VTs.push_back(MVT::Flag);
2434
Chris Lattner7d892d62010-03-01 07:43:08 +00002435 // This is hot code, so optimize the two most common cases of 1 and 2
2436 // results.
2437 SDVTList VTList;
2438 if (VTs.size() == 1)
2439 VTList = CurDAG->getVTList(VTs[0]);
2440 else if (VTs.size() == 2)
2441 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2442 else
2443 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
Chris Lattner2a49d572010-02-28 22:37:22 +00002444
2445 // Get the operand list.
2446 unsigned NumOps = MatcherTable[MatcherIndex++];
2447 SmallVector<SDValue, 8> Ops;
2448 for (unsigned i = 0; i != NumOps; ++i) {
2449 unsigned RecNo = MatcherTable[MatcherIndex++];
2450 if (RecNo & 128)
2451 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2452
2453 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2454 Ops.push_back(RecordedNodes[RecNo]);
2455 }
2456
2457 // If there are variadic operands to add, handle them now.
2458 if (EmitNodeInfo & OPFL_VariadicInfo) {
2459 // Determine the start index to copy from.
2460 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2461 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2462 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2463 "Invalid variadic node");
2464 // Copy all of the variadic operands, not including a potential flag
2465 // input.
2466 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2467 i != e; ++i) {
2468 SDValue V = NodeToMatch->getOperand(i);
2469 if (V.getValueType() == MVT::Flag) break;
2470 Ops.push_back(V);
2471 }
2472 }
2473
2474 // If this has chain/flag inputs, add them.
2475 if (EmitNodeInfo & OPFL_Chain)
2476 Ops.push_back(InputChain);
2477 if ((EmitNodeInfo & OPFL_FlagInput) && InputFlag.getNode() != 0)
2478 Ops.push_back(InputFlag);
2479
2480 // Create the node.
2481 SDNode *Res = 0;
2482 if (Opcode != OPC_MorphNodeTo) {
2483 // If this is a normal EmitNode command, just create the new node and
2484 // add the results to the RecordedNodes list.
2485 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2486 VTList, Ops.data(), Ops.size());
2487
2488 // Add all the non-flag/non-chain results to the RecordedNodes list.
2489 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2490 if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
2491 RecordedNodes.push_back(SDValue(Res, i));
2492 }
2493
2494 } else {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00002495 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2496 EmitNodeInfo);
Chris Lattner2a49d572010-02-28 22:37:22 +00002497 }
2498
2499 // If the node had chain/flag results, update our notion of the current
2500 // chain and flag.
Chris Lattner82dd3d32010-03-02 07:50:03 +00002501 if (EmitNodeInfo & OPFL_FlagOutput) {
Chris Lattner2a49d572010-02-28 22:37:22 +00002502 InputFlag = SDValue(Res, VTs.size()-1);
2503 if (EmitNodeInfo & OPFL_Chain)
2504 InputChain = SDValue(Res, VTs.size()-2);
2505 } else if (EmitNodeInfo & OPFL_Chain)
2506 InputChain = SDValue(Res, VTs.size()-1);
2507
2508 // If the OPFL_MemRefs flag is set on this node, slap all of the
2509 // accumulated memrefs onto it.
2510 //
2511 // FIXME: This is vastly incorrect for patterns with multiple outputs
2512 // instructions that access memory and for ComplexPatterns that match
2513 // loads.
2514 if (EmitNodeInfo & OPFL_MemRefs) {
2515 MachineSDNode::mmo_iterator MemRefs =
2516 MF->allocateMemRefsArray(MatchedMemRefs.size());
2517 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2518 cast<MachineSDNode>(Res)
2519 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2520 }
2521
2522 DEBUG(errs() << " "
2523 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2524 << " node: "; Res->dump(CurDAG); errs() << "\n");
2525
2526 // If this was a MorphNodeTo then we're completely done!
2527 if (Opcode == OPC_MorphNodeTo) {
2528 // Update chain and flag uses.
2529 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002530 InputFlag, FlagResultNodesMatched, true);
2531 return Res;
Chris Lattner2a49d572010-02-28 22:37:22 +00002532 }
2533
2534 continue;
2535 }
2536
2537 case OPC_MarkFlagResults: {
2538 unsigned NumNodes = MatcherTable[MatcherIndex++];
2539
2540 // Read and remember all the flag-result nodes.
2541 for (unsigned i = 0; i != NumNodes; ++i) {
2542 unsigned RecNo = MatcherTable[MatcherIndex++];
2543 if (RecNo & 128)
2544 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2545
2546 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2547 FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2548 }
2549 continue;
2550 }
2551
2552 case OPC_CompleteMatch: {
2553 // The match has been completed, and any new nodes (if any) have been
2554 // created. Patch up references to the matched dag to use the newly
2555 // created nodes.
2556 unsigned NumResults = MatcherTable[MatcherIndex++];
2557
2558 for (unsigned i = 0; i != NumResults; ++i) {
2559 unsigned ResSlot = MatcherTable[MatcherIndex++];
2560 if (ResSlot & 128)
2561 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2562
2563 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2564 SDValue Res = RecordedNodes[ResSlot];
2565
Chris Lattnerb0e483e2010-03-28 05:54:03 +00002566 assert(i < NodeToMatch->getNumValues() &&
2567 NodeToMatch->getValueType(i) != MVT::Other &&
2568 NodeToMatch->getValueType(i) != MVT::Flag &&
2569 "Invalid number of results to complete!");
Chris Lattner2a49d572010-02-28 22:37:22 +00002570 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2571 NodeToMatch->getValueType(i) == MVT::iPTR ||
2572 Res.getValueType() == MVT::iPTR ||
2573 NodeToMatch->getValueType(i).getSizeInBits() ==
2574 Res.getValueType().getSizeInBits()) &&
2575 "invalid replacement");
2576 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2577 }
2578
2579 // If the root node defines a flag, add it to the flag nodes to update
2580 // list.
2581 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
2582 FlagResultNodesMatched.push_back(NodeToMatch);
2583
2584 // Update chain and flag uses.
2585 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002586 InputFlag, FlagResultNodesMatched, false);
Chris Lattner2a49d572010-02-28 22:37:22 +00002587
2588 assert(NodeToMatch->use_empty() &&
2589 "Didn't replace all uses of the node?");
2590
2591 // FIXME: We just return here, which interacts correctly with SelectRoot
2592 // above. We should fix this to not return an SDNode* anymore.
2593 return 0;
2594 }
2595 }
2596
2597 // If the code reached this point, then the match failed. See if there is
2598 // another child to try in the current 'Scope', otherwise pop it until we
2599 // find a case to check.
Dan Gohman19b38262010-03-09 02:15:05 +00002600 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002601 ++NumDAGIselRetries;
Chris Lattner2a49d572010-02-28 22:37:22 +00002602 while (1) {
2603 if (MatchScopes.empty()) {
2604 CannotYetSelect(NodeToMatch);
2605 return 0;
2606 }
2607
2608 // Restore the interpreter state back to the point where the scope was
2609 // formed.
2610 MatchScope &LastScope = MatchScopes.back();
2611 RecordedNodes.resize(LastScope.NumRecordedNodes);
2612 NodeStack.clear();
2613 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2614 N = NodeStack.back();
2615
Chris Lattner2a49d572010-02-28 22:37:22 +00002616 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2617 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2618 MatcherIndex = LastScope.FailIndex;
2619
Dan Gohman19b38262010-03-09 02:15:05 +00002620 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2621
Chris Lattner2a49d572010-02-28 22:37:22 +00002622 InputChain = LastScope.InputChain;
2623 InputFlag = LastScope.InputFlag;
2624 if (!LastScope.HasChainNodesMatched)
2625 ChainNodesMatched.clear();
2626 if (!LastScope.HasFlagResultNodesMatched)
2627 FlagResultNodesMatched.clear();
2628
2629 // Check to see what the offset is at the new MatcherIndex. If it is zero
2630 // we have reached the end of this scope, otherwise we have another child
2631 // in the current scope to try.
2632 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2633 if (NumToSkip & 128)
2634 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2635
2636 // If we have another child in this scope to match, update FailIndex and
2637 // try it.
2638 if (NumToSkip != 0) {
2639 LastScope.FailIndex = MatcherIndex+NumToSkip;
2640 break;
2641 }
2642
2643 // End of this scope, pop it and try the next child in the containing
2644 // scope.
2645 MatchScopes.pop_back();
2646 }
2647 }
2648}
2649
2650
2651
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002652void SelectionDAGISel::CannotYetSelect(SDNode *N) {
Dan Gohmane1f188f2009-10-29 22:30:23 +00002653 std::string msg;
2654 raw_string_ostream Msg(msg);
2655 Msg << "Cannot yet select: ";
Chris Lattner2c4afd12010-03-04 00:21:16 +00002656
2657 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2658 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2659 N->getOpcode() != ISD::INTRINSIC_VOID) {
2660 N->printrFull(Msg, CurDAG);
2661 } else {
2662 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2663 unsigned iid =
2664 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2665 if (iid < Intrinsic::num_intrinsics)
2666 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2667 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2668 Msg << "target intrinsic %" << TII->getName(iid);
2669 else
2670 Msg << "unknown intrinsic #" << iid;
2671 }
Chris Lattner75361b62010-04-07 22:58:41 +00002672 report_fatal_error(Msg.str());
Dan Gohmane1f188f2009-10-29 22:30:23 +00002673}
2674
Devang Patel19974732007-05-03 01:11:54 +00002675char SelectionDAGISel::ID = 0;