blob: ae2b41899abc308348a9e7059da54c3cc6736425 [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"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000080 ISHeuristic("pre-RA-sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Chris Lattner5bab7852008-01-25 17:24:52 +000082 cl::desc("Instruction schedulers available (before register"
83 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000084
Jim Laskey9ff542f2006-08-01 18:29:48 +000085 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000086 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000088} // namespace
89
Evan Cheng5c807602008-02-26 02:33:44 +000090namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000091
Chris Lattner864635a2006-02-22 22:37:12 +000092namespace {
93 /// RegsForValue - This struct represents the physical registers that a
94 /// particular value is assigned and the type information about the value.
95 /// This is needed because values can be promoted into larger registers and
96 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000097 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohmanb6f5b002007-06-28 23:29:44 +000098 /// Regs - This list holds the register (for legal and promoted values)
Chris Lattner864635a2006-02-22 22:37:12 +000099 /// or register set (for expanded values) that the value should be assigned
100 /// to.
101 std::vector<unsigned> Regs;
102
103 /// RegVT - The value type of each register.
104 ///
105 MVT::ValueType RegVT;
106
107 /// ValueVT - The value type of the LLVM value, which may be promoted from
108 /// RegVT or made from merging the two expanded parts.
109 MVT::ValueType ValueVT;
110
111 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
112
113 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
114 : RegVT(regvt), ValueVT(valuevt) {
115 Regs.push_back(Reg);
116 }
117 RegsForValue(const std::vector<unsigned> &regs,
118 MVT::ValueType regvt, MVT::ValueType valuevt)
119 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
120 }
121
122 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
123 /// this value and returns the result as a ValueVT value. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000125 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000126 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000127 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000128
129 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
130 /// specified value into the registers specified by this object. This uses
131 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000132 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000134 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000141 };
142}
Evan Cheng4ef10862006-01-23 07:01:07 +0000143
Chris Lattner1c08c712005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000146 /// createDefaultScheduler - This creates an instruction scheduler appropriate
147 /// for the target.
148 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
149 SelectionDAG *DAG,
150 MachineBasicBlock *BB) {
151 TargetLowering &TLI = IS->getTargetLowering();
152
153 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
154 return createTDListDAGScheduler(IS, DAG, BB);
155 } else {
156 assert(TLI.getSchedulingPreference() ==
157 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
158 return createBURRListDAGScheduler(IS, DAG, BB);
159 }
160 }
161
162
163 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000164 /// FunctionLoweringInfo - This contains information that is global to a
165 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000166 class FunctionLoweringInfo {
167 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000168 TargetLowering &TLI;
169 Function &Fn;
170 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000171 MachineRegisterInfo &RegInfo;
Dale Johannesen1544e472008-03-31 23:40:23 +0000172 bool needsExceptionHandling;
Chris Lattner1c08c712005-01-07 07:47:53 +0000173
174 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
175
176 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
177 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
178
179 /// ValueMap - Since we emit code for the function a basic block at a time,
180 /// we must remember which virtual registers hold the values for
181 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000182 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000183
184 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
185 /// the entry block. This allows the allocas to be efficiently referenced
186 /// anywhere in the function.
187 std::map<const AllocaInst*, int> StaticAllocaMap;
188
Duncan Sandsf4070822007-06-15 19:04:19 +0000189#ifndef NDEBUG
190 SmallSet<Instruction*, 8> CatchInfoLost;
191 SmallSet<Instruction*, 8> CatchInfoFound;
192#endif
193
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000195 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000196 }
Chris Lattner571e4342006-10-27 21:36:01 +0000197
198 /// isExportedInst - Return true if the specified value is an instruction
199 /// exported from its block.
200 bool isExportedInst(const Value *V) {
201 return ValueMap.count(V);
202 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000203
Chris Lattner3c384492006-03-16 19:51:18 +0000204 unsigned CreateRegForValue(const Value *V);
205
Chris Lattner1c08c712005-01-07 07:47:53 +0000206 unsigned InitializeRegForValue(const Value *V) {
207 unsigned &R = ValueMap[V];
208 assert(R == 0 && "Already initialized this value register!");
209 return R = CreateRegForValue(V);
210 }
211 };
212}
213
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000214/// isSelector - Return true if this instruction is a call to the
215/// eh.selector intrinsic.
216static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000217 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000218 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
219 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000220 return false;
221}
222
Chris Lattner1c08c712005-01-07 07:47:53 +0000223/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000224/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000225/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000226static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
227 if (isa<PHINode>(I)) return true;
228 BasicBlock *BB = I->getParent();
229 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000230 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000231 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000232 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000233 return true;
234 return false;
235}
236
Chris Lattnerbf209482005-10-30 19:42:35 +0000237/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000238/// entry block, return true. This includes arguments used by switches, since
239/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000240static bool isOnlyUsedInEntryBlock(Argument *A) {
241 BasicBlock *Entry = A->getParent()->begin();
242 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000243 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000244 return false; // Use not in entry block.
245 return true;
246}
247
Chris Lattner1c08c712005-01-07 07:47:53 +0000248FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000249 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000250 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000251
Chris Lattnerbf209482005-10-30 19:42:35 +0000252 // Create a vreg for each argument register that is not dead and is used
253 // outside of the entry block for the function.
254 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
255 AI != E; ++AI)
256 if (!isOnlyUsedInEntryBlock(AI))
257 InitializeRegForValue(AI);
258
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 // Initialize the mapping of values to registers. This is only set up for
260 // instruction values that are used outside of the block that defines
261 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000262 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
264 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000265 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000266 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000267 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000268 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000269 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000270 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000271
Reid Spencerb83eb642006-10-20 07:07:24 +0000272 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000273 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000274 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000275 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000276 }
277
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000278 for (; BB != EB; ++BB)
279 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000280 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
281 if (!isa<AllocaInst>(I) ||
282 !StaticAllocaMap.count(cast<AllocaInst>(I)))
283 InitializeRegForValue(I);
284
285 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
286 // also creates the initial PHI MachineInstrs, though none of the input
287 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000288 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000289 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
290 MBBMap[BB] = MBB;
291 MF.getBasicBlockList().push_back(MBB);
292
293 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
294 // appropriate.
295 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000296 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
297 if (PN->use_empty()) continue;
298
299 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000300 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000301 unsigned PHIReg = ValueMap[PN];
302 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000303 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000304 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000305 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000306 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000307 }
Dale Johannesen1544e472008-03-31 23:40:23 +0000308
309 // Figure out whether we need to generate EH info. Currently we do this for
310 // all functions not marked no-unwind, or if requested via -enable-eh.
311 needsExceptionHandling = ExceptionHandling || !Fn.doesNotThrow();
Chris Lattner1c08c712005-01-07 07:47:53 +0000312}
313
Chris Lattner3c384492006-03-16 19:51:18 +0000314/// CreateRegForValue - Allocate the appropriate number of virtual registers of
315/// the correctly promoted or expanded types. Assign these registers
316/// consecutive vreg numbers and return the first assigned number.
317unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
318 MVT::ValueType VT = TLI.getValueType(V->getType());
319
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000320 unsigned NumRegisters = TLI.getNumRegisters(VT);
321 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
Bill Wendling95b39552007-04-24 21:13:23 +0000322
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000323 unsigned R = MakeReg(RegisterVT);
324 for (unsigned i = 1; i != NumRegisters; ++i)
325 MakeReg(RegisterVT);
326
Chris Lattner3c384492006-03-16 19:51:18 +0000327 return R;
328}
Chris Lattner1c08c712005-01-07 07:47:53 +0000329
330//===----------------------------------------------------------------------===//
331/// SelectionDAGLowering - This is the common target-independent lowering
332/// implementation that is parameterized by a TargetLowering object.
333/// Also, targets can overload any lowering method.
334///
335namespace llvm {
336class SelectionDAGLowering {
337 MachineBasicBlock *CurMBB;
338
Chris Lattner0da331f2007-02-04 01:31:47 +0000339 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000340
Chris Lattnerd3948112005-01-17 22:19:26 +0000341 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
342 /// them up and then emit token factor nodes when possible. This allows us to
343 /// get simple disambiguation between loads without worrying about alias
344 /// analysis.
345 std::vector<SDOperand> PendingLoads;
346
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000347 /// PendingExports - CopyToReg nodes that copy values to virtual registers
348 /// for export to other blocks need to be emitted before any terminator
349 /// instruction, but they have no other ordering requirements. We bunch them
350 /// up and the emit a single tokenfactor for them just before terminator
351 /// instructions.
352 std::vector<SDOperand> PendingExports;
353
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000354 /// Case - A struct to record the Value for a switch case, and the
355 /// case's target basic block.
356 struct Case {
357 Constant* Low;
358 Constant* High;
359 MachineBasicBlock* BB;
360
361 Case() : Low(0), High(0), BB(0) { }
362 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
363 Low(low), High(high), BB(bb) { }
364 uint64_t size() const {
365 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
366 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
367 return (rHigh - rLow + 1ULL);
368 }
369 };
370
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000371 struct CaseBits {
372 uint64_t Mask;
373 MachineBasicBlock* BB;
374 unsigned Bits;
375
376 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
377 Mask(mask), BB(bb), Bits(bits) { }
378 };
379
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000380 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000381 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000382 typedef CaseVector::iterator CaseItr;
383 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000384
385 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
386 /// of conditional branches.
387 struct CaseRec {
388 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
389 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
390
391 /// CaseBB - The MBB in which to emit the compare and branch
392 MachineBasicBlock *CaseBB;
393 /// LT, GE - If nonzero, we know the current case value must be less-than or
394 /// greater-than-or-equal-to these Constants.
395 Constant *LT;
396 Constant *GE;
397 /// Range - A pair of iterators representing the range of case values to be
398 /// processed at this point in the binary search tree.
399 CaseRange Range;
400 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000401
402 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000403
404 /// The comparison function for sorting the switch case values in the vector.
405 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000406 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000407 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000408 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
409 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
410 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
411 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000412 }
413 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000414
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000415 struct CaseBitsCmp {
416 bool operator () (const CaseBits& C1, const CaseBits& C2) {
417 return C1.Bits > C2.Bits;
418 }
419 };
420
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000421 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000422
Chris Lattner1c08c712005-01-07 07:47:53 +0000423public:
424 // TLI - This is information that describes the available target features we
425 // need for lowering. This indicates when operations are unavailable,
426 // implemented with a libcall, etc.
427 TargetLowering &TLI;
428 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000429 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000430 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000431
Nate Begemanf15485a2006-03-27 01:32:24 +0000432 /// SwitchCases - Vector of CaseBlock structures used to communicate
433 /// SwitchInst code generation information.
434 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000435 /// JTCases - Vector of JumpTable structures used to communicate
436 /// SwitchInst code generation information.
437 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000438 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000439
Chris Lattner1c08c712005-01-07 07:47:53 +0000440 /// FuncInfo - Information about the function as a whole.
441 ///
442 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000443
444 /// GCI - Garbage collection metadata for the function.
445 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000446
447 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000448 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000449 FunctionLoweringInfo &funcinfo,
450 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000451 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000452 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000453 }
454
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000455 /// getRoot - Return the current virtual root of the Selection DAG,
456 /// flushing any PendingLoad items. This must be done before emitting
457 /// a store or any other node that may need to be ordered after any
458 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000459 ///
460 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000461 if (PendingLoads.empty())
462 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000463
Chris Lattnerd3948112005-01-17 22:19:26 +0000464 if (PendingLoads.size() == 1) {
465 SDOperand Root = PendingLoads[0];
466 DAG.setRoot(Root);
467 PendingLoads.clear();
468 return Root;
469 }
470
471 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000472 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
473 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000474 PendingLoads.clear();
475 DAG.setRoot(Root);
476 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000477 }
478
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000479 /// getControlRoot - Similar to getRoot, but instead of flushing all the
480 /// PendingLoad items, flush all the PendingExports items. It is necessary
481 /// to do this before emitting a terminator instruction.
482 ///
483 SDOperand getControlRoot() {
484 SDOperand Root = DAG.getRoot();
485
486 if (PendingExports.empty())
487 return Root;
488
489 // Turn all of the CopyToReg chains into one factored node.
490 if (Root.getOpcode() != ISD::EntryToken) {
491 unsigned i = 0, e = PendingExports.size();
492 for (; i != e; ++i) {
493 assert(PendingExports[i].Val->getNumOperands() > 1);
494 if (PendingExports[i].Val->getOperand(0) == Root)
495 break; // Don't add the root if we already indirectly depend on it.
496 }
497
498 if (i == e)
499 PendingExports.push_back(Root);
500 }
501
502 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
503 &PendingExports[0],
504 PendingExports.size());
505 PendingExports.clear();
506 DAG.setRoot(Root);
507 return Root;
508 }
509
510 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000511
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 void visit(Instruction &I) { visit(I.getOpcode(), I); }
513
514 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000515 // Note: this doesn't use InstVisitor, because it has to work with
516 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000517 switch (Opcode) {
518 default: assert(0 && "Unknown instruction type encountered!");
519 abort();
520 // Build the switch statement using the Instruction.def file.
521#define HANDLE_INST(NUM, OPCODE, CLASS) \
522 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
523#include "llvm/Instruction.def"
524 }
525 }
526
527 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
528
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000529 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000530 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000531 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000532
Chris Lattner199862b2006-03-16 19:57:50 +0000533 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000534
Chris Lattner0da331f2007-02-04 01:31:47 +0000535 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000536 SDOperand &N = NodeMap[V];
537 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000538 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000539 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000540
Evan Cheng5c807602008-02-26 02:33:44 +0000541 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000542 std::set<unsigned> &OutputRegs,
543 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000544
Chris Lattner571e4342006-10-27 21:36:01 +0000545 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
546 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
547 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000548 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000549 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000550 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000551 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000552
Chris Lattner1c08c712005-01-07 07:47:53 +0000553 // Terminator instructions.
554 void visitRet(ReturnInst &I);
555 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000556 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 void visitUnreachable(UnreachableInst &I) { /* noop */ }
558
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000559 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000560 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000561 CaseRecVector& WorkList,
562 Value* SV,
563 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000564 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000565 CaseRecVector& WorkList,
566 Value* SV,
567 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000568 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000569 CaseRecVector& WorkList,
570 Value* SV,
571 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000572 bool handleBitTestsSwitchCase(CaseRec& CR,
573 CaseRecVector& WorkList,
574 Value* SV,
575 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000576 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000577 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
578 void visitBitTestCase(MachineBasicBlock* NextMBB,
579 unsigned Reg,
580 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000581 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000582 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
583 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000584
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000586 void visitInvoke(InvokeInst &I);
587 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000588
Dan Gohman7f321562007-06-25 16:23:39 +0000589 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000590 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000591 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000592 if (I.getType()->isFPOrFPVector())
593 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000594 else
Dan Gohman7f321562007-06-25 16:23:39 +0000595 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000596 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000597 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000598 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000599 if (I.getType()->isFPOrFPVector())
600 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000601 else
Dan Gohman7f321562007-06-25 16:23:39 +0000602 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000603 }
Dan Gohman7f321562007-06-25 16:23:39 +0000604 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
605 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
606 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
607 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
608 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
609 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
610 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
611 void visitOr (User &I) { visitBinary(I, ISD::OR); }
612 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000613 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000614 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
615 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000616 void visitICmp(User &I);
617 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000618 // Visit the conversion instructions
619 void visitTrunc(User &I);
620 void visitZExt(User &I);
621 void visitSExt(User &I);
622 void visitFPTrunc(User &I);
623 void visitFPExt(User &I);
624 void visitFPToUI(User &I);
625 void visitFPToSI(User &I);
626 void visitUIToFP(User &I);
627 void visitSIToFP(User &I);
628 void visitPtrToInt(User &I);
629 void visitIntToPtr(User &I);
630 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000631
Chris Lattner2bbd8102006-03-29 00:11:43 +0000632 void visitExtractElement(User &I);
633 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000634 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000635
Chris Lattner1c08c712005-01-07 07:47:53 +0000636 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000637 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000638
639 void visitMalloc(MallocInst &I);
640 void visitFree(FreeInst &I);
641 void visitAlloca(AllocaInst &I);
642 void visitLoad(LoadInst &I);
643 void visitStore(StoreInst &I);
644 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
645 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000646 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000647 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000648 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000649
Chris Lattner1c08c712005-01-07 07:47:53 +0000650 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000651 void visitVAArg(VAArgInst &I);
652 void visitVAEnd(CallInst &I);
653 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000654
Chris Lattner7041ee32005-01-11 05:56:49 +0000655 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000656
Dan Gohmanef5d1942008-03-11 21:11:25 +0000657 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000658
Chris Lattner1c08c712005-01-07 07:47:53 +0000659 void visitUserOp1(Instruction &I) {
660 assert(0 && "UserOp1 should not exist at instruction selection time!");
661 abort();
662 }
663 void visitUserOp2(Instruction &I) {
664 assert(0 && "UserOp2 should not exist at instruction selection time!");
665 abort();
666 }
667};
668} // end namespace llvm
669
Dan Gohman6183f782007-07-05 20:12:34 +0000670
Duncan Sandsb988bac2008-02-11 20:58:28 +0000671/// getCopyFromParts - Create a value that contains the specified legal parts
672/// combined into the value they represent. If the parts combine to a type
673/// larger then ValueVT then AssertOp can be used to specify whether the extra
674/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000675/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000676static SDOperand getCopyFromParts(SelectionDAG &DAG,
677 const SDOperand *Parts,
678 unsigned NumParts,
679 MVT::ValueType PartVT,
680 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000681 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000682 assert(NumParts > 0 && "No parts to assemble!");
683 TargetLowering &TLI = DAG.getTargetLoweringInfo();
684 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000685
Duncan Sands014e04a2008-02-12 20:46:31 +0000686 if (NumParts > 1) {
687 // Assemble the value from multiple parts.
688 if (!MVT::isVector(ValueVT)) {
689 unsigned PartBits = MVT::getSizeInBits(PartVT);
690 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000691
Duncan Sands014e04a2008-02-12 20:46:31 +0000692 // Assemble the power of 2 part.
693 unsigned RoundParts = NumParts & (NumParts - 1) ?
694 1 << Log2_32(NumParts) : NumParts;
695 unsigned RoundBits = PartBits * RoundParts;
696 MVT::ValueType RoundVT = RoundBits == ValueBits ?
697 ValueVT : MVT::getIntegerType(RoundBits);
698 SDOperand Lo, Hi;
699
700 if (RoundParts > 2) {
701 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
702 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
703 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
704 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000705 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000706 Lo = Parts[0];
707 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000708 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000709 if (TLI.isBigEndian())
710 std::swap(Lo, Hi);
711 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
712
713 if (RoundParts < NumParts) {
714 // Assemble the trailing non-power-of-2 part.
715 unsigned OddParts = NumParts - RoundParts;
716 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
717 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
718
719 // Combine the round and odd parts.
720 Lo = Val;
721 if (TLI.isBigEndian())
722 std::swap(Lo, Hi);
723 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
724 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
725 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
726 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
727 TLI.getShiftAmountTy()));
728 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
729 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
730 }
731 } else {
732 // Handle a multi-element vector.
733 MVT::ValueType IntermediateVT, RegisterVT;
734 unsigned NumIntermediates;
735 unsigned NumRegs =
736 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
737 RegisterVT);
738
739 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
740 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
741 assert(RegisterVT == Parts[0].getValueType() &&
742 "Part type doesn't match part!");
743
744 // Assemble the parts into intermediate operands.
745 SmallVector<SDOperand, 8> Ops(NumIntermediates);
746 if (NumIntermediates == NumParts) {
747 // If the register was not expanded, truncate or copy the value,
748 // as appropriate.
749 for (unsigned i = 0; i != NumParts; ++i)
750 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
751 PartVT, IntermediateVT);
752 } else if (NumParts > 0) {
753 // If the intermediate type was expanded, build the intermediate operands
754 // from the parts.
755 assert(NumParts % NumIntermediates == 0 &&
756 "Must expand into a divisible number of parts!");
757 unsigned Factor = NumParts / NumIntermediates;
758 for (unsigned i = 0; i != NumIntermediates; ++i)
759 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
760 PartVT, IntermediateVT);
761 }
762
763 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
764 // operands.
765 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
766 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
767 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000768 }
Dan Gohman6183f782007-07-05 20:12:34 +0000769 }
770
Duncan Sands014e04a2008-02-12 20:46:31 +0000771 // There is now one part, held in Val. Correct it to match ValueVT.
772 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000773
Duncan Sands014e04a2008-02-12 20:46:31 +0000774 if (PartVT == ValueVT)
775 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000776
Duncan Sands014e04a2008-02-12 20:46:31 +0000777 if (MVT::isVector(PartVT)) {
778 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
779 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000780 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000781
782 if (MVT::isVector(ValueVT)) {
783 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
784 MVT::getVectorNumElements(ValueVT) == 1 &&
785 "Only trivial scalar-to-vector conversions should get here!");
786 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
787 }
788
789 if (MVT::isInteger(PartVT) &&
790 MVT::isInteger(ValueVT)) {
791 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
792 // For a truncate, see if we have any information to
793 // indicate whether the truncated bits will always be
794 // zero or sign-extension.
795 if (AssertOp != ISD::DELETED_NODE)
796 Val = DAG.getNode(AssertOp, PartVT, Val,
797 DAG.getValueType(ValueVT));
798 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
799 } else {
800 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
801 }
802 }
803
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000804 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
805 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000806 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000807 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000808 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000809 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
810 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000811
812 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
813 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
814
815 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000816 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000817}
818
Duncan Sandsb988bac2008-02-11 20:58:28 +0000819/// getCopyToParts - Create a series of nodes that contain the specified value
820/// split into legal parts. If the parts contain more bits than Val, then, for
821/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000822static void getCopyToParts(SelectionDAG &DAG,
823 SDOperand Val,
824 SDOperand *Parts,
825 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000826 MVT::ValueType PartVT,
827 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000828 TargetLowering &TLI = DAG.getTargetLoweringInfo();
829 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000830 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000831 unsigned PartBits = MVT::getSizeInBits(PartVT);
832 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000833
Duncan Sands014e04a2008-02-12 20:46:31 +0000834 if (!NumParts)
835 return;
836
837 if (!MVT::isVector(ValueVT)) {
838 if (PartVT == ValueVT) {
839 assert(NumParts == 1 && "No-op copy with multiple parts!");
840 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000841 return;
842 }
843
Duncan Sands014e04a2008-02-12 20:46:31 +0000844 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
845 // If the parts cover more bits than the value has, promote the value.
846 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
847 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000848 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
850 ValueVT = MVT::getIntegerType(NumParts * PartBits);
851 Val = DAG.getNode(ExtendKind, ValueVT, Val);
852 } else {
853 assert(0 && "Unknown mismatch!");
854 }
855 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
856 // Different types of the same size.
857 assert(NumParts == 1 && PartVT != ValueVT);
858 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
859 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
860 // If the parts cover less bits than value has, truncate the value.
861 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
862 ValueVT = MVT::getIntegerType(NumParts * PartBits);
863 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000864 } else {
865 assert(0 && "Unknown mismatch!");
866 }
867 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000868
869 // The value may have changed - recompute ValueVT.
870 ValueVT = Val.getValueType();
871 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
872 "Failed to tile the value with PartVT!");
873
874 if (NumParts == 1) {
875 assert(PartVT == ValueVT && "Type conversion failed!");
876 Parts[0] = Val;
877 return;
878 }
879
880 // Expand the value into multiple parts.
881 if (NumParts & (NumParts - 1)) {
882 // The number of parts is not a power of 2. Split off and copy the tail.
883 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
884 "Do not know what to expand to!");
885 unsigned RoundParts = 1 << Log2_32(NumParts);
886 unsigned RoundBits = RoundParts * PartBits;
887 unsigned OddParts = NumParts - RoundParts;
888 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
889 DAG.getConstant(RoundBits,
890 TLI.getShiftAmountTy()));
891 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
892 if (TLI.isBigEndian())
893 // The odd parts were reversed by getCopyToParts - unreverse them.
894 std::reverse(Parts + RoundParts, Parts + NumParts);
895 NumParts = RoundParts;
896 ValueVT = MVT::getIntegerType(NumParts * PartBits);
897 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
898 }
899
900 // The number of parts is a power of 2. Repeatedly bisect the value using
901 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000902 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
903 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
904 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000905 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
906 for (unsigned i = 0; i < NumParts; i += StepSize) {
907 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000908 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
909 SDOperand &Part0 = Parts[i];
910 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000911
Duncan Sands25eb0432008-03-12 20:30:08 +0000912 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
913 DAG.getConstant(1, PtrVT));
914 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
915 DAG.getConstant(0, PtrVT));
916
917 if (ThisBits == PartBits && ThisVT != PartVT) {
918 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
919 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
920 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000921 }
922 }
923
924 if (TLI.isBigEndian())
925 std::reverse(Parts, Parts + NumParts);
926
927 return;
928 }
929
930 // Vector ValueVT.
931 if (NumParts == 1) {
932 if (PartVT != ValueVT) {
933 if (MVT::isVector(PartVT)) {
934 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
935 } else {
936 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
937 MVT::getVectorNumElements(ValueVT) == 1 &&
938 "Only trivial vector-to-scalar conversions should get here!");
939 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
940 DAG.getConstant(0, PtrVT));
941 }
942 }
943
Dan Gohman6183f782007-07-05 20:12:34 +0000944 Parts[0] = Val;
945 return;
946 }
947
948 // Handle a multi-element vector.
949 MVT::ValueType IntermediateVT, RegisterVT;
950 unsigned NumIntermediates;
951 unsigned NumRegs =
952 DAG.getTargetLoweringInfo()
953 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
954 RegisterVT);
955 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
956
957 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
958 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
959
960 // Split the vector into intermediate operands.
961 SmallVector<SDOperand, 8> Ops(NumIntermediates);
962 for (unsigned i = 0; i != NumIntermediates; ++i)
963 if (MVT::isVector(IntermediateVT))
964 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
965 IntermediateVT, Val,
966 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +0000967 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +0000968 else
969 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
970 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +0000971 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +0000972
973 // Split the intermediate operands into legal parts.
974 if (NumParts == NumIntermediates) {
975 // If the register was not expanded, promote or copy the value,
976 // as appropriate.
977 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +0000978 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000979 } else if (NumParts > 0) {
980 // If the intermediate type was expanded, split each the value into
981 // legal parts.
982 assert(NumParts % NumIntermediates == 0 &&
983 "Must expand into a divisible number of parts!");
984 unsigned Factor = NumParts / NumIntermediates;
985 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +0000986 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000987 }
988}
989
990
Chris Lattner199862b2006-03-16 19:57:50 +0000991SDOperand SelectionDAGLowering::getValue(const Value *V) {
992 SDOperand &N = NodeMap[V];
993 if (N.Val) return N;
994
995 const Type *VTy = V->getType();
996 MVT::ValueType VT = TLI.getValueType(VTy);
997 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
998 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
999 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +00001000 SDOperand N1 = NodeMap[V];
1001 assert(N1.Val && "visit didn't populate the ValueMap!");
1002 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +00001003 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
1004 return N = DAG.getGlobalAddress(GV, VT);
1005 } else if (isa<ConstantPointerNull>(C)) {
1006 return N = DAG.getConstant(0, TLI.getPointerTy());
1007 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001008 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +00001009 return N = DAG.getNode(ISD::UNDEF, VT);
1010
Dan Gohman7f321562007-06-25 16:23:39 +00001011 // Create a BUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001012 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +00001013 unsigned NumElements = PTy->getNumElements();
1014 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1015
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001016 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +00001017 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1018
1019 // Create a VConstant node with generic Vector type.
Dan Gohman7f321562007-06-25 16:23:39 +00001020 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1021 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001022 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001023 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001024 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +00001025 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +00001026 unsigned NumElements = PTy->getNumElements();
1027 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +00001028
1029 // Now that we know the number and type of the elements, push a
1030 // Constant or ConstantFP node onto the ops list for each element of
Dan Gohman07a96762007-07-16 14:29:03 +00001031 // the vector constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001032 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001033 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +00001034 for (unsigned i = 0; i != NumElements; ++i)
1035 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +00001036 } else {
Dan Gohman07a96762007-07-16 14:29:03 +00001037 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Chris Lattner199862b2006-03-16 19:57:50 +00001038 SDOperand Op;
1039 if (MVT::isFloatingPoint(PVT))
1040 Op = DAG.getConstantFP(0, PVT);
1041 else
1042 Op = DAG.getConstant(0, PVT);
1043 Ops.assign(NumElements, Op);
1044 }
1045
Dan Gohman7f321562007-06-25 16:23:39 +00001046 // Create a BUILD_VECTOR node.
1047 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1048 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner0da331f2007-02-04 01:31:47 +00001049 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001050 } else {
1051 // Canonicalize all constant ints to be unsigned.
Dan Gohmanc6f9a062008-02-29 01:41:59 +00001052 return N = DAG.getConstant(cast<ConstantInt>(C)->getValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +00001053 }
1054 }
1055
1056 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1057 std::map<const AllocaInst*, int>::iterator SI =
1058 FuncInfo.StaticAllocaMap.find(AI);
1059 if (SI != FuncInfo.StaticAllocaMap.end())
1060 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1061 }
1062
Chris Lattner251db182007-02-25 18:40:32 +00001063 unsigned InReg = FuncInfo.ValueMap[V];
1064 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001065
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001066 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
1067 unsigned NumRegs = TLI.getNumRegisters(VT);
Chris Lattner70c2a612006-03-31 02:06:56 +00001068
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001069 std::vector<unsigned> Regs(NumRegs);
1070 for (unsigned i = 0; i != NumRegs; ++i)
1071 Regs[i] = InReg + i;
1072
1073 RegsForValue RFV(Regs, RegisterVT, VT);
1074 SDOperand Chain = DAG.getEntryNode();
1075
1076 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001077}
1078
1079
Chris Lattner1c08c712005-01-07 07:47:53 +00001080void SelectionDAGLowering::visitRet(ReturnInst &I) {
1081 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001082 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001083 return;
1084 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001085 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001086 NewValues.push_back(getControlRoot());
1087 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001088 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001089 MVT::ValueType VT = RetOp.getValueType();
1090
Evan Cheng8e7d0562006-05-26 23:09:09 +00001091 // FIXME: C calling convention requires the return type to be promoted to
1092 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001093 if (MVT::isInteger(VT)) {
1094 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1095 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1096 VT = MinVT;
1097 }
1098
1099 unsigned NumParts = TLI.getNumRegisters(VT);
1100 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1101 SmallVector<SDOperand, 4> Parts(NumParts);
1102 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1103
1104 const Function *F = I.getParent()->getParent();
1105 if (F->paramHasAttr(0, ParamAttr::SExt))
1106 ExtendKind = ISD::SIGN_EXTEND;
1107 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1108 ExtendKind = ISD::ZERO_EXTEND;
1109
1110 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1111
1112 for (unsigned i = 0; i < NumParts; ++i) {
1113 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001114 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001115 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001116 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001117 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1118 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001119}
1120
Chris Lattner571e4342006-10-27 21:36:01 +00001121/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1122/// the current basic block, add it to ValueMap now so that we'll get a
1123/// CopyTo/FromReg.
1124void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1125 // No need to export constants.
1126 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1127
1128 // Already exported?
1129 if (FuncInfo.isExportedInst(V)) return;
1130
1131 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001132 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001133}
1134
Chris Lattner8c494ab2006-10-27 23:50:33 +00001135bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1136 const BasicBlock *FromBB) {
1137 // The operands of the setcc have to be in this block. We don't know
1138 // how to export them from some other block.
1139 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1140 // Can export from current BB.
1141 if (VI->getParent() == FromBB)
1142 return true;
1143
1144 // Is already exported, noop.
1145 return FuncInfo.isExportedInst(V);
1146 }
1147
1148 // If this is an argument, we can export it if the BB is the entry block or
1149 // if it is already exported.
1150 if (isa<Argument>(V)) {
1151 if (FromBB == &FromBB->getParent()->getEntryBlock())
1152 return true;
1153
1154 // Otherwise, can only export this if it is already exported.
1155 return FuncInfo.isExportedInst(V);
1156 }
1157
1158 // Otherwise, constants can always be exported.
1159 return true;
1160}
1161
Chris Lattner6a586c82006-10-29 21:01:20 +00001162static bool InBlock(const Value *V, const BasicBlock *BB) {
1163 if (const Instruction *I = dyn_cast<Instruction>(V))
1164 return I->getParent() == BB;
1165 return true;
1166}
1167
Chris Lattner571e4342006-10-27 21:36:01 +00001168/// FindMergedConditions - If Cond is an expression like
1169void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1170 MachineBasicBlock *TBB,
1171 MachineBasicBlock *FBB,
1172 MachineBasicBlock *CurBB,
1173 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001174 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001175 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001176
Reid Spencere4d87aa2006-12-23 06:05:41 +00001177 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1178 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001179 BOp->getParent() != CurBB->getBasicBlock() ||
1180 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1181 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001182 const BasicBlock *BB = CurBB->getBasicBlock();
1183
Reid Spencere4d87aa2006-12-23 06:05:41 +00001184 // If the leaf of the tree is a comparison, merge the condition into
1185 // the caseblock.
1186 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1187 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001188 // how to export them from some other block. If this is the first block
1189 // of the sequence, no exporting is needed.
1190 (CurBB == CurMBB ||
1191 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1192 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001193 BOp = cast<Instruction>(Cond);
1194 ISD::CondCode Condition;
1195 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1196 switch (IC->getPredicate()) {
1197 default: assert(0 && "Unknown icmp predicate opcode!");
1198 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1199 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1200 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1201 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1202 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1203 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1204 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1205 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1206 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1207 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1208 }
1209 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1210 ISD::CondCode FPC, FOC;
1211 switch (FC->getPredicate()) {
1212 default: assert(0 && "Unknown fcmp predicate opcode!");
1213 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1214 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1215 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1216 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1217 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1218 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1219 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1220 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1221 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1222 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1223 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1224 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1225 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1226 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1227 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1228 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1229 }
1230 if (FiniteOnlyFPMath())
1231 Condition = FOC;
1232 else
1233 Condition = FPC;
1234 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001235 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001237 }
1238
Chris Lattner571e4342006-10-27 21:36:01 +00001239 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001240 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001241 SwitchCases.push_back(CB);
1242 return;
1243 }
1244
1245 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001246 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001247 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001248 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001249 return;
1250 }
1251
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001252
1253 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001254 MachineFunction::iterator BBI = CurBB;
1255 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1256 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1257
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001258 if (Opc == Instruction::Or) {
1259 // Codegen X | Y as:
1260 // jmp_if_X TBB
1261 // jmp TmpBB
1262 // TmpBB:
1263 // jmp_if_Y TBB
1264 // jmp FBB
1265 //
Chris Lattner571e4342006-10-27 21:36:01 +00001266
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001267 // Emit the LHS condition.
1268 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1269
1270 // Emit the RHS condition into TmpBB.
1271 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1272 } else {
1273 assert(Opc == Instruction::And && "Unknown merge op!");
1274 // Codegen X & Y as:
1275 // jmp_if_X TmpBB
1276 // jmp FBB
1277 // TmpBB:
1278 // jmp_if_Y TBB
1279 // jmp FBB
1280 //
1281 // This requires creation of TmpBB after CurBB.
1282
1283 // Emit the LHS condition.
1284 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1285
1286 // Emit the RHS condition into TmpBB.
1287 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1288 }
Chris Lattner571e4342006-10-27 21:36:01 +00001289}
1290
Chris Lattnerdf19f272006-10-31 22:37:42 +00001291/// If the set of cases should be emitted as a series of branches, return true.
1292/// If we should emit this as a bunch of and/or'd together conditions, return
1293/// false.
1294static bool
1295ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1296 if (Cases.size() != 2) return true;
1297
Chris Lattner0ccb5002006-10-31 23:06:00 +00001298 // If this is two comparisons of the same values or'd or and'd together, they
1299 // will get folded into a single comparison, so don't emit two blocks.
1300 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1301 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1302 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1303 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1304 return false;
1305 }
1306
Chris Lattnerdf19f272006-10-31 22:37:42 +00001307 return true;
1308}
1309
Chris Lattner1c08c712005-01-07 07:47:53 +00001310void SelectionDAGLowering::visitBr(BranchInst &I) {
1311 // Update machine-CFG edges.
1312 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001313
1314 // Figure out which block is immediately after the current one.
1315 MachineBasicBlock *NextBlock = 0;
1316 MachineFunction::iterator BBI = CurMBB;
1317 if (++BBI != CurMBB->getParent()->end())
1318 NextBlock = BBI;
1319
1320 if (I.isUnconditional()) {
1321 // If this is not a fall-through branch, emit the branch.
1322 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001323 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001324 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001325
Chris Lattner57ab6592006-10-24 17:57:59 +00001326 // Update machine-CFG edges.
1327 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001328 return;
1329 }
1330
1331 // If this condition is one of the special cases we handle, do special stuff
1332 // now.
1333 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001334 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001335
1336 // If this is a series of conditions that are or'd or and'd together, emit
1337 // this as a sequence of branches instead of setcc's with and/or operations.
1338 // For example, instead of something like:
1339 // cmp A, B
1340 // C = seteq
1341 // cmp D, E
1342 // F = setle
1343 // or C, F
1344 // jnz foo
1345 // Emit:
1346 // cmp A, B
1347 // je foo
1348 // cmp D, E
1349 // jle foo
1350 //
1351 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1352 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001353 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001354 BOp->getOpcode() == Instruction::Or)) {
1355 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001356 // If the compares in later blocks need to use values not currently
1357 // exported from this block, export them now. This block should always
1358 // be the first entry.
1359 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1360
Chris Lattnerdf19f272006-10-31 22:37:42 +00001361 // Allow some cases to be rejected.
1362 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001363 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1364 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1365 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1366 }
1367
1368 // Emit the branch for this block.
1369 visitSwitchCase(SwitchCases[0]);
1370 SwitchCases.erase(SwitchCases.begin());
1371 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001372 }
1373
Chris Lattner0ccb5002006-10-31 23:06:00 +00001374 // Okay, we decided not to do this, remove any inserted MBB's and clear
1375 // SwitchCases.
1376 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1377 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1378
Chris Lattnerdf19f272006-10-31 22:37:42 +00001379 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001380 }
1381 }
Chris Lattner24525952006-10-24 18:07:37 +00001382
1383 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001384 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001385 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001386 // Use visitSwitchCase to actually insert the fast branch sequence for this
1387 // cond branch.
1388 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001389}
1390
Nate Begemanf15485a2006-03-27 01:32:24 +00001391/// visitSwitchCase - Emits the necessary code to represent a single node in
1392/// the binary search tree resulting from lowering a switch instruction.
1393void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001394 SDOperand Cond;
1395 SDOperand CondLHS = getValue(CB.CmpLHS);
1396
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001397 // Build the setcc now.
1398 if (CB.CmpMHS == NULL) {
1399 // Fold "(X == true)" to X and "(X == false)" to !X to
1400 // handle common cases produced by branch lowering.
1401 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1402 Cond = CondLHS;
1403 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1404 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1405 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1406 } else
1407 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1408 } else {
1409 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001410
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001411 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1412 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1413
1414 SDOperand CmpOp = getValue(CB.CmpMHS);
1415 MVT::ValueType VT = CmpOp.getValueType();
1416
1417 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1418 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1419 } else {
1420 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1421 Cond = DAG.getSetCC(MVT::i1, SUB,
1422 DAG.getConstant(High-Low, VT), ISD::SETULE);
1423 }
1424
1425 }
1426
Nate Begemanf15485a2006-03-27 01:32:24 +00001427 // Set NextBlock to be the MBB immediately after the current one, if any.
1428 // This is used to avoid emitting unnecessary branches to the next block.
1429 MachineBasicBlock *NextBlock = 0;
1430 MachineFunction::iterator BBI = CurMBB;
1431 if (++BBI != CurMBB->getParent()->end())
1432 NextBlock = BBI;
1433
1434 // If the lhs block is the next block, invert the condition so that we can
1435 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001436 if (CB.TrueBB == NextBlock) {
1437 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001438 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1439 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1440 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001441 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001442 DAG.getBasicBlock(CB.TrueBB));
1443 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001444 DAG.setRoot(BrCond);
1445 else
1446 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001447 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001448 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001449 CurMBB->addSuccessor(CB.TrueBB);
1450 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001451}
1452
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001453/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001454void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001455 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001456 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001457 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001458 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001459 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1460 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1461 Table, Index));
1462 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001463}
1464
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001465/// visitJumpTableHeader - This function emits necessary code to produce index
1466/// in the JumpTable from switch case.
1467void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1468 SelectionDAGISel::JumpTableHeader &JTH) {
1469 // Subtract the lowest switch case value from the value being switched on
1470 // and conditional branch to default mbb if the result is greater than the
1471 // difference between smallest and largest cases.
1472 SDOperand SwitchOp = getValue(JTH.SValue);
1473 MVT::ValueType VT = SwitchOp.getValueType();
1474 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1475 DAG.getConstant(JTH.First, VT));
1476
1477 // The SDNode we just created, which holds the value being switched on
1478 // minus the the smallest case value, needs to be copied to a virtual
1479 // register so it can be used as an index into the jump table in a
1480 // subsequent basic block. This value may be smaller or larger than the
1481 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001482 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001483 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1484 else
1485 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1486
1487 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001488 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001489 JT.Reg = JumpTableReg;
1490
1491 // Emit the range check for the jump table, and branch to the default
1492 // block for the switch statement if the value being switched on exceeds
1493 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001494 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001495 DAG.getConstant(JTH.Last-JTH.First,VT),
1496 ISD::SETUGT);
1497
1498 // Set NextBlock to be the MBB immediately after the current one, if any.
1499 // This is used to avoid emitting unnecessary branches to the next block.
1500 MachineBasicBlock *NextBlock = 0;
1501 MachineFunction::iterator BBI = CurMBB;
1502 if (++BBI != CurMBB->getParent()->end())
1503 NextBlock = BBI;
1504
1505 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1506 DAG.getBasicBlock(JT.Default));
1507
1508 if (JT.MBB == NextBlock)
1509 DAG.setRoot(BrCond);
1510 else
1511 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001512 DAG.getBasicBlock(JT.MBB)));
1513
1514 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001515}
1516
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001517/// visitBitTestHeader - This function emits necessary code to produce value
1518/// suitable for "bit tests"
1519void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1520 // Subtract the minimum value
1521 SDOperand SwitchOp = getValue(B.SValue);
1522 MVT::ValueType VT = SwitchOp.getValueType();
1523 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1524 DAG.getConstant(B.First, VT));
1525
1526 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001527 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001528 DAG.getConstant(B.Range, VT),
1529 ISD::SETUGT);
1530
1531 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001532 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001533 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1534 else
1535 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1536
1537 // Make desired shift
1538 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1539 DAG.getConstant(1, TLI.getPointerTy()),
1540 ShiftOp);
1541
1542 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001543 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001544 B.Reg = SwitchReg;
1545
1546 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1547 DAG.getBasicBlock(B.Default));
1548
1549 // Set NextBlock to be the MBB immediately after the current one, if any.
1550 // This is used to avoid emitting unnecessary branches to the next block.
1551 MachineBasicBlock *NextBlock = 0;
1552 MachineFunction::iterator BBI = CurMBB;
1553 if (++BBI != CurMBB->getParent()->end())
1554 NextBlock = BBI;
1555
1556 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1557 if (MBB == NextBlock)
1558 DAG.setRoot(BrRange);
1559 else
1560 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1561 DAG.getBasicBlock(MBB)));
1562
1563 CurMBB->addSuccessor(B.Default);
1564 CurMBB->addSuccessor(MBB);
1565
1566 return;
1567}
1568
1569/// visitBitTestCase - this function produces one "bit test"
1570void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1571 unsigned Reg,
1572 SelectionDAGISel::BitTestCase &B) {
1573 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001574 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001575
1576 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1577 SwitchVal,
1578 DAG.getConstant(B.Mask,
1579 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001580 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001581 DAG.getConstant(0, TLI.getPointerTy()),
1582 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001583 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001584 AndCmp, DAG.getBasicBlock(B.TargetBB));
1585
1586 // Set NextBlock to be the MBB immediately after the current one, if any.
1587 // This is used to avoid emitting unnecessary branches to the next block.
1588 MachineBasicBlock *NextBlock = 0;
1589 MachineFunction::iterator BBI = CurMBB;
1590 if (++BBI != CurMBB->getParent()->end())
1591 NextBlock = BBI;
1592
1593 if (NextMBB == NextBlock)
1594 DAG.setRoot(BrAnd);
1595 else
1596 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1597 DAG.getBasicBlock(NextMBB)));
1598
1599 CurMBB->addSuccessor(B.TargetBB);
1600 CurMBB->addSuccessor(NextMBB);
1601
1602 return;
1603}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001604
Jim Laskeyb180aa12007-02-21 22:53:45 +00001605void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1606 // Retrieve successors.
1607 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001608 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001609
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001610 if (isa<InlineAsm>(I.getCalledValue()))
1611 visitInlineAsm(&I);
1612 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001613 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001614
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001615 // If the value of the invoke is used outside of its defining block, make it
1616 // available as a virtual register.
1617 if (!I.use_empty()) {
1618 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1619 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001620 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001621 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001622
1623 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001624 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001625 DAG.getBasicBlock(Return)));
1626
1627 // Update successor info
1628 CurMBB->addSuccessor(Return);
1629 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001630}
1631
1632void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1633}
1634
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001635/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001636/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001637bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001638 CaseRecVector& WorkList,
1639 Value* SV,
1640 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001641 Case& BackCase = *(CR.Range.second-1);
1642
1643 // Size is the number of Cases represented by this range.
1644 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001645 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001646 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001647
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001648 // Get the MachineFunction which holds the current MBB. This is used when
1649 // inserting any additional MBBs necessary to represent the switch.
1650 MachineFunction *CurMF = CurMBB->getParent();
1651
1652 // Figure out which block is immediately after the current one.
1653 MachineBasicBlock *NextBlock = 0;
1654 MachineFunction::iterator BBI = CR.CaseBB;
1655
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001656 if (++BBI != CurMBB->getParent()->end())
1657 NextBlock = BBI;
1658
1659 // TODO: If any two of the cases has the same destination, and if one value
1660 // is the same as the other, but has one bit unset that the other has set,
1661 // use bit manipulation to do two compares at once. For example:
1662 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1663
1664 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001665 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001666 // The last case block won't fall through into 'NextBlock' if we emit the
1667 // branches in this order. See if rearranging a case value would help.
1668 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001669 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001670 std::swap(*I, BackCase);
1671 break;
1672 }
1673 }
1674 }
1675
1676 // Create a CaseBlock record representing a conditional branch to
1677 // the Case's target mbb if the value being switched on SV is equal
1678 // to C.
1679 MachineBasicBlock *CurBlock = CR.CaseBB;
1680 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1681 MachineBasicBlock *FallThrough;
1682 if (I != E-1) {
1683 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1684 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1685 } else {
1686 // If the last case doesn't match, go to the default block.
1687 FallThrough = Default;
1688 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001689
1690 Value *RHS, *LHS, *MHS;
1691 ISD::CondCode CC;
1692 if (I->High == I->Low) {
1693 // This is just small small case range :) containing exactly 1 case
1694 CC = ISD::SETEQ;
1695 LHS = SV; RHS = I->High; MHS = NULL;
1696 } else {
1697 CC = ISD::SETLE;
1698 LHS = I->Low; MHS = SV; RHS = I->High;
1699 }
1700 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1701 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001702
1703 // If emitting the first comparison, just call visitSwitchCase to emit the
1704 // code into the current block. Otherwise, push the CaseBlock onto the
1705 // vector to be later processed by SDISel, and insert the node's MBB
1706 // before the next MBB.
1707 if (CurBlock == CurMBB)
1708 visitSwitchCase(CB);
1709 else
1710 SwitchCases.push_back(CB);
1711
1712 CurBlock = FallThrough;
1713 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001714
1715 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001716}
1717
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001718static inline bool areJTsAllowed(const TargetLowering &TLI) {
1719 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1720 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1721}
1722
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001723/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001724bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001725 CaseRecVector& WorkList,
1726 Value* SV,
1727 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001728 Case& FrontCase = *CR.Range.first;
1729 Case& BackCase = *(CR.Range.second-1);
1730
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001731 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1732 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1733
1734 uint64_t TSize = 0;
1735 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1736 I!=E; ++I)
1737 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001738
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001739 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001740 return false;
1741
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001742 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1743 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001744 return false;
1745
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001746 DOUT << "Lowering jump table\n"
1747 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001748 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001749
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001750 // Get the MachineFunction which holds the current MBB. This is used when
1751 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001752 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001753
1754 // Figure out which block is immediately after the current one.
1755 MachineBasicBlock *NextBlock = 0;
1756 MachineFunction::iterator BBI = CR.CaseBB;
1757
1758 if (++BBI != CurMBB->getParent()->end())
1759 NextBlock = BBI;
1760
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001761 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1762
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001763 // Create a new basic block to hold the code for loading the address
1764 // of the jump table, and jumping to it. Update successor information;
1765 // we will either branch to the default case for the switch, or the jump
1766 // table.
1767 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1768 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1769 CR.CaseBB->addSuccessor(Default);
1770 CR.CaseBB->addSuccessor(JumpTableBB);
1771
1772 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001773 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001774 // a case statement, push the case's BB onto the vector, otherwise, push
1775 // the default BB.
1776 std::vector<MachineBasicBlock*> DestBBs;
1777 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001778 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1779 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1780 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1781
1782 if ((Low <= TEI) && (TEI <= High)) {
1783 DestBBs.push_back(I->BB);
1784 if (TEI==High)
1785 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001786 } else {
1787 DestBBs.push_back(Default);
1788 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001789 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001790
1791 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001792 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001793 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1794 E = DestBBs.end(); I != E; ++I) {
1795 if (!SuccsHandled[(*I)->getNumber()]) {
1796 SuccsHandled[(*I)->getNumber()] = true;
1797 JumpTableBB->addSuccessor(*I);
1798 }
1799 }
1800
1801 // Create a jump table index for this jump table, or return an existing
1802 // one.
1803 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1804
1805 // Set the jump table information so that we can codegen it as a second
1806 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001807 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001808 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1809 (CR.CaseBB == CurMBB));
1810 if (CR.CaseBB == CurMBB)
1811 visitJumpTableHeader(JT, JTH);
1812
1813 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001814
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001815 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001816}
1817
1818/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1819/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001820bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001821 CaseRecVector& WorkList,
1822 Value* SV,
1823 MachineBasicBlock* Default) {
1824 // Get the MachineFunction which holds the current MBB. This is used when
1825 // inserting any additional MBBs necessary to represent the switch.
1826 MachineFunction *CurMF = CurMBB->getParent();
1827
1828 // Figure out which block is immediately after the current one.
1829 MachineBasicBlock *NextBlock = 0;
1830 MachineFunction::iterator BBI = CR.CaseBB;
1831
1832 if (++BBI != CurMBB->getParent()->end())
1833 NextBlock = BBI;
1834
1835 Case& FrontCase = *CR.Range.first;
1836 Case& BackCase = *(CR.Range.second-1);
1837 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1838
1839 // Size is the number of Cases represented by this range.
1840 unsigned Size = CR.Range.second - CR.Range.first;
1841
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001842 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1843 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001844 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001845 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001846
1847 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1848 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001849 uint64_t TSize = 0;
1850 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1851 I!=E; ++I)
1852 TSize += I->size();
1853
1854 uint64_t LSize = FrontCase.size();
1855 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001856 DOUT << "Selecting best pivot: \n"
1857 << "First: " << First << ", Last: " << Last <<"\n"
1858 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001859 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001860 J!=E; ++I, ++J) {
1861 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1862 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001863 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001864 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1865 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001866 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001867 // Should always split in some non-trivial place
1868 DOUT <<"=>Step\n"
1869 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1870 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1871 << "Metric: " << Metric << "\n";
1872 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001873 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001874 FMetric = Metric;
1875 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001876 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001877
1878 LSize += J->size();
1879 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001881 if (areJTsAllowed(TLI)) {
1882 // If our case is dense we *really* should handle it earlier!
1883 assert((FMetric > 0) && "Should handle dense range earlier!");
1884 } else {
1885 Pivot = CR.Range.first + Size/2;
1886 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001887
1888 CaseRange LHSR(CR.Range.first, Pivot);
1889 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001890 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001891 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1892
1893 // We know that we branch to the LHS if the Value being switched on is
1894 // less than the Pivot value, C. We use this to optimize our binary
1895 // tree a bit, by recognizing that if SV is greater than or equal to the
1896 // LHS's Case Value, and that Case Value is exactly one less than the
1897 // Pivot's Value, then we can branch directly to the LHS's Target,
1898 // rather than creating a leaf node for it.
1899 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001900 LHSR.first->High == CR.GE &&
1901 cast<ConstantInt>(C)->getSExtValue() ==
1902 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1903 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001904 } else {
1905 TrueBB = new MachineBasicBlock(LLVMBB);
1906 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1907 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1908 }
1909
1910 // Similar to the optimization above, if the Value being switched on is
1911 // known to be less than the Constant CR.LT, and the current Case Value
1912 // is CR.LT - 1, then we can branch directly to the target block for
1913 // the current Case Value, rather than emitting a RHS leaf node for it.
1914 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001915 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1916 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1917 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001918 } else {
1919 FalseBB = new MachineBasicBlock(LLVMBB);
1920 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1921 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1922 }
1923
1924 // Create a CaseBlock record representing a conditional branch to
1925 // the LHS node if the value being switched on SV is less than C.
1926 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001927 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1928 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001929
1930 if (CR.CaseBB == CurMBB)
1931 visitSwitchCase(CB);
1932 else
1933 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001934
1935 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936}
1937
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001938/// handleBitTestsSwitchCase - if current case range has few destination and
1939/// range span less, than machine word bitwidth, encode case range into series
1940/// of masks and emit bit tests with these masks.
1941bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1942 CaseRecVector& WorkList,
1943 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001944 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001945 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001946
1947 Case& FrontCase = *CR.Range.first;
1948 Case& BackCase = *(CR.Range.second-1);
1949
1950 // Get the MachineFunction which holds the current MBB. This is used when
1951 // inserting any additional MBBs necessary to represent the switch.
1952 MachineFunction *CurMF = CurMBB->getParent();
1953
1954 unsigned numCmps = 0;
1955 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1956 I!=E; ++I) {
1957 // Single case counts one, case range - two.
1958 if (I->Low == I->High)
1959 numCmps +=1;
1960 else
1961 numCmps +=2;
1962 }
1963
1964 // Count unique destinations
1965 SmallSet<MachineBasicBlock*, 4> Dests;
1966 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1967 Dests.insert(I->BB);
1968 if (Dests.size() > 3)
1969 // Don't bother the code below, if there are too much unique destinations
1970 return false;
1971 }
1972 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1973 << "Total number of comparisons: " << numCmps << "\n";
1974
1975 // Compute span of values.
1976 Constant* minValue = FrontCase.Low;
1977 Constant* maxValue = BackCase.High;
1978 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1979 cast<ConstantInt>(minValue)->getSExtValue();
1980 DOUT << "Compare range: " << range << "\n"
1981 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1982 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1983
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00001984 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001985 (!(Dests.size() == 1 && numCmps >= 3) &&
1986 !(Dests.size() == 2 && numCmps >= 5) &&
1987 !(Dests.size() >= 3 && numCmps >= 6)))
1988 return false;
1989
1990 DOUT << "Emitting bit tests\n";
1991 int64_t lowBound = 0;
1992
1993 // Optimize the case where all the case values fit in a
1994 // word without having to subtract minValue. In this case,
1995 // we can optimize away the subtraction.
1996 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001997 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001998 range = cast<ConstantInt>(maxValue)->getSExtValue();
1999 } else {
2000 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2001 }
2002
2003 CaseBitsVector CasesBits;
2004 unsigned i, count = 0;
2005
2006 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2007 MachineBasicBlock* Dest = I->BB;
2008 for (i = 0; i < count; ++i)
2009 if (Dest == CasesBits[i].BB)
2010 break;
2011
2012 if (i == count) {
2013 assert((count < 3) && "Too much destinations to test!");
2014 CasesBits.push_back(CaseBits(0, Dest, 0));
2015 count++;
2016 }
2017
2018 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2019 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2020
2021 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002022 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002023 CasesBits[i].Bits++;
2024 }
2025
2026 }
2027 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2028
2029 SelectionDAGISel::BitTestInfo BTC;
2030
2031 // Figure out which block is immediately after the current one.
2032 MachineFunction::iterator BBI = CR.CaseBB;
2033 ++BBI;
2034
2035 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2036
2037 DOUT << "Cases:\n";
2038 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2039 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2040 << ", BB: " << CasesBits[i].BB << "\n";
2041
2042 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2043 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2044 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2045 CaseBB,
2046 CasesBits[i].BB));
2047 }
2048
2049 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002050 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002051 CR.CaseBB, Default, BTC);
2052
2053 if (CR.CaseBB == CurMBB)
2054 visitBitTestHeader(BTB);
2055
2056 BitTestCases.push_back(BTB);
2057
2058 return true;
2059}
2060
2061
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002062/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002063unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2064 const SwitchInst& SI) {
2065 unsigned numCmps = 0;
2066
2067 // Start with "simple" cases
2068 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2069 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2070 Cases.push_back(Case(SI.getSuccessorValue(i),
2071 SI.getSuccessorValue(i),
2072 SMBB));
2073 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002074 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002075
2076 // Merge case into clusters
2077 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002078 // Must recompute end() each iteration because it may be
2079 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002080 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002081 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2082 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2083 MachineBasicBlock* nextBB = J->BB;
2084 MachineBasicBlock* currentBB = I->BB;
2085
2086 // If the two neighboring cases go to the same destination, merge them
2087 // into a single case.
2088 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2089 I->High = J->High;
2090 J = Cases.erase(J);
2091 } else {
2092 I = J++;
2093 }
2094 }
2095
2096 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2097 if (I->Low != I->High)
2098 // A range counts double, since it requires two compares.
2099 ++numCmps;
2100 }
2101
2102 return numCmps;
2103}
2104
2105void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002106 // Figure out which block is immediately after the current one.
2107 MachineBasicBlock *NextBlock = 0;
2108 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002109
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002110 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002111
Nate Begemanf15485a2006-03-27 01:32:24 +00002112 // If there is only the default destination, branch to it if it is not the
2113 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002114 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002115 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002116
Nate Begemanf15485a2006-03-27 01:32:24 +00002117 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002118 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002119 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002120 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002121
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002122 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002123 return;
2124 }
2125
2126 // If there are any non-default case statements, create a vector of Cases
2127 // representing each one, and sort the vector so that we can efficiently
2128 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002129 CaseVector Cases;
2130 unsigned numCmps = Clusterify(Cases, SI);
2131 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2132 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002133
Nate Begemanf15485a2006-03-27 01:32:24 +00002134 // Get the Value to be switched on and default basic blocks, which will be
2135 // inserted into CaseBlock records, representing basic blocks in the binary
2136 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002137 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002138
Nate Begemanf15485a2006-03-27 01:32:24 +00002139 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002140 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002141 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2142
2143 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002144 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002145 CaseRec CR = WorkList.back();
2146 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002147
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002148 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2149 continue;
2150
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002151 // If the range has few cases (two or less) emit a series of specific
2152 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002153 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2154 continue;
2155
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002156 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002157 // target supports indirect branches, then emit a jump table rather than
2158 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002159 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2160 continue;
2161
2162 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2163 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2164 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002165 }
2166}
2167
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002168
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002169void SelectionDAGLowering::visitSub(User &I) {
2170 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002171 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002172 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002173 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2174 const VectorType *DestTy = cast<VectorType>(I.getType());
2175 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002176 if (ElTy->isFloatingPoint()) {
2177 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002178 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002179 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2180 if (CV == CNZ) {
2181 SDOperand Op2 = getValue(I.getOperand(1));
2182 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2183 return;
2184 }
Dan Gohman7f321562007-06-25 16:23:39 +00002185 }
2186 }
2187 }
2188 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002189 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002190 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002191 SDOperand Op2 = getValue(I.getOperand(1));
2192 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2193 return;
2194 }
Dan Gohman7f321562007-06-25 16:23:39 +00002195 }
2196
2197 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002198}
2199
Dan Gohman7f321562007-06-25 16:23:39 +00002200void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002201 SDOperand Op1 = getValue(I.getOperand(0));
2202 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002203
2204 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002205}
2206
Nate Begemane21ea612005-11-18 07:42:56 +00002207void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2208 SDOperand Op1 = getValue(I.getOperand(0));
2209 SDOperand Op2 = getValue(I.getOperand(1));
2210
Dan Gohman7f321562007-06-25 16:23:39 +00002211 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2212 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002213 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2214 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2215 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002216
Chris Lattner1c08c712005-01-07 07:47:53 +00002217 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2218}
2219
Reid Spencer45fb3f32006-11-20 01:22:35 +00002220void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002221 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2222 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2223 predicate = IC->getPredicate();
2224 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2225 predicate = ICmpInst::Predicate(IC->getPredicate());
2226 SDOperand Op1 = getValue(I.getOperand(0));
2227 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002228 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002229 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002230 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2231 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2232 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2233 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2234 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2235 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2236 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2237 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2238 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2239 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2240 default:
2241 assert(!"Invalid ICmp predicate value");
2242 Opcode = ISD::SETEQ;
2243 break;
2244 }
2245 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2246}
2247
2248void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002249 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2250 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2251 predicate = FC->getPredicate();
2252 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2253 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002254 SDOperand Op1 = getValue(I.getOperand(0));
2255 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002256 ISD::CondCode Condition, FOC, FPC;
2257 switch (predicate) {
2258 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2259 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2260 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2261 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2262 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2263 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2264 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2265 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2266 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2267 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2268 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2269 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2270 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2271 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2272 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2273 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2274 default:
2275 assert(!"Invalid FCmp predicate value");
2276 FOC = FPC = ISD::SETFALSE;
2277 break;
2278 }
2279 if (FiniteOnlyFPMath())
2280 Condition = FOC;
2281 else
2282 Condition = FPC;
2283 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002284}
2285
2286void SelectionDAGLowering::visitSelect(User &I) {
2287 SDOperand Cond = getValue(I.getOperand(0));
2288 SDOperand TrueVal = getValue(I.getOperand(1));
2289 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002290 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2291 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002292}
2293
Reid Spencer3da59db2006-11-27 01:05:10 +00002294
2295void SelectionDAGLowering::visitTrunc(User &I) {
2296 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2297 SDOperand N = getValue(I.getOperand(0));
2298 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2299 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2300}
2301
2302void SelectionDAGLowering::visitZExt(User &I) {
2303 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2304 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2305 SDOperand N = getValue(I.getOperand(0));
2306 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2307 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2308}
2309
2310void SelectionDAGLowering::visitSExt(User &I) {
2311 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2312 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2313 SDOperand N = getValue(I.getOperand(0));
2314 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2315 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2316}
2317
2318void SelectionDAGLowering::visitFPTrunc(User &I) {
2319 // FPTrunc is never a no-op cast, no need to check
2320 SDOperand N = getValue(I.getOperand(0));
2321 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002322 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002323}
2324
2325void SelectionDAGLowering::visitFPExt(User &I){
2326 // FPTrunc is never a no-op cast, no need to check
2327 SDOperand N = getValue(I.getOperand(0));
2328 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2329 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2330}
2331
2332void SelectionDAGLowering::visitFPToUI(User &I) {
2333 // FPToUI is never a no-op cast, no need to check
2334 SDOperand N = getValue(I.getOperand(0));
2335 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2336 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2337}
2338
2339void SelectionDAGLowering::visitFPToSI(User &I) {
2340 // FPToSI is never a no-op cast, no need to check
2341 SDOperand N = getValue(I.getOperand(0));
2342 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2343 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2344}
2345
2346void SelectionDAGLowering::visitUIToFP(User &I) {
2347 // UIToFP is never a no-op cast, no need to check
2348 SDOperand N = getValue(I.getOperand(0));
2349 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2350 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2351}
2352
2353void SelectionDAGLowering::visitSIToFP(User &I){
2354 // UIToFP is never a no-op cast, no need to check
2355 SDOperand N = getValue(I.getOperand(0));
2356 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2357 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2358}
2359
2360void SelectionDAGLowering::visitPtrToInt(User &I) {
2361 // What to do depends on the size of the integer and the size of the pointer.
2362 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002363 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002364 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002366 SDOperand Result;
2367 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2368 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2369 else
2370 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2371 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2372 setValue(&I, Result);
2373}
Chris Lattner1c08c712005-01-07 07:47:53 +00002374
Reid Spencer3da59db2006-11-27 01:05:10 +00002375void SelectionDAGLowering::visitIntToPtr(User &I) {
2376 // What to do depends on the size of the integer and the size of the pointer.
2377 // We can either truncate, zero extend, or no-op, accordingly.
2378 SDOperand N = getValue(I.getOperand(0));
2379 MVT::ValueType SrcVT = N.getValueType();
2380 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2381 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2382 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2383 else
2384 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2385 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2386}
2387
2388void SelectionDAGLowering::visitBitCast(User &I) {
2389 SDOperand N = getValue(I.getOperand(0));
2390 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002391
2392 // BitCast assures us that source and destination are the same size so this
2393 // is either a BIT_CONVERT or a no-op.
2394 if (DestVT != N.getValueType())
2395 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2396 else
2397 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002398}
2399
Chris Lattner2bbd8102006-03-29 00:11:43 +00002400void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002401 SDOperand InVec = getValue(I.getOperand(0));
2402 SDOperand InVal = getValue(I.getOperand(1));
2403 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2404 getValue(I.getOperand(2)));
2405
Dan Gohman7f321562007-06-25 16:23:39 +00002406 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2407 TLI.getValueType(I.getType()),
2408 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002409}
2410
Chris Lattner2bbd8102006-03-29 00:11:43 +00002411void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002412 SDOperand InVec = getValue(I.getOperand(0));
2413 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2414 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002415 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002416 TLI.getValueType(I.getType()), InVec, InIdx));
2417}
Chris Lattnerc7029802006-03-18 01:44:44 +00002418
Chris Lattner3e104b12006-04-08 04:15:24 +00002419void SelectionDAGLowering::visitShuffleVector(User &I) {
2420 SDOperand V1 = getValue(I.getOperand(0));
2421 SDOperand V2 = getValue(I.getOperand(1));
2422 SDOperand Mask = getValue(I.getOperand(2));
2423
Dan Gohman7f321562007-06-25 16:23:39 +00002424 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2425 TLI.getValueType(I.getType()),
2426 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002427}
2428
2429
Chris Lattner1c08c712005-01-07 07:47:53 +00002430void SelectionDAGLowering::visitGetElementPtr(User &I) {
2431 SDOperand N = getValue(I.getOperand(0));
2432 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002433
2434 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2435 OI != E; ++OI) {
2436 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002437 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002438 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002439 if (Field) {
2440 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002441 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002442 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002443 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002444 }
2445 Ty = StTy->getElementType(Field);
2446 } else {
2447 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002448
Chris Lattner7c0104b2005-11-09 04:45:33 +00002449 // If this is a constant subscript, handle it quickly.
2450 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002451 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002452 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002453 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002454 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2455 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002456 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002457 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002458
2459 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002460 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002461 SDOperand IdxN = getValue(Idx);
2462
2463 // If the index is smaller or larger than intptr_t, truncate or extend
2464 // it.
2465 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002466 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002467 } else if (IdxN.getValueType() > N.getValueType())
2468 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2469
2470 // If this is a multiply by a power of two, turn it into a shl
2471 // immediately. This is a very common case.
2472 if (isPowerOf2_64(ElementSize)) {
2473 unsigned Amt = Log2_64(ElementSize);
2474 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002475 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002476 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2477 continue;
2478 }
2479
Chris Lattner0bd48932008-01-17 07:00:52 +00002480 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002481 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2482 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002483 }
2484 }
2485 setValue(&I, N);
2486}
2487
2488void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2489 // If this is a fixed sized alloca in the entry block of the function,
2490 // allocate it statically on the stack.
2491 if (FuncInfo.StaticAllocaMap.count(&I))
2492 return; // getValue will auto-populate this.
2493
2494 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002495 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002496 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002497 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002498 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002499
2500 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002501 MVT::ValueType IntPtr = TLI.getPointerTy();
2502 if (IntPtr < AllocSize.getValueType())
2503 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2504 else if (IntPtr > AllocSize.getValueType())
2505 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002506
Chris Lattner68cd65e2005-01-22 23:04:37 +00002507 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002508 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002509
Evan Cheng45157792007-08-16 23:46:29 +00002510 // Handle alignment. If the requested alignment is less than or equal to
2511 // the stack alignment, ignore it. If the size is greater than or equal to
2512 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002513 unsigned StackAlign =
2514 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002515 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002516 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002517
2518 // Round the size of the allocation up to the stack alignment size
2519 // by add SA-1 to the size.
2520 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002521 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002522 // Mask out the low bits for alignment purposes.
2523 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002524 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002525
Chris Lattner0bd48932008-01-17 07:00:52 +00002526 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002527 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2528 MVT::Other);
2529 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002530 setValue(&I, DSA);
2531 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002532
2533 // Inform the Frame Information that we have just allocated a variable-sized
2534 // object.
2535 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2536}
2537
Chris Lattner1c08c712005-01-07 07:47:53 +00002538void SelectionDAGLowering::visitLoad(LoadInst &I) {
2539 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002540
Chris Lattnerd3948112005-01-17 22:19:26 +00002541 SDOperand Root;
2542 if (I.isVolatile())
2543 Root = getRoot();
2544 else {
2545 // Do not serialize non-volatile loads against each other.
2546 Root = DAG.getRoot();
2547 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002548
Evan Cheng466685d2006-10-09 20:57:25 +00002549 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002550 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002551}
2552
2553SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002554 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002555 bool isVolatile,
2556 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002557 SDOperand L =
2558 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2559 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002560
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002561 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002562 DAG.setRoot(L.getValue(1));
2563 else
2564 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002565
2566 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002567}
2568
2569
2570void SelectionDAGLowering::visitStore(StoreInst &I) {
2571 Value *SrcV = I.getOperand(0);
2572 SDOperand Src = getValue(SrcV);
2573 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002574 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002575 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002576}
2577
Chris Lattner0eade312006-03-24 02:22:33 +00002578/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2579/// node.
2580void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2581 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002582 bool HasChain = !I.doesNotAccessMemory();
2583 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2584
Chris Lattner0eade312006-03-24 02:22:33 +00002585 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002586 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002587 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2588 if (OnlyLoad) {
2589 // We don't need to serialize loads against other loads.
2590 Ops.push_back(DAG.getRoot());
2591 } else {
2592 Ops.push_back(getRoot());
2593 }
2594 }
Chris Lattner0eade312006-03-24 02:22:33 +00002595
2596 // Add the intrinsic ID as an integer operand.
2597 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2598
2599 // Add all operands of the call to the operand list.
2600 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2601 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002602 assert(TLI.isTypeLegal(Op.getValueType()) &&
2603 "Intrinsic uses a non-legal type?");
2604 Ops.push_back(Op);
2605 }
2606
2607 std::vector<MVT::ValueType> VTs;
2608 if (I.getType() != Type::VoidTy) {
2609 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002610 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002611 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002612 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2613
2614 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2615 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2616 }
2617
2618 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2619 VTs.push_back(VT);
2620 }
2621 if (HasChain)
2622 VTs.push_back(MVT::Other);
2623
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002624 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2625
Chris Lattner0eade312006-03-24 02:22:33 +00002626 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002627 SDOperand Result;
2628 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002629 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2630 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002631 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002632 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2633 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002634 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002635 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2636 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002637
Chris Lattnere58a7802006-04-02 03:41:14 +00002638 if (HasChain) {
2639 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2640 if (OnlyLoad)
2641 PendingLoads.push_back(Chain);
2642 else
2643 DAG.setRoot(Chain);
2644 }
Chris Lattner0eade312006-03-24 02:22:33 +00002645 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002646 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002647 MVT::ValueType VT = TLI.getValueType(PTy);
2648 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002649 }
2650 setValue(&I, Result);
2651 }
2652}
2653
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002654/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002655static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002656 V = IntrinsicInst::StripPointerCasts(V);
2657 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002658 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002659 "TypeInfo must be a global variable or NULL");
2660 return GV;
2661}
2662
Duncan Sandsf4070822007-06-15 19:04:19 +00002663/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002664/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002665static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2666 MachineBasicBlock *MBB) {
2667 // Inform the MachineModuleInfo of the personality for this landing pad.
2668 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2669 assert(CE->getOpcode() == Instruction::BitCast &&
2670 isa<Function>(CE->getOperand(0)) &&
2671 "Personality should be a function");
2672 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2673
2674 // Gather all the type infos for this landing pad and pass them along to
2675 // MachineModuleInfo.
2676 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002677 unsigned N = I.getNumOperands();
2678
2679 for (unsigned i = N - 1; i > 2; --i) {
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2681 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002682 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002683 assert (FirstCatch <= N && "Invalid filter length");
2684
2685 if (FirstCatch < N) {
2686 TyInfo.reserve(N - FirstCatch);
2687 for (unsigned j = FirstCatch; j < N; ++j)
2688 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2689 MMI->addCatchTypeInfo(MBB, TyInfo);
2690 TyInfo.clear();
2691 }
2692
Duncan Sands6590b042007-08-27 15:47:50 +00002693 if (!FilterLength) {
2694 // Cleanup.
2695 MMI->addCleanup(MBB);
2696 } else {
2697 // Filter.
2698 TyInfo.reserve(FilterLength - 1);
2699 for (unsigned j = i + 1; j < FirstCatch; ++j)
2700 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2701 MMI->addFilterTypeInfo(MBB, TyInfo);
2702 TyInfo.clear();
2703 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002704
2705 N = i;
2706 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002707 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002708
2709 if (N > 3) {
2710 TyInfo.reserve(N - 3);
2711 for (unsigned j = 3; j < N; ++j)
2712 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002713 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002714 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002715}
2716
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002717/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2718/// we want to emit this as a call to a named external function, return the name
2719/// otherwise lower it and return null.
2720const char *
2721SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2722 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002723 default:
2724 // By default, turn this into a target intrinsic node.
2725 visitTargetIntrinsic(I, Intrinsic);
2726 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002727 case Intrinsic::vastart: visitVAStart(I); return 0;
2728 case Intrinsic::vaend: visitVAEnd(I); return 0;
2729 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002730 case Intrinsic::returnaddress:
2731 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2732 getValue(I.getOperand(1))));
2733 return 0;
2734 case Intrinsic::frameaddress:
2735 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2736 getValue(I.getOperand(1))));
2737 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002738 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002739 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002740 break;
2741 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002742 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002743 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002744 case Intrinsic::memcpy_i32:
2745 case Intrinsic::memcpy_i64:
2746 visitMemIntrinsic(I, ISD::MEMCPY);
2747 return 0;
2748 case Intrinsic::memset_i32:
2749 case Intrinsic::memset_i64:
2750 visitMemIntrinsic(I, ISD::MEMSET);
2751 return 0;
2752 case Intrinsic::memmove_i32:
2753 case Intrinsic::memmove_i64:
2754 visitMemIntrinsic(I, ISD::MEMMOVE);
2755 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002756
Chris Lattner86cb6432005-12-13 17:40:33 +00002757 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002758 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002759 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002760 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002761 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002762
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002763 Ops[0] = getRoot();
2764 Ops[1] = getValue(SPI.getLineValue());
2765 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002766
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002767 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002768 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002769 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2770
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002771 Ops[3] = DAG.getString(CompileUnit->getFileName());
2772 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002773
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002774 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002775 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002776
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002777 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002778 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002779 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002780 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002781 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002782 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2783 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002784 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002785 DAG.getConstant(LabelID, MVT::i32),
2786 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002787 }
2788
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002789 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002790 }
2791 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002792 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002793 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002794 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2795 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002796 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2797 DAG.getConstant(LabelID, MVT::i32),
2798 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002799 }
2800
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002801 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002802 }
2803 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002804 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002805 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002806 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002807 Value *SP = FSI.getSubprogram();
2808 if (SP && MMI->Verify(SP)) {
2809 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2810 // what (most?) gdb expects.
2811 DebugInfoDesc *DD = MMI->getDescFor(SP);
2812 assert(DD && "Not a debug information descriptor");
2813 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2814 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2815 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2816 CompileUnit->getFileName());
2817 // Record the source line but does create a label. It will be emitted
2818 // at asm emission time.
2819 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002820 }
2821
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002822 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002823 }
2824 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002825 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002826 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002827 Value *Variable = DI.getVariable();
2828 if (MMI && Variable && MMI->Verify(Variable))
2829 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2830 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002831 return 0;
2832 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002833
Jim Laskeyb180aa12007-02-21 22:53:45 +00002834 case Intrinsic::eh_exception: {
Dale Johannesen1544e472008-03-31 23:40:23 +00002835 if (FuncInfo.needsExceptionHandling) {
Duncan Sands90291952007-07-06 09:18:59 +00002836 if (!CurMBB->isLandingPad()) {
2837 // FIXME: Mark exception register as live in. Hack for PR1508.
2838 unsigned Reg = TLI.getExceptionAddressRegister();
2839 if (Reg) CurMBB->addLiveIn(Reg);
2840 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002841 // Insert the EXCEPTIONADDR instruction.
2842 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2843 SDOperand Ops[1];
2844 Ops[0] = DAG.getRoot();
2845 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2846 setValue(&I, Op);
2847 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002848 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002849 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002850 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002851 return 0;
2852 }
2853
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002854 case Intrinsic::eh_selector_i32:
2855 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002856 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002857 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2858 MVT::i32 : MVT::i64);
2859
Dale Johannesen1544e472008-03-31 23:40:23 +00002860 if (FuncInfo.needsExceptionHandling && MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002861 if (CurMBB->isLandingPad())
2862 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002863 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002864#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002865 FuncInfo.CatchInfoLost.insert(&I);
2866#endif
Duncan Sands90291952007-07-06 09:18:59 +00002867 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2868 unsigned Reg = TLI.getExceptionSelectorRegister();
2869 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002870 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002871
2872 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002873 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002874 SDOperand Ops[2];
2875 Ops[0] = getValue(I.getOperand(1));
2876 Ops[1] = getRoot();
2877 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2878 setValue(&I, Op);
2879 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002880 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002881 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002882 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002883
2884 return 0;
2885 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002886
2887 case Intrinsic::eh_typeid_for_i32:
2888 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002889 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002890 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2891 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002892
Jim Laskey735b6f82007-02-22 15:38:06 +00002893 if (MMI) {
2894 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002895 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002896
Jim Laskey735b6f82007-02-22 15:38:06 +00002897 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002898 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00002899 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002900 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002901 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002902 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002903
2904 return 0;
2905 }
2906
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002907 case Intrinsic::eh_return: {
2908 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2909
Dale Johannesen1544e472008-03-31 23:40:23 +00002910 if (MMI && FuncInfo.needsExceptionHandling) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002911 MMI->setCallsEHReturn(true);
2912 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2913 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002914 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002915 getValue(I.getOperand(1)),
2916 getValue(I.getOperand(2))));
2917 } else {
2918 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2919 }
2920
2921 return 0;
2922 }
2923
2924 case Intrinsic::eh_unwind_init: {
2925 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2926 MMI->setCallsUnwindInit(true);
2927 }
2928
2929 return 0;
2930 }
2931
2932 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1544e472008-03-31 23:40:23 +00002933 if (FuncInfo.needsExceptionHandling) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002934 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
Anton Korobeynikov2f597bd2007-08-23 07:21:06 +00002935 SDOperand CfaArg;
2936 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
2937 CfaArg = DAG.getNode(ISD::TRUNCATE,
2938 TLI.getPointerTy(), getValue(I.getOperand(1)));
2939 else
2940 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2941 TLI.getPointerTy(), getValue(I.getOperand(1)));
2942
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002943 SDOperand Offset = DAG.getNode(ISD::ADD,
2944 TLI.getPointerTy(),
2945 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
Anton Korobeynikov2f597bd2007-08-23 07:21:06 +00002946 TLI.getPointerTy()),
2947 CfaArg);
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002948 setValue(&I, DAG.getNode(ISD::ADD,
2949 TLI.getPointerTy(),
2950 DAG.getNode(ISD::FRAMEADDR,
2951 TLI.getPointerTy(),
2952 DAG.getConstant(0,
2953 TLI.getPointerTy())),
2954 Offset));
2955 } else {
2956 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2957 }
2958
2959 return 0;
2960 }
2961
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002962 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002963 setValue(&I, DAG.getNode(ISD::FSQRT,
2964 getValue(I.getOperand(1)).getValueType(),
2965 getValue(I.getOperand(1))));
2966 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002967 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002968 setValue(&I, DAG.getNode(ISD::FPOWI,
2969 getValue(I.getOperand(1)).getValueType(),
2970 getValue(I.getOperand(1)),
2971 getValue(I.getOperand(2))));
2972 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00002973 case Intrinsic::sin:
2974 setValue(&I, DAG.getNode(ISD::FSIN,
2975 getValue(I.getOperand(1)).getValueType(),
2976 getValue(I.getOperand(1))));
2977 return 0;
2978 case Intrinsic::cos:
2979 setValue(&I, DAG.getNode(ISD::FCOS,
2980 getValue(I.getOperand(1)).getValueType(),
2981 getValue(I.getOperand(1))));
2982 return 0;
2983 case Intrinsic::pow:
2984 setValue(&I, DAG.getNode(ISD::FPOW,
2985 getValue(I.getOperand(1)).getValueType(),
2986 getValue(I.getOperand(1)),
2987 getValue(I.getOperand(2))));
2988 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002989 case Intrinsic::pcmarker: {
2990 SDOperand Tmp = getValue(I.getOperand(1));
2991 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2992 return 0;
2993 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002994 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002995 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002996 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2997 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2998 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002999 setValue(&I, Tmp);
3000 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003001 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003002 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003003 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003004 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003005 assert(0 && "part_select intrinsic not implemented");
3006 abort();
3007 }
3008 case Intrinsic::part_set: {
3009 // Currently not implemented: just abort
3010 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003011 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003012 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003013 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003014 setValue(&I, DAG.getNode(ISD::BSWAP,
3015 getValue(I.getOperand(1)).getValueType(),
3016 getValue(I.getOperand(1))));
3017 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003018 case Intrinsic::cttz: {
3019 SDOperand Arg = getValue(I.getOperand(1));
3020 MVT::ValueType Ty = Arg.getValueType();
3021 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003022 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003023 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003024 }
3025 case Intrinsic::ctlz: {
3026 SDOperand Arg = getValue(I.getOperand(1));
3027 MVT::ValueType Ty = Arg.getValueType();
3028 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003029 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003030 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003031 }
3032 case Intrinsic::ctpop: {
3033 SDOperand Arg = getValue(I.getOperand(1));
3034 MVT::ValueType Ty = Arg.getValueType();
3035 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003036 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003037 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003038 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003039 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003040 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003041 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3042 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003043 setValue(&I, Tmp);
3044 DAG.setRoot(Tmp.getValue(1));
3045 return 0;
3046 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003047 case Intrinsic::stackrestore: {
3048 SDOperand Tmp = getValue(I.getOperand(1));
3049 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003050 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003051 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003052 case Intrinsic::var_annotation:
3053 // Discard annotate attributes
3054 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003055
Duncan Sands36397f52007-07-27 12:58:54 +00003056 case Intrinsic::init_trampoline: {
3057 const Function *F =
3058 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3059
3060 SDOperand Ops[6];
3061 Ops[0] = getRoot();
3062 Ops[1] = getValue(I.getOperand(1));
3063 Ops[2] = getValue(I.getOperand(2));
3064 Ops[3] = getValue(I.getOperand(3));
3065 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3066 Ops[5] = DAG.getSrcValue(F);
3067
Duncan Sandsf7331b32007-09-11 14:10:23 +00003068 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3069 DAG.getNodeValueTypes(TLI.getPointerTy(),
3070 MVT::Other), 2,
3071 Ops, 6);
3072
3073 setValue(&I, Tmp);
3074 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003075 return 0;
3076 }
Gordon Henriksence224772008-01-07 01:30:38 +00003077
3078 case Intrinsic::gcroot:
3079 if (GCI) {
3080 Value *Alloca = I.getOperand(1);
3081 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3082
3083 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3084 GCI->addStackRoot(FI->getIndex(), TypeMap);
3085 }
3086 return 0;
3087
3088 case Intrinsic::gcread:
3089 case Intrinsic::gcwrite:
3090 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3091 return 0;
3092
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003093 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003094 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003095 return 0;
3096 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003097
3098 case Intrinsic::trap: {
3099 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3100 return 0;
3101 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003102 case Intrinsic::prefetch: {
3103 SDOperand Ops[4];
3104 Ops[0] = getRoot();
3105 Ops[1] = getValue(I.getOperand(1));
3106 Ops[2] = getValue(I.getOperand(2));
3107 Ops[3] = getValue(I.getOperand(3));
3108 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3109 return 0;
3110 }
3111
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003112 case Intrinsic::memory_barrier: {
3113 SDOperand Ops[6];
3114 Ops[0] = getRoot();
3115 for (int x = 1; x < 6; ++x)
3116 Ops[x] = getValue(I.getOperand(x));
3117
3118 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3119 return 0;
3120 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003121 case Intrinsic::atomic_lcs: {
3122 SDOperand Root = getRoot();
3123 SDOperand O3 = getValue(I.getOperand(3));
3124 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3125 getValue(I.getOperand(1)),
3126 getValue(I.getOperand(2)),
3127 O3, O3.getValueType());
3128 setValue(&I, L);
3129 DAG.setRoot(L.getValue(1));
3130 return 0;
3131 }
3132 case Intrinsic::atomic_las: {
3133 SDOperand Root = getRoot();
3134 SDOperand O2 = getValue(I.getOperand(2));
3135 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3136 getValue(I.getOperand(1)),
3137 O2, O2.getValueType());
3138 setValue(&I, L);
3139 DAG.setRoot(L.getValue(1));
3140 return 0;
3141 }
3142 case Intrinsic::atomic_swap: {
3143 SDOperand Root = getRoot();
3144 SDOperand O2 = getValue(I.getOperand(2));
3145 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3146 getValue(I.getOperand(1)),
3147 O2, O2.getValueType());
3148 setValue(&I, L);
3149 DAG.setRoot(L.getValue(1));
3150 return 0;
3151 }
3152
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003153 }
3154}
3155
3156
Duncan Sands6f74b482007-12-19 09:48:52 +00003157void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003158 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003159 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003160 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003161 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003162 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3163 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003164
Jim Laskey735b6f82007-02-22 15:38:06 +00003165 TargetLowering::ArgListTy Args;
3166 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003167 Args.reserve(CS.arg_size());
3168 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3169 i != e; ++i) {
3170 SDOperand ArgNode = getValue(*i);
3171 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003172
Duncan Sands6f74b482007-12-19 09:48:52 +00003173 unsigned attrInd = i - CS.arg_begin() + 1;
3174 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3175 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3176 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3177 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3178 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3179 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003180 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003181 Args.push_back(Entry);
3182 }
3183
Dale Johannesen1544e472008-03-31 23:40:23 +00003184 if (LandingPad && FuncInfo.needsExceptionHandling && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003185 // Insert a label before the invoke call to mark the try range. This can be
3186 // used to detect deletion of the invoke via the MachineModuleInfo.
3187 BeginLabel = MMI->NextLabelID();
3188 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003189 DAG.getConstant(BeginLabel, MVT::i32),
3190 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003191 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003192
Jim Laskey735b6f82007-02-22 15:38:06 +00003193 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003194 TLI.LowerCallTo(getRoot(), CS.getType(),
3195 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003196 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003197 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003198 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003199 if (CS.getType() != Type::VoidTy)
3200 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003201 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003202
Dale Johannesen1544e472008-03-31 23:40:23 +00003203 if (LandingPad && FuncInfo.needsExceptionHandling && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003204 // Insert a label at the end of the invoke call to mark the try range. This
3205 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3206 EndLabel = MMI->NextLabelID();
3207 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003208 DAG.getConstant(EndLabel, MVT::i32),
3209 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003210
Duncan Sands6f74b482007-12-19 09:48:52 +00003211 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003212 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3213 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003214}
3215
3216
Chris Lattner1c08c712005-01-07 07:47:53 +00003217void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003218 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003219 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003220 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003221 if (unsigned IID = F->getIntrinsicID()) {
3222 RenameFn = visitIntrinsicCall(I, IID);
3223 if (!RenameFn)
3224 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003225 }
3226 }
3227
3228 // Check for well-known libc/libm calls. If the function is internal, it
3229 // can't be a library call.
3230 unsigned NameLen = F->getNameLen();
3231 if (!F->hasInternalLinkage() && NameLen) {
3232 const char *NameStr = F->getNameStart();
3233 if (NameStr[0] == 'c' &&
3234 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3235 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3236 if (I.getNumOperands() == 3 && // Basic sanity checks.
3237 I.getOperand(1)->getType()->isFloatingPoint() &&
3238 I.getType() == I.getOperand(1)->getType() &&
3239 I.getType() == I.getOperand(2)->getType()) {
3240 SDOperand LHS = getValue(I.getOperand(1));
3241 SDOperand RHS = getValue(I.getOperand(2));
3242 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3243 LHS, RHS));
3244 return;
3245 }
3246 } else if (NameStr[0] == 'f' &&
3247 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003248 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3249 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003250 if (I.getNumOperands() == 2 && // Basic sanity checks.
3251 I.getOperand(1)->getType()->isFloatingPoint() &&
3252 I.getType() == I.getOperand(1)->getType()) {
3253 SDOperand Tmp = getValue(I.getOperand(1));
3254 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3255 return;
3256 }
3257 } else if (NameStr[0] == 's' &&
3258 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003259 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3260 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003261 if (I.getNumOperands() == 2 && // Basic sanity checks.
3262 I.getOperand(1)->getType()->isFloatingPoint() &&
3263 I.getType() == I.getOperand(1)->getType()) {
3264 SDOperand Tmp = getValue(I.getOperand(1));
3265 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3266 return;
3267 }
3268 } else if (NameStr[0] == 'c' &&
3269 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003270 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3271 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003272 if (I.getNumOperands() == 2 && // Basic sanity checks.
3273 I.getOperand(1)->getType()->isFloatingPoint() &&
3274 I.getType() == I.getOperand(1)->getType()) {
3275 SDOperand Tmp = getValue(I.getOperand(1));
3276 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3277 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003278 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003279 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003280 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003281 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003282 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003283 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003284 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003285
Chris Lattner64e14b12005-01-08 22:48:57 +00003286 SDOperand Callee;
3287 if (!RenameFn)
3288 Callee = getValue(I.getOperand(0));
3289 else
3290 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003291
Duncan Sands6f74b482007-12-19 09:48:52 +00003292 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003293}
3294
Jim Laskey735b6f82007-02-22 15:38:06 +00003295
Dan Gohmanef5d1942008-03-11 21:11:25 +00003296void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3297 SDOperand Call = getValue(I.getOperand(0));
3298 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3299}
3300
3301
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003302/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3303/// this value and returns the result as a ValueVT value. This uses
3304/// Chain/Flag as the input and updates them for the output Chain/Flag.
3305/// If the Flag pointer is NULL, no flag is used.
3306SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3307 SDOperand &Chain, SDOperand *Flag)const{
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003308 // Copy the legal parts from the registers.
3309 unsigned NumParts = Regs.size();
3310 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohman27a70be2007-07-02 16:18:06 +00003311 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003312 SDOperand Part = Flag ?
3313 DAG.getCopyFromReg(Chain, Regs[i], RegVT, *Flag) :
3314 DAG.getCopyFromReg(Chain, Regs[i], RegVT);
3315 Chain = Part.getValue(1);
3316 if (Flag)
3317 *Flag = Part.getValue(2);
3318 Parts[i] = Part;
Chris Lattnercf752aa2006-06-08 18:22:48 +00003319 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003320
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003321 // Assemble the legal parts into the final value.
Chris Lattner4c55c632008-03-09 20:04:36 +00003322 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
Chris Lattner864635a2006-02-22 22:37:12 +00003323}
3324
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003325/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3326/// specified value into the registers specified by this object. This uses
3327/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003328/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003329void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003330 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003331 // Get the list of the values's legal parts.
3332 unsigned NumParts = Regs.size();
3333 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohman532dc2e2007-07-09 20:59:04 +00003334 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003335
3336 // Copy the parts into the registers.
Dan Gohman27a70be2007-07-02 16:18:06 +00003337 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003338 SDOperand Part = Flag ?
Dan Gohman532dc2e2007-07-09 20:59:04 +00003339 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3340 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003341 Chain = Part.getValue(0);
3342 if (Flag)
3343 *Flag = Part.getValue(1);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003344 }
3345}
Chris Lattner864635a2006-02-22 22:37:12 +00003346
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003347/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3348/// operand list. This adds the code marker and includes the number of
3349/// values added into it.
3350void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003351 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003352 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3353 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003354 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3355 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3356}
Chris Lattner864635a2006-02-22 22:37:12 +00003357
3358/// isAllocatableRegister - If the specified register is safe to allocate,
3359/// i.e. it isn't a stack pointer or some other special register, return the
3360/// register class for the register. Otherwise, return null.
3361static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003362isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003363 const TargetLowering &TLI,
3364 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003365 MVT::ValueType FoundVT = MVT::Other;
3366 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003367 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3368 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003369 MVT::ValueType ThisVT = MVT::Other;
3370
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003371 const TargetRegisterClass *RC = *RCI;
3372 // If none of the the value types for this register class are valid, we
3373 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003374 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3375 I != E; ++I) {
3376 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003377 // If we have already found this register in a different register class,
3378 // choose the one with the largest VT specified. For example, on
3379 // PowerPC, we favor f64 register classes over f32.
3380 if (FoundVT == MVT::Other ||
3381 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3382 ThisVT = *I;
3383 break;
3384 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003385 }
3386 }
3387
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003388 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003389
Chris Lattner864635a2006-02-22 22:37:12 +00003390 // NOTE: This isn't ideal. In particular, this might allocate the
3391 // frame pointer in functions that need it (due to them not being taken
3392 // out of allocation, because a variable sized allocation hasn't been seen
3393 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003394 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3395 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003396 if (*I == Reg) {
3397 // We found a matching register class. Keep looking at others in case
3398 // we find one with larger registers that this physreg is also in.
3399 FoundRC = RC;
3400 FoundVT = ThisVT;
3401 break;
3402 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003403 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003404 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003405}
3406
Chris Lattner4e4b5762006-02-01 18:59:47 +00003407
Chris Lattner0c583402007-04-28 20:49:53 +00003408namespace {
3409/// AsmOperandInfo - This contains information for each constraint that we are
3410/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003411struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3412 /// CallOperand - If this is the result output operand or a clobber
3413 /// this is null, otherwise it is the incoming operand to the CallInst.
3414 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003415 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003416
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003417 /// AssignedRegs - If this is a register or register class operand, this
3418 /// contains the set of register corresponding to the operand.
3419 RegsForValue AssignedRegs;
3420
Evan Cheng5c807602008-02-26 02:33:44 +00003421 SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3422 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003423 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003424
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003425 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3426 /// busy in OutputRegs/InputRegs.
3427 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3428 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003429 std::set<unsigned> &InputRegs,
3430 const TargetRegisterInfo &TRI) const {
3431 if (isOutReg) {
3432 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3433 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3434 }
3435 if (isInReg) {
3436 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3437 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3438 }
3439 }
3440
3441private:
3442 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3443 /// specified set.
3444 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3445 const TargetRegisterInfo &TRI) {
3446 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3447 Regs.insert(Reg);
3448 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3449 for (; *Aliases; ++Aliases)
3450 Regs.insert(*Aliases);
3451 }
Chris Lattner0c583402007-04-28 20:49:53 +00003452};
3453} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003454
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003455
Chris Lattner0fe71e92008-02-21 19:43:13 +00003456/// GetRegistersForValue - Assign registers (virtual or physical) for the
3457/// specified operand. We prefer to assign virtual registers, to allow the
3458/// register allocator handle the assignment process. However, if the asm uses
3459/// features that we can't model on machineinstrs, we have SDISel do the
3460/// allocation. This produces generally horrible, but correct, code.
3461///
3462/// OpInfo describes the operand.
3463/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3464/// or any explicitly clobbered registers.
3465/// Input and OutputRegs are the set of already allocated physical registers.
3466///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003467void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003468GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003469 std::set<unsigned> &OutputRegs,
3470 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003471 // Compute whether this value requires an input register, an output register,
3472 // or both.
3473 bool isOutReg = false;
3474 bool isInReg = false;
3475 switch (OpInfo.Type) {
3476 case InlineAsm::isOutput:
3477 isOutReg = true;
3478
3479 // If this is an early-clobber output, or if there is an input
3480 // constraint that matches this, we need to reserve the input register
3481 // so no other inputs allocate to it.
3482 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3483 break;
3484 case InlineAsm::isInput:
3485 isInReg = true;
3486 isOutReg = false;
3487 break;
3488 case InlineAsm::isClobber:
3489 isOutReg = true;
3490 isInReg = true;
3491 break;
3492 }
3493
3494
3495 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003496 std::vector<unsigned> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003497
3498 // If this is a constraint for a single physreg, or a constraint for a
3499 // register class, find it.
3500 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3501 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3502 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003503
3504 unsigned NumRegs = 1;
3505 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003506 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003507 MVT::ValueType RegVT;
3508 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3509
Chris Lattnerbf996f12007-04-30 17:29:31 +00003510
3511 // If this is a constraint for a specific physical register, like {r17},
3512 // assign it now.
3513 if (PhysReg.first) {
3514 if (OpInfo.ConstraintVT == MVT::Other)
3515 ValueVT = *PhysReg.second->vt_begin();
3516
3517 // Get the actual register value type. This is important, because the user
3518 // may have asked for (e.g.) the AX register in i32 type. We need to
3519 // remember that AX is actually i16 to get the right extension.
3520 RegVT = *PhysReg.second->vt_begin();
3521
3522 // This is a explicit reference to a physical register.
3523 Regs.push_back(PhysReg.first);
3524
3525 // If this is an expanded reference, add the rest of the regs to Regs.
3526 if (NumRegs != 1) {
3527 TargetRegisterClass::iterator I = PhysReg.second->begin();
3528 TargetRegisterClass::iterator E = PhysReg.second->end();
3529 for (; *I != PhysReg.first; ++I)
3530 assert(I != E && "Didn't find reg!");
3531
3532 // Already added the first reg.
3533 --NumRegs; ++I;
3534 for (; NumRegs; --NumRegs, ++I) {
3535 assert(I != E && "Ran out of registers to allocate!");
3536 Regs.push_back(*I);
3537 }
3538 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003539 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003540 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3541 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003542 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003543 }
3544
3545 // Otherwise, if this was a reference to an LLVM register class, create vregs
3546 // for this reference.
3547 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003548 const TargetRegisterClass *RC = PhysReg.second;
3549 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003550 // If this is an early clobber or tied register, our regalloc doesn't know
3551 // how to maintain the constraint. If it isn't, go ahead and create vreg
3552 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003553 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3554 // If there is some other early clobber and this is an input register,
3555 // then we are forced to pre-allocate the input reg so it doesn't
3556 // conflict with the earlyclobber.
3557 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003558 RegVT = *PhysReg.second->vt_begin();
3559
3560 if (OpInfo.ConstraintVT == MVT::Other)
3561 ValueVT = RegVT;
3562
3563 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003564 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003565 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003566 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003567
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003568 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003569 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003570 }
3571
3572 // Otherwise, we can't allocate it. Let the code below figure out how to
3573 // maintain these constraints.
3574 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3575
3576 } else {
3577 // This is a reference to a register class that doesn't directly correspond
3578 // to an LLVM register class. Allocate NumRegs consecutive, available,
3579 // registers from the class.
3580 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3581 OpInfo.ConstraintVT);
3582 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003583
Dan Gohman6f0d0242008-02-10 18:45:23 +00003584 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003585 unsigned NumAllocated = 0;
3586 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3587 unsigned Reg = RegClassRegs[i];
3588 // See if this register is available.
3589 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3590 (isInReg && InputRegs.count(Reg))) { // Already used.
3591 // Make sure we find consecutive registers.
3592 NumAllocated = 0;
3593 continue;
3594 }
3595
3596 // Check to see if this register is allocatable (i.e. don't give out the
3597 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003598 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003599 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003600 if (!RC) { // Couldn't allocate this register.
3601 // Reset NumAllocated to make sure we return consecutive registers.
3602 NumAllocated = 0;
3603 continue;
3604 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003605 }
3606
3607 // Okay, this register is good, we can use it.
3608 ++NumAllocated;
3609
3610 // If we allocated enough consecutive registers, succeed.
3611 if (NumAllocated == NumRegs) {
3612 unsigned RegStart = (i-NumAllocated)+1;
3613 unsigned RegEnd = i+1;
3614 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003615 for (unsigned i = RegStart; i != RegEnd; ++i)
3616 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003617
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003618 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3619 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003620 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003621 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003622 }
3623 }
3624
3625 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003626 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003627}
3628
3629
Chris Lattnerce7518c2006-01-26 22:24:51 +00003630/// visitInlineAsm - Handle a call to an InlineAsm object.
3631///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003632void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3633 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003634
Chris Lattner0c583402007-04-28 20:49:53 +00003635 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003636 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003637
3638 SDOperand Chain = getRoot();
3639 SDOperand Flag;
3640
Chris Lattner4e4b5762006-02-01 18:59:47 +00003641 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003642
Chris Lattner0c583402007-04-28 20:49:53 +00003643 // Do a prepass over the constraints, canonicalizing them, and building up the
3644 // ConstraintOperands list.
3645 std::vector<InlineAsm::ConstraintInfo>
3646 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003647
3648 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3649 // constraint. If so, we can't let the register allocator allocate any input
3650 // registers, because it will not know to avoid the earlyclobbered output reg.
3651 bool SawEarlyClobber = false;
3652
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003653 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattner0c583402007-04-28 20:49:53 +00003654 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003655 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3656 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003657
Chris Lattner0c583402007-04-28 20:49:53 +00003658 MVT::ValueType OpVT = MVT::Other;
3659
3660 // Compute the value type for each operand.
3661 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003662 case InlineAsm::isOutput:
Chris Lattner0c583402007-04-28 20:49:53 +00003663 if (!OpInfo.isIndirect) {
3664 // The return value of the call is this value. As such, there is no
3665 // corresponding argument.
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003666 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3667 OpVT = TLI.getValueType(CS.getType());
Chris Lattner1efa40f2006-02-22 00:56:39 +00003668 } else {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003669 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003670 }
3671 break;
3672 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003673 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003674 break;
3675 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003676 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003677 break;
3678 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003679
Chris Lattner0c583402007-04-28 20:49:53 +00003680 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003681 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003682 if (OpInfo.CallOperandVal) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003683 if (isa<BasicBlock>(OpInfo.CallOperandVal))
3684 OpInfo.CallOperand =
Dale Johannesenba2a0b92008-01-29 02:21:21 +00003685 DAG.getBasicBlock(FuncInfo.MBBMap[cast<BasicBlock>(
3686 OpInfo.CallOperandVal)]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003687 else {
3688 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3689 const Type *OpTy = OpInfo.CallOperandVal->getType();
3690 // If this is an indirect operand, the operand is a pointer to the
3691 // accessed type.
3692 if (OpInfo.isIndirect)
3693 OpTy = cast<PointerType>(OpTy)->getElementType();
3694
3695 // If OpTy is not a first-class value, it may be a struct/union that we
3696 // can tile with integers.
3697 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3698 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3699 switch (BitSize) {
3700 default: break;
3701 case 1:
3702 case 8:
3703 case 16:
3704 case 32:
3705 case 64:
3706 OpTy = IntegerType::get(BitSize);
3707 break;
3708 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003709 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003710
3711 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003712 }
3713 }
3714
3715 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003716
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003717 // Compute the constraint code and ConstraintType to use.
3718 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattner0c583402007-04-28 20:49:53 +00003719
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003720 // Keep track of whether we see an earlyclobber.
3721 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003722
Chris Lattner0fe71e92008-02-21 19:43:13 +00003723 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003724 if (!SawEarlyClobber &&
3725 OpInfo.Type == InlineAsm::isClobber &&
3726 OpInfo.ConstraintType == TargetLowering::C_Register) {
3727 // Note that we want to ignore things that we don't trick here, like
3728 // dirflag, fpsr, flags, etc.
3729 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3730 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3731 OpInfo.ConstraintVT);
3732 if (PhysReg.first || PhysReg.second) {
3733 // This is a register we know of.
3734 SawEarlyClobber = true;
3735 }
3736 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003737
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003738 // If this is a memory input, and if the operand is not indirect, do what we
3739 // need to to provide an address for the memory input.
3740 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3741 !OpInfo.isIndirect) {
3742 assert(OpInfo.Type == InlineAsm::isInput &&
3743 "Can only indirectify direct input operands!");
3744
3745 // Memory operands really want the address of the value. If we don't have
3746 // an indirect input, put it in the constpool if we can, otherwise spill
3747 // it to a stack slot.
3748
3749 // If the operand is a float, integer, or vector constant, spill to a
3750 // constant pool entry to get its address.
3751 Value *OpVal = OpInfo.CallOperandVal;
3752 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3753 isa<ConstantVector>(OpVal)) {
3754 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3755 TLI.getPointerTy());
3756 } else {
3757 // Otherwise, create a stack slot and emit a store to it before the
3758 // asm.
3759 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003760 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003761 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3762 MachineFunction &MF = DAG.getMachineFunction();
3763 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3764 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3765 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3766 OpInfo.CallOperand = StackSlot;
3767 }
3768
3769 // There is no longer a Value* corresponding to this operand.
3770 OpInfo.CallOperandVal = 0;
3771 // It is now an indirect operand.
3772 OpInfo.isIndirect = true;
3773 }
3774
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003775 // If this constraint is for a specific register, allocate it before
3776 // anything else.
3777 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3778 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003779 }
Chris Lattner0c583402007-04-28 20:49:53 +00003780 ConstraintInfos.clear();
3781
3782
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003783 // Second pass - Loop over all of the operands, assigning virtual or physregs
3784 // to registerclass operands.
3785 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003786 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003787
3788 // C_Register operands have already been allocated, Other/Memory don't need
3789 // to be.
3790 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3791 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3792 }
3793
Chris Lattner0c583402007-04-28 20:49:53 +00003794 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3795 std::vector<SDOperand> AsmNodeOperands;
3796 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3797 AsmNodeOperands.push_back(
3798 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3799
Chris Lattner2cc2f662006-02-01 01:28:23 +00003800
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003801 // Loop over all of the inputs, copying the operand values into the
3802 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003803 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003804
Chris Lattner0c583402007-04-28 20:49:53 +00003805 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3806 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3807
3808 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003809 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003810
Chris Lattner0c583402007-04-28 20:49:53 +00003811 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003812 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003813 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3814 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003815 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003816 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003817
Chris Lattner22873462006-02-27 23:45:39 +00003818 // Add information to the INLINEASM node to know about this output.
3819 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003820 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3821 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003822 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003823 break;
3824 }
3825
Chris Lattner2a600be2007-04-28 21:01:43 +00003826 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003827
Chris Lattner864635a2006-02-22 22:37:12 +00003828 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003829 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003830 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003831 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003832 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003833 exit(1);
3834 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003835
Chris Lattner0c583402007-04-28 20:49:53 +00003836 if (!OpInfo.isIndirect) {
3837 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003838 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003839 "Cannot have multiple output constraints yet!");
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003840 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003841 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003842 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003843 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003844 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003845 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003846
3847 // Add information to the INLINEASM node to know that this register is
3848 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003849 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3850 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003851 break;
3852 }
3853 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003854 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003855
Chris Lattner0c583402007-04-28 20:49:53 +00003856 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003857 // If this is required to match an output register we have already set,
3858 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003859 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003860
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003861 // Scan until we find the definition we already emitted of this operand.
3862 // When we find it, create a RegsForValue operand.
3863 unsigned CurOp = 2; // The first operand.
3864 for (; OperandNo; --OperandNo) {
3865 // Advance to the next operand.
3866 unsigned NumOps =
3867 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003868 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3869 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003870 "Skipped past definitions?");
3871 CurOp += (NumOps>>3)+1;
3872 }
3873
3874 unsigned NumOps =
3875 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003876 if ((NumOps & 7) == 2 /*REGDEF*/) {
3877 // Add NumOps>>3 registers to MatchedRegs.
3878 RegsForValue MatchedRegs;
3879 MatchedRegs.ValueVT = InOperandVal.getValueType();
3880 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3881 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3882 unsigned Reg =
3883 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3884 MatchedRegs.Regs.push_back(Reg);
3885 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003886
Chris Lattner527fae12007-02-01 01:21:12 +00003887 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003888 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00003889 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3890 break;
3891 } else {
3892 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00003893 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
3894 // Add information to the INLINEASM node to know about this input.
3895 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3896 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3897 TLI.getPointerTy()));
3898 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
3899 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003900 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003901 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003902
Chris Lattner2a600be2007-04-28 21:01:43 +00003903 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00003904 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003905 "Don't know how to handle indirect other inputs yet!");
3906
Chris Lattner48884cd2007-08-25 00:47:38 +00003907 std::vector<SDOperand> Ops;
3908 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3909 Ops, DAG);
3910 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003911 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003912 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003913 exit(1);
3914 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003915
3916 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00003917 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003918 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3919 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00003920 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003921 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00003922 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003923 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00003924 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3925 "Memory operands expect pointer values");
3926
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003927 // Add information to the INLINEASM node to know about this input.
3928 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003929 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3930 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003931 AsmNodeOperands.push_back(InOperandVal);
3932 break;
3933 }
3934
Chris Lattner2a600be2007-04-28 21:01:43 +00003935 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3936 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3937 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00003938 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003939 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003940
3941 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003942 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3943 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003944
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003945 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003946
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003947 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3948 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003949 break;
3950 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003951 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003952 // Add the clobbered value to the operand list, so that the register
3953 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003954 if (!OpInfo.AssignedRegs.Regs.empty())
3955 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3956 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003957 break;
3958 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003959 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003960 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003961
3962 // Finish up input operands.
3963 AsmNodeOperands[0] = Chain;
3964 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3965
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003966 Chain = DAG.getNode(ISD::INLINEASM,
3967 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003968 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003969 Flag = Chain.getValue(1);
3970
Chris Lattner6656dd12006-01-31 02:03:41 +00003971 // If this asm returns a register value, copy the result from that register
3972 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003973 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003974 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00003975
3976 // If the result of the inline asm is a vector, it may have the wrong
3977 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00003978 // bit_convert.
3979 if (MVT::isVector(Val.getValueType())) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003980 const VectorType *VTy = cast<VectorType>(CS.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00003981 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00003982
Dan Gohman7f321562007-06-25 16:23:39 +00003983 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00003984 }
3985
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003986 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00003987 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003988
Chris Lattner6656dd12006-01-31 02:03:41 +00003989 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3990
3991 // Process indirect outputs, first output all of the flagged copies out of
3992 // physregs.
3993 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003994 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003995 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003996 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00003997 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003998 }
3999
4000 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004001 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004002 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004003 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004004 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004005 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004006 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004007 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4008 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004009 DAG.setRoot(Chain);
4010}
4011
4012
Chris Lattner1c08c712005-01-07 07:47:53 +00004013void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4014 SDOperand Src = getValue(I.getOperand(0));
4015
4016 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004017
4018 if (IntPtr < Src.getValueType())
4019 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4020 else if (IntPtr > Src.getValueType())
4021 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004022
4023 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004024 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004025 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004026 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004027
Reid Spencer47857812006-12-31 05:55:36 +00004028 TargetLowering::ArgListTy Args;
4029 TargetLowering::ArgListEntry Entry;
4030 Entry.Node = Src;
4031 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004032 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004033
4034 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004035 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4036 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004037 setValue(&I, Result.first); // Pointers always fit in registers
4038 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004039}
4040
4041void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004042 TargetLowering::ArgListTy Args;
4043 TargetLowering::ArgListEntry Entry;
4044 Entry.Node = getValue(I.getOperand(0));
4045 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004046 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004047 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004048 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004049 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4050 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004051 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4052 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004053}
4054
Evan Chengff9b3732008-01-30 18:18:23 +00004055// EmitInstrWithCustomInserter - This method should be implemented by targets
4056// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004057// instructions are special in various ways, which require special support to
4058// insert. The specified MachineInstr is created but not inserted into any
4059// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004060MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004061 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004062 cerr << "If a target marks an instruction with "
4063 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004064 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004065 abort();
4066 return 0;
4067}
4068
Chris Lattner39ae3622005-01-09 00:00:49 +00004069void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004070 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4071 getValue(I.getOperand(1)),
4072 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004073}
4074
4075void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004076 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4077 getValue(I.getOperand(0)),
4078 DAG.getSrcValue(I.getOperand(0)));
4079 setValue(&I, V);
4080 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004081}
4082
4083void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004084 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4085 getValue(I.getOperand(1)),
4086 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004087}
4088
4089void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004090 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4091 getValue(I.getOperand(1)),
4092 getValue(I.getOperand(2)),
4093 DAG.getSrcValue(I.getOperand(1)),
4094 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004095}
4096
Chris Lattnerfdfded52006-04-12 16:20:43 +00004097/// TargetLowering::LowerArguments - This is the default LowerArguments
4098/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004099/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4100/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004101std::vector<SDOperand>
4102TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4103 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4104 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004105 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004106 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4107 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4108
4109 // Add one result value for each formal argument.
4110 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004111 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004112 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4113 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004114 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004115 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004116 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004117 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004118
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004119 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004120 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004121 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004122 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004123 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004124 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004125 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004126 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004127 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004128 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004129 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004130 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004131 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004132 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004133 // For ByVal, alignment should be passed from FE. BE will guess if
4134 // this info is not there but there are cases it cannot get right.
4135 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004136 FrameAlign = F.getParamAlignment(j);
4137 Flags.setByValAlign(FrameAlign);
4138 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004139 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004140 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004141 Flags.setNest();
4142 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004143
4144 MVT::ValueType RegisterVT = getRegisterType(VT);
4145 unsigned NumRegs = getNumRegisters(VT);
4146 for (unsigned i = 0; i != NumRegs; ++i) {
4147 RetVals.push_back(RegisterVT);
4148 // if it isn't first piece, alignment must be 1
4149 if (i > 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004150 Flags.setOrigAlign(1);
4151 Ops.push_back(DAG.getArgFlags(Flags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004152 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004153 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004154
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004155 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004156
4157 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004158 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004159 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004160 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004161
4162 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4163 // allows exposing the loads that may be part of the argument access to the
4164 // first DAGCombiner pass.
4165 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4166
4167 // The number of results should match up, except that the lowered one may have
4168 // an extra flag result.
4169 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4170 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4171 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4172 && "Lowering produced unexpected number of results!");
4173 Result = TmpRes.Val;
4174
Dan Gohman27a70be2007-07-02 16:18:06 +00004175 unsigned NumArgRegs = Result->getNumValues() - 1;
4176 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004177
4178 // Set up the return result vector.
4179 Ops.clear();
4180 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004181 unsigned Idx = 1;
4182 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4183 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004184 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004185 MVT::ValueType PartVT = getRegisterType(VT);
4186
4187 unsigned NumParts = getNumRegisters(VT);
4188 SmallVector<SDOperand, 4> Parts(NumParts);
4189 for (unsigned j = 0; j != NumParts; ++j)
4190 Parts[j] = SDOperand(Result, i++);
4191
4192 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4193 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4194 AssertOp = ISD::AssertSext;
4195 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4196 AssertOp = ISD::AssertZext;
4197
4198 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004199 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004200 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004201 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004202 return Ops;
4203}
4204
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004205
4206/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4207/// implementation, which just inserts an ISD::CALL node, which is later custom
4208/// lowered by the target to something concrete. FIXME: When all targets are
4209/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4210std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004211TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4212 bool RetSExt, bool RetZExt, bool isVarArg,
4213 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004214 SDOperand Callee,
4215 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004216 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004217 Ops.push_back(Chain); // Op#0 - Chain
4218 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4219 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4220 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4221 Ops.push_back(Callee);
4222
4223 // Handle all of the outgoing arguments.
4224 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004225 MVT::ValueType VT = getValueType(Args[i].Ty);
4226 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004227 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004228 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004229 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004230
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004231 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004232 Flags.setZExt();
4233 if (Args[i].isSExt)
4234 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004235 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004236 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004237 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004238 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004239 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004240 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004241 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004242 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004243 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004244 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004245 // For ByVal, alignment should come from FE. BE will guess if this
4246 // info is not there but there are cases it cannot get right.
4247 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004248 FrameAlign = Args[i].Alignment;
4249 Flags.setByValAlign(FrameAlign);
4250 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004251 }
Duncan Sands36397f52007-07-27 12:58:54 +00004252 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004253 Flags.setNest();
4254 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004255
Duncan Sandsb988bac2008-02-11 20:58:28 +00004256 MVT::ValueType PartVT = getRegisterType(VT);
4257 unsigned NumParts = getNumRegisters(VT);
4258 SmallVector<SDOperand, 4> Parts(NumParts);
4259 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4260
4261 if (Args[i].isSExt)
4262 ExtendKind = ISD::SIGN_EXTEND;
4263 else if (Args[i].isZExt)
4264 ExtendKind = ISD::ZERO_EXTEND;
4265
4266 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4267
4268 for (unsigned i = 0; i != NumParts; ++i) {
4269 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004270 ISD::ArgFlagsTy MyFlags = Flags;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004271 if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004272 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004273
4274 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004275 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004276 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004277 }
4278
Dan Gohmanef5d1942008-03-11 21:11:25 +00004279 // Figure out the result value types. We start by making a list of
4280 // the high-level LLVM return types.
4281 SmallVector<const Type *, 4> LLVMRetTys;
4282 if (const StructType *ST = dyn_cast<StructType>(RetTy))
4283 // A struct return type in the LLVM IR means we have multiple return values.
4284 LLVMRetTys.insert(LLVMRetTys.end(), ST->element_begin(), ST->element_end());
4285 else
4286 LLVMRetTys.push_back(RetTy);
4287
4288 // Then we translate that to a list of lowered codegen result types.
4289 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4290 SmallVector<MVT::ValueType, 4> RetTys;
4291 for (unsigned I = 0, E = LLVMRetTys.size(); I != E; ++I) {
4292 MVT::ValueType VT = getValueType(LLVMRetTys[I]);
4293 RetTys.push_back(VT);
4294
4295 MVT::ValueType RegisterVT = getRegisterType(VT);
4296 unsigned NumRegs = getNumRegisters(VT);
4297 for (unsigned i = 0; i != NumRegs; ++i)
4298 LoweredRetTys.push_back(RegisterVT);
4299 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004300
Dan Gohmanef5d1942008-03-11 21:11:25 +00004301 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004302
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004303 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004304 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004305 DAG.getVTList(&LoweredRetTys[0],
4306 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004307 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004308 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004309
4310 // Gather up the call result into a single value.
4311 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004312 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4313
4314 if (RetSExt)
4315 AssertOp = ISD::AssertSext;
4316 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004317 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004318
Dan Gohmanef5d1942008-03-11 21:11:25 +00004319 SmallVector<SDOperand, 4> ReturnValues;
4320 unsigned RegNo = 0;
4321 for (unsigned I = 0, E = LLVMRetTys.size(); I != E; ++I) {
4322 MVT::ValueType VT = getValueType(LLVMRetTys[I]);
4323 MVT::ValueType RegisterVT = getRegisterType(VT);
4324 unsigned NumRegs = getNumRegisters(VT);
4325 unsigned RegNoEnd = NumRegs + RegNo;
4326 SmallVector<SDOperand, 4> Results;
4327 for (; RegNo != RegNoEnd; ++RegNo)
4328 Results.push_back(Res.getValue(RegNo));
4329 SDOperand ReturnValue =
4330 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4331 AssertOp);
4332 ReturnValues.push_back(ReturnValue);
4333 }
4334 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4335 DAG.getNode(ISD::MERGE_VALUES,
4336 DAG.getVTList(&RetTys[0], RetTys.size()),
4337 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004338 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004339
4340 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004341}
4342
Chris Lattner50381b62005-05-14 05:50:48 +00004343SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004344 assert(0 && "LowerOperation not implemented for this target!");
4345 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004346 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004347}
4348
Nate Begeman0aed7842006-01-28 03:14:31 +00004349SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4350 SelectionDAG &DAG) {
4351 assert(0 && "CustomPromoteOperation not implemented for this target!");
4352 abort();
4353 return SDOperand();
4354}
4355
Evan Cheng74d0aa92006-02-15 21:59:04 +00004356/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004357/// operand.
4358static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004359 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004360 MVT::ValueType CurVT = VT;
4361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4362 uint64_t Val = C->getValue() & 255;
4363 unsigned Shift = 8;
4364 while (CurVT != MVT::i8) {
4365 Val = (Val << Shift) | Val;
4366 Shift <<= 1;
4367 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004368 }
4369 return DAG.getConstant(Val, VT);
4370 } else {
4371 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4372 unsigned Shift = 8;
4373 while (CurVT != MVT::i8) {
4374 Value =
4375 DAG.getNode(ISD::OR, VT,
4376 DAG.getNode(ISD::SHL, VT, Value,
4377 DAG.getConstant(Shift, MVT::i8)), Value);
4378 Shift <<= 1;
4379 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004380 }
4381
4382 return Value;
4383 }
4384}
4385
Evan Cheng74d0aa92006-02-15 21:59:04 +00004386/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4387/// used when a memcpy is turned into a memset when the source is a constant
4388/// string ptr.
4389static SDOperand getMemsetStringVal(MVT::ValueType VT,
4390 SelectionDAG &DAG, TargetLowering &TLI,
4391 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004392 uint64_t Val = 0;
Dan Gohmanb55757e2007-05-18 17:52:13 +00004393 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004394 if (TLI.isLittleEndian())
4395 Offset = Offset + MSB - 1;
4396 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004397 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004398 Offset += TLI.isLittleEndian() ? -1 : 1;
4399 }
4400 return DAG.getConstant(Val, VT);
4401}
4402
Evan Cheng1db92f92006-02-14 08:22:34 +00004403/// getMemBasePlusOffset - Returns base and offset node for the
4404static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4405 SelectionDAG &DAG, TargetLowering &TLI) {
4406 MVT::ValueType VT = Base.getValueType();
4407 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4408}
4409
Evan Chengc4f8eee2006-02-14 20:12:38 +00004410/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004411/// to replace the memset / memcpy is below the threshold. It also returns the
4412/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004413static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4414 unsigned Limit, uint64_t Size,
4415 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004416 MVT::ValueType VT;
4417
4418 if (TLI.allowsUnalignedMemoryAccesses()) {
4419 VT = MVT::i64;
4420 } else {
4421 switch (Align & 7) {
4422 case 0:
4423 VT = MVT::i64;
4424 break;
4425 case 4:
4426 VT = MVT::i32;
4427 break;
4428 case 2:
4429 VT = MVT::i16;
4430 break;
4431 default:
4432 VT = MVT::i8;
4433 break;
4434 }
4435 }
4436
Evan Cheng80e89d72006-02-14 09:11:59 +00004437 MVT::ValueType LVT = MVT::i64;
4438 while (!TLI.isTypeLegal(LVT))
4439 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4440 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004441
Evan Cheng80e89d72006-02-14 09:11:59 +00004442 if (VT > LVT)
4443 VT = LVT;
4444
Evan Chengdea72452006-02-14 23:05:54 +00004445 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004446 while (Size != 0) {
Dan Gohmanb55757e2007-05-18 17:52:13 +00004447 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng1db92f92006-02-14 08:22:34 +00004448 while (VTSize > Size) {
4449 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004450 VTSize >>= 1;
4451 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004452 assert(MVT::isInteger(VT));
4453
4454 if (++NumMemOps > Limit)
4455 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004456 MemOps.push_back(VT);
4457 Size -= VTSize;
4458 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004459
4460 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004461}
4462
Chris Lattner7041ee32005-01-11 05:56:49 +00004463void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004464 SDOperand Op1 = getValue(I.getOperand(1));
4465 SDOperand Op2 = getValue(I.getOperand(2));
4466 SDOperand Op3 = getValue(I.getOperand(3));
4467 SDOperand Op4 = getValue(I.getOperand(4));
4468 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4469 if (Align == 0) Align = 1;
4470
Dan Gohman5f43f922007-08-27 16:26:13 +00004471 // If the source and destination are known to not be aliases, we can
4472 // lower memmove as memcpy.
4473 if (Op == ISD::MEMMOVE) {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00004474 uint64_t Size = -1ULL;
Dan Gohman5f43f922007-08-27 16:26:13 +00004475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4476 Size = C->getValue();
4477 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4478 AliasAnalysis::NoAlias)
4479 Op = ISD::MEMCPY;
4480 }
4481
Evan Cheng1db92f92006-02-14 08:22:34 +00004482 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4483 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004484
4485 // Expand memset / memcpy to a series of load / store ops
4486 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004487 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004488 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004489 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004490 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004491 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4492 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004493 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004494 unsigned Offset = 0;
4495 for (unsigned i = 0; i < NumMemOps; i++) {
4496 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004497 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004498 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004499 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004500 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004501 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004502 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004503 Offset += VTSize;
4504 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004505 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004506 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004507 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004508 case ISD::MEMCPY: {
4509 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4510 Size->getValue(), Align, TLI)) {
4511 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004512 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004513 GlobalAddressSDNode *G = NULL;
4514 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004515 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004516
4517 if (Op2.getOpcode() == ISD::GlobalAddress)
4518 G = cast<GlobalAddressSDNode>(Op2);
4519 else if (Op2.getOpcode() == ISD::ADD &&
4520 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4521 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4522 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004523 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004524 }
4525 if (G) {
4526 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004527 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004528 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004529 if (!Str.empty()) {
4530 CopyFromStr = true;
4531 SrcOff += SrcDelta;
4532 }
4533 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004534 }
4535
Evan Chengc080d6f2006-02-15 01:54:51 +00004536 for (unsigned i = 0; i < NumMemOps; i++) {
4537 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004538 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004539 SDOperand Value, Chain, Store;
4540
Evan Chengcffbb512006-02-16 23:11:42 +00004541 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004542 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4543 Chain = getRoot();
4544 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004545 DAG.getStore(Chain, Value,
4546 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004547 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004548 } else {
4549 Value = DAG.getLoad(VT, getRoot(),
Bill Wendling984e9862007-10-26 20:24:42 +00004550 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4551 I.getOperand(2), SrcOff, false, Align);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004552 Chain = Value.getValue(1);
4553 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004554 DAG.getStore(Chain, Value,
4555 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Bill Wendling984e9862007-10-26 20:24:42 +00004556 I.getOperand(1), DstOff, false, Align);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004557 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004558 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004559 SrcOff += VTSize;
4560 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004561 }
4562 }
4563 break;
4564 }
4565 }
4566
4567 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004568 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4569 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004570 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004571 }
4572 }
4573
Rafael Espindola5c0d6ed2007-10-19 10:41:11 +00004574 SDOperand AlwaysInline = DAG.getConstant(0, MVT::i1);
4575 SDOperand Node;
4576 switch(Op) {
4577 default:
4578 assert(0 && "Unknown Op");
4579 case ISD::MEMCPY:
4580 Node = DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4581 break;
4582 case ISD::MEMMOVE:
4583 Node = DAG.getMemmove(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4584 break;
4585 case ISD::MEMSET:
4586 Node = DAG.getMemset(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4587 break;
4588 }
4589 DAG.setRoot(Node);
Chris Lattner1c08c712005-01-07 07:47:53 +00004590}
4591
Chris Lattner7041ee32005-01-11 05:56:49 +00004592//===----------------------------------------------------------------------===//
4593// SelectionDAGISel code
4594//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004595
4596unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004597 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004598}
4599
Chris Lattner495a0b52005-08-17 06:37:43 +00004600void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004601 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004602 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004603 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004604}
Chris Lattner1c08c712005-01-07 07:47:53 +00004605
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004606
Chris Lattnerbad7f482006-10-28 19:22:10 +00004607
Chris Lattner1c08c712005-01-07 07:47:53 +00004608bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004609 // Get alias analysis for load/store combining.
4610 AA = &getAnalysis<AliasAnalysis>();
4611
Chris Lattner1c08c712005-01-07 07:47:53 +00004612 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004613 if (MF.getFunction()->hasCollector())
4614 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4615 else
4616 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004617 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004618 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004619
4620 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4621
Dale Johannesen1544e472008-03-31 23:40:23 +00004622 if (FuncInfo.needsExceptionHandling)
Duncan Sandsea632432007-06-13 16:53:21 +00004623 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4624 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4625 // Mark landing pad.
4626 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004627
4628 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004629 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004630
Evan Chengad2070c2007-02-10 02:43:39 +00004631 // Add function live-ins to entry block live-in set.
4632 BasicBlock *EntryBB = &Fn.getEntryBlock();
4633 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004634 if (!RegInfo->livein_empty())
4635 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4636 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004637 BB->addLiveIn(I->first);
4638
Duncan Sandsf4070822007-06-15 19:04:19 +00004639#ifndef NDEBUG
4640 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4641 "Not all catch info was assigned to a landing pad!");
4642#endif
4643
Chris Lattner1c08c712005-01-07 07:47:53 +00004644 return true;
4645}
4646
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004647void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4648 unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004649 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004650 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004651 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004652 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004653 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004654
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004655 MVT::ValueType SrcVT = Op.getValueType();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004656 MVT::ValueType RegisterVT = TLI.getRegisterType(SrcVT);
4657 unsigned NumRegs = TLI.getNumRegisters(SrcVT);
4658 SmallVector<SDOperand, 8> Regs(NumRegs);
4659 SmallVector<SDOperand, 8> Chains(NumRegs);
4660
4661 // Copy the value by legal parts into sequential virtual registers.
Dan Gohman532dc2e2007-07-09 20:59:04 +00004662 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
Dan Gohman27a70be2007-07-02 16:18:06 +00004663 for (unsigned i = 0; i != NumRegs; ++i)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004664 Chains[i] = DAG.getCopyToReg(DAG.getEntryNode(), Reg + i, Regs[i]);
4665 SDOperand Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4666 PendingExports.push_back(Ch);
Chris Lattner1c08c712005-01-07 07:47:53 +00004667}
4668
Chris Lattner068a81e2005-01-17 17:15:02 +00004669void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004670LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004671 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004672 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004673 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004674 SDOperand OldRoot = SDL.DAG.getRoot();
4675 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004676
Chris Lattnerbf209482005-10-30 19:42:35 +00004677 unsigned a = 0;
4678 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4679 AI != E; ++AI, ++a)
4680 if (!AI->use_empty()) {
4681 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004682
Chris Lattnerbf209482005-10-30 19:42:35 +00004683 // If this argument is live outside of the entry block, insert a copy from
4684 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004685 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4686 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004687 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004688 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004689 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004690
Chris Lattnerbf209482005-10-30 19:42:35 +00004691 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004692 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004693 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004694}
4695
Duncan Sandsf4070822007-06-15 19:04:19 +00004696static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4697 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004698 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004699 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004700 // Apply the catch info to DestBB.
4701 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4702#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004703 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4704 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004705#endif
4706 }
4707}
4708
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004709/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004710/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004711static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4712 TargetLowering& TLI) {
4713 SDNode * Ret = NULL;
4714 SDOperand Terminator = DAG.getRoot();
4715
4716 // Find RET node.
4717 if (Terminator.getOpcode() == ISD::RET) {
4718 Ret = Terminator.Val;
4719 }
4720
4721 // Fix tail call attribute of CALL nodes.
4722 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4723 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4724 if (BI->getOpcode() == ISD::CALL) {
4725 SDOperand OpRet(Ret, 0);
4726 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4727 bool isMarkedTailCall =
4728 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4729 // If CALL node has tail call attribute set to true and the call is not
4730 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004731 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004732 // must correctly identify tail call optimizable calls.
4733 if (isMarkedTailCall &&
4734 (Ret==NULL ||
4735 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4736 SmallVector<SDOperand, 32> Ops;
4737 unsigned idx=0;
4738 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4739 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4740 if (idx!=3)
4741 Ops.push_back(*I);
4742 else
4743 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4744 }
4745 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4746 }
4747 }
4748 }
4749}
4750
Chris Lattner1c08c712005-01-07 07:47:53 +00004751void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4752 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004753 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004754 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004755
Chris Lattnerbf209482005-10-30 19:42:35 +00004756 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004757 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004758 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004759
4760 BB = FuncInfo.MBBMap[LLVMBB];
4761 SDL.setCurrentBasicBlock(BB);
4762
Duncan Sandsf4070822007-06-15 19:04:19 +00004763 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004764
Dale Johannesen1544e472008-03-31 23:40:23 +00004765 if (FuncInfo.needsExceptionHandling && MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004766 // Add a label to mark the beginning of the landing pad. Deletion of the
4767 // landing pad can thus be detected via the MachineModuleInfo.
4768 unsigned LabelID = MMI->addLandingPad(BB);
4769 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004770 DAG.getConstant(LabelID, MVT::i32),
4771 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004772
Evan Chenge47c3332007-06-27 18:45:32 +00004773 // Mark exception register as live in.
4774 unsigned Reg = TLI.getExceptionAddressRegister();
4775 if (Reg) BB->addLiveIn(Reg);
4776
4777 // Mark exception selector register as live in.
4778 Reg = TLI.getExceptionSelectorRegister();
4779 if (Reg) BB->addLiveIn(Reg);
4780
Duncan Sandsf4070822007-06-15 19:04:19 +00004781 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4782 // function and list of typeids logically belong to the invoke (or, if you
4783 // like, the basic block containing the invoke), and need to be associated
4784 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004785 // information is provided by an intrinsic (eh.selector) that can be moved
4786 // to unexpected places by the optimizers: if the unwind edge is critical,
4787 // then breaking it can result in the intrinsics being in the successor of
4788 // the landing pad, not the landing pad itself. This results in exceptions
4789 // not being caught because no typeids are associated with the invoke.
4790 // This may not be the only way things can go wrong, but it is the only way
4791 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004792 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4793
4794 if (Br && Br->isUnconditional()) { // Critical edge?
4795 BasicBlock::iterator I, E;
4796 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004797 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004798 break;
4799
4800 if (I == E)
4801 // No catch info found - try to extract some from the successor.
4802 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004803 }
4804 }
4805
Chris Lattner1c08c712005-01-07 07:47:53 +00004806 // Lower all of the non-terminator instructions.
4807 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4808 I != E; ++I)
4809 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004810
Chris Lattner1c08c712005-01-07 07:47:53 +00004811 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004812 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004813 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004814 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004815 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004816 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004817 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004818 }
4819
4820 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4821 // ensure constants are generated when needed. Remember the virtual registers
4822 // that need to be added to the Machine PHI nodes as input. We cannot just
4823 // directly add them, because expansion might result in multiple MBB's for one
4824 // BB. As such, the start of the BB might correspond to a different MBB than
4825 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004826 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004827 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004828
4829 // Emit constants only once even if used by multiple PHI nodes.
4830 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004831
Chris Lattner8c494ab2006-10-27 23:50:33 +00004832 // Vector bool would be better, but vector<bool> is really slow.
4833 std::vector<unsigned char> SuccsHandled;
4834 if (TI->getNumSuccessors())
4835 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4836
Dan Gohman532dc2e2007-07-09 20:59:04 +00004837 // Check successor nodes' PHI nodes that expect a constant to be available
4838 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004839 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4840 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004841 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004842 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004843
Chris Lattner8c494ab2006-10-27 23:50:33 +00004844 // If this terminator has multiple identical successors (common for
4845 // switches), only handle each succ once.
4846 unsigned SuccMBBNo = SuccMBB->getNumber();
4847 if (SuccsHandled[SuccMBBNo]) continue;
4848 SuccsHandled[SuccMBBNo] = true;
4849
4850 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004851 PHINode *PN;
4852
4853 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4854 // nodes and Machine PHI nodes, but the incoming operands have not been
4855 // emitted yet.
4856 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004857 (PN = dyn_cast<PHINode>(I)); ++I) {
4858 // Ignore dead phi's.
4859 if (PN->use_empty()) continue;
4860
4861 unsigned Reg;
4862 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004863
Chris Lattner8c494ab2006-10-27 23:50:33 +00004864 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4865 unsigned &RegOut = ConstantsOut[C];
4866 if (RegOut == 0) {
4867 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004868 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004869 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004870 Reg = RegOut;
4871 } else {
4872 Reg = FuncInfo.ValueMap[PHIOp];
4873 if (Reg == 0) {
4874 assert(isa<AllocaInst>(PHIOp) &&
4875 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4876 "Didn't codegen value into a register!??");
4877 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004878 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004879 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004880 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004881
4882 // Remember that this register needs to added to the machine PHI node as
4883 // the input for this MBB.
4884 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004885 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004886 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004887 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4888 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004889 }
4890 ConstantsOut.clear();
4891
4892 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004893 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004894
Nate Begemanf15485a2006-03-27 01:32:24 +00004895 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004896 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004897 SwitchCases.clear();
4898 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004899 JTCases.clear();
4900 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004901 BitTestCases.clear();
4902 BitTestCases = SDL.BitTestCases;
4903
Chris Lattnera651cf62005-01-17 19:43:36 +00004904 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004905 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004906
4907 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4908 // with correct tailcall attribute so that the target can rely on the tailcall
4909 // attribute indicating whether the call is really eligible for tail call
4910 // optimization.
4911 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004912}
4913
Nate Begemanf15485a2006-03-27 01:32:24 +00004914void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004915 DOUT << "Lowered selection DAG:\n";
4916 DEBUG(DAG.dump());
4917
Chris Lattneraf21d552005-10-10 16:47:10 +00004918 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004919 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004920
Dan Gohman417e11b2007-10-08 15:12:17 +00004921 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004922 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004923
Chris Lattner1c08c712005-01-07 07:47:53 +00004924 // Second step, hack on the DAG until it only uses operations and types that
4925 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004926#if 0 // Enable this some day.
4927 DAG.LegalizeTypes();
4928 // Someday even later, enable a dag combine pass here.
4929#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004930 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004931
Bill Wendling832171c2006-12-07 20:04:42 +00004932 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004933 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004934
Chris Lattneraf21d552005-10-10 16:47:10 +00004935 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004936 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004937
Dan Gohman417e11b2007-10-08 15:12:17 +00004938 DOUT << "Optimized legalized selection DAG:\n";
4939 DEBUG(DAG.dump());
4940
Evan Chenga9c20912006-01-21 02:32:06 +00004941 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004942
Chris Lattnera33ef482005-03-30 01:10:47 +00004943 // Third, instruction select all of the operations to machine code, adding the
4944 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004945 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004946
Bill Wendling832171c2006-12-07 20:04:42 +00004947 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004948 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004949}
Chris Lattner1c08c712005-01-07 07:47:53 +00004950
Nate Begemanf15485a2006-03-27 01:32:24 +00004951void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4952 FunctionLoweringInfo &FuncInfo) {
4953 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4954 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004955 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004956 CurDAG = &DAG;
4957
4958 // First step, lower LLVM code to some DAG. This DAG may use operations and
4959 // types that are not supported by the target.
4960 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4961
4962 // Second step, emit the lowered DAG as machine code.
4963 CodeGenAndEmitDAG(DAG);
4964 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004965
4966 DOUT << "Total amount of phi nodes to update: "
4967 << PHINodesToUpdate.size() << "\n";
4968 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4969 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4970 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004971
Chris Lattnera33ef482005-03-30 01:10:47 +00004972 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004973 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004974 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004975 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4976 MachineInstr *PHI = PHINodesToUpdate[i].first;
4977 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4978 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004979 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4980 false));
4981 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004982 }
4983 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004984 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004985
4986 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4987 // Lower header first, if it wasn't already lowered
4988 if (!BitTestCases[i].Emitted) {
4989 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4990 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004991 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004992 // Set the current basic block to the mbb we wish to insert the code into
4993 BB = BitTestCases[i].Parent;
4994 HSDL.setCurrentBasicBlock(BB);
4995 // Emit the code
4996 HSDL.visitBitTestHeader(BitTestCases[i]);
4997 HSDAG.setRoot(HSDL.getRoot());
4998 CodeGenAndEmitDAG(HSDAG);
4999 }
5000
5001 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5002 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5003 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005004 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005005 // Set the current basic block to the mbb we wish to insert the code into
5006 BB = BitTestCases[i].Cases[j].ThisBB;
5007 BSDL.setCurrentBasicBlock(BB);
5008 // Emit the code
5009 if (j+1 != ej)
5010 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5011 BitTestCases[i].Reg,
5012 BitTestCases[i].Cases[j]);
5013 else
5014 BSDL.visitBitTestCase(BitTestCases[i].Default,
5015 BitTestCases[i].Reg,
5016 BitTestCases[i].Cases[j]);
5017
5018
5019 BSDAG.setRoot(BSDL.getRoot());
5020 CodeGenAndEmitDAG(BSDAG);
5021 }
5022
5023 // Update PHI Nodes
5024 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5025 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5026 MachineBasicBlock *PHIBB = PHI->getParent();
5027 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5028 "This is not a machine PHI node that we are updating!");
5029 // This is "default" BB. We have two jumps to it. From "header" BB and
5030 // from last "case" BB.
5031 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005032 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5033 false));
5034 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5035 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5036 false));
5037 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5038 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005039 }
5040 // One of "cases" BB.
5041 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5042 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5043 if (cBB->succ_end() !=
5044 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005045 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5046 false));
5047 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005048 }
5049 }
5050 }
5051 }
5052
Nate Begeman9453eea2006-04-23 06:26:20 +00005053 // If the JumpTable record is filled in, then we need to emit a jump table.
5054 // Updating the PHI nodes is tricky in this case, since we need to determine
5055 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005056 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5057 // Lower header first, if it wasn't already lowered
5058 if (!JTCases[i].first.Emitted) {
5059 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5060 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005061 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = JTCases[i].first.HeaderBB;
5064 HSDL.setCurrentBasicBlock(BB);
5065 // Emit the code
5066 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5067 HSDAG.setRoot(HSDL.getRoot());
5068 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005069 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005070
5071 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5072 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005073 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005074 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005075 BB = JTCases[i].second.MBB;
5076 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005077 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005078 JSDL.visitJumpTable(JTCases[i].second);
5079 JSDAG.setRoot(JSDL.getRoot());
5080 CodeGenAndEmitDAG(JSDAG);
5081
Nate Begeman37efe672006-04-22 18:53:45 +00005082 // Update PHI Nodes
5083 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5084 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5085 MachineBasicBlock *PHIBB = PHI->getParent();
5086 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5087 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005088 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005089 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005090 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5091 false));
5092 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005093 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005094 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005095 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005096 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5097 false));
5098 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005099 }
5100 }
Nate Begeman37efe672006-04-22 18:53:45 +00005101 }
5102
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005103 // If the switch block involved a branch to one of the actual successors, we
5104 // need to update PHI nodes in that block.
5105 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5106 MachineInstr *PHI = PHINodesToUpdate[i].first;
5107 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5108 "This is not a machine PHI node that we are updating!");
5109 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005110 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5111 false));
5112 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005113 }
5114 }
5115
Nate Begemanf15485a2006-03-27 01:32:24 +00005116 // If we generated any switch lowering information, build and codegen any
5117 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005118 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005119 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005120 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005121 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005122
Nate Begemanf15485a2006-03-27 01:32:24 +00005123 // Set the current basic block to the mbb we wish to insert the code into
5124 BB = SwitchCases[i].ThisBB;
5125 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005126
Nate Begemanf15485a2006-03-27 01:32:24 +00005127 // Emit the code
5128 SDL.visitSwitchCase(SwitchCases[i]);
5129 SDAG.setRoot(SDL.getRoot());
5130 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005131
5132 // Handle any PHI nodes in successors of this chunk, as if we were coming
5133 // from the original BB before switch expansion. Note that PHI nodes can
5134 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5135 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005136 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005137 for (MachineBasicBlock::iterator Phi = BB->begin();
5138 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5139 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5140 for (unsigned pn = 0; ; ++pn) {
5141 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5142 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005143 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5144 second, false));
5145 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005146 break;
5147 }
5148 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005149 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005150
5151 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005152 if (BB == SwitchCases[i].FalseBB)
5153 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005154
5155 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005156 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005157 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005158 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005159 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005160 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005161}
Evan Chenga9c20912006-01-21 02:32:06 +00005162
Jim Laskey13ec7022006-08-01 14:21:23 +00005163
Evan Chenga9c20912006-01-21 02:32:06 +00005164//===----------------------------------------------------------------------===//
5165/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5166/// target node in the graph.
5167void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5168 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005169
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005170 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005171
5172 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005173 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005174 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005175 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005176
Jim Laskey9ff542f2006-08-01 18:29:48 +00005177 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005178 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005179
5180 if (ViewSUnitDAGs) SL->viewGraph();
5181
Evan Chengcccf1232006-02-04 06:49:00 +00005182 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005183}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005184
Chris Lattner03fc53c2006-03-06 00:22:00 +00005185
Jim Laskey9ff542f2006-08-01 18:29:48 +00005186HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5187 return new HazardRecognizer();
5188}
5189
Chris Lattner75548062006-10-11 03:58:02 +00005190//===----------------------------------------------------------------------===//
5191// Helper functions used by the generated instruction selector.
5192//===----------------------------------------------------------------------===//
5193// Calls to these methods are generated by tblgen.
5194
5195/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5196/// the dag combiner simplified the 255, we still want to match. RHS is the
5197/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5198/// specified in the .td file (e.g. 255).
5199bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005200 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005201 const APInt &ActualMask = RHS->getAPIntValue();
5202 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005203
5204 // If the actual mask exactly matches, success!
5205 if (ActualMask == DesiredMask)
5206 return true;
5207
5208 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005209 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005210 return false;
5211
5212 // Otherwise, the DAG Combiner may have proven that the value coming in is
5213 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005214 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005215 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005216 return true;
5217
5218 // TODO: check to see if missing bits are just not demanded.
5219
5220 // Otherwise, this pattern doesn't match.
5221 return false;
5222}
5223
5224/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5225/// the dag combiner simplified the 255, we still want to match. RHS is the
5226/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5227/// specified in the .td file (e.g. 255).
5228bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005229 int64_t DesiredMaskS) const {
5230 const APInt &ActualMask = RHS->getAPIntValue();
5231 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005232
5233 // If the actual mask exactly matches, success!
5234 if (ActualMask == DesiredMask)
5235 return true;
5236
5237 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005238 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005239 return false;
5240
5241 // Otherwise, the DAG Combiner may have proven that the value coming in is
5242 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005243 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005244
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005245 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005246 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005247
5248 // If all the missing bits in the or are already known to be set, match!
5249 if ((NeededMask & KnownOne) == NeededMask)
5250 return true;
5251
5252 // TODO: check to see if missing bits are just not demanded.
5253
5254 // Otherwise, this pattern doesn't match.
5255 return false;
5256}
5257
Jim Laskey9ff542f2006-08-01 18:29:48 +00005258
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005259/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5260/// by tblgen. Others should not call it.
5261void SelectionDAGISel::
5262SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5263 std::vector<SDOperand> InOps;
5264 std::swap(InOps, Ops);
5265
5266 Ops.push_back(InOps[0]); // input chain.
5267 Ops.push_back(InOps[1]); // input asm string.
5268
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005269 unsigned i = 2, e = InOps.size();
5270 if (InOps[e-1].getValueType() == MVT::Flag)
5271 --e; // Don't process a flag operand if it is here.
5272
5273 while (i != e) {
5274 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5275 if ((Flags & 7) != 4 /*MEM*/) {
5276 // Just skip over this operand, copying the operands verbatim.
5277 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5278 i += (Flags >> 3) + 1;
5279 } else {
5280 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5281 // Otherwise, this is a memory operand. Ask the target to select it.
5282 std::vector<SDOperand> SelOps;
5283 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005284 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005285 exit(1);
5286 }
5287
5288 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005289 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005290 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005291 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005292 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5293 i += 2;
5294 }
5295 }
5296
5297 // Add the flag input back if present.
5298 if (e != InOps.size())
5299 Ops.push_back(InOps.back());
5300}
Devang Patel794fd752007-05-01 21:15:47 +00005301
Devang Patel19974732007-05-03 01:11:54 +00005302char SelectionDAGISel::ID = 0;