blob: 1947414884c5360795c0e0b09529558aa2bf24fd [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000043#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattnerda8abb02005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000051ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
53static cl::opt<bool>
54ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000056#else
Chris Lattner5e46a192006-04-02 03:07:27 +000057static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Jim Laskeyeb577ba2006-08-02 12:30:23 +000060//===---------------------------------------------------------------------===//
61///
62/// RegisterScheduler class - Track the registration of instruction schedulers.
63///
64//===---------------------------------------------------------------------===//
65MachinePassRegistry RegisterScheduler::Registry;
66
67//===---------------------------------------------------------------------===//
68///
69/// ISHeuristic command line option for instruction schedulers.
70///
71//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000072namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000073 cl::opt<RegisterScheduler::FunctionPassCtor, false,
74 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000075 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000076 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000077 cl::desc("Instruction schedulers available:"));
78
Jim Laskey9ff542f2006-08-01 18:29:48 +000079 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000080 defaultListDAGScheduler("default", " Best scheduler for the target",
81 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000082} // namespace
83
Chris Lattner864635a2006-02-22 22:37:12 +000084namespace {
85 /// RegsForValue - This struct represents the physical registers that a
86 /// particular value is assigned and the type information about the value.
87 /// This is needed because values can be promoted into larger registers and
88 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000089 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000090 /// Regs - This list hold the register (for legal and promoted values)
91 /// or register set (for expanded values) that the value should be assigned
92 /// to.
93 std::vector<unsigned> Regs;
94
95 /// RegVT - The value type of each register.
96 ///
97 MVT::ValueType RegVT;
98
99 /// ValueVT - The value type of the LLVM value, which may be promoted from
100 /// RegVT or made from merging the two expanded parts.
101 MVT::ValueType ValueVT;
102
103 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
104
105 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
106 : RegVT(regvt), ValueVT(valuevt) {
107 Regs.push_back(Reg);
108 }
109 RegsForValue(const std::vector<unsigned> &regs,
110 MVT::ValueType regvt, MVT::ValueType valuevt)
111 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
112 }
113
114 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
115 /// this value and returns the result as a ValueVT value. This uses
116 /// Chain/Flag as the input and updates them for the output Chain/Flag.
117 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000118 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000119
120 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
121 /// specified value into the registers specified by this object. This uses
122 /// Chain/Flag as the input and updates them for the output Chain/Flag.
123 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000124 SDOperand &Chain, SDOperand &Flag,
125 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000126
127 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
128 /// operand list. This adds the code marker and includes the number of
129 /// values added into it.
130 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000131 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000132 };
133}
Evan Cheng4ef10862006-01-23 07:01:07 +0000134
Chris Lattner1c08c712005-01-07 07:47:53 +0000135namespace llvm {
136 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000137 /// createDefaultScheduler - This creates an instruction scheduler appropriate
138 /// for the target.
139 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
140 SelectionDAG *DAG,
141 MachineBasicBlock *BB) {
142 TargetLowering &TLI = IS->getTargetLowering();
143
144 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
145 return createTDListDAGScheduler(IS, DAG, BB);
146 } else {
147 assert(TLI.getSchedulingPreference() ==
148 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
149 return createBURRListDAGScheduler(IS, DAG, BB);
150 }
151 }
152
153
154 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000155 /// FunctionLoweringInfo - This contains information that is global to a
156 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000157 class FunctionLoweringInfo {
158 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000159 TargetLowering &TLI;
160 Function &Fn;
161 MachineFunction &MF;
162 SSARegMap *RegMap;
163
164 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
165
166 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
167 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
168
169 /// ValueMap - Since we emit code for the function a basic block at a time,
170 /// we must remember which virtual registers hold the values for
171 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000172 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000173
174 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
175 /// the entry block. This allows the allocas to be efficiently referenced
176 /// anywhere in the function.
177 std::map<const AllocaInst*, int> StaticAllocaMap;
178
179 unsigned MakeReg(MVT::ValueType VT) {
180 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
181 }
Chris Lattner571e4342006-10-27 21:36:01 +0000182
183 /// isExportedInst - Return true if the specified value is an instruction
184 /// exported from its block.
185 bool isExportedInst(const Value *V) {
186 return ValueMap.count(V);
187 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000188
Chris Lattner3c384492006-03-16 19:51:18 +0000189 unsigned CreateRegForValue(const Value *V);
190
Chris Lattner1c08c712005-01-07 07:47:53 +0000191 unsigned InitializeRegForValue(const Value *V) {
192 unsigned &R = ValueMap[V];
193 assert(R == 0 && "Already initialized this value register!");
194 return R = CreateRegForValue(V);
195 }
196 };
197}
198
199/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000200/// PHI nodes or outside of the basic block that defines it, or used by a
201/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000202static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
203 if (isa<PHINode>(I)) return true;
204 BasicBlock *BB = I->getParent();
205 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000206 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000207 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000208 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000209 return true;
210 return false;
211}
212
Chris Lattnerbf209482005-10-30 19:42:35 +0000213/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000214/// entry block, return true. This includes arguments used by switches, since
215/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000216static bool isOnlyUsedInEntryBlock(Argument *A) {
217 BasicBlock *Entry = A->getParent()->begin();
218 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000219 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000220 return false; // Use not in entry block.
221 return true;
222}
223
Chris Lattner1c08c712005-01-07 07:47:53 +0000224FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000225 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000226 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
227
Chris Lattnerbf209482005-10-30 19:42:35 +0000228 // Create a vreg for each argument register that is not dead and is used
229 // outside of the entry block for the function.
230 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
231 AI != E; ++AI)
232 if (!isOnlyUsedInEntryBlock(AI))
233 InitializeRegForValue(AI);
234
Chris Lattner1c08c712005-01-07 07:47:53 +0000235 // Initialize the mapping of values to registers. This is only set up for
236 // instruction values that are used outside of the block that defines
237 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000238 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000239 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
240 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000241 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000242 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000243 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000244 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000245 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000246 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000247
Reid Spencerb83eb642006-10-20 07:07:24 +0000248 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000249 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000250 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000251 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 }
253
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000254 for (; BB != EB; ++BB)
255 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000256 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
257 if (!isa<AllocaInst>(I) ||
258 !StaticAllocaMap.count(cast<AllocaInst>(I)))
259 InitializeRegForValue(I);
260
261 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
262 // also creates the initial PHI MachineInstrs, though none of the input
263 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000264 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000265 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
266 MBBMap[BB] = MBB;
267 MF.getBasicBlockList().push_back(MBB);
268
269 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
270 // appropriate.
271 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000272 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
273 if (PN->use_empty()) continue;
274
275 MVT::ValueType VT = TLI.getValueType(PN->getType());
276 unsigned NumElements;
277 if (VT != MVT::Vector)
278 NumElements = TLI.getNumElements(VT);
279 else {
280 MVT::ValueType VT1,VT2;
281 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000282 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000283 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000284 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000285 unsigned PHIReg = ValueMap[PN];
286 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000287 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000288 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000289 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000290 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000291 }
292}
293
Chris Lattner3c384492006-03-16 19:51:18 +0000294/// CreateRegForValue - Allocate the appropriate number of virtual registers of
295/// the correctly promoted or expanded types. Assign these registers
296/// consecutive vreg numbers and return the first assigned number.
297unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
298 MVT::ValueType VT = TLI.getValueType(V->getType());
299
300 // The number of multiples of registers that we need, to, e.g., split up
301 // a <2 x int64> -> 4 x i32 registers.
302 unsigned NumVectorRegs = 1;
303
Reid Spencerac9dcb92007-02-15 03:39:18 +0000304 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000305 // and how many of the elements it will use.
306 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000307 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000308 unsigned NumElts = PTy->getNumElements();
309 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
310
311 // Divide the input until we get to a supported size. This will always
312 // end with a scalar if the target doesn't support vectors.
313 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
314 NumElts >>= 1;
315 NumVectorRegs <<= 1;
316 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000317 if (NumElts == 1)
318 VT = EltTy;
319 else
320 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000321 }
322
323 // The common case is that we will only create one register for this
324 // value. If we have that case, create and return the virtual register.
325 unsigned NV = TLI.getNumElements(VT);
326 if (NV == 1) {
327 // If we are promoting this value, pick the next largest supported type.
328 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
329 unsigned Reg = MakeReg(PromotedType);
330 // If this is a vector of supported or promoted types (e.g. 4 x i16),
331 // create all of the registers.
332 for (unsigned i = 1; i != NumVectorRegs; ++i)
333 MakeReg(PromotedType);
334 return Reg;
335 }
336
337 // If this value is represented with multiple target registers, make sure
338 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000339 VT = TLI.getTypeToExpandTo(VT);
340 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000341 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000342 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000343 return R;
344}
Chris Lattner1c08c712005-01-07 07:47:53 +0000345
346//===----------------------------------------------------------------------===//
347/// SelectionDAGLowering - This is the common target-independent lowering
348/// implementation that is parameterized by a TargetLowering object.
349/// Also, targets can overload any lowering method.
350///
351namespace llvm {
352class SelectionDAGLowering {
353 MachineBasicBlock *CurMBB;
354
Chris Lattner0da331f2007-02-04 01:31:47 +0000355 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000356
Chris Lattnerd3948112005-01-17 22:19:26 +0000357 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
358 /// them up and then emit token factor nodes when possible. This allows us to
359 /// get simple disambiguation between loads without worrying about alias
360 /// analysis.
361 std::vector<SDOperand> PendingLoads;
362
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000363 /// Case - A struct to record the Value for a switch case, and the
364 /// case's target basic block.
365 struct Case {
366 Constant* Low;
367 Constant* High;
368 MachineBasicBlock* BB;
369
370 Case() : Low(0), High(0), BB(0) { }
371 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
372 Low(low), High(high), BB(bb) { }
373 uint64_t size() const {
374 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
375 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
376 return (rHigh - rLow + 1ULL);
377 }
378 };
379
380 typedef std::vector<Case> CaseVector;
381 typedef CaseVector::iterator CaseItr;
382 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000383
384 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
385 /// of conditional branches.
386 struct CaseRec {
387 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
388 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
389
390 /// CaseBB - The MBB in which to emit the compare and branch
391 MachineBasicBlock *CaseBB;
392 /// LT, GE - If nonzero, we know the current case value must be less-than or
393 /// greater-than-or-equal-to these Constants.
394 Constant *LT;
395 Constant *GE;
396 /// Range - A pair of iterators representing the range of case values to be
397 /// processed at this point in the binary search tree.
398 CaseRange Range;
399 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000400
401 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000402
403 /// The comparison function for sorting the switch case values in the vector.
404 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 struct CaseCmp {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000406 bool operator () (const Case& C1,
407 const Case& C2) {
408
409 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
410 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
411 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
412 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000413 }
414 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000415
416 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000417
Chris Lattner1c08c712005-01-07 07:47:53 +0000418public:
419 // TLI - This is information that describes the available target features we
420 // need for lowering. This indicates when operations are unavailable,
421 // implemented with a libcall, etc.
422 TargetLowering &TLI;
423 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000424 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000425
Nate Begemanf15485a2006-03-27 01:32:24 +0000426 /// SwitchCases - Vector of CaseBlock structures used to communicate
427 /// SwitchInst code generation information.
428 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000429 /// JTCases - Vector of JumpTable structures used to communicate
430 /// SwitchInst code generation information.
431 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000432
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 /// FuncInfo - Information about the function as a whole.
434 ///
435 FunctionLoweringInfo &FuncInfo;
436
437 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000438 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000439 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000440 FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000441 }
442
Chris Lattnera651cf62005-01-17 19:43:36 +0000443 /// getRoot - Return the current virtual root of the Selection DAG.
444 ///
445 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000446 if (PendingLoads.empty())
447 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000448
Chris Lattnerd3948112005-01-17 22:19:26 +0000449 if (PendingLoads.size() == 1) {
450 SDOperand Root = PendingLoads[0];
451 DAG.setRoot(Root);
452 PendingLoads.clear();
453 return Root;
454 }
455
456 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000457 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
458 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000459 PendingLoads.clear();
460 DAG.setRoot(Root);
461 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000462 }
463
Chris Lattner571e4342006-10-27 21:36:01 +0000464 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
465
Chris Lattner1c08c712005-01-07 07:47:53 +0000466 void visit(Instruction &I) { visit(I.getOpcode(), I); }
467
468 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000469 // Note: this doesn't use InstVisitor, because it has to work with
470 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000471 switch (Opcode) {
472 default: assert(0 && "Unknown instruction type encountered!");
473 abort();
474 // Build the switch statement using the Instruction.def file.
475#define HANDLE_INST(NUM, OPCODE, CLASS) \
476 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
477#include "llvm/Instruction.def"
478 }
479 }
480
481 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
482
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000483 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000484 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000485 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000486
487 SDOperand getIntPtrConstant(uint64_t Val) {
488 return DAG.getConstant(Val, TLI.getPointerTy());
489 }
490
Chris Lattner199862b2006-03-16 19:57:50 +0000491 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000492
Chris Lattner0da331f2007-02-04 01:31:47 +0000493 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000494 SDOperand &N = NodeMap[V];
495 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000496 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000497 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000498
Chris Lattner864635a2006-02-22 22:37:12 +0000499 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
500 MVT::ValueType VT,
501 bool OutReg, bool InReg,
502 std::set<unsigned> &OutputRegs,
503 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000504
Chris Lattner571e4342006-10-27 21:36:01 +0000505 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
506 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
507 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000508 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000509 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000510 void LowerCallTo(Instruction &I,
511 const Type *CalledValueTy, unsigned CallingConv,
512 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey735b6f82007-02-22 15:38:06 +0000513
Chris Lattner1c08c712005-01-07 07:47:53 +0000514 // Terminator instructions.
515 void visitRet(ReturnInst &I);
516 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000517 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000518 void visitUnreachable(UnreachableInst &I) { /* noop */ }
519
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000520 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000521 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000522 CaseRecVector& WorkList,
523 Value* SV,
524 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000525 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000526 CaseRecVector& WorkList,
527 Value* SV,
528 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000529 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000530 CaseRecVector& WorkList,
531 Value* SV,
532 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000533 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000534 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000535 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
536 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000537
Chris Lattner1c08c712005-01-07 07:47:53 +0000538 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000539 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000540 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000541 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000542
Reid Spencer24d6da52007-01-21 00:29:26 +0000543 void visitScalarBinary(User &I, unsigned OpCode);
544 void visitVectorBinary(User &I, unsigned OpCode);
545 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000546 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000547 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000548 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000549 visitVectorBinary(I, ISD::VADD);
550 else if (I.getType()->isFloatingPoint())
551 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000552 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000553 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000554 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000555 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000556 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000557 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000558 visitVectorBinary(I, ISD::VMUL);
559 else if (I.getType()->isFloatingPoint())
560 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000561 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000562 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000563 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000564 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
565 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
566 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
567 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
568 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
569 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
570 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
571 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
572 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
573 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000574 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
575 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000576 void visitICmp(User &I);
577 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000578 // Visit the conversion instructions
579 void visitTrunc(User &I);
580 void visitZExt(User &I);
581 void visitSExt(User &I);
582 void visitFPTrunc(User &I);
583 void visitFPExt(User &I);
584 void visitFPToUI(User &I);
585 void visitFPToSI(User &I);
586 void visitUIToFP(User &I);
587 void visitSIToFP(User &I);
588 void visitPtrToInt(User &I);
589 void visitIntToPtr(User &I);
590 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000591
Chris Lattner2bbd8102006-03-29 00:11:43 +0000592 void visitExtractElement(User &I);
593 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000594 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000595
Chris Lattner1c08c712005-01-07 07:47:53 +0000596 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000597 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000598
599 void visitMalloc(MallocInst &I);
600 void visitFree(FreeInst &I);
601 void visitAlloca(AllocaInst &I);
602 void visitLoad(LoadInst &I);
603 void visitStore(StoreInst &I);
604 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
605 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000606 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000607 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000608 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000609
Chris Lattner1c08c712005-01-07 07:47:53 +0000610 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000611 void visitVAArg(VAArgInst &I);
612 void visitVAEnd(CallInst &I);
613 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000614
Chris Lattner7041ee32005-01-11 05:56:49 +0000615 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000616
617 void visitUserOp1(Instruction &I) {
618 assert(0 && "UserOp1 should not exist at instruction selection time!");
619 abort();
620 }
621 void visitUserOp2(Instruction &I) {
622 assert(0 && "UserOp2 should not exist at instruction selection time!");
623 abort();
624 }
625};
626} // end namespace llvm
627
Chris Lattner199862b2006-03-16 19:57:50 +0000628SDOperand SelectionDAGLowering::getValue(const Value *V) {
629 SDOperand &N = NodeMap[V];
630 if (N.Val) return N;
631
632 const Type *VTy = V->getType();
633 MVT::ValueType VT = TLI.getValueType(VTy);
634 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
635 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
636 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000637 SDOperand N1 = NodeMap[V];
638 assert(N1.Val && "visit didn't populate the ValueMap!");
639 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000640 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
641 return N = DAG.getGlobalAddress(GV, VT);
642 } else if (isa<ConstantPointerNull>(C)) {
643 return N = DAG.getConstant(0, TLI.getPointerTy());
644 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000645 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000646 return N = DAG.getNode(ISD::UNDEF, VT);
647
Chris Lattnerb2827b02006-03-19 00:52:58 +0000648 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000649 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000650 unsigned NumElements = PTy->getNumElements();
651 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
652
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000653 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000654 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
655
656 // Create a VConstant node with generic Vector type.
657 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
658 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000659 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
660 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000661 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
662 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000663 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000664 unsigned NumElements = PTy->getNumElements();
665 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000666
667 // Now that we know the number and type of the elements, push a
668 // Constant or ConstantFP node onto the ops list for each element of
669 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000670 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000671 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000672 for (unsigned i = 0; i != NumElements; ++i)
673 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000674 } else {
675 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
676 SDOperand Op;
677 if (MVT::isFloatingPoint(PVT))
678 Op = DAG.getConstantFP(0, PVT);
679 else
680 Op = DAG.getConstant(0, PVT);
681 Ops.assign(NumElements, Op);
682 }
683
Chris Lattnerb2827b02006-03-19 00:52:58 +0000684 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
686 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000687 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
688 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000689 } else {
690 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000691 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000692 }
693 }
694
695 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
696 std::map<const AllocaInst*, int>::iterator SI =
697 FuncInfo.StaticAllocaMap.find(AI);
698 if (SI != FuncInfo.StaticAllocaMap.end())
699 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
700 }
701
Chris Lattner251db182007-02-25 18:40:32 +0000702 unsigned InReg = FuncInfo.ValueMap[V];
703 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000704
705 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000706 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000707 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000708 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000709 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000710 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
711 unsigned NumVals = TLI.getNumElements(VT);
712 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
713 if (NumVals == 1)
714 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
715 else {
716 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
717 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
718 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
719 }
720 } else {
721 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
722 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
723 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
724 N = MVT::isFloatingPoint(VT)
725 ? DAG.getNode(ISD::FP_ROUND, VT, N)
726 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000727 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000728 } else {
729 // Otherwise, if this is a vector, make it available as a generic vector
730 // here.
731 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000732 const VectorType *PTy = cast<VectorType>(VTy);
733 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000734 PTyLegalElementVT);
735
736 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000737 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000738 if (PTyElementVT == PTyLegalElementVT) {
739 // If the value types are legal, just VBUILD the CopyFromReg nodes.
740 for (unsigned i = 0; i != NE; ++i)
741 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
742 PTyElementVT));
743 } else if (PTyElementVT < PTyLegalElementVT) {
744 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
745 for (unsigned i = 0; i != NE; ++i) {
746 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
747 PTyElementVT);
748 if (MVT::isFloatingPoint(PTyElementVT))
749 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
750 else
751 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
752 Ops.push_back(Op);
753 }
754 } else {
755 // If the register was expanded, use BUILD_PAIR.
756 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
757 for (unsigned i = 0; i != NE/2; ++i) {
758 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
759 PTyElementVT);
760 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
761 PTyElementVT);
762 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
763 }
764 }
765
766 Ops.push_back(DAG.getConstant(NE, MVT::i32));
767 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000768 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000769
770 // Finally, use a VBIT_CONVERT to make this available as the appropriate
771 // vector type.
772 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
773 DAG.getConstant(PTy->getNumElements(),
774 MVT::i32),
775 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000776 }
777
778 return N;
779}
780
781
Chris Lattner1c08c712005-01-07 07:47:53 +0000782void SelectionDAGLowering::visitRet(ReturnInst &I) {
783 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000784 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000785 return;
786 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000787 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000788 NewValues.push_back(getRoot());
789 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
790 SDOperand RetOp = getValue(I.getOperand(i));
791
792 // If this is an integer return value, we need to promote it ourselves to
793 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
794 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000795 // FIXME: C calling convention requires the return type to be promoted to
796 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000797 if (MVT::isInteger(RetOp.getValueType()) &&
798 RetOp.getValueType() < MVT::i64) {
799 MVT::ValueType TmpVT;
800 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
801 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
802 else
803 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000804 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000805 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000806 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
807 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000808 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
809 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000810 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000811 }
812 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000813 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000814 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000815 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
816 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000817}
818
Chris Lattner571e4342006-10-27 21:36:01 +0000819/// ExportFromCurrentBlock - If this condition isn't known to be exported from
820/// the current basic block, add it to ValueMap now so that we'll get a
821/// CopyTo/FromReg.
822void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
823 // No need to export constants.
824 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
825
826 // Already exported?
827 if (FuncInfo.isExportedInst(V)) return;
828
829 unsigned Reg = FuncInfo.InitializeRegForValue(V);
830 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
831}
832
Chris Lattner8c494ab2006-10-27 23:50:33 +0000833bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
834 const BasicBlock *FromBB) {
835 // The operands of the setcc have to be in this block. We don't know
836 // how to export them from some other block.
837 if (Instruction *VI = dyn_cast<Instruction>(V)) {
838 // Can export from current BB.
839 if (VI->getParent() == FromBB)
840 return true;
841
842 // Is already exported, noop.
843 return FuncInfo.isExportedInst(V);
844 }
845
846 // If this is an argument, we can export it if the BB is the entry block or
847 // if it is already exported.
848 if (isa<Argument>(V)) {
849 if (FromBB == &FromBB->getParent()->getEntryBlock())
850 return true;
851
852 // Otherwise, can only export this if it is already exported.
853 return FuncInfo.isExportedInst(V);
854 }
855
856 // Otherwise, constants can always be exported.
857 return true;
858}
859
Chris Lattner6a586c82006-10-29 21:01:20 +0000860static bool InBlock(const Value *V, const BasicBlock *BB) {
861 if (const Instruction *I = dyn_cast<Instruction>(V))
862 return I->getParent() == BB;
863 return true;
864}
865
Chris Lattner571e4342006-10-27 21:36:01 +0000866/// FindMergedConditions - If Cond is an expression like
867void SelectionDAGLowering::FindMergedConditions(Value *Cond,
868 MachineBasicBlock *TBB,
869 MachineBasicBlock *FBB,
870 MachineBasicBlock *CurBB,
871 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000872 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000873 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000874
Reid Spencere4d87aa2006-12-23 06:05:41 +0000875 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
876 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000877 BOp->getParent() != CurBB->getBasicBlock() ||
878 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
879 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000880 const BasicBlock *BB = CurBB->getBasicBlock();
881
Reid Spencere4d87aa2006-12-23 06:05:41 +0000882 // If the leaf of the tree is a comparison, merge the condition into
883 // the caseblock.
884 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
885 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000886 // how to export them from some other block. If this is the first block
887 // of the sequence, no exporting is needed.
888 (CurBB == CurMBB ||
889 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
890 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000891 BOp = cast<Instruction>(Cond);
892 ISD::CondCode Condition;
893 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
894 switch (IC->getPredicate()) {
895 default: assert(0 && "Unknown icmp predicate opcode!");
896 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
897 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
898 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
899 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
900 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
901 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
902 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
903 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
904 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
905 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
906 }
907 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
908 ISD::CondCode FPC, FOC;
909 switch (FC->getPredicate()) {
910 default: assert(0 && "Unknown fcmp predicate opcode!");
911 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
912 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
913 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
914 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
915 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
916 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
917 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
918 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
919 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
920 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
921 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
922 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
923 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
924 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
925 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
926 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
927 }
928 if (FiniteOnlyFPMath())
929 Condition = FOC;
930 else
931 Condition = FPC;
932 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000933 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000934 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000935 }
936
Chris Lattner571e4342006-10-27 21:36:01 +0000937 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000938 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000939 SwitchCases.push_back(CB);
940 return;
941 }
942
943 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000944 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000945 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000946 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000947 return;
948 }
949
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000950
951 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000952 MachineFunction::iterator BBI = CurBB;
953 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
954 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
955
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000956 if (Opc == Instruction::Or) {
957 // Codegen X | Y as:
958 // jmp_if_X TBB
959 // jmp TmpBB
960 // TmpBB:
961 // jmp_if_Y TBB
962 // jmp FBB
963 //
Chris Lattner571e4342006-10-27 21:36:01 +0000964
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000965 // Emit the LHS condition.
966 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
967
968 // Emit the RHS condition into TmpBB.
969 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
970 } else {
971 assert(Opc == Instruction::And && "Unknown merge op!");
972 // Codegen X & Y as:
973 // jmp_if_X TmpBB
974 // jmp FBB
975 // TmpBB:
976 // jmp_if_Y TBB
977 // jmp FBB
978 //
979 // This requires creation of TmpBB after CurBB.
980
981 // Emit the LHS condition.
982 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
983
984 // Emit the RHS condition into TmpBB.
985 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
986 }
Chris Lattner571e4342006-10-27 21:36:01 +0000987}
988
Chris Lattnerdf19f272006-10-31 22:37:42 +0000989/// If the set of cases should be emitted as a series of branches, return true.
990/// If we should emit this as a bunch of and/or'd together conditions, return
991/// false.
992static bool
993ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
994 if (Cases.size() != 2) return true;
995
Chris Lattner0ccb5002006-10-31 23:06:00 +0000996 // If this is two comparisons of the same values or'd or and'd together, they
997 // will get folded into a single comparison, so don't emit two blocks.
998 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
999 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1000 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1001 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1002 return false;
1003 }
1004
Chris Lattnerdf19f272006-10-31 22:37:42 +00001005 return true;
1006}
1007
Chris Lattner1c08c712005-01-07 07:47:53 +00001008void SelectionDAGLowering::visitBr(BranchInst &I) {
1009 // Update machine-CFG edges.
1010 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001011
1012 // Figure out which block is immediately after the current one.
1013 MachineBasicBlock *NextBlock = 0;
1014 MachineFunction::iterator BBI = CurMBB;
1015 if (++BBI != CurMBB->getParent()->end())
1016 NextBlock = BBI;
1017
1018 if (I.isUnconditional()) {
1019 // If this is not a fall-through branch, emit the branch.
1020 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001021 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001022 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001023
Chris Lattner57ab6592006-10-24 17:57:59 +00001024 // Update machine-CFG edges.
1025 CurMBB->addSuccessor(Succ0MBB);
1026
1027 return;
1028 }
1029
1030 // If this condition is one of the special cases we handle, do special stuff
1031 // now.
1032 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001033 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001034
1035 // If this is a series of conditions that are or'd or and'd together, emit
1036 // this as a sequence of branches instead of setcc's with and/or operations.
1037 // For example, instead of something like:
1038 // cmp A, B
1039 // C = seteq
1040 // cmp D, E
1041 // F = setle
1042 // or C, F
1043 // jnz foo
1044 // Emit:
1045 // cmp A, B
1046 // je foo
1047 // cmp D, E
1048 // jle foo
1049 //
1050 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1051 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001052 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001053 BOp->getOpcode() == Instruction::Or)) {
1054 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001055 // If the compares in later blocks need to use values not currently
1056 // exported from this block, export them now. This block should always
1057 // be the first entry.
1058 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1059
Chris Lattnerdf19f272006-10-31 22:37:42 +00001060 // Allow some cases to be rejected.
1061 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001062 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1063 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1064 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1065 }
1066
1067 // Emit the branch for this block.
1068 visitSwitchCase(SwitchCases[0]);
1069 SwitchCases.erase(SwitchCases.begin());
1070 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001071 }
1072
Chris Lattner0ccb5002006-10-31 23:06:00 +00001073 // Okay, we decided not to do this, remove any inserted MBB's and clear
1074 // SwitchCases.
1075 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1076 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1077
Chris Lattnerdf19f272006-10-31 22:37:42 +00001078 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001079 }
1080 }
Chris Lattner24525952006-10-24 18:07:37 +00001081
1082 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001083 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001084 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001085 // Use visitSwitchCase to actually insert the fast branch sequence for this
1086 // cond branch.
1087 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001088}
1089
Nate Begemanf15485a2006-03-27 01:32:24 +00001090/// visitSwitchCase - Emits the necessary code to represent a single node in
1091/// the binary search tree resulting from lowering a switch instruction.
1092void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001093 SDOperand Cond;
1094 SDOperand CondLHS = getValue(CB.CmpLHS);
1095
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001096 // Build the setcc now.
1097 if (CB.CmpMHS == NULL) {
1098 // Fold "(X == true)" to X and "(X == false)" to !X to
1099 // handle common cases produced by branch lowering.
1100 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1101 Cond = CondLHS;
1102 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1103 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1104 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1105 } else
1106 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1107 } else {
1108 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001109
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001110 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1111 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1112
1113 SDOperand CmpOp = getValue(CB.CmpMHS);
1114 MVT::ValueType VT = CmpOp.getValueType();
1115
1116 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1117 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1118 } else {
1119 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1120 Cond = DAG.getSetCC(MVT::i1, SUB,
1121 DAG.getConstant(High-Low, VT), ISD::SETULE);
1122 }
1123
1124 }
1125
Nate Begemanf15485a2006-03-27 01:32:24 +00001126 // Set NextBlock to be the MBB immediately after the current one, if any.
1127 // This is used to avoid emitting unnecessary branches to the next block.
1128 MachineBasicBlock *NextBlock = 0;
1129 MachineFunction::iterator BBI = CurMBB;
1130 if (++BBI != CurMBB->getParent()->end())
1131 NextBlock = BBI;
1132
1133 // If the lhs block is the next block, invert the condition so that we can
1134 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001135 if (CB.TrueBB == NextBlock) {
1136 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001137 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1138 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1139 }
1140 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001141 DAG.getBasicBlock(CB.TrueBB));
1142 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001143 DAG.setRoot(BrCond);
1144 else
1145 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001146 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001147 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001148 CurMBB->addSuccessor(CB.TrueBB);
1149 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001150}
1151
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001152/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001153void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001154 // Emit the code for the jump table
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001155 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001156 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001157 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1158 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1159 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1160 Table, Index));
1161 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001162}
1163
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001164/// visitJumpTableHeader - This function emits necessary code to produce index
1165/// in the JumpTable from switch case.
1166void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1167 SelectionDAGISel::JumpTableHeader &JTH) {
1168 // Subtract the lowest switch case value from the value being switched on
1169 // and conditional branch to default mbb if the result is greater than the
1170 // difference between smallest and largest cases.
1171 SDOperand SwitchOp = getValue(JTH.SValue);
1172 MVT::ValueType VT = SwitchOp.getValueType();
1173 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1174 DAG.getConstant(JTH.First, VT));
1175
1176 // The SDNode we just created, which holds the value being switched on
1177 // minus the the smallest case value, needs to be copied to a virtual
1178 // register so it can be used as an index into the jump table in a
1179 // subsequent basic block. This value may be smaller or larger than the
1180 // target's pointer type, and therefore require extension or truncating.
1181 if (VT > TLI.getPointerTy())
1182 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1183 else
1184 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1185
1186 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1187 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1188 JT.Reg = JumpTableReg;
1189
1190 // Emit the range check for the jump table, and branch to the default
1191 // block for the switch statement if the value being switched on exceeds
1192 // the largest case in the switch.
1193 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1194 DAG.getConstant(JTH.Last-JTH.First,VT),
1195 ISD::SETUGT);
1196
1197 // Set NextBlock to be the MBB immediately after the current one, if any.
1198 // This is used to avoid emitting unnecessary branches to the next block.
1199 MachineBasicBlock *NextBlock = 0;
1200 MachineFunction::iterator BBI = CurMBB;
1201 if (++BBI != CurMBB->getParent()->end())
1202 NextBlock = BBI;
1203
1204 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1205 DAG.getBasicBlock(JT.Default));
1206
1207 if (JT.MBB == NextBlock)
1208 DAG.setRoot(BrCond);
1209 else
1210 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1211 DAG.getBasicBlock(JT.MBB)));
1212}
1213
1214
Jim Laskeyb180aa12007-02-21 22:53:45 +00001215void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001216 assert(0 && "Should never be visited directly");
1217}
1218void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001219 // Retrieve successors.
1220 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1221 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1222
Jim Laskey183f47f2007-02-25 21:43:59 +00001223 if (!AsTerminator) {
1224 // Mark landing pad so that it doesn't get deleted in branch folding.
1225 LandingPad->setIsLandingPad();
1226
1227 // Insert a label before the invoke call to mark the try range.
1228 // This can be used to detect deletion of the invoke via the
1229 // MachineModuleInfo.
1230 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1231 unsigned BeginLabel = MMI->NextLabelID();
1232 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1233 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001234
Jim Laskey183f47f2007-02-25 21:43:59 +00001235 LowerCallTo(I, I.getCalledValue()->getType(),
1236 I.getCallingConv(),
1237 false,
1238 getValue(I.getOperand(0)),
1239 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001240
Jim Laskey183f47f2007-02-25 21:43:59 +00001241 // Insert a label before the invoke call to mark the try range.
1242 // This can be used to detect deletion of the invoke via the
1243 // MachineModuleInfo.
1244 unsigned EndLabel = MMI->NextLabelID();
1245 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1246 DAG.getConstant(EndLabel, MVT::i32)));
1247
1248 // Inform MachineModuleInfo of range.
1249 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1250
1251 // Update successor info
1252 CurMBB->addSuccessor(Return);
1253 CurMBB->addSuccessor(LandingPad);
1254 } else {
1255 // Drop into normal successor.
1256 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1257 DAG.getBasicBlock(Return)));
1258 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001259}
1260
1261void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1262}
1263
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001264/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001265/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001266bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001267 CaseRecVector& WorkList,
1268 Value* SV,
1269 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001270 Case& BackCase = *(CR.Range.second-1);
1271
1272 // Size is the number of Cases represented by this range.
1273 unsigned Size = CR.Range.second - CR.Range.first;
1274 if (Size >=3)
1275 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001276
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001277 // Get the MachineFunction which holds the current MBB. This is used when
1278 // inserting any additional MBBs necessary to represent the switch.
1279 MachineFunction *CurMF = CurMBB->getParent();
1280
1281 // Figure out which block is immediately after the current one.
1282 MachineBasicBlock *NextBlock = 0;
1283 MachineFunction::iterator BBI = CR.CaseBB;
1284
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001285 if (++BBI != CurMBB->getParent()->end())
1286 NextBlock = BBI;
1287
1288 // TODO: If any two of the cases has the same destination, and if one value
1289 // is the same as the other, but has one bit unset that the other has set,
1290 // use bit manipulation to do two compares at once. For example:
1291 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1292
1293 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001294 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001295 // The last case block won't fall through into 'NextBlock' if we emit the
1296 // branches in this order. See if rearranging a case value would help.
1297 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001298 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001299 std::swap(*I, BackCase);
1300 break;
1301 }
1302 }
1303 }
1304
1305 // Create a CaseBlock record representing a conditional branch to
1306 // the Case's target mbb if the value being switched on SV is equal
1307 // to C.
1308 MachineBasicBlock *CurBlock = CR.CaseBB;
1309 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1310 MachineBasicBlock *FallThrough;
1311 if (I != E-1) {
1312 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1313 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1314 } else {
1315 // If the last case doesn't match, go to the default block.
1316 FallThrough = Default;
1317 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001318
1319 Value *RHS, *LHS, *MHS;
1320 ISD::CondCode CC;
1321 if (I->High == I->Low) {
1322 // This is just small small case range :) containing exactly 1 case
1323 CC = ISD::SETEQ;
1324 LHS = SV; RHS = I->High; MHS = NULL;
1325 } else {
1326 CC = ISD::SETLE;
1327 LHS = I->Low; MHS = SV; RHS = I->High;
1328 }
1329 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1330 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001331
1332 // If emitting the first comparison, just call visitSwitchCase to emit the
1333 // code into the current block. Otherwise, push the CaseBlock onto the
1334 // vector to be later processed by SDISel, and insert the node's MBB
1335 // before the next MBB.
1336 if (CurBlock == CurMBB)
1337 visitSwitchCase(CB);
1338 else
1339 SwitchCases.push_back(CB);
1340
1341 CurBlock = FallThrough;
1342 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001343
1344 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001345}
1346
1347/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001348bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001349 CaseRecVector& WorkList,
1350 Value* SV,
1351 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001352 Case& FrontCase = *CR.Range.first;
1353 Case& BackCase = *(CR.Range.second-1);
1354
1355 // Size is the number of Cases represented by this range.
1356 unsigned Size = CR.Range.second - CR.Range.first;
1357
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001358 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1359 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1360
1361 uint64_t TSize = 0;
1362 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1363 I!=E; ++I)
1364 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001365
1366 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1367 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
1368 Size <= 5)
1369 return false;
1370
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001371 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1372 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001373 return false;
1374
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001375 DOUT << "Lowering jump table\n"
1376 << "First entry: " << First << ". Last entry: " << Last << "\n"
1377 << "Size: " << TSize << ". Density: " << Density << "\n";
1378
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001379 // Get the MachineFunction which holds the current MBB. This is used when
1380 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001381 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001382
1383 // Figure out which block is immediately after the current one.
1384 MachineBasicBlock *NextBlock = 0;
1385 MachineFunction::iterator BBI = CR.CaseBB;
1386
1387 if (++BBI != CurMBB->getParent()->end())
1388 NextBlock = BBI;
1389
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001390 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1391
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001392 // Create a new basic block to hold the code for loading the address
1393 // of the jump table, and jumping to it. Update successor information;
1394 // we will either branch to the default case for the switch, or the jump
1395 // table.
1396 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1397 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1398 CR.CaseBB->addSuccessor(Default);
1399 CR.CaseBB->addSuccessor(JumpTableBB);
1400
1401 // Build a vector of destination BBs, corresponding to each target
1402 // of the jump table. If the value of the jump table slot corresponds to
1403 // a case statement, push the case's BB onto the vector, otherwise, push
1404 // the default BB.
1405 std::vector<MachineBasicBlock*> DestBBs;
1406 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001407 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1408 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1409 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1410
1411 if ((Low <= TEI) && (TEI <= High)) {
1412 DestBBs.push_back(I->BB);
1413 if (TEI==High)
1414 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001415 } else {
1416 DestBBs.push_back(Default);
1417 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001418 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001419
1420 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001421 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001422 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1423 E = DestBBs.end(); I != E; ++I) {
1424 if (!SuccsHandled[(*I)->getNumber()]) {
1425 SuccsHandled[(*I)->getNumber()] = true;
1426 JumpTableBB->addSuccessor(*I);
1427 }
1428 }
1429
1430 // Create a jump table index for this jump table, or return an existing
1431 // one.
1432 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1433
1434 // Set the jump table information so that we can codegen it as a second
1435 // MachineBasicBlock
1436 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1437 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1438 (CR.CaseBB == CurMBB));
1439 if (CR.CaseBB == CurMBB)
1440 visitJumpTableHeader(JT, JTH);
1441
1442 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001443
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001444 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001445}
1446
1447/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1448/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001449bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001450 CaseRecVector& WorkList,
1451 Value* SV,
1452 MachineBasicBlock* Default) {
1453 // Get the MachineFunction which holds the current MBB. This is used when
1454 // inserting any additional MBBs necessary to represent the switch.
1455 MachineFunction *CurMF = CurMBB->getParent();
1456
1457 // Figure out which block is immediately after the current one.
1458 MachineBasicBlock *NextBlock = 0;
1459 MachineFunction::iterator BBI = CR.CaseBB;
1460
1461 if (++BBI != CurMBB->getParent()->end())
1462 NextBlock = BBI;
1463
1464 Case& FrontCase = *CR.Range.first;
1465 Case& BackCase = *(CR.Range.second-1);
1466 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1467
1468 // Size is the number of Cases represented by this range.
1469 unsigned Size = CR.Range.second - CR.Range.first;
1470
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001471 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1472 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001473 double Density = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001474 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001475
1476 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1477 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001478 uint64_t TSize = 0;
1479 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1480 I!=E; ++I)
1481 TSize += I->size();
1482
1483 uint64_t LSize = FrontCase.size();
1484 uint64_t RSize = TSize-LSize;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001485 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001486 J!=E; ++I, ++J) {
1487 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1488 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001489 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1490 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1491 if (Density < (LDensity + RDensity)) {
1492 Pivot = J;
1493 Density = LDensity + RDensity;
1494 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001495
1496 LSize += J->size();
1497 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001498 }
1499
1500 CaseRange LHSR(CR.Range.first, Pivot);
1501 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001502 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001503 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1504
1505 // We know that we branch to the LHS if the Value being switched on is
1506 // less than the Pivot value, C. We use this to optimize our binary
1507 // tree a bit, by recognizing that if SV is greater than or equal to the
1508 // LHS's Case Value, and that Case Value is exactly one less than the
1509 // Pivot's Value, then we can branch directly to the LHS's Target,
1510 // rather than creating a leaf node for it.
1511 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001512 LHSR.first->High == CR.GE &&
1513 cast<ConstantInt>(C)->getSExtValue() ==
1514 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1515 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001516 } else {
1517 TrueBB = new MachineBasicBlock(LLVMBB);
1518 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1519 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1520 }
1521
1522 // Similar to the optimization above, if the Value being switched on is
1523 // known to be less than the Constant CR.LT, and the current Case Value
1524 // is CR.LT - 1, then we can branch directly to the target block for
1525 // the current Case Value, rather than emitting a RHS leaf node for it.
1526 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001527 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1528 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1529 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001530 } else {
1531 FalseBB = new MachineBasicBlock(LLVMBB);
1532 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1533 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1534 }
1535
1536 // Create a CaseBlock record representing a conditional branch to
1537 // the LHS node if the value being switched on SV is less than C.
1538 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001539 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1540 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001541
1542 if (CR.CaseBB == CurMBB)
1543 visitSwitchCase(CB);
1544 else
1545 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001546
1547 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001548}
1549
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001550// Clusterify - Transform simple list of Cases into list of CaseRange's
1551unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1552 const SwitchInst& SI) {
1553 unsigned numCmps = 0;
1554
1555 // Start with "simple" cases
1556 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1557 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1558 Cases.push_back(Case(SI.getSuccessorValue(i),
1559 SI.getSuccessorValue(i),
1560 SMBB));
1561 }
1562 sort(Cases.begin(), Cases.end(), CaseCmp());
1563
1564 // Merge case into clusters
1565 if (Cases.size()>=2)
1566 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1567 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1568 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1569 MachineBasicBlock* nextBB = J->BB;
1570 MachineBasicBlock* currentBB = I->BB;
1571
1572 // If the two neighboring cases go to the same destination, merge them
1573 // into a single case.
1574 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1575 I->High = J->High;
1576 J = Cases.erase(J);
1577 } else {
1578 I = J++;
1579 }
1580 }
1581
1582 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1583 if (I->Low != I->High)
1584 // A range counts double, since it requires two compares.
1585 ++numCmps;
1586 }
1587
1588 return numCmps;
1589}
1590
1591void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001592 // Figure out which block is immediately after the current one.
1593 MachineBasicBlock *NextBlock = 0;
1594 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001595
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001596 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001597
Nate Begemanf15485a2006-03-27 01:32:24 +00001598 // If there is only the default destination, branch to it if it is not the
1599 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001600 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001601 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001602
Nate Begemanf15485a2006-03-27 01:32:24 +00001603 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001604 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001605 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001606 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001607
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001608 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001609 return;
1610 }
1611
1612 // If there are any non-default case statements, create a vector of Cases
1613 // representing each one, and sort the vector so that we can efficiently
1614 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001615 CaseVector Cases;
1616 unsigned numCmps = Clusterify(Cases, SI);
1617 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1618 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001619
Nate Begemanf15485a2006-03-27 01:32:24 +00001620 // Get the Value to be switched on and default basic blocks, which will be
1621 // inserted into CaseBlock records, representing basic blocks in the binary
1622 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001623 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001624
Nate Begemanf15485a2006-03-27 01:32:24 +00001625 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001626 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001627 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1628
1629 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001630 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001631 CaseRec CR = WorkList.back();
1632 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001633
1634 // If the range has few cases (two or less) emit a series of specific
1635 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001636 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1637 continue;
1638
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001639 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1640 // target supports indirect branches, then emit a jump table rather than
1641 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001642 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1643 continue;
1644
1645 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1646 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1647 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001648 }
1649}
1650
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001651
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001652void SelectionDAGLowering::visitSub(User &I) {
1653 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001654 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001655 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001656 visitVectorBinary(I, ISD::VSUB);
1657 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1659 if (CFP->isExactlyValue(-0.0)) {
1660 SDOperand Op2 = getValue(I.getOperand(1));
1661 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1662 return;
1663 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001664 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001665 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001666 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001667}
1668
Reid Spencer24d6da52007-01-21 00:29:26 +00001669void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001670 SDOperand Op1 = getValue(I.getOperand(0));
1671 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001672
1673 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001674}
1675
Reid Spencer24d6da52007-01-21 00:29:26 +00001676void
1677SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001678 assert(isa<VectorType>(I.getType()));
1679 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001680 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001681
Reid Spencer24d6da52007-01-21 00:29:26 +00001682 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1683 getValue(I.getOperand(0)),
1684 getValue(I.getOperand(1)),
1685 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1686 Typ));
1687}
1688
1689void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1690 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001691 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001692 visitVectorBinary(I, VectorOp);
1693 else
1694 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001695}
Chris Lattner2c49f272005-01-19 22:31:21 +00001696
Nate Begemane21ea612005-11-18 07:42:56 +00001697void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1698 SDOperand Op1 = getValue(I.getOperand(0));
1699 SDOperand Op2 = getValue(I.getOperand(1));
1700
Reid Spencer832254e2007-02-02 02:16:23 +00001701 if (TLI.getShiftAmountTy() < Op2.getValueType())
1702 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1703 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1704 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001705
Chris Lattner1c08c712005-01-07 07:47:53 +00001706 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1707}
1708
Reid Spencer45fb3f32006-11-20 01:22:35 +00001709void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001710 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1711 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1712 predicate = IC->getPredicate();
1713 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1714 predicate = ICmpInst::Predicate(IC->getPredicate());
1715 SDOperand Op1 = getValue(I.getOperand(0));
1716 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001717 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001718 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001719 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1720 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1721 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1722 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1723 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1724 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1725 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1726 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1727 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1728 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1729 default:
1730 assert(!"Invalid ICmp predicate value");
1731 Opcode = ISD::SETEQ;
1732 break;
1733 }
1734 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1735}
1736
1737void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001738 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1739 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1740 predicate = FC->getPredicate();
1741 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1742 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001743 SDOperand Op1 = getValue(I.getOperand(0));
1744 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001745 ISD::CondCode Condition, FOC, FPC;
1746 switch (predicate) {
1747 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1748 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1749 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1750 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1751 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1752 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1753 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1754 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1755 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1756 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1757 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1758 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1759 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1760 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1761 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1762 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1763 default:
1764 assert(!"Invalid FCmp predicate value");
1765 FOC = FPC = ISD::SETFALSE;
1766 break;
1767 }
1768 if (FiniteOnlyFPMath())
1769 Condition = FOC;
1770 else
1771 Condition = FPC;
1772 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001773}
1774
1775void SelectionDAGLowering::visitSelect(User &I) {
1776 SDOperand Cond = getValue(I.getOperand(0));
1777 SDOperand TrueVal = getValue(I.getOperand(1));
1778 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001779 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001780 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1781 TrueVal, FalseVal));
1782 } else {
1783 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1784 *(TrueVal.Val->op_end()-2),
1785 *(TrueVal.Val->op_end()-1)));
1786 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001787}
1788
Reid Spencer3da59db2006-11-27 01:05:10 +00001789
1790void SelectionDAGLowering::visitTrunc(User &I) {
1791 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1792 SDOperand N = getValue(I.getOperand(0));
1793 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1794 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1795}
1796
1797void SelectionDAGLowering::visitZExt(User &I) {
1798 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1799 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1800 SDOperand N = getValue(I.getOperand(0));
1801 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1802 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1803}
1804
1805void SelectionDAGLowering::visitSExt(User &I) {
1806 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1807 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1808 SDOperand N = getValue(I.getOperand(0));
1809 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1810 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1811}
1812
1813void SelectionDAGLowering::visitFPTrunc(User &I) {
1814 // FPTrunc is never a no-op cast, no need to check
1815 SDOperand N = getValue(I.getOperand(0));
1816 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1817 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1818}
1819
1820void SelectionDAGLowering::visitFPExt(User &I){
1821 // FPTrunc is never a no-op cast, no need to check
1822 SDOperand N = getValue(I.getOperand(0));
1823 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1824 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1825}
1826
1827void SelectionDAGLowering::visitFPToUI(User &I) {
1828 // FPToUI is never a no-op cast, no need to check
1829 SDOperand N = getValue(I.getOperand(0));
1830 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1831 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1832}
1833
1834void SelectionDAGLowering::visitFPToSI(User &I) {
1835 // FPToSI is never a no-op cast, no need to check
1836 SDOperand N = getValue(I.getOperand(0));
1837 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1838 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1839}
1840
1841void SelectionDAGLowering::visitUIToFP(User &I) {
1842 // UIToFP is never a no-op cast, no need to check
1843 SDOperand N = getValue(I.getOperand(0));
1844 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1845 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1846}
1847
1848void SelectionDAGLowering::visitSIToFP(User &I){
1849 // UIToFP is never a no-op cast, no need to check
1850 SDOperand N = getValue(I.getOperand(0));
1851 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1852 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1853}
1854
1855void SelectionDAGLowering::visitPtrToInt(User &I) {
1856 // What to do depends on the size of the integer and the size of the pointer.
1857 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001858 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001859 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001860 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001861 SDOperand Result;
1862 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1863 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1864 else
1865 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1866 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1867 setValue(&I, Result);
1868}
Chris Lattner1c08c712005-01-07 07:47:53 +00001869
Reid Spencer3da59db2006-11-27 01:05:10 +00001870void SelectionDAGLowering::visitIntToPtr(User &I) {
1871 // What to do depends on the size of the integer and the size of the pointer.
1872 // We can either truncate, zero extend, or no-op, accordingly.
1873 SDOperand N = getValue(I.getOperand(0));
1874 MVT::ValueType SrcVT = N.getValueType();
1875 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1876 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1877 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1878 else
1879 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1880 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1881}
1882
1883void SelectionDAGLowering::visitBitCast(User &I) {
1884 SDOperand N = getValue(I.getOperand(0));
1885 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001886 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001887 // This is a cast to a vector from something else.
1888 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001889 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001890 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1891 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1892 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1893 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001894 return;
1895 }
1896 MVT::ValueType SrcVT = N.getValueType();
1897 if (SrcVT == MVT::Vector) {
1898 // This is a cast from a vctor to something else.
1899 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001900 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001901 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001902 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001903
1904 // BitCast assures us that source and destination are the same size so this
1905 // is either a BIT_CONVERT or a no-op.
1906 if (DestVT != N.getValueType())
1907 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1908 else
1909 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001910}
1911
Chris Lattner2bbd8102006-03-29 00:11:43 +00001912void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001913 SDOperand InVec = getValue(I.getOperand(0));
1914 SDOperand InVal = getValue(I.getOperand(1));
1915 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1916 getValue(I.getOperand(2)));
1917
Chris Lattner2332b9f2006-03-19 01:17:20 +00001918 SDOperand Num = *(InVec.Val->op_end()-2);
1919 SDOperand Typ = *(InVec.Val->op_end()-1);
1920 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1921 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001922}
1923
Chris Lattner2bbd8102006-03-29 00:11:43 +00001924void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001925 SDOperand InVec = getValue(I.getOperand(0));
1926 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1927 getValue(I.getOperand(1)));
1928 SDOperand Typ = *(InVec.Val->op_end()-1);
1929 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1930 TLI.getValueType(I.getType()), InVec, InIdx));
1931}
Chris Lattnerc7029802006-03-18 01:44:44 +00001932
Chris Lattner3e104b12006-04-08 04:15:24 +00001933void SelectionDAGLowering::visitShuffleVector(User &I) {
1934 SDOperand V1 = getValue(I.getOperand(0));
1935 SDOperand V2 = getValue(I.getOperand(1));
1936 SDOperand Mask = getValue(I.getOperand(2));
1937
1938 SDOperand Num = *(V1.Val->op_end()-2);
1939 SDOperand Typ = *(V2.Val->op_end()-1);
1940 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1941 V1, V2, Mask, Num, Typ));
1942}
1943
1944
Chris Lattner1c08c712005-01-07 07:47:53 +00001945void SelectionDAGLowering::visitGetElementPtr(User &I) {
1946 SDOperand N = getValue(I.getOperand(0));
1947 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001948
1949 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1950 OI != E; ++OI) {
1951 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001952 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001953 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001954 if (Field) {
1955 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00001956 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00001957 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001958 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001959 }
1960 Ty = StTy->getElementType(Field);
1961 } else {
1962 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001963
Chris Lattner7c0104b2005-11-09 04:45:33 +00001964 // If this is a constant subscript, handle it quickly.
1965 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001966 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001967 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001968 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001969 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1970 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001971 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001972
1973 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001974 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001975 SDOperand IdxN = getValue(Idx);
1976
1977 // If the index is smaller or larger than intptr_t, truncate or extend
1978 // it.
1979 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001980 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001981 } else if (IdxN.getValueType() > N.getValueType())
1982 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1983
1984 // If this is a multiply by a power of two, turn it into a shl
1985 // immediately. This is a very common case.
1986 if (isPowerOf2_64(ElementSize)) {
1987 unsigned Amt = Log2_64(ElementSize);
1988 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001989 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001990 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1991 continue;
1992 }
1993
1994 SDOperand Scale = getIntPtrConstant(ElementSize);
1995 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1996 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001997 }
1998 }
1999 setValue(&I, N);
2000}
2001
2002void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2003 // If this is a fixed sized alloca in the entry block of the function,
2004 // allocate it statically on the stack.
2005 if (FuncInfo.StaticAllocaMap.count(&I))
2006 return; // getValue will auto-populate this.
2007
2008 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00002009 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002010 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002011 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002012 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002013
2014 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002015 MVT::ValueType IntPtr = TLI.getPointerTy();
2016 if (IntPtr < AllocSize.getValueType())
2017 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2018 else if (IntPtr > AllocSize.getValueType())
2019 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002020
Chris Lattner68cd65e2005-01-22 23:04:37 +00002021 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00002022 getIntPtrConstant(TySize));
2023
2024 // Handle alignment. If the requested alignment is less than or equal to the
2025 // stack alignment, ignore it and round the size of the allocation up to the
2026 // stack alignment size. If the size is greater than the stack alignment, we
2027 // note this in the DYNAMIC_STACKALLOC node.
2028 unsigned StackAlign =
2029 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2030 if (Align <= StackAlign) {
2031 Align = 0;
2032 // Add SA-1 to the size.
2033 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2034 getIntPtrConstant(StackAlign-1));
2035 // Mask out the low bits for alignment purposes.
2036 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2037 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2038 }
2039
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002040 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002041 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2042 MVT::Other);
2043 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002044 setValue(&I, DSA);
2045 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002046
2047 // Inform the Frame Information that we have just allocated a variable-sized
2048 // object.
2049 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2050}
2051
Chris Lattner1c08c712005-01-07 07:47:53 +00002052void SelectionDAGLowering::visitLoad(LoadInst &I) {
2053 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002054
Chris Lattnerd3948112005-01-17 22:19:26 +00002055 SDOperand Root;
2056 if (I.isVolatile())
2057 Root = getRoot();
2058 else {
2059 // Do not serialize non-volatile loads against each other.
2060 Root = DAG.getRoot();
2061 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002062
Evan Cheng466685d2006-10-09 20:57:25 +00002063 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002064 Root, I.isVolatile()));
2065}
2066
2067SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002068 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002069 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002070 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002071 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00002072 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00002073 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2074 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002075 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002076 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002077 }
Chris Lattnerd3948112005-01-17 22:19:26 +00002078
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002079 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002080 DAG.setRoot(L.getValue(1));
2081 else
2082 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002083
2084 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002085}
2086
2087
2088void SelectionDAGLowering::visitStore(StoreInst &I) {
2089 Value *SrcV = I.getOperand(0);
2090 SDOperand Src = getValue(SrcV);
2091 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002092 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00002093 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002094}
2095
Chris Lattner0eade312006-03-24 02:22:33 +00002096/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2097/// access memory and has no other side effects at all.
2098static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2099#define GET_NO_MEMORY_INTRINSICS
2100#include "llvm/Intrinsics.gen"
2101#undef GET_NO_MEMORY_INTRINSICS
2102 return false;
2103}
2104
Chris Lattnere58a7802006-04-02 03:41:14 +00002105// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2106// have any side-effects or if it only reads memory.
2107static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2108#define GET_SIDE_EFFECT_INFO
2109#include "llvm/Intrinsics.gen"
2110#undef GET_SIDE_EFFECT_INFO
2111 return false;
2112}
2113
Chris Lattner0eade312006-03-24 02:22:33 +00002114/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2115/// node.
2116void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2117 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00002118 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002119 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002120
2121 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002122 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002123 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2124 if (OnlyLoad) {
2125 // We don't need to serialize loads against other loads.
2126 Ops.push_back(DAG.getRoot());
2127 } else {
2128 Ops.push_back(getRoot());
2129 }
2130 }
Chris Lattner0eade312006-03-24 02:22:33 +00002131
2132 // Add the intrinsic ID as an integer operand.
2133 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2134
2135 // Add all operands of the call to the operand list.
2136 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2137 SDOperand Op = getValue(I.getOperand(i));
2138
Reid Spencerac9dcb92007-02-15 03:39:18 +00002139 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00002140 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002141 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002142 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2143
2144 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2145 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2146 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2147 }
2148
2149 assert(TLI.isTypeLegal(Op.getValueType()) &&
2150 "Intrinsic uses a non-legal type?");
2151 Ops.push_back(Op);
2152 }
2153
2154 std::vector<MVT::ValueType> VTs;
2155 if (I.getType() != Type::VoidTy) {
2156 MVT::ValueType VT = TLI.getValueType(I.getType());
2157 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002158 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002159 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2160
2161 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2162 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2163 }
2164
2165 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2166 VTs.push_back(VT);
2167 }
2168 if (HasChain)
2169 VTs.push_back(MVT::Other);
2170
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002171 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2172
Chris Lattner0eade312006-03-24 02:22:33 +00002173 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002174 SDOperand Result;
2175 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002176 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2177 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002178 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002179 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2180 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002181 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002182 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2183 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002184
Chris Lattnere58a7802006-04-02 03:41:14 +00002185 if (HasChain) {
2186 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2187 if (OnlyLoad)
2188 PendingLoads.push_back(Chain);
2189 else
2190 DAG.setRoot(Chain);
2191 }
Chris Lattner0eade312006-03-24 02:22:33 +00002192 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002193 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00002194 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2195 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2196 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2197 DAG.getValueType(EVT));
2198 }
2199 setValue(&I, Result);
2200 }
2201}
2202
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002203/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2204/// we want to emit this as a call to a named external function, return the name
2205/// otherwise lower it and return null.
2206const char *
2207SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2208 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002209 default:
2210 // By default, turn this into a target intrinsic node.
2211 visitTargetIntrinsic(I, Intrinsic);
2212 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002213 case Intrinsic::vastart: visitVAStart(I); return 0;
2214 case Intrinsic::vaend: visitVAEnd(I); return 0;
2215 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002216 case Intrinsic::returnaddress:
2217 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2218 getValue(I.getOperand(1))));
2219 return 0;
2220 case Intrinsic::frameaddress:
2221 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2222 getValue(I.getOperand(1))));
2223 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002224 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002225 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002226 break;
2227 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002228 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002229 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002230 case Intrinsic::memcpy_i32:
2231 case Intrinsic::memcpy_i64:
2232 visitMemIntrinsic(I, ISD::MEMCPY);
2233 return 0;
2234 case Intrinsic::memset_i32:
2235 case Intrinsic::memset_i64:
2236 visitMemIntrinsic(I, ISD::MEMSET);
2237 return 0;
2238 case Intrinsic::memmove_i32:
2239 case Intrinsic::memmove_i64:
2240 visitMemIntrinsic(I, ISD::MEMMOVE);
2241 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002242
Chris Lattner86cb6432005-12-13 17:40:33 +00002243 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002244 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002245 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002246 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002247 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002248
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002249 Ops[0] = getRoot();
2250 Ops[1] = getValue(SPI.getLineValue());
2251 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002252
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002253 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002254 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002255 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2256
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002257 Ops[3] = DAG.getString(CompileUnit->getFileName());
2258 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002259
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002260 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002261 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002262
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002263 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002264 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002265 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002266 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002267 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002268 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2269 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002270 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002271 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002272 }
2273
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002274 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002275 }
2276 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002277 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002278 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002279 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2280 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002281 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002282 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002283 }
2284
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002285 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002286 }
2287 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002288 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002289 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002290 if (MMI && FSI.getSubprogram() &&
2291 MMI->Verify(FSI.getSubprogram())) {
2292 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002293 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002294 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002295 }
2296
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002297 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002298 }
2299 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002300 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002301 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002302 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002303 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002304 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002305 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002306 }
2307
2308 return 0;
2309 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002310
Jim Laskeyb180aa12007-02-21 22:53:45 +00002311 case Intrinsic::eh_exception: {
2312 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2313
Jim Laskey735b6f82007-02-22 15:38:06 +00002314 if (MMI) {
2315 // Add a label to mark the beginning of the landing pad. Deletion of the
2316 // landing pad can thus be detected via the MachineModuleInfo.
2317 unsigned LabelID = MMI->addLandingPad(CurMBB);
2318 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2319 DAG.getConstant(LabelID, MVT::i32)));
2320
2321 // Mark exception register as live in.
2322 unsigned Reg = TLI.getExceptionAddressRegister();
2323 if (Reg) CurMBB->addLiveIn(Reg);
2324
2325 // Insert the EXCEPTIONADDR instruction.
2326 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2327 SDOperand Ops[1];
2328 Ops[0] = DAG.getRoot();
2329 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2330 setValue(&I, Op);
2331 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002332 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002333 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002334 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002335 return 0;
2336 }
2337
Jim Laskey0b4711b2007-03-01 20:24:30 +00002338 case Intrinsic::eh_selector:
2339 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002340 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2341
Jim Laskey735b6f82007-02-22 15:38:06 +00002342 if (MMI) {
2343 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002344 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2345 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2346 isa<Function>(CE->getOperand(0)) &&
2347 "Personality should be a function");
2348 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey0b4711b2007-03-01 20:24:30 +00002349 if (Intrinsic == Intrinsic::eh_filter)
2350 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002351
Jim Laskey735b6f82007-02-22 15:38:06 +00002352 // Gather all the type infos for this landing pad and pass them along to
2353 // MachineModuleInfo.
2354 std::vector<GlobalVariable *> TyInfo;
2355 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002356 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2357 if (CE && CE->getOpcode() == Instruction::BitCast &&
2358 isa<GlobalVariable>(CE->getOperand(0))) {
2359 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2360 } else {
2361 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2362 assert(CI && CI->getZExtValue() == 0 &&
2363 "TypeInfo must be a global variable typeinfo or NULL");
2364 TyInfo.push_back(NULL);
Jim Laskey735b6f82007-02-22 15:38:06 +00002365 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002366 }
2367 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2368
2369 // Mark exception selector register as live in.
2370 unsigned Reg = TLI.getExceptionSelectorRegister();
2371 if (Reg) CurMBB->addLiveIn(Reg);
2372
2373 // Insert the EHSELECTION instruction.
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002374 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002375 SDOperand Ops[2];
2376 Ops[0] = getValue(I.getOperand(1));
2377 Ops[1] = getRoot();
2378 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2379 setValue(&I, Op);
2380 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002381 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002382 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002383 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002384
2385 return 0;
2386 }
2387
2388 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002389 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002390
Jim Laskey735b6f82007-02-22 15:38:06 +00002391 if (MMI) {
2392 // Find the type id for the given typeinfo.
2393 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002394 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2395 if (CE && CE->getOpcode() == Instruction::BitCast &&
2396 isa<GlobalVariable>(CE->getOperand(0))) {
2397 GV = cast<GlobalVariable>(CE->getOperand(0));
2398 } else {
2399 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2400 assert(CI && CI->getZExtValue() == 0 &&
2401 "TypeInfo must be a global variable typeinfo or NULL");
2402 GV = NULL;
Jim Laskey735b6f82007-02-22 15:38:06 +00002403 }
2404
2405 unsigned TypeID = MMI->getTypeIDFor(GV);
2406 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002407 } else {
2408 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002409 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002410
2411 return 0;
2412 }
2413
Reid Spencer0b118202006-01-16 21:12:35 +00002414 case Intrinsic::sqrt_f32:
2415 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002416 setValue(&I, DAG.getNode(ISD::FSQRT,
2417 getValue(I.getOperand(1)).getValueType(),
2418 getValue(I.getOperand(1))));
2419 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002420 case Intrinsic::powi_f32:
2421 case Intrinsic::powi_f64:
2422 setValue(&I, DAG.getNode(ISD::FPOWI,
2423 getValue(I.getOperand(1)).getValueType(),
2424 getValue(I.getOperand(1)),
2425 getValue(I.getOperand(2))));
2426 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002427 case Intrinsic::pcmarker: {
2428 SDOperand Tmp = getValue(I.getOperand(1));
2429 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2430 return 0;
2431 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002432 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002433 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002434 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2435 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2436 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002437 setValue(&I, Tmp);
2438 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002439 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002440 }
Reid Spenceraddd11d2007-04-04 23:48:25 +00002441 case Intrinsic::bit_part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002442 // MVT::ValueType Ty = getValue(I.getOperand(1)).getValueType();
2443 // setValue(&I, DAG.getTargetConstant(0, Ty));
2444 // Currently not implemented: just abort
2445 assert(0 && "bit_part_select intrinsic not implemented");
2446 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002447 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002448 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002449 setValue(&I, DAG.getNode(ISD::BSWAP,
2450 getValue(I.getOperand(1)).getValueType(),
2451 getValue(I.getOperand(1))));
2452 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002453 case Intrinsic::cttz: {
2454 SDOperand Arg = getValue(I.getOperand(1));
2455 MVT::ValueType Ty = Arg.getValueType();
2456 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2457 if (Ty < MVT::i32)
2458 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2459 else if (Ty > MVT::i32)
2460 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2461 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002462 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002463 }
2464 case Intrinsic::ctlz: {
2465 SDOperand Arg = getValue(I.getOperand(1));
2466 MVT::ValueType Ty = Arg.getValueType();
2467 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2468 if (Ty < MVT::i32)
2469 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2470 else if (Ty > MVT::i32)
2471 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2472 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002473 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002474 }
2475 case Intrinsic::ctpop: {
2476 SDOperand Arg = getValue(I.getOperand(1));
2477 MVT::ValueType Ty = Arg.getValueType();
2478 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2479 if (Ty < MVT::i32)
2480 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2481 else if (Ty > MVT::i32)
2482 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2483 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002484 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002485 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002486 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002487 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002488 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2489 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002490 setValue(&I, Tmp);
2491 DAG.setRoot(Tmp.getValue(1));
2492 return 0;
2493 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002494 case Intrinsic::stackrestore: {
2495 SDOperand Tmp = getValue(I.getOperand(1));
2496 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002497 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002498 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002499 case Intrinsic::prefetch:
2500 // FIXME: Currently discarding prefetches.
2501 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002502 }
2503}
2504
2505
Jim Laskey1da20a72007-02-23 21:45:01 +00002506void SelectionDAGLowering::LowerCallTo(Instruction &I,
2507 const Type *CalledValueTy,
2508 unsigned CallingConv,
2509 bool IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002510 SDOperand Callee, unsigned OpIdx) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002511 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002512 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2513
2514 TargetLowering::ArgListTy Args;
2515 TargetLowering::ArgListEntry Entry;
2516 Args.reserve(I.getNumOperands());
2517 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2518 Value *Arg = I.getOperand(i);
2519 SDOperand ArgNode = getValue(Arg);
2520 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00002521 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2522 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey735b6f82007-02-22 15:38:06 +00002523 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2524 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2525 Args.push_back(Entry);
2526 }
2527
2528 std::pair<SDOperand,SDOperand> Result =
2529 TLI.LowerCallTo(getRoot(), I.getType(),
2530 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey1da20a72007-02-23 21:45:01 +00002531 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002532 Callee, Args, DAG);
2533 if (I.getType() != Type::VoidTy)
2534 setValue(&I, Result.first);
2535 DAG.setRoot(Result.second);
2536}
2537
2538
Chris Lattner1c08c712005-01-07 07:47:53 +00002539void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002540 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002541 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002542 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002543 if (unsigned IID = F->getIntrinsicID()) {
2544 RenameFn = visitIntrinsicCall(I, IID);
2545 if (!RenameFn)
2546 return;
2547 } else { // Not an LLVM intrinsic.
2548 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002549 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2550 if (I.getNumOperands() == 3 && // Basic sanity checks.
2551 I.getOperand(1)->getType()->isFloatingPoint() &&
2552 I.getType() == I.getOperand(1)->getType() &&
2553 I.getType() == I.getOperand(2)->getType()) {
2554 SDOperand LHS = getValue(I.getOperand(1));
2555 SDOperand RHS = getValue(I.getOperand(2));
2556 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2557 LHS, RHS));
2558 return;
2559 }
2560 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002561 if (I.getNumOperands() == 2 && // Basic sanity checks.
2562 I.getOperand(1)->getType()->isFloatingPoint() &&
2563 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002564 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002565 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2566 return;
2567 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002568 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002569 if (I.getNumOperands() == 2 && // Basic sanity checks.
2570 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002571 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002572 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002573 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2574 return;
2575 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002576 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002577 if (I.getNumOperands() == 2 && // Basic sanity checks.
2578 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002579 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002580 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002581 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2582 return;
2583 }
2584 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002585 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002586 } else if (isa<InlineAsm>(I.getOperand(0))) {
2587 visitInlineAsm(I);
2588 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002589 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002590
Chris Lattner64e14b12005-01-08 22:48:57 +00002591 SDOperand Callee;
2592 if (!RenameFn)
2593 Callee = getValue(I.getOperand(0));
2594 else
2595 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002596
Jim Laskey1da20a72007-02-23 21:45:01 +00002597 LowerCallTo(I, I.getCalledValue()->getType(),
2598 I.getCallingConv(),
2599 I.isTailCall(),
2600 Callee,
2601 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002602}
2603
Jim Laskey735b6f82007-02-22 15:38:06 +00002604
Chris Lattner864635a2006-02-22 22:37:12 +00002605SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002606 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002607 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2608 Chain = Val.getValue(1);
2609 Flag = Val.getValue(2);
2610
2611 // If the result was expanded, copy from the top part.
2612 if (Regs.size() > 1) {
2613 assert(Regs.size() == 2 &&
2614 "Cannot expand to more than 2 elts yet!");
2615 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002616 Chain = Hi.getValue(1);
2617 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002618 if (DAG.getTargetLoweringInfo().isLittleEndian())
2619 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2620 else
2621 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002622 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002623
Chris Lattnercf752aa2006-06-08 18:22:48 +00002624 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002625 // appropriate type.
2626 if (RegVT == ValueVT)
2627 return Val;
2628
Chris Lattner5df99b32007-03-25 05:00:54 +00002629 if (MVT::isVector(RegVT)) {
2630 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2631 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2632 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2633 MVT::i32),
2634 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2635 }
2636
Chris Lattnercf752aa2006-06-08 18:22:48 +00002637 if (MVT::isInteger(RegVT)) {
2638 if (ValueVT < RegVT)
2639 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2640 else
2641 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002642 }
Chris Lattner5df99b32007-03-25 05:00:54 +00002643
2644 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2645 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002646}
2647
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002648/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2649/// specified value into the registers specified by this object. This uses
2650/// Chain/Flag as the input and updates them for the output Chain/Flag.
2651void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002652 SDOperand &Chain, SDOperand &Flag,
2653 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002654 if (Regs.size() == 1) {
2655 // If there is a single register and the types differ, this must be
2656 // a promotion.
2657 if (RegVT != ValueVT) {
Chris Lattner5df99b32007-03-25 05:00:54 +00002658 if (MVT::isVector(RegVT)) {
2659 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2660 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2661 } else if (MVT::isInteger(RegVT)) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002662 if (RegVT < ValueVT)
2663 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2664 else
2665 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2666 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002667 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2668 }
2669 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2670 Flag = Chain.getValue(1);
2671 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002672 std::vector<unsigned> R(Regs);
2673 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2674 std::reverse(R.begin(), R.end());
2675
2676 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002677 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002678 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002679 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002680 Flag = Chain.getValue(1);
2681 }
2682 }
2683}
Chris Lattner864635a2006-02-22 22:37:12 +00002684
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002685/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2686/// operand list. This adds the code marker and includes the number of
2687/// values added into it.
2688void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002689 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002690 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2691 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2692 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2693}
Chris Lattner864635a2006-02-22 22:37:12 +00002694
2695/// isAllocatableRegister - If the specified register is safe to allocate,
2696/// i.e. it isn't a stack pointer or some other special register, return the
2697/// register class for the register. Otherwise, return null.
2698static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002699isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2700 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002701 MVT::ValueType FoundVT = MVT::Other;
2702 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002703 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2704 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002705 MVT::ValueType ThisVT = MVT::Other;
2706
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002707 const TargetRegisterClass *RC = *RCI;
2708 // If none of the the value types for this register class are valid, we
2709 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002710 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2711 I != E; ++I) {
2712 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002713 // If we have already found this register in a different register class,
2714 // choose the one with the largest VT specified. For example, on
2715 // PowerPC, we favor f64 register classes over f32.
2716 if (FoundVT == MVT::Other ||
2717 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2718 ThisVT = *I;
2719 break;
2720 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002721 }
2722 }
2723
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002724 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002725
Chris Lattner864635a2006-02-22 22:37:12 +00002726 // NOTE: This isn't ideal. In particular, this might allocate the
2727 // frame pointer in functions that need it (due to them not being taken
2728 // out of allocation, because a variable sized allocation hasn't been seen
2729 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002730 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2731 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002732 if (*I == Reg) {
2733 // We found a matching register class. Keep looking at others in case
2734 // we find one with larger registers that this physreg is also in.
2735 FoundRC = RC;
2736 FoundVT = ThisVT;
2737 break;
2738 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002739 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002740 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002741}
2742
2743RegsForValue SelectionDAGLowering::
2744GetRegistersForValue(const std::string &ConstrCode,
2745 MVT::ValueType VT, bool isOutReg, bool isInReg,
2746 std::set<unsigned> &OutputRegs,
2747 std::set<unsigned> &InputRegs) {
2748 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2749 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2750 std::vector<unsigned> Regs;
2751
2752 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2753 MVT::ValueType RegVT;
2754 MVT::ValueType ValueVT = VT;
2755
Chris Lattner2a821602006-11-02 01:41:49 +00002756 // If this is a constraint for a specific physical register, like {r17},
2757 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002758 if (PhysReg.first) {
2759 if (VT == MVT::Other)
2760 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002761
2762 // Get the actual register value type. This is important, because the user
2763 // may have asked for (e.g.) the AX register in i32 type. We need to
2764 // remember that AX is actually i16 to get the right extension.
2765 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002766
2767 // This is a explicit reference to a physical register.
2768 Regs.push_back(PhysReg.first);
2769
2770 // If this is an expanded reference, add the rest of the regs to Regs.
2771 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002772 TargetRegisterClass::iterator I = PhysReg.second->begin();
2773 TargetRegisterClass::iterator E = PhysReg.second->end();
2774 for (; *I != PhysReg.first; ++I)
2775 assert(I != E && "Didn't find reg!");
2776
2777 // Already added the first reg.
2778 --NumRegs; ++I;
2779 for (; NumRegs; --NumRegs, ++I) {
2780 assert(I != E && "Ran out of registers to allocate!");
2781 Regs.push_back(*I);
2782 }
2783 }
2784 return RegsForValue(Regs, RegVT, ValueVT);
2785 }
2786
Chris Lattner2a821602006-11-02 01:41:49 +00002787 // Otherwise, if this was a reference to an LLVM register class, create vregs
2788 // for this reference.
2789 std::vector<unsigned> RegClassRegs;
2790 if (PhysReg.second) {
2791 // If this is an early clobber or tied register, our regalloc doesn't know
2792 // how to maintain the constraint. If it isn't, go ahead and create vreg
2793 // and let the regalloc do the right thing.
2794 if (!isOutReg || !isInReg) {
2795 if (VT == MVT::Other)
2796 ValueVT = *PhysReg.second->vt_begin();
2797 RegVT = *PhysReg.second->vt_begin();
2798
2799 // Create the appropriate number of virtual registers.
2800 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2801 for (; NumRegs; --NumRegs)
2802 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2803
2804 return RegsForValue(Regs, RegVT, ValueVT);
2805 }
2806
2807 // Otherwise, we can't allocate it. Let the code below figure out how to
2808 // maintain these constraints.
2809 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2810
2811 } else {
2812 // This is a reference to a register class that doesn't directly correspond
2813 // to an LLVM register class. Allocate NumRegs consecutive, available,
2814 // registers from the class.
2815 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2816 }
Chris Lattner864635a2006-02-22 22:37:12 +00002817
2818 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2819 MachineFunction &MF = *CurMBB->getParent();
2820 unsigned NumAllocated = 0;
2821 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2822 unsigned Reg = RegClassRegs[i];
2823 // See if this register is available.
2824 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2825 (isInReg && InputRegs.count(Reg))) { // Already used.
2826 // Make sure we find consecutive registers.
2827 NumAllocated = 0;
2828 continue;
2829 }
2830
2831 // Check to see if this register is allocatable (i.e. don't give out the
2832 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002833 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002834 if (!RC) {
2835 // Make sure we find consecutive registers.
2836 NumAllocated = 0;
2837 continue;
2838 }
2839
2840 // Okay, this register is good, we can use it.
2841 ++NumAllocated;
2842
Chris Lattnere303ac92007-04-06 17:47:14 +00002843 // If we allocated enough consecutive registers, succeed.
Chris Lattner864635a2006-02-22 22:37:12 +00002844 if (NumAllocated == NumRegs) {
2845 unsigned RegStart = (i-NumAllocated)+1;
2846 unsigned RegEnd = i+1;
2847 // Mark all of the allocated registers used.
2848 for (unsigned i = RegStart; i != RegEnd; ++i) {
2849 unsigned Reg = RegClassRegs[i];
2850 Regs.push_back(Reg);
2851 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2852 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2853 }
2854
2855 return RegsForValue(Regs, *RC->vt_begin(), VT);
2856 }
2857 }
2858
2859 // Otherwise, we couldn't allocate enough registers for this.
2860 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002861}
2862
Chris Lattner367f1092007-01-29 23:45:14 +00002863/// getConstraintGenerality - Return an integer indicating how general CT is.
2864static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2865 switch (CT) {
2866 default: assert(0 && "Unknown constraint type!");
2867 case TargetLowering::C_Other:
2868 case TargetLowering::C_Unknown:
2869 return 0;
2870 case TargetLowering::C_Register:
2871 return 1;
2872 case TargetLowering::C_RegisterClass:
2873 return 2;
2874 case TargetLowering::C_Memory:
2875 return 3;
2876 }
2877}
2878
2879static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2880 const TargetLowering &TLI) {
2881 assert(!C.empty() && "Must have at least one constraint");
2882 if (C.size() == 1) return C[0];
2883
2884 std::string *Current = &C[0];
2885 // If we have multiple constraints, try to pick the most general one ahead
2886 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattner4234f572007-03-25 02:14:49 +00002887 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattner367f1092007-01-29 23:45:14 +00002888 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattner4234f572007-03-25 02:14:49 +00002889 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattner367f1092007-01-29 23:45:14 +00002890 if (getConstraintGenerality(ThisFlavor) >
2891 getConstraintGenerality(Flavor)) {
2892 // This constraint letter is more general than the previous one,
2893 // use it.
2894 Flavor = ThisFlavor;
2895 Current = &C[j];
2896 }
2897 }
2898 return *Current;
2899}
2900
Chris Lattner864635a2006-02-22 22:37:12 +00002901
Chris Lattnerce7518c2006-01-26 22:24:51 +00002902/// visitInlineAsm - Handle a call to an InlineAsm object.
2903///
2904void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2905 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2906
2907 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2908 MVT::Other);
2909
Chris Lattner2cc2f662006-02-01 01:28:23 +00002910 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002911 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002912
2913 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2914 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2915 /// if it is a def of that register.
2916 std::vector<SDOperand> AsmNodeOperands;
2917 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2918 AsmNodeOperands.push_back(AsmStr);
2919
2920 SDOperand Chain = getRoot();
2921 SDOperand Flag;
2922
Chris Lattner4e4b5762006-02-01 18:59:47 +00002923 // We fully assign registers here at isel time. This is not optimal, but
2924 // should work. For register classes that correspond to LLVM classes, we
2925 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2926 // over the constraints, collecting fixed registers that we know we can't use.
2927 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002928 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002929 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002930 std::string ConstraintCode =
2931 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002932
Chris Lattner1efa40f2006-02-22 00:56:39 +00002933 MVT::ValueType OpVT;
2934
2935 // Compute the value type for each operand and add it to ConstraintVTs.
2936 switch (Constraints[i].Type) {
2937 case InlineAsm::isOutput:
2938 if (!Constraints[i].isIndirectOutput) {
2939 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2940 OpVT = TLI.getValueType(I.getType());
2941 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002942 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002943 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2944 OpNum++; // Consumes a call operand.
2945 }
2946 break;
2947 case InlineAsm::isInput:
2948 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2949 OpNum++; // Consumes a call operand.
2950 break;
2951 case InlineAsm::isClobber:
2952 OpVT = MVT::Other;
2953 break;
2954 }
2955
2956 ConstraintVTs.push_back(OpVT);
2957
Chris Lattner864635a2006-02-22 22:37:12 +00002958 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2959 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002960
Chris Lattner864635a2006-02-22 22:37:12 +00002961 // Build a list of regs that this operand uses. This always has a single
2962 // element for promoted/expanded operands.
2963 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2964 false, false,
2965 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002966
2967 switch (Constraints[i].Type) {
2968 case InlineAsm::isOutput:
2969 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002970 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002971 // If this is an early-clobber output, it cannot be assigned to the same
2972 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002973 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002974 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002975 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002976 case InlineAsm::isInput:
2977 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002978 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002979 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002980 case InlineAsm::isClobber:
2981 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002982 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2983 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002984 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002985 }
2986 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002987
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002988 // Loop over all of the inputs, copying the operand values into the
2989 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002990 RegsForValue RetValRegs;
2991 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002992 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002993
Chris Lattner6656dd12006-01-31 02:03:41 +00002994 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002995 std::string ConstraintCode =
2996 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002997
Chris Lattner2cc2f662006-02-01 01:28:23 +00002998 switch (Constraints[i].Type) {
2999 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00003000 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3001 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003002 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner22873462006-02-27 23:45:39 +00003003
3004 if (CTy == TargetLowering::C_Memory) {
3005 // Memory output.
3006 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3007
3008 // Check that the operand (the address to store to) isn't a float.
3009 if (!MVT::isInteger(InOperandVal.getValueType()))
3010 assert(0 && "MATCH FAIL!");
3011
3012 if (!Constraints[i].isIndirectOutput)
3013 assert(0 && "MATCH FAIL!");
3014
3015 OpNum++; // Consumes a call operand.
3016
3017 // Extend/truncate to the right pointer type if needed.
3018 MVT::ValueType PtrType = TLI.getPointerTy();
3019 if (InOperandVal.getValueType() < PtrType)
3020 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3021 else if (InOperandVal.getValueType() > PtrType)
3022 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3023
3024 // Add information to the INLINEASM node to know about this output.
3025 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3026 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3027 AsmNodeOperands.push_back(InOperandVal);
3028 break;
3029 }
3030
3031 // Otherwise, this is a register output.
3032 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3033
Chris Lattner864635a2006-02-22 22:37:12 +00003034 // If this is an early-clobber output, or if there is an input
3035 // constraint that matches this, we need to reserve the input register
3036 // so no other inputs allocate to it.
3037 bool UsesInputRegister = false;
3038 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3039 UsesInputRegister = true;
3040
3041 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003042 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00003043 RegsForValue Regs =
3044 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3045 true, UsesInputRegister,
3046 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00003047 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003048 cerr << "Couldn't allocate output reg for contraint '"
3049 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003050 exit(1);
3051 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003052
Chris Lattner2cc2f662006-02-01 01:28:23 +00003053 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00003054 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003055 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003056 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00003057 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003058 } else {
Chris Lattner22873462006-02-27 23:45:39 +00003059 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3060 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003061 OpNum++; // Consumes a call operand.
3062 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003063
3064 // Add information to the INLINEASM node to know that this register is
3065 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003066 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003067 break;
3068 }
3069 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00003070 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00003071 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00003072
Chris Lattner2223aea2006-02-02 00:25:23 +00003073 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3074 // If this is required to match an output register we have already set,
3075 // just use its register.
3076 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003077
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003078 // Scan until we find the definition we already emitted of this operand.
3079 // When we find it, create a RegsForValue operand.
3080 unsigned CurOp = 2; // The first operand.
3081 for (; OperandNo; --OperandNo) {
3082 // Advance to the next operand.
3083 unsigned NumOps =
3084 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003085 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3086 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003087 "Skipped past definitions?");
3088 CurOp += (NumOps>>3)+1;
3089 }
3090
3091 unsigned NumOps =
3092 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003093 if ((NumOps & 7) == 2 /*REGDEF*/) {
3094 // Add NumOps>>3 registers to MatchedRegs.
3095 RegsForValue MatchedRegs;
3096 MatchedRegs.ValueVT = InOperandVal.getValueType();
3097 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3098 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3099 unsigned Reg =
3100 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3101 MatchedRegs.Regs.push_back(Reg);
3102 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003103
Chris Lattner527fae12007-02-01 01:21:12 +00003104 // Use the produced MatchedRegs object to
3105 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3106 TLI.getPointerTy());
3107 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3108 break;
3109 } else {
3110 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3111 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003112 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003113 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003114
3115 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3116 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003117 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003118
3119 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00003120 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3121 ConstraintCode[0], DAG);
3122 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00003123 cerr << "Invalid operand for inline asm constraint '"
3124 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003125 exit(1);
3126 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003127
3128 // Add information to the INLINEASM node to know about this input.
3129 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3130 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3131 AsmNodeOperands.push_back(InOperandVal);
3132 break;
3133 } else if (CTy == TargetLowering::C_Memory) {
3134 // Memory input.
3135
Chris Lattner6dfc6802007-03-08 22:29:47 +00003136 // If the operand is a float, spill to a constant pool entry to get its
3137 // address.
3138 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3139 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3140
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003141 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattner6dfc6802007-03-08 22:29:47 +00003142 cerr << "Match failed, cannot handle this yet!\n";
3143 InOperandVal.Val->dump();
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003144 exit(1);
3145 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003146
3147 // Extend/truncate to the right pointer type if needed.
3148 MVT::ValueType PtrType = TLI.getPointerTy();
3149 if (InOperandVal.getValueType() < PtrType)
3150 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3151 else if (InOperandVal.getValueType() > PtrType)
3152 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3153
3154 // Add information to the INLINEASM node to know about this input.
3155 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3156 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3157 AsmNodeOperands.push_back(InOperandVal);
3158 break;
3159 }
3160
3161 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3162
3163 // Copy the input into the appropriate registers.
3164 RegsForValue InRegs =
3165 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3166 false, true, OutputRegs, InputRegs);
3167 // FIXME: should be match fail.
3168 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3169
Evan Chenga8441262006-06-15 08:11:54 +00003170 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003171
3172 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003173 break;
3174 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003175 case InlineAsm::isClobber: {
3176 RegsForValue ClobberedRegs =
3177 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3178 OutputRegs, InputRegs);
3179 // Add the clobbered value to the operand list, so that the register
3180 // allocator is aware that the physreg got clobbered.
3181 if (!ClobberedRegs.Regs.empty())
3182 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003183 break;
3184 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003185 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003186 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003187
3188 // Finish up input operands.
3189 AsmNodeOperands[0] = Chain;
3190 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3191
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003192 Chain = DAG.getNode(ISD::INLINEASM,
3193 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003194 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003195 Flag = Chain.getValue(1);
3196
Chris Lattner6656dd12006-01-31 02:03:41 +00003197 // If this asm returns a register value, copy the result from that register
3198 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003199 if (!RetValRegs.Regs.empty())
3200 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00003201
Chris Lattner6656dd12006-01-31 02:03:41 +00003202 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3203
3204 // Process indirect outputs, first output all of the flagged copies out of
3205 // physregs.
3206 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003207 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003208 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00003209 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3210 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003211 }
3212
3213 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003214 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003215 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00003216 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003217 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003218 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003219 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003220 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3221 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003222 DAG.setRoot(Chain);
3223}
3224
3225
Chris Lattner1c08c712005-01-07 07:47:53 +00003226void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3227 SDOperand Src = getValue(I.getOperand(0));
3228
3229 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003230
3231 if (IntPtr < Src.getValueType())
3232 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3233 else if (IntPtr > Src.getValueType())
3234 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003235
3236 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003237 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003238 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3239 Src, getIntPtrConstant(ElementSize));
3240
Reid Spencer47857812006-12-31 05:55:36 +00003241 TargetLowering::ArgListTy Args;
3242 TargetLowering::ArgListEntry Entry;
3243 Entry.Node = Src;
3244 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003245 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003246
3247 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003248 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003249 DAG.getExternalSymbol("malloc", IntPtr),
3250 Args, DAG);
3251 setValue(&I, Result.first); // Pointers always fit in registers
3252 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003253}
3254
3255void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003256 TargetLowering::ArgListTy Args;
3257 TargetLowering::ArgListEntry Entry;
3258 Entry.Node = getValue(I.getOperand(0));
3259 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003260 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003261 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003262 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003263 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003264 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3265 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003266}
3267
Chris Lattner025c39b2005-08-26 20:54:47 +00003268// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3269// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3270// instructions are special in various ways, which require special support to
3271// insert. The specified MachineInstr is created but not inserted into any
3272// basic blocks, and the scheduler passes ownership of it to this method.
3273MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3274 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003275 cerr << "If a target marks an instruction with "
3276 << "'usesCustomDAGSchedInserter', it must implement "
3277 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003278 abort();
3279 return 0;
3280}
3281
Chris Lattner39ae3622005-01-09 00:00:49 +00003282void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003283 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3284 getValue(I.getOperand(1)),
3285 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003286}
3287
3288void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003289 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3290 getValue(I.getOperand(0)),
3291 DAG.getSrcValue(I.getOperand(0)));
3292 setValue(&I, V);
3293 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003294}
3295
3296void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003297 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3298 getValue(I.getOperand(1)),
3299 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003300}
3301
3302void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003303 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3304 getValue(I.getOperand(1)),
3305 getValue(I.getOperand(2)),
3306 DAG.getSrcValue(I.getOperand(1)),
3307 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003308}
3309
Evan Chengb15974a2006-12-12 07:27:38 +00003310/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3311/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3312static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3313 unsigned &i, SelectionDAG &DAG,
3314 TargetLowering &TLI) {
3315 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3316 return SDOperand(Arg, i++);
3317
3318 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3319 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3320 if (NumVals == 1) {
3321 return DAG.getNode(ISD::BIT_CONVERT, VT,
3322 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3323 } else if (NumVals == 2) {
3324 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3325 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3326 if (!TLI.isLittleEndian())
3327 std::swap(Lo, Hi);
3328 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3329 } else {
3330 // Value scalarized into many values. Unimp for now.
3331 assert(0 && "Cannot expand i64 -> i16 yet!");
3332 }
3333 return SDOperand();
3334}
3335
Chris Lattnerfdfded52006-04-12 16:20:43 +00003336/// TargetLowering::LowerArguments - This is the default LowerArguments
3337/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003338/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3339/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003340std::vector<SDOperand>
3341TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003342 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003343 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3344 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003345 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003346 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3347 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3348
3349 // Add one result value for each formal argument.
3350 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003351 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003352 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3353 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003354 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003355 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003356 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003357 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003358
Chris Lattnerddf53e42007-02-26 02:56:58 +00003359 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3360 // that is zero extended!
3361 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003362 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003363 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003364 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003365 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003366 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003367 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003368 Flags |= ISD::ParamFlags::StructReturn;
3369 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003370
Chris Lattnerfdfded52006-04-12 16:20:43 +00003371 switch (getTypeAction(VT)) {
3372 default: assert(0 && "Unknown type action!");
3373 case Legal:
3374 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003375 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003376 break;
3377 case Promote:
3378 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003379 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003380 break;
3381 case Expand:
3382 if (VT != MVT::Vector) {
3383 // If this is a large integer, it needs to be broken up into small
3384 // integers. Figure out what the destination type is and how many small
3385 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003386 MVT::ValueType NVT = getTypeToExpandTo(VT);
3387 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003388 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003389 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003390 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003391 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003392 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3393 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003394 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3395 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003396 } else {
3397 // Otherwise, this is a vector type. We only support legal vectors
3398 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003399 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3400 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003401
Chris Lattnerfdfded52006-04-12 16:20:43 +00003402 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003403 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003404 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3405 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3406 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003407 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003408 } else {
3409 assert(0 && "Don't support illegal by-val vector arguments yet!");
3410 }
3411 }
3412 break;
3413 }
3414 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003415
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003416 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003417
3418 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003419 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3420 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003421 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003422
3423 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003424
3425 // Set up the return result vector.
3426 Ops.clear();
3427 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003428 unsigned Idx = 1;
3429 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3430 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003431 MVT::ValueType VT = getValueType(I->getType());
3432
3433 switch (getTypeAction(VT)) {
3434 default: assert(0 && "Unknown type action!");
3435 case Legal:
3436 Ops.push_back(SDOperand(Result, i++));
3437 break;
3438 case Promote: {
3439 SDOperand Op(Result, i++);
3440 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003441 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3442 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3443 DAG.getValueType(VT));
3444 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3445 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3446 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003447 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3448 } else {
3449 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3450 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3451 }
3452 Ops.push_back(Op);
3453 break;
3454 }
3455 case Expand:
3456 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003457 // If this is a large integer or a floating point node that needs to be
3458 // expanded, it needs to be reassembled from small integers. Figure out
3459 // what the source elt type is and how many small integers it is.
3460 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003461 } else {
3462 // Otherwise, this is a vector type. We only support legal vectors
3463 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003464 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003465 unsigned NumElems = PTy->getNumElements();
3466 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003467
Chris Lattnerfdfded52006-04-12 16:20:43 +00003468 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003469 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003470 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003471 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003472 SDOperand N = SDOperand(Result, i++);
3473 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003474 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3475 DAG.getConstant(NumElems, MVT::i32),
3476 DAG.getValueType(getValueType(EltTy)));
3477 Ops.push_back(N);
3478 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003479 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003480 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003481 }
3482 }
3483 break;
3484 }
3485 }
3486 return Ops;
3487}
3488
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003489
Evan Chengb15974a2006-12-12 07:27:38 +00003490/// ExpandScalarCallArgs - Recursively expand call argument node by
3491/// bit_converting it or extract a pair of elements from the larger node.
3492static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003493 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003494 SmallVector<SDOperand, 32> &Ops,
3495 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003496 TargetLowering &TLI,
3497 bool isFirst = true) {
3498
Evan Chengb15974a2006-12-12 07:27:38 +00003499 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003500 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003501 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003502 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3503 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003504 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003505 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003506 return;
3507 }
3508
3509 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3510 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3511 if (NumVals == 1) {
3512 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003513 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003514 } else if (NumVals == 2) {
3515 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3516 DAG.getConstant(0, TLI.getPointerTy()));
3517 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3518 DAG.getConstant(1, TLI.getPointerTy()));
3519 if (!TLI.isLittleEndian())
3520 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003521 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3522 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003523 } else {
3524 // Value scalarized into many values. Unimp for now.
3525 assert(0 && "Cannot expand i64 -> i16 yet!");
3526 }
3527}
3528
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003529/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3530/// implementation, which just inserts an ISD::CALL node, which is later custom
3531/// lowered by the target to something concrete. FIXME: When all targets are
3532/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3533std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003534TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3535 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003536 unsigned CallingConv, bool isTailCall,
3537 SDOperand Callee,
3538 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003539 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003540 Ops.push_back(Chain); // Op#0 - Chain
3541 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3542 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3543 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3544 Ops.push_back(Callee);
3545
3546 // Handle all of the outgoing arguments.
3547 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003548 MVT::ValueType VT = getValueType(Args[i].Ty);
3549 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003550 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003551 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003552 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003553
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003554 if (Args[i].isSExt)
3555 Flags |= ISD::ParamFlags::SExt;
3556 if (Args[i].isZExt)
3557 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003558 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003559 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003560 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003561 Flags |= ISD::ParamFlags::StructReturn;
3562 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003563
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003564 switch (getTypeAction(VT)) {
3565 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003566 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003567 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003568 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003569 break;
3570 case Promote:
3571 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003572 unsigned ExtOp;
3573 if (Args[i].isSExt)
3574 ExtOp = ISD::SIGN_EXTEND;
3575 else if (Args[i].isZExt)
3576 ExtOp = ISD::ZERO_EXTEND;
3577 else
3578 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003579 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3580 } else {
3581 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3582 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3583 }
3584 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003585 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003586 break;
3587 case Expand:
3588 if (VT != MVT::Vector) {
3589 // If this is a large integer, it needs to be broken down into small
3590 // integers. Figure out what the source elt type is and how many small
3591 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003592 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003593 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003594 // Otherwise, this is a vector type. We only support legal vectors
3595 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003596 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003597 unsigned NumElems = PTy->getNumElements();
3598 const Type *EltTy = PTy->getElementType();
3599
3600 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003601 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003602 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003603 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003604 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003605 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3606 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003607 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003608 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003609 assert(0 && "Don't support illegal by-val vector call args yet!");
3610 abort();
3611 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003612 }
3613 break;
3614 }
3615 }
3616
3617 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003618 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003619
3620 if (RetTy != Type::VoidTy) {
3621 MVT::ValueType VT = getValueType(RetTy);
3622 switch (getTypeAction(VT)) {
3623 default: assert(0 && "Unknown type action!");
3624 case Legal:
3625 RetTys.push_back(VT);
3626 break;
3627 case Promote:
3628 RetTys.push_back(getTypeToTransformTo(VT));
3629 break;
3630 case Expand:
3631 if (VT != MVT::Vector) {
3632 // If this is a large integer, it needs to be reassembled from small
3633 // integers. Figure out what the source elt type is and how many small
3634 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003635 MVT::ValueType NVT = getTypeToExpandTo(VT);
3636 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003637 for (unsigned i = 0; i != NumVals; ++i)
3638 RetTys.push_back(NVT);
3639 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003640 // Otherwise, this is a vector type. We only support legal vectors
3641 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003642 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003643 unsigned NumElems = PTy->getNumElements();
3644 const Type *EltTy = PTy->getElementType();
3645
3646 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003647 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003648 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3649 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3650 RetTys.push_back(TVT);
3651 } else {
3652 assert(0 && "Don't support illegal by-val vector call results yet!");
3653 abort();
3654 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003655 }
3656 }
3657 }
3658
3659 RetTys.push_back(MVT::Other); // Always has a chain.
3660
3661 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003662 SDOperand Res = DAG.getNode(ISD::CALL,
3663 DAG.getVTList(&RetTys[0], RetTys.size()),
3664 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003665
3666 // This returns a pair of operands. The first element is the
3667 // return value for the function (if RetTy is not VoidTy). The second
3668 // element is the outgoing token chain.
3669 SDOperand ResVal;
3670 if (RetTys.size() != 1) {
3671 MVT::ValueType VT = getValueType(RetTy);
3672 if (RetTys.size() == 2) {
3673 ResVal = Res;
3674
3675 // If this value was promoted, truncate it down.
3676 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003677 if (VT == MVT::Vector) {
Chris Lattner5df99b32007-03-25 05:00:54 +00003678 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerda098e72006-05-16 23:39:44 +00003679 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003680 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3681 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003682
3683 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003684 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003685 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003686 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003687 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3688 // "N x PTyElementVT" MVT::Vector type.
3689 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003690 DAG.getConstant(NumElems, MVT::i32),
3691 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003692 } else {
3693 abort();
3694 }
3695 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003696 unsigned AssertOp = ISD::AssertSext;
3697 if (!RetTyIsSigned)
3698 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003699 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3700 DAG.getValueType(VT));
3701 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3702 } else {
3703 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003704 if (getTypeAction(VT) == Expand)
3705 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3706 else
3707 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003708 }
3709 }
3710 } else if (RetTys.size() == 3) {
3711 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3712 Res.getValue(0), Res.getValue(1));
3713
3714 } else {
3715 assert(0 && "Case not handled yet!");
3716 }
3717 }
3718
3719 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3720}
3721
Chris Lattner50381b62005-05-14 05:50:48 +00003722SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003723 assert(0 && "LowerOperation not implemented for this target!");
3724 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003725 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003726}
3727
Nate Begeman0aed7842006-01-28 03:14:31 +00003728SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3729 SelectionDAG &DAG) {
3730 assert(0 && "CustomPromoteOperation not implemented for this target!");
3731 abort();
3732 return SDOperand();
3733}
3734
Evan Cheng74d0aa92006-02-15 21:59:04 +00003735/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003736/// operand.
3737static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003738 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003739 MVT::ValueType CurVT = VT;
3740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3741 uint64_t Val = C->getValue() & 255;
3742 unsigned Shift = 8;
3743 while (CurVT != MVT::i8) {
3744 Val = (Val << Shift) | Val;
3745 Shift <<= 1;
3746 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003747 }
3748 return DAG.getConstant(Val, VT);
3749 } else {
3750 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3751 unsigned Shift = 8;
3752 while (CurVT != MVT::i8) {
3753 Value =
3754 DAG.getNode(ISD::OR, VT,
3755 DAG.getNode(ISD::SHL, VT, Value,
3756 DAG.getConstant(Shift, MVT::i8)), Value);
3757 Shift <<= 1;
3758 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003759 }
3760
3761 return Value;
3762 }
3763}
3764
Evan Cheng74d0aa92006-02-15 21:59:04 +00003765/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3766/// used when a memcpy is turned into a memset when the source is a constant
3767/// string ptr.
3768static SDOperand getMemsetStringVal(MVT::ValueType VT,
3769 SelectionDAG &DAG, TargetLowering &TLI,
3770 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003771 uint64_t Val = 0;
3772 unsigned MSB = getSizeInBits(VT) / 8;
3773 if (TLI.isLittleEndian())
3774 Offset = Offset + MSB - 1;
3775 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003776 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003777 Offset += TLI.isLittleEndian() ? -1 : 1;
3778 }
3779 return DAG.getConstant(Val, VT);
3780}
3781
Evan Cheng1db92f92006-02-14 08:22:34 +00003782/// getMemBasePlusOffset - Returns base and offset node for the
3783static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3784 SelectionDAG &DAG, TargetLowering &TLI) {
3785 MVT::ValueType VT = Base.getValueType();
3786 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3787}
3788
Evan Chengc4f8eee2006-02-14 20:12:38 +00003789/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003790/// to replace the memset / memcpy is below the threshold. It also returns the
3791/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003792static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3793 unsigned Limit, uint64_t Size,
3794 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003795 MVT::ValueType VT;
3796
3797 if (TLI.allowsUnalignedMemoryAccesses()) {
3798 VT = MVT::i64;
3799 } else {
3800 switch (Align & 7) {
3801 case 0:
3802 VT = MVT::i64;
3803 break;
3804 case 4:
3805 VT = MVT::i32;
3806 break;
3807 case 2:
3808 VT = MVT::i16;
3809 break;
3810 default:
3811 VT = MVT::i8;
3812 break;
3813 }
3814 }
3815
Evan Cheng80e89d72006-02-14 09:11:59 +00003816 MVT::ValueType LVT = MVT::i64;
3817 while (!TLI.isTypeLegal(LVT))
3818 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3819 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003820
Evan Cheng80e89d72006-02-14 09:11:59 +00003821 if (VT > LVT)
3822 VT = LVT;
3823
Evan Chengdea72452006-02-14 23:05:54 +00003824 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003825 while (Size != 0) {
3826 unsigned VTSize = getSizeInBits(VT) / 8;
3827 while (VTSize > Size) {
3828 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003829 VTSize >>= 1;
3830 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003831 assert(MVT::isInteger(VT));
3832
3833 if (++NumMemOps > Limit)
3834 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003835 MemOps.push_back(VT);
3836 Size -= VTSize;
3837 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003838
3839 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003840}
3841
Chris Lattner7041ee32005-01-11 05:56:49 +00003842void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003843 SDOperand Op1 = getValue(I.getOperand(1));
3844 SDOperand Op2 = getValue(I.getOperand(2));
3845 SDOperand Op3 = getValue(I.getOperand(3));
3846 SDOperand Op4 = getValue(I.getOperand(4));
3847 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3848 if (Align == 0) Align = 1;
3849
3850 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3851 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003852
3853 // Expand memset / memcpy to a series of load / store ops
3854 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003855 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003856 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003857 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003858 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003859 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3860 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003861 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003862 unsigned Offset = 0;
3863 for (unsigned i = 0; i < NumMemOps; i++) {
3864 MVT::ValueType VT = MemOps[i];
3865 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003866 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003867 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003868 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003869 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003870 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003871 Offset += VTSize;
3872 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003873 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003874 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003875 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003876 case ISD::MEMCPY: {
3877 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3878 Size->getValue(), Align, TLI)) {
3879 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003880 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003881 GlobalAddressSDNode *G = NULL;
3882 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003883 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003884
3885 if (Op2.getOpcode() == ISD::GlobalAddress)
3886 G = cast<GlobalAddressSDNode>(Op2);
3887 else if (Op2.getOpcode() == ISD::ADD &&
3888 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3889 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3890 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003891 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003892 }
3893 if (G) {
3894 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003895 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003896 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003897 if (!Str.empty()) {
3898 CopyFromStr = true;
3899 SrcOff += SrcDelta;
3900 }
3901 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003902 }
3903
Evan Chengc080d6f2006-02-15 01:54:51 +00003904 for (unsigned i = 0; i < NumMemOps; i++) {
3905 MVT::ValueType VT = MemOps[i];
3906 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003907 SDOperand Value, Chain, Store;
3908
Evan Chengcffbb512006-02-16 23:11:42 +00003909 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003910 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3911 Chain = getRoot();
3912 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003913 DAG.getStore(Chain, Value,
3914 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003915 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003916 } else {
3917 Value = DAG.getLoad(VT, getRoot(),
3918 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003919 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003920 Chain = Value.getValue(1);
3921 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003922 DAG.getStore(Chain, Value,
3923 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003924 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003925 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003926 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003927 SrcOff += VTSize;
3928 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003929 }
3930 }
3931 break;
3932 }
3933 }
3934
3935 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003936 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3937 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003938 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003939 }
3940 }
3941
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003942 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003943}
3944
Chris Lattner7041ee32005-01-11 05:56:49 +00003945//===----------------------------------------------------------------------===//
3946// SelectionDAGISel code
3947//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003948
3949unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3950 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3951}
3952
Chris Lattner495a0b52005-08-17 06:37:43 +00003953void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003954 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00003955 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00003956}
Chris Lattner1c08c712005-01-07 07:47:53 +00003957
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003958
Chris Lattnerbad7f482006-10-28 19:22:10 +00003959
Chris Lattner1c08c712005-01-07 07:47:53 +00003960bool SelectionDAGISel::runOnFunction(Function &Fn) {
3961 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3962 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003963 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003964
3965 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3966
3967 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3968 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003969
Evan Chengad2070c2007-02-10 02:43:39 +00003970 // Add function live-ins to entry block live-in set.
3971 BasicBlock *EntryBB = &Fn.getEntryBlock();
3972 BB = FuncInfo.MBBMap[EntryBB];
3973 if (!MF.livein_empty())
3974 for (MachineFunction::livein_iterator I = MF.livein_begin(),
3975 E = MF.livein_end(); I != E; ++I)
3976 BB->addLiveIn(I->first);
3977
Chris Lattner1c08c712005-01-07 07:47:53 +00003978 return true;
3979}
3980
Chris Lattner571e4342006-10-27 21:36:01 +00003981SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3982 unsigned Reg) {
3983 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003984 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003985 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003986 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003987
3988 // If this type is not legal, we must make sure to not create an invalid
3989 // register use.
3990 MVT::ValueType SrcVT = Op.getValueType();
3991 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003992 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003993 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003994 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003995 // Handle copies from generic vectors to registers.
3996 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003997 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00003998 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003999
Chris Lattner70c2a612006-03-31 02:06:56 +00004000 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4001 // MVT::Vector type.
4002 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4003 DAG.getConstant(NE, MVT::i32),
4004 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004005
Chris Lattner70c2a612006-03-31 02:06:56 +00004006 // Loop over all of the elements of the resultant vector,
4007 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4008 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004009 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004010 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004011 for (unsigned i = 0; i != NE; ++i) {
4012 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004013 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004014 if (PTyElementVT == PTyLegalElementVT) {
4015 // Elements are legal.
4016 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4017 } else if (PTyLegalElementVT > PTyElementVT) {
4018 // Elements are promoted.
4019 if (MVT::isFloatingPoint(PTyLegalElementVT))
4020 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4021 else
4022 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4023 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4024 } else {
4025 // Elements are expanded.
4026 // The src value is expanded into multiple registers.
4027 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004028 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004029 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004030 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004031 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4032 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4033 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004034 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004035 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4036 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004037 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004038 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004039 if (MVT::isFloatingPoint(SrcVT))
4040 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4041 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004042 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004043 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004044 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004045 DestVT = TLI.getTypeToExpandTo(SrcVT);
4046 unsigned NumVals = TLI.getNumElements(SrcVT);
4047 if (NumVals == 1)
4048 return DAG.getCopyToReg(getRoot(), Reg,
4049 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4050 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004051 // The src value is expanded into multiple registers.
4052 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004053 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004054 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004055 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004056 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004057 return DAG.getCopyToReg(Op, Reg+1, Hi);
4058 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004059}
4060
Chris Lattner068a81e2005-01-17 17:15:02 +00004061void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004062LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004063 std::vector<SDOperand> &UnorderedChains) {
4064 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004065 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004066 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004067 SDOperand OldRoot = SDL.DAG.getRoot();
4068 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004069
Chris Lattnerbf209482005-10-30 19:42:35 +00004070 unsigned a = 0;
4071 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4072 AI != E; ++AI, ++a)
4073 if (!AI->use_empty()) {
4074 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004075
Chris Lattnerbf209482005-10-30 19:42:35 +00004076 // If this argument is live outside of the entry block, insert a copy from
4077 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004078 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4079 if (VMI != FuncInfo.ValueMap.end()) {
4080 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004081 UnorderedChains.push_back(Copy);
4082 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004083 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004084
Chris Lattnerbf209482005-10-30 19:42:35 +00004085 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004086 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004087 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004088}
4089
Chris Lattner1c08c712005-01-07 07:47:53 +00004090void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4091 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004092 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004093 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004094
4095 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004096
Chris Lattnerbf209482005-10-30 19:42:35 +00004097 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004098 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004099 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004100
4101 BB = FuncInfo.MBBMap[LLVMBB];
4102 SDL.setCurrentBasicBlock(BB);
4103
4104 // Lower all of the non-terminator instructions.
4105 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4106 I != E; ++I)
4107 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004108
4109 // Lower call part of invoke.
4110 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4111 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004112
Chris Lattner1c08c712005-01-07 07:47:53 +00004113 // Ensure that all instructions which are used outside of their defining
4114 // blocks are available as virtual registers.
4115 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004116 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004117 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004118 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004119 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004120 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004121 }
4122
4123 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4124 // ensure constants are generated when needed. Remember the virtual registers
4125 // that need to be added to the Machine PHI nodes as input. We cannot just
4126 // directly add them, because expansion might result in multiple MBB's for one
4127 // BB. As such, the start of the BB might correspond to a different MBB than
4128 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004129 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004130 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004131
4132 // Emit constants only once even if used by multiple PHI nodes.
4133 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004134
Chris Lattner8c494ab2006-10-27 23:50:33 +00004135 // Vector bool would be better, but vector<bool> is really slow.
4136 std::vector<unsigned char> SuccsHandled;
4137 if (TI->getNumSuccessors())
4138 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4139
Chris Lattner1c08c712005-01-07 07:47:53 +00004140 // Check successor nodes PHI nodes that expect a constant to be available from
4141 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004142 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4143 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004144 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004145 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004146
Chris Lattner8c494ab2006-10-27 23:50:33 +00004147 // If this terminator has multiple identical successors (common for
4148 // switches), only handle each succ once.
4149 unsigned SuccMBBNo = SuccMBB->getNumber();
4150 if (SuccsHandled[SuccMBBNo]) continue;
4151 SuccsHandled[SuccMBBNo] = true;
4152
4153 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004154 PHINode *PN;
4155
4156 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4157 // nodes and Machine PHI nodes, but the incoming operands have not been
4158 // emitted yet.
4159 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004160 (PN = dyn_cast<PHINode>(I)); ++I) {
4161 // Ignore dead phi's.
4162 if (PN->use_empty()) continue;
4163
4164 unsigned Reg;
4165 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004166
Chris Lattner8c494ab2006-10-27 23:50:33 +00004167 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4168 unsigned &RegOut = ConstantsOut[C];
4169 if (RegOut == 0) {
4170 RegOut = FuncInfo.CreateRegForValue(C);
4171 UnorderedChains.push_back(
4172 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004173 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004174 Reg = RegOut;
4175 } else {
4176 Reg = FuncInfo.ValueMap[PHIOp];
4177 if (Reg == 0) {
4178 assert(isa<AllocaInst>(PHIOp) &&
4179 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4180 "Didn't codegen value into a register!??");
4181 Reg = FuncInfo.CreateRegForValue(PHIOp);
4182 UnorderedChains.push_back(
4183 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004184 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004185 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004186
4187 // Remember that this register needs to added to the machine PHI node as
4188 // the input for this MBB.
4189 MVT::ValueType VT = TLI.getValueType(PN->getType());
4190 unsigned NumElements;
4191 if (VT != MVT::Vector)
4192 NumElements = TLI.getNumElements(VT);
4193 else {
4194 MVT::ValueType VT1,VT2;
4195 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004196 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004197 VT1, VT2);
4198 }
4199 for (unsigned i = 0, e = NumElements; i != e; ++i)
4200 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4201 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004202 }
4203 ConstantsOut.clear();
4204
Chris Lattnerddb870b2005-01-13 17:59:43 +00004205 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004206 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004207 SDOperand Root = SDL.getRoot();
4208 if (Root.getOpcode() != ISD::EntryToken) {
4209 unsigned i = 0, e = UnorderedChains.size();
4210 for (; i != e; ++i) {
4211 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4212 if (UnorderedChains[i].Val->getOperand(0) == Root)
4213 break; // Don't add the root if we already indirectly depend on it.
4214 }
4215
4216 if (i == e)
4217 UnorderedChains.push_back(Root);
4218 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004219 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4220 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004221 }
4222
Chris Lattner1c08c712005-01-07 07:47:53 +00004223 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004224 if (Invoke) {
4225 // Just the branch part of invoke.
4226 SDL.visitInvoke(*Invoke, true);
4227 } else {
4228 SDL.visit(*LLVMBB->getTerminator());
4229 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004230
Nate Begemanf15485a2006-03-27 01:32:24 +00004231 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004232 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004233 SwitchCases.clear();
4234 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004235 JTCases.clear();
4236 JTCases = SDL.JTCases;
Nate Begemanf15485a2006-03-27 01:32:24 +00004237
Chris Lattnera651cf62005-01-17 19:43:36 +00004238 // Make sure the root of the DAG is up-to-date.
4239 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004240}
4241
Nate Begemanf15485a2006-03-27 01:32:24 +00004242void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004243 // Get alias analysis for load/store combining.
4244 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4245
Chris Lattneraf21d552005-10-10 16:47:10 +00004246 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004247 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004248
Bill Wendling832171c2006-12-07 20:04:42 +00004249 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004250 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004251
Chris Lattner1c08c712005-01-07 07:47:53 +00004252 // Second step, hack on the DAG until it only uses operations and types that
4253 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004254 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004255
Bill Wendling832171c2006-12-07 20:04:42 +00004256 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004257 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004258
Chris Lattneraf21d552005-10-10 16:47:10 +00004259 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004260 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004261
Evan Chenga9c20912006-01-21 02:32:06 +00004262 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004263
Chris Lattnera33ef482005-03-30 01:10:47 +00004264 // Third, instruction select all of the operations to machine code, adding the
4265 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004266 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004267
Bill Wendling832171c2006-12-07 20:04:42 +00004268 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004269 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004270}
Chris Lattner1c08c712005-01-07 07:47:53 +00004271
Nate Begemanf15485a2006-03-27 01:32:24 +00004272void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4273 FunctionLoweringInfo &FuncInfo) {
4274 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4275 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004276 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004277 CurDAG = &DAG;
4278
4279 // First step, lower LLVM code to some DAG. This DAG may use operations and
4280 // types that are not supported by the target.
4281 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4282
4283 // Second step, emit the lowered DAG as machine code.
4284 CodeGenAndEmitDAG(DAG);
4285 }
4286
Chris Lattnera33ef482005-03-30 01:10:47 +00004287 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004288 // PHI nodes in successors.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004289 if (SwitchCases.empty() && JTCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004290 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4291 MachineInstr *PHI = PHINodesToUpdate[i].first;
4292 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4293 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004294 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004295 PHI->addMachineBasicBlockOperand(BB);
4296 }
4297 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004298 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004299
Nate Begeman9453eea2006-04-23 06:26:20 +00004300 // If the JumpTable record is filled in, then we need to emit a jump table.
4301 // Updating the PHI nodes is tricky in this case, since we need to determine
4302 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004303 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4304 // Lower header first, if it wasn't already lowered
4305 if (!JTCases[i].first.Emitted) {
4306 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4307 CurDAG = &HSDAG;
4308 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4309 // Set the current basic block to the mbb we wish to insert the code into
4310 BB = JTCases[i].first.HeaderBB;
4311 HSDL.setCurrentBasicBlock(BB);
4312 // Emit the code
4313 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4314 HSDAG.setRoot(HSDL.getRoot());
4315 CodeGenAndEmitDAG(HSDAG);
4316 }
4317
4318 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4319 CurDAG = &JSDAG;
4320 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004321 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004322 BB = JTCases[i].second.MBB;
4323 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004324 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004325 JSDL.visitJumpTable(JTCases[i].second);
4326 JSDAG.setRoot(JSDL.getRoot());
4327 CodeGenAndEmitDAG(JSDAG);
4328
Nate Begeman37efe672006-04-22 18:53:45 +00004329 // Update PHI Nodes
4330 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4331 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4332 MachineBasicBlock *PHIBB = PHI->getParent();
4333 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4334 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004335 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004336 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004337 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004338 }
4339 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004340 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004341 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004342 }
4343 }
Nate Begeman37efe672006-04-22 18:53:45 +00004344 }
4345
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004346 // If the switch block involved a branch to one of the actual successors, we
4347 // need to update PHI nodes in that block.
4348 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4349 MachineInstr *PHI = PHINodesToUpdate[i].first;
4350 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4351 "This is not a machine PHI node that we are updating!");
4352 if (BB->isSuccessor(PHI->getParent())) {
4353 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4354 PHI->addMachineBasicBlockOperand(BB);
4355 }
4356 }
4357
Nate Begemanf15485a2006-03-27 01:32:24 +00004358 // If we generated any switch lowering information, build and codegen any
4359 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004360 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004361 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004362 CurDAG = &SDAG;
4363 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004364
Nate Begemanf15485a2006-03-27 01:32:24 +00004365 // Set the current basic block to the mbb we wish to insert the code into
4366 BB = SwitchCases[i].ThisBB;
4367 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004368
Nate Begemanf15485a2006-03-27 01:32:24 +00004369 // Emit the code
4370 SDL.visitSwitchCase(SwitchCases[i]);
4371 SDAG.setRoot(SDL.getRoot());
4372 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004373
4374 // Handle any PHI nodes in successors of this chunk, as if we were coming
4375 // from the original BB before switch expansion. Note that PHI nodes can
4376 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4377 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004378 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004379 for (MachineBasicBlock::iterator Phi = BB->begin();
4380 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4381 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4382 for (unsigned pn = 0; ; ++pn) {
4383 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4384 if (PHINodesToUpdate[pn].first == Phi) {
4385 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4386 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4387 break;
4388 }
4389 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004390 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004391
4392 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004393 if (BB == SwitchCases[i].FalseBB)
4394 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004395
4396 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004397 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004398 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004399 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004400 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004401 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004402}
Evan Chenga9c20912006-01-21 02:32:06 +00004403
Jim Laskey13ec7022006-08-01 14:21:23 +00004404
Evan Chenga9c20912006-01-21 02:32:06 +00004405//===----------------------------------------------------------------------===//
4406/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4407/// target node in the graph.
4408void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4409 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004410
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004411 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004412
4413 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004414 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004415 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004416 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004417
Jim Laskey9ff542f2006-08-01 18:29:48 +00004418 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004419 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004420 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004421}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004422
Chris Lattner03fc53c2006-03-06 00:22:00 +00004423
Jim Laskey9ff542f2006-08-01 18:29:48 +00004424HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4425 return new HazardRecognizer();
4426}
4427
Chris Lattner75548062006-10-11 03:58:02 +00004428//===----------------------------------------------------------------------===//
4429// Helper functions used by the generated instruction selector.
4430//===----------------------------------------------------------------------===//
4431// Calls to these methods are generated by tblgen.
4432
4433/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4434/// the dag combiner simplified the 255, we still want to match. RHS is the
4435/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4436/// specified in the .td file (e.g. 255).
4437bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4438 int64_t DesiredMaskS) {
4439 uint64_t ActualMask = RHS->getValue();
4440 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4441
4442 // If the actual mask exactly matches, success!
4443 if (ActualMask == DesiredMask)
4444 return true;
4445
4446 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4447 if (ActualMask & ~DesiredMask)
4448 return false;
4449
4450 // Otherwise, the DAG Combiner may have proven that the value coming in is
4451 // either already zero or is not demanded. Check for known zero input bits.
4452 uint64_t NeededMask = DesiredMask & ~ActualMask;
4453 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4454 return true;
4455
4456 // TODO: check to see if missing bits are just not demanded.
4457
4458 // Otherwise, this pattern doesn't match.
4459 return false;
4460}
4461
4462/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4463/// the dag combiner simplified the 255, we still want to match. RHS is the
4464/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4465/// specified in the .td file (e.g. 255).
4466bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4467 int64_t DesiredMaskS) {
4468 uint64_t ActualMask = RHS->getValue();
4469 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4470
4471 // If the actual mask exactly matches, success!
4472 if (ActualMask == DesiredMask)
4473 return true;
4474
4475 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4476 if (ActualMask & ~DesiredMask)
4477 return false;
4478
4479 // Otherwise, the DAG Combiner may have proven that the value coming in is
4480 // either already zero or is not demanded. Check for known zero input bits.
4481 uint64_t NeededMask = DesiredMask & ~ActualMask;
4482
4483 uint64_t KnownZero, KnownOne;
4484 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4485
4486 // If all the missing bits in the or are already known to be set, match!
4487 if ((NeededMask & KnownOne) == NeededMask)
4488 return true;
4489
4490 // TODO: check to see if missing bits are just not demanded.
4491
4492 // Otherwise, this pattern doesn't match.
4493 return false;
4494}
4495
Jim Laskey9ff542f2006-08-01 18:29:48 +00004496
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004497/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4498/// by tblgen. Others should not call it.
4499void SelectionDAGISel::
4500SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4501 std::vector<SDOperand> InOps;
4502 std::swap(InOps, Ops);
4503
4504 Ops.push_back(InOps[0]); // input chain.
4505 Ops.push_back(InOps[1]); // input asm string.
4506
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004507 unsigned i = 2, e = InOps.size();
4508 if (InOps[e-1].getValueType() == MVT::Flag)
4509 --e; // Don't process a flag operand if it is here.
4510
4511 while (i != e) {
4512 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4513 if ((Flags & 7) != 4 /*MEM*/) {
4514 // Just skip over this operand, copying the operands verbatim.
4515 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4516 i += (Flags >> 3) + 1;
4517 } else {
4518 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4519 // Otherwise, this is a memory operand. Ask the target to select it.
4520 std::vector<SDOperand> SelOps;
4521 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004522 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004523 exit(1);
4524 }
4525
4526 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004527 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4528 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004529 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4530 i += 2;
4531 }
4532 }
4533
4534 // Add the flag input back if present.
4535 if (e != InOps.size())
4536 Ops.push_back(InOps.back());
4537}