blob: 7a62da55712bec6c00324a657305728c939eae0a [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"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000073namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey9ff542f2006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner864635a2006-02-22 22:37:12 +000085namespace {
86 /// RegsForValue - This struct represents the physical registers that a
87 /// particular value is assigned and the type information about the value.
88 /// This is needed because values can be promoted into larger registers and
89 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000090 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000091 /// Regs - This list hold the register (for legal and promoted values)
92 /// or register set (for expanded values) that the value should be assigned
93 /// to.
94 std::vector<unsigned> Regs;
95
96 /// RegVT - The value type of each register.
97 ///
98 MVT::ValueType RegVT;
99
100 /// ValueVT - The value type of the LLVM value, which may be promoted from
101 /// RegVT or made from merging the two expanded parts.
102 MVT::ValueType ValueVT;
103
104 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
105
106 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
107 : RegVT(regvt), ValueVT(valuevt) {
108 Regs.push_back(Reg);
109 }
110 RegsForValue(const std::vector<unsigned> &regs,
111 MVT::ValueType regvt, MVT::ValueType valuevt)
112 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
113 }
114
115 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
116 /// this value and returns the result as a ValueVT value. This uses
117 /// Chain/Flag as the input and updates them for the output Chain/Flag.
118 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000119 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000120
121 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
122 /// specified value into the registers specified by this object. This uses
123 /// Chain/Flag as the input and updates them for the output Chain/Flag.
124 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000125 SDOperand &Chain, SDOperand &Flag,
126 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000127
128 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
129 /// operand list. This adds the code marker and includes the number of
130 /// values added into it.
131 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000132 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000133 };
134}
Evan Cheng4ef10862006-01-23 07:01:07 +0000135
Chris Lattner1c08c712005-01-07 07:47:53 +0000136namespace llvm {
137 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
139 /// for the target.
140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
141 SelectionDAG *DAG,
142 MachineBasicBlock *BB) {
143 TargetLowering &TLI = IS->getTargetLowering();
144
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
146 return createTDListDAGScheduler(IS, DAG, BB);
147 } else {
148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
150 return createBURRListDAGScheduler(IS, DAG, BB);
151 }
152 }
153
154
155 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000156 /// FunctionLoweringInfo - This contains information that is global to a
157 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000158 class FunctionLoweringInfo {
159 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000160 TargetLowering &TLI;
161 Function &Fn;
162 MachineFunction &MF;
163 SSARegMap *RegMap;
164
165 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
166
167 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
168 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
169
170 /// ValueMap - Since we emit code for the function a basic block at a time,
171 /// we must remember which virtual registers hold the values for
172 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000173 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000174
175 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
176 /// the entry block. This allows the allocas to be efficiently referenced
177 /// anywhere in the function.
178 std::map<const AllocaInst*, int> StaticAllocaMap;
179
180 unsigned MakeReg(MVT::ValueType VT) {
181 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
182 }
Chris Lattner571e4342006-10-27 21:36:01 +0000183
184 /// isExportedInst - Return true if the specified value is an instruction
185 /// exported from its block.
186 bool isExportedInst(const Value *V) {
187 return ValueMap.count(V);
188 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000189
Chris Lattner3c384492006-03-16 19:51:18 +0000190 unsigned CreateRegForValue(const Value *V);
191
Chris Lattner1c08c712005-01-07 07:47:53 +0000192 unsigned InitializeRegForValue(const Value *V) {
193 unsigned &R = ValueMap[V];
194 assert(R == 0 && "Already initialized this value register!");
195 return R = CreateRegForValue(V);
196 }
197 };
198}
199
200/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000201/// PHI nodes or outside of the basic block that defines it, or used by a
202/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000203static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
204 if (isa<PHINode>(I)) return true;
205 BasicBlock *BB = I->getParent();
206 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000207 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000208 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000209 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000210 return true;
211 return false;
212}
213
Chris Lattnerbf209482005-10-30 19:42:35 +0000214/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000215/// entry block, return true. This includes arguments used by switches, since
216/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000220 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner1c08c712005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattnerbf209482005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner1c08c712005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000242 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000243 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000244 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000245 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000246 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000247 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000248
Reid Spencerb83eb642006-10-20 07:07:24 +0000249 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000250 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000251 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000252 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 }
254
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000255 for (; BB != EB; ++BB)
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
258 if (!isa<AllocaInst>(I) ||
259 !StaticAllocaMap.count(cast<AllocaInst>(I)))
260 InitializeRegForValue(I);
261
262 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
263 // also creates the initial PHI MachineInstrs, though none of the input
264 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000265 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000266 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
267 MBBMap[BB] = MBB;
268 MF.getBasicBlockList().push_back(MBB);
269
270 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
271 // appropriate.
272 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000273 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
274 if (PN->use_empty()) continue;
275
276 MVT::ValueType VT = TLI.getValueType(PN->getType());
277 unsigned NumElements;
278 if (VT != MVT::Vector)
279 NumElements = TLI.getNumElements(VT);
280 else {
281 MVT::ValueType VT1,VT2;
282 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000283 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000284 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000285 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000286 unsigned PHIReg = ValueMap[PN];
287 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000288 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000289 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000290 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000291 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000292 }
293}
294
Chris Lattner3c384492006-03-16 19:51:18 +0000295/// CreateRegForValue - Allocate the appropriate number of virtual registers of
296/// the correctly promoted or expanded types. Assign these registers
297/// consecutive vreg numbers and return the first assigned number.
298unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
299 MVT::ValueType VT = TLI.getValueType(V->getType());
300
301 // The number of multiples of registers that we need, to, e.g., split up
302 // a <2 x int64> -> 4 x i32 registers.
303 unsigned NumVectorRegs = 1;
304
Reid Spencerac9dcb92007-02-15 03:39:18 +0000305 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000306 // and how many of the elements it will use.
307 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000308 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000309 unsigned NumElts = PTy->getNumElements();
310 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Bill Wendling95b39552007-04-24 21:13:23 +0000311 MVT::ValueType VecTy = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
Bill Wendling95b39552007-04-24 21:13:23 +0000315 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner3c384492006-03-16 19:51:18 +0000316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Bill Wendling95b39552007-04-24 21:13:23 +0000319
320 // Check that VecTy isn't a 1-element vector.
321 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner6cb70042006-03-16 23:05:19 +0000322 VT = EltTy;
323 else
Bill Wendling95b39552007-04-24 21:13:23 +0000324 VT = VecTy;
Chris Lattner3c384492006-03-16 19:51:18 +0000325 }
Bill Wendling95b39552007-04-24 21:13:23 +0000326
Chris Lattner3c384492006-03-16 19:51:18 +0000327 // The common case is that we will only create one register for this
328 // value. If we have that case, create and return the virtual register.
329 unsigned NV = TLI.getNumElements(VT);
330 if (NV == 1) {
331 // If we are promoting this value, pick the next largest supported type.
332 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
333 unsigned Reg = MakeReg(PromotedType);
334 // If this is a vector of supported or promoted types (e.g. 4 x i16),
335 // create all of the registers.
336 for (unsigned i = 1; i != NumVectorRegs; ++i)
337 MakeReg(PromotedType);
338 return Reg;
339 }
340
341 // If this value is represented with multiple target registers, make sure
342 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000343 VT = TLI.getTypeToExpandTo(VT);
344 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000345 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000346 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000347 return R;
348}
Chris Lattner1c08c712005-01-07 07:47:53 +0000349
350//===----------------------------------------------------------------------===//
351/// SelectionDAGLowering - This is the common target-independent lowering
352/// implementation that is parameterized by a TargetLowering object.
353/// Also, targets can overload any lowering method.
354///
355namespace llvm {
356class SelectionDAGLowering {
357 MachineBasicBlock *CurMBB;
358
Chris Lattner0da331f2007-02-04 01:31:47 +0000359 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000360
Chris Lattnerd3948112005-01-17 22:19:26 +0000361 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
362 /// them up and then emit token factor nodes when possible. This allows us to
363 /// get simple disambiguation between loads without worrying about alias
364 /// analysis.
365 std::vector<SDOperand> PendingLoads;
366
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000367 /// Case - A struct to record the Value for a switch case, and the
368 /// case's target basic block.
369 struct Case {
370 Constant* Low;
371 Constant* High;
372 MachineBasicBlock* BB;
373
374 Case() : Low(0), High(0), BB(0) { }
375 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
376 Low(low), High(high), BB(bb) { }
377 uint64_t size() const {
378 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
379 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
380 return (rHigh - rLow + 1ULL);
381 }
382 };
383
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000384 struct CaseBits {
385 uint64_t Mask;
386 MachineBasicBlock* BB;
387 unsigned Bits;
388
389 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
390 Mask(mask), BB(bb), Bits(bits) { }
391 };
392
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000393 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000394 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000395 typedef CaseVector::iterator CaseItr;
396 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000397
398 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
399 /// of conditional branches.
400 struct CaseRec {
401 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
402 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
403
404 /// CaseBB - The MBB in which to emit the compare and branch
405 MachineBasicBlock *CaseBB;
406 /// LT, GE - If nonzero, we know the current case value must be less-than or
407 /// greater-than-or-equal-to these Constants.
408 Constant *LT;
409 Constant *GE;
410 /// Range - A pair of iterators representing the range of case values to be
411 /// processed at this point in the binary search tree.
412 CaseRange Range;
413 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000414
415 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000416
417 /// The comparison function for sorting the switch case values in the vector.
418 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000419 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000420 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000421 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
422 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
423 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
424 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000425 }
426 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000427
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000428 struct CaseBitsCmp {
429 bool operator () (const CaseBits& C1, const CaseBits& C2) {
430 return C1.Bits > C2.Bits;
431 }
432 };
433
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000434 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000435
Chris Lattner1c08c712005-01-07 07:47:53 +0000436public:
437 // TLI - This is information that describes the available target features we
438 // need for lowering. This indicates when operations are unavailable,
439 // implemented with a libcall, etc.
440 TargetLowering &TLI;
441 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000442 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000443
Nate Begemanf15485a2006-03-27 01:32:24 +0000444 /// SwitchCases - Vector of CaseBlock structures used to communicate
445 /// SwitchInst code generation information.
446 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000447 /// JTCases - Vector of JumpTable structures used to communicate
448 /// SwitchInst code generation information.
449 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000450 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000451
Chris Lattner1c08c712005-01-07 07:47:53 +0000452 /// FuncInfo - Information about the function as a whole.
453 ///
454 FunctionLoweringInfo &FuncInfo;
455
456 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000457 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000458 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000459 FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000460 }
461
Chris Lattnera651cf62005-01-17 19:43:36 +0000462 /// getRoot - Return the current virtual root of the Selection DAG.
463 ///
464 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000465 if (PendingLoads.empty())
466 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000467
Chris Lattnerd3948112005-01-17 22:19:26 +0000468 if (PendingLoads.size() == 1) {
469 SDOperand Root = PendingLoads[0];
470 DAG.setRoot(Root);
471 PendingLoads.clear();
472 return Root;
473 }
474
475 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000476 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
477 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000478 PendingLoads.clear();
479 DAG.setRoot(Root);
480 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000481 }
482
Chris Lattner571e4342006-10-27 21:36:01 +0000483 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
484
Chris Lattner1c08c712005-01-07 07:47:53 +0000485 void visit(Instruction &I) { visit(I.getOpcode(), I); }
486
487 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000488 // Note: this doesn't use InstVisitor, because it has to work with
489 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000490 switch (Opcode) {
491 default: assert(0 && "Unknown instruction type encountered!");
492 abort();
493 // Build the switch statement using the Instruction.def file.
494#define HANDLE_INST(NUM, OPCODE, CLASS) \
495 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
496#include "llvm/Instruction.def"
497 }
498 }
499
500 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
501
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000502 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000503 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000504 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000505
506 SDOperand getIntPtrConstant(uint64_t Val) {
507 return DAG.getConstant(Val, TLI.getPointerTy());
508 }
509
Chris Lattner199862b2006-03-16 19:57:50 +0000510 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000511
Chris Lattner0da331f2007-02-04 01:31:47 +0000512 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 SDOperand &N = NodeMap[V];
514 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000515 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000516 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000517
Chris Lattner864635a2006-02-22 22:37:12 +0000518 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
519 MVT::ValueType VT,
520 bool OutReg, bool InReg,
521 std::set<unsigned> &OutputRegs,
522 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000523
Chris Lattner571e4342006-10-27 21:36:01 +0000524 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
525 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
526 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000527 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000528 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000529 void LowerCallTo(Instruction &I,
530 const Type *CalledValueTy, unsigned CallingConv,
531 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey735b6f82007-02-22 15:38:06 +0000532
Chris Lattner1c08c712005-01-07 07:47:53 +0000533 // Terminator instructions.
534 void visitRet(ReturnInst &I);
535 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000536 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000537 void visitUnreachable(UnreachableInst &I) { /* noop */ }
538
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000539 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000540 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000541 CaseRecVector& WorkList,
542 Value* SV,
543 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000544 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000545 CaseRecVector& WorkList,
546 Value* SV,
547 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000548 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000549 CaseRecVector& WorkList,
550 Value* SV,
551 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000552 bool handleBitTestsSwitchCase(CaseRec& CR,
553 CaseRecVector& WorkList,
554 Value* SV,
555 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000556 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000557 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
558 void visitBitTestCase(MachineBasicBlock* NextMBB,
559 unsigned Reg,
560 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000561 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000562 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
563 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000564
Chris Lattner1c08c712005-01-07 07:47:53 +0000565 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000566 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000567 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000568 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000569
Reid Spencer24d6da52007-01-21 00:29:26 +0000570 void visitScalarBinary(User &I, unsigned OpCode);
571 void visitVectorBinary(User &I, unsigned OpCode);
572 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000573 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000574 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000575 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000576 visitVectorBinary(I, ISD::VADD);
577 else if (I.getType()->isFloatingPoint())
578 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000579 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000580 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000581 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000582 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000583 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000584 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000585 visitVectorBinary(I, ISD::VMUL);
586 else if (I.getType()->isFloatingPoint())
587 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000588 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000589 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000590 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000591 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
592 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
593 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
594 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
595 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
596 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
597 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
598 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
599 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
600 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000601 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
602 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000603 void visitICmp(User &I);
604 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000605 // Visit the conversion instructions
606 void visitTrunc(User &I);
607 void visitZExt(User &I);
608 void visitSExt(User &I);
609 void visitFPTrunc(User &I);
610 void visitFPExt(User &I);
611 void visitFPToUI(User &I);
612 void visitFPToSI(User &I);
613 void visitUIToFP(User &I);
614 void visitSIToFP(User &I);
615 void visitPtrToInt(User &I);
616 void visitIntToPtr(User &I);
617 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000618
Chris Lattner2bbd8102006-03-29 00:11:43 +0000619 void visitExtractElement(User &I);
620 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000621 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000622
Chris Lattner1c08c712005-01-07 07:47:53 +0000623 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000624 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625
626 void visitMalloc(MallocInst &I);
627 void visitFree(FreeInst &I);
628 void visitAlloca(AllocaInst &I);
629 void visitLoad(LoadInst &I);
630 void visitStore(StoreInst &I);
631 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
632 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000633 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000634 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000635 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000636
Chris Lattner1c08c712005-01-07 07:47:53 +0000637 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000638 void visitVAArg(VAArgInst &I);
639 void visitVAEnd(CallInst &I);
640 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000641
Chris Lattner7041ee32005-01-11 05:56:49 +0000642 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000643
644 void visitUserOp1(Instruction &I) {
645 assert(0 && "UserOp1 should not exist at instruction selection time!");
646 abort();
647 }
648 void visitUserOp2(Instruction &I) {
649 assert(0 && "UserOp2 should not exist at instruction selection time!");
650 abort();
651 }
652};
653} // end namespace llvm
654
Chris Lattner199862b2006-03-16 19:57:50 +0000655SDOperand SelectionDAGLowering::getValue(const Value *V) {
656 SDOperand &N = NodeMap[V];
657 if (N.Val) return N;
658
659 const Type *VTy = V->getType();
660 MVT::ValueType VT = TLI.getValueType(VTy);
661 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
662 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
663 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000664 SDOperand N1 = NodeMap[V];
665 assert(N1.Val && "visit didn't populate the ValueMap!");
666 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000667 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
668 return N = DAG.getGlobalAddress(GV, VT);
669 } else if (isa<ConstantPointerNull>(C)) {
670 return N = DAG.getConstant(0, TLI.getPointerTy());
671 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000672 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000673 return N = DAG.getNode(ISD::UNDEF, VT);
674
Chris Lattnerb2827b02006-03-19 00:52:58 +0000675 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000676 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000677 unsigned NumElements = PTy->getNumElements();
678 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
679
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000680 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000681 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
682
683 // Create a VConstant node with generic Vector type.
684 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
685 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000686 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
687 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000688 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
689 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000690 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000691 unsigned NumElements = PTy->getNumElements();
692 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000693
694 // Now that we know the number and type of the elements, push a
695 // Constant or ConstantFP node onto the ops list for each element of
696 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000697 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000698 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000699 for (unsigned i = 0; i != NumElements; ++i)
700 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000701 } else {
702 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
703 SDOperand Op;
704 if (MVT::isFloatingPoint(PVT))
705 Op = DAG.getConstantFP(0, PVT);
706 else
707 Op = DAG.getConstant(0, PVT);
708 Ops.assign(NumElements, Op);
709 }
710
Chris Lattnerb2827b02006-03-19 00:52:58 +0000711 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000712 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
713 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000714 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
715 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000716 } else {
717 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000718 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000719 }
720 }
721
722 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
723 std::map<const AllocaInst*, int>::iterator SI =
724 FuncInfo.StaticAllocaMap.find(AI);
725 if (SI != FuncInfo.StaticAllocaMap.end())
726 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
727 }
728
Chris Lattner251db182007-02-25 18:40:32 +0000729 unsigned InReg = FuncInfo.ValueMap[V];
730 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000731
732 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000733 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000734 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000735 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000736 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000737 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
738 unsigned NumVals = TLI.getNumElements(VT);
739 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
740 if (NumVals == 1)
741 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
742 else {
743 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
744 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
745 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
746 }
747 } else {
748 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
749 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
750 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
751 N = MVT::isFloatingPoint(VT)
752 ? DAG.getNode(ISD::FP_ROUND, VT, N)
753 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000754 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000755 } else {
756 // Otherwise, if this is a vector, make it available as a generic vector
757 // here.
758 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000759 const VectorType *PTy = cast<VectorType>(VTy);
760 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000761 PTyLegalElementVT);
762
763 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000764 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000765 if (PTyElementVT == PTyLegalElementVT) {
766 // If the value types are legal, just VBUILD the CopyFromReg nodes.
767 for (unsigned i = 0; i != NE; ++i)
768 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
769 PTyElementVT));
770 } else if (PTyElementVT < PTyLegalElementVT) {
771 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
772 for (unsigned i = 0; i != NE; ++i) {
773 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
774 PTyElementVT);
775 if (MVT::isFloatingPoint(PTyElementVT))
776 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
777 else
778 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
779 Ops.push_back(Op);
780 }
781 } else {
782 // If the register was expanded, use BUILD_PAIR.
783 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
784 for (unsigned i = 0; i != NE/2; ++i) {
785 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
786 PTyElementVT);
787 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
788 PTyElementVT);
789 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
790 }
791 }
792
793 Ops.push_back(DAG.getConstant(NE, MVT::i32));
794 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000795 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000796
797 // Finally, use a VBIT_CONVERT to make this available as the appropriate
798 // vector type.
799 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
800 DAG.getConstant(PTy->getNumElements(),
801 MVT::i32),
802 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000803 }
804
805 return N;
806}
807
808
Chris Lattner1c08c712005-01-07 07:47:53 +0000809void SelectionDAGLowering::visitRet(ReturnInst &I) {
810 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000811 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000812 return;
813 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000814 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000815 NewValues.push_back(getRoot());
816 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
817 SDOperand RetOp = getValue(I.getOperand(i));
818
819 // If this is an integer return value, we need to promote it ourselves to
820 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
821 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000822 // FIXME: C calling convention requires the return type to be promoted to
823 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000824 if (MVT::isInteger(RetOp.getValueType()) &&
825 RetOp.getValueType() < MVT::i64) {
826 MVT::ValueType TmpVT;
827 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
828 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
829 else
830 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000831 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +0000832 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerbcca3402007-01-03 16:49:33 +0000833 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000834 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000835 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000836 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencer47857812006-12-31 05:55:36 +0000837 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000838 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000839 }
840 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000841 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000842 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000843 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
844 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000845}
846
Chris Lattner571e4342006-10-27 21:36:01 +0000847/// ExportFromCurrentBlock - If this condition isn't known to be exported from
848/// the current basic block, add it to ValueMap now so that we'll get a
849/// CopyTo/FromReg.
850void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
851 // No need to export constants.
852 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
853
854 // Already exported?
855 if (FuncInfo.isExportedInst(V)) return;
856
857 unsigned Reg = FuncInfo.InitializeRegForValue(V);
858 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
859}
860
Chris Lattner8c494ab2006-10-27 23:50:33 +0000861bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
862 const BasicBlock *FromBB) {
863 // The operands of the setcc have to be in this block. We don't know
864 // how to export them from some other block.
865 if (Instruction *VI = dyn_cast<Instruction>(V)) {
866 // Can export from current BB.
867 if (VI->getParent() == FromBB)
868 return true;
869
870 // Is already exported, noop.
871 return FuncInfo.isExportedInst(V);
872 }
873
874 // If this is an argument, we can export it if the BB is the entry block or
875 // if it is already exported.
876 if (isa<Argument>(V)) {
877 if (FromBB == &FromBB->getParent()->getEntryBlock())
878 return true;
879
880 // Otherwise, can only export this if it is already exported.
881 return FuncInfo.isExportedInst(V);
882 }
883
884 // Otherwise, constants can always be exported.
885 return true;
886}
887
Chris Lattner6a586c82006-10-29 21:01:20 +0000888static bool InBlock(const Value *V, const BasicBlock *BB) {
889 if (const Instruction *I = dyn_cast<Instruction>(V))
890 return I->getParent() == BB;
891 return true;
892}
893
Chris Lattner571e4342006-10-27 21:36:01 +0000894/// FindMergedConditions - If Cond is an expression like
895void SelectionDAGLowering::FindMergedConditions(Value *Cond,
896 MachineBasicBlock *TBB,
897 MachineBasicBlock *FBB,
898 MachineBasicBlock *CurBB,
899 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000900 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000901 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000902
Reid Spencere4d87aa2006-12-23 06:05:41 +0000903 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
904 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000905 BOp->getParent() != CurBB->getBasicBlock() ||
906 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
907 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000908 const BasicBlock *BB = CurBB->getBasicBlock();
909
Reid Spencere4d87aa2006-12-23 06:05:41 +0000910 // If the leaf of the tree is a comparison, merge the condition into
911 // the caseblock.
912 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
913 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000914 // how to export them from some other block. If this is the first block
915 // of the sequence, no exporting is needed.
916 (CurBB == CurMBB ||
917 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
918 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000919 BOp = cast<Instruction>(Cond);
920 ISD::CondCode Condition;
921 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
922 switch (IC->getPredicate()) {
923 default: assert(0 && "Unknown icmp predicate opcode!");
924 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
925 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
926 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
927 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
928 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
929 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
930 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
931 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
932 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
933 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
934 }
935 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
936 ISD::CondCode FPC, FOC;
937 switch (FC->getPredicate()) {
938 default: assert(0 && "Unknown fcmp predicate opcode!");
939 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
940 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
941 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
942 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
943 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
944 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
945 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
946 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
947 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
948 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
949 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
950 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
951 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
952 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
953 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
954 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
955 }
956 if (FiniteOnlyFPMath())
957 Condition = FOC;
958 else
959 Condition = FPC;
960 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000961 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000962 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000963 }
964
Chris Lattner571e4342006-10-27 21:36:01 +0000965 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000966 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000967 SwitchCases.push_back(CB);
968 return;
969 }
970
971 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000972 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000973 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000974 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000975 return;
976 }
977
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000978
979 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000980 MachineFunction::iterator BBI = CurBB;
981 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
982 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
983
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000984 if (Opc == Instruction::Or) {
985 // Codegen X | Y as:
986 // jmp_if_X TBB
987 // jmp TmpBB
988 // TmpBB:
989 // jmp_if_Y TBB
990 // jmp FBB
991 //
Chris Lattner571e4342006-10-27 21:36:01 +0000992
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000993 // Emit the LHS condition.
994 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
995
996 // Emit the RHS condition into TmpBB.
997 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
998 } else {
999 assert(Opc == Instruction::And && "Unknown merge op!");
1000 // Codegen X & Y as:
1001 // jmp_if_X TmpBB
1002 // jmp FBB
1003 // TmpBB:
1004 // jmp_if_Y TBB
1005 // jmp FBB
1006 //
1007 // This requires creation of TmpBB after CurBB.
1008
1009 // Emit the LHS condition.
1010 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1011
1012 // Emit the RHS condition into TmpBB.
1013 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1014 }
Chris Lattner571e4342006-10-27 21:36:01 +00001015}
1016
Chris Lattnerdf19f272006-10-31 22:37:42 +00001017/// If the set of cases should be emitted as a series of branches, return true.
1018/// If we should emit this as a bunch of and/or'd together conditions, return
1019/// false.
1020static bool
1021ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1022 if (Cases.size() != 2) return true;
1023
Chris Lattner0ccb5002006-10-31 23:06:00 +00001024 // If this is two comparisons of the same values or'd or and'd together, they
1025 // will get folded into a single comparison, so don't emit two blocks.
1026 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1027 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1028 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1029 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1030 return false;
1031 }
1032
Chris Lattnerdf19f272006-10-31 22:37:42 +00001033 return true;
1034}
1035
Chris Lattner1c08c712005-01-07 07:47:53 +00001036void SelectionDAGLowering::visitBr(BranchInst &I) {
1037 // Update machine-CFG edges.
1038 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001039
1040 // Figure out which block is immediately after the current one.
1041 MachineBasicBlock *NextBlock = 0;
1042 MachineFunction::iterator BBI = CurMBB;
1043 if (++BBI != CurMBB->getParent()->end())
1044 NextBlock = BBI;
1045
1046 if (I.isUnconditional()) {
1047 // If this is not a fall-through branch, emit the branch.
1048 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001049 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001050 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001051
Chris Lattner57ab6592006-10-24 17:57:59 +00001052 // Update machine-CFG edges.
1053 CurMBB->addSuccessor(Succ0MBB);
1054
1055 return;
1056 }
1057
1058 // If this condition is one of the special cases we handle, do special stuff
1059 // now.
1060 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001061 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001062
1063 // If this is a series of conditions that are or'd or and'd together, emit
1064 // this as a sequence of branches instead of setcc's with and/or operations.
1065 // For example, instead of something like:
1066 // cmp A, B
1067 // C = seteq
1068 // cmp D, E
1069 // F = setle
1070 // or C, F
1071 // jnz foo
1072 // Emit:
1073 // cmp A, B
1074 // je foo
1075 // cmp D, E
1076 // jle foo
1077 //
1078 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1079 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001080 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001081 BOp->getOpcode() == Instruction::Or)) {
1082 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001083 // If the compares in later blocks need to use values not currently
1084 // exported from this block, export them now. This block should always
1085 // be the first entry.
1086 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1087
Chris Lattnerdf19f272006-10-31 22:37:42 +00001088 // Allow some cases to be rejected.
1089 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001090 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1091 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1092 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1093 }
1094
1095 // Emit the branch for this block.
1096 visitSwitchCase(SwitchCases[0]);
1097 SwitchCases.erase(SwitchCases.begin());
1098 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001099 }
1100
Chris Lattner0ccb5002006-10-31 23:06:00 +00001101 // Okay, we decided not to do this, remove any inserted MBB's and clear
1102 // SwitchCases.
1103 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1104 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1105
Chris Lattnerdf19f272006-10-31 22:37:42 +00001106 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001107 }
1108 }
Chris Lattner24525952006-10-24 18:07:37 +00001109
1110 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001111 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001112 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001113 // Use visitSwitchCase to actually insert the fast branch sequence for this
1114 // cond branch.
1115 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001116}
1117
Nate Begemanf15485a2006-03-27 01:32:24 +00001118/// visitSwitchCase - Emits the necessary code to represent a single node in
1119/// the binary search tree resulting from lowering a switch instruction.
1120void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001121 SDOperand Cond;
1122 SDOperand CondLHS = getValue(CB.CmpLHS);
1123
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001124 // Build the setcc now.
1125 if (CB.CmpMHS == NULL) {
1126 // Fold "(X == true)" to X and "(X == false)" to !X to
1127 // handle common cases produced by branch lowering.
1128 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1129 Cond = CondLHS;
1130 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1131 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1132 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1133 } else
1134 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1135 } else {
1136 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001137
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001138 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1139 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1140
1141 SDOperand CmpOp = getValue(CB.CmpMHS);
1142 MVT::ValueType VT = CmpOp.getValueType();
1143
1144 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1145 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1146 } else {
1147 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1148 Cond = DAG.getSetCC(MVT::i1, SUB,
1149 DAG.getConstant(High-Low, VT), ISD::SETULE);
1150 }
1151
1152 }
1153
Nate Begemanf15485a2006-03-27 01:32:24 +00001154 // Set NextBlock to be the MBB immediately after the current one, if any.
1155 // This is used to avoid emitting unnecessary branches to the next block.
1156 MachineBasicBlock *NextBlock = 0;
1157 MachineFunction::iterator BBI = CurMBB;
1158 if (++BBI != CurMBB->getParent()->end())
1159 NextBlock = BBI;
1160
1161 // If the lhs block is the next block, invert the condition so that we can
1162 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001163 if (CB.TrueBB == NextBlock) {
1164 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001165 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1166 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1167 }
1168 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001169 DAG.getBasicBlock(CB.TrueBB));
1170 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001171 DAG.setRoot(BrCond);
1172 else
1173 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001174 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001175 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001176 CurMBB->addSuccessor(CB.TrueBB);
1177 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001178}
1179
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001180/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001181void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001182 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001183 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001184 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001185 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1186 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1187 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1188 Table, Index));
1189 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001190}
1191
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001192/// visitJumpTableHeader - This function emits necessary code to produce index
1193/// in the JumpTable from switch case.
1194void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1195 SelectionDAGISel::JumpTableHeader &JTH) {
1196 // Subtract the lowest switch case value from the value being switched on
1197 // and conditional branch to default mbb if the result is greater than the
1198 // difference between smallest and largest cases.
1199 SDOperand SwitchOp = getValue(JTH.SValue);
1200 MVT::ValueType VT = SwitchOp.getValueType();
1201 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1202 DAG.getConstant(JTH.First, VT));
1203
1204 // The SDNode we just created, which holds the value being switched on
1205 // minus the the smallest case value, needs to be copied to a virtual
1206 // register so it can be used as an index into the jump table in a
1207 // subsequent basic block. This value may be smaller or larger than the
1208 // target's pointer type, and therefore require extension or truncating.
1209 if (VT > TLI.getPointerTy())
1210 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1211 else
1212 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1213
1214 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1215 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1216 JT.Reg = JumpTableReg;
1217
1218 // Emit the range check for the jump table, and branch to the default
1219 // block for the switch statement if the value being switched on exceeds
1220 // the largest case in the switch.
1221 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1222 DAG.getConstant(JTH.Last-JTH.First,VT),
1223 ISD::SETUGT);
1224
1225 // Set NextBlock to be the MBB immediately after the current one, if any.
1226 // This is used to avoid emitting unnecessary branches to the next block.
1227 MachineBasicBlock *NextBlock = 0;
1228 MachineFunction::iterator BBI = CurMBB;
1229 if (++BBI != CurMBB->getParent()->end())
1230 NextBlock = BBI;
1231
1232 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1233 DAG.getBasicBlock(JT.Default));
1234
1235 if (JT.MBB == NextBlock)
1236 DAG.setRoot(BrCond);
1237 else
1238 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001239 DAG.getBasicBlock(JT.MBB)));
1240
1241 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001242}
1243
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001244/// visitBitTestHeader - This function emits necessary code to produce value
1245/// suitable for "bit tests"
1246void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1247 // Subtract the minimum value
1248 SDOperand SwitchOp = getValue(B.SValue);
1249 MVT::ValueType VT = SwitchOp.getValueType();
1250 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1251 DAG.getConstant(B.First, VT));
1252
1253 // Check range
1254 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1255 DAG.getConstant(B.Range, VT),
1256 ISD::SETUGT);
1257
1258 SDOperand ShiftOp;
1259 if (VT > TLI.getShiftAmountTy())
1260 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1261 else
1262 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1263
1264 // Make desired shift
1265 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1266 DAG.getConstant(1, TLI.getPointerTy()),
1267 ShiftOp);
1268
1269 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1270 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1271 B.Reg = SwitchReg;
1272
1273 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1274 DAG.getBasicBlock(B.Default));
1275
1276 // Set NextBlock to be the MBB immediately after the current one, if any.
1277 // This is used to avoid emitting unnecessary branches to the next block.
1278 MachineBasicBlock *NextBlock = 0;
1279 MachineFunction::iterator BBI = CurMBB;
1280 if (++BBI != CurMBB->getParent()->end())
1281 NextBlock = BBI;
1282
1283 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1284 if (MBB == NextBlock)
1285 DAG.setRoot(BrRange);
1286 else
1287 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1288 DAG.getBasicBlock(MBB)));
1289
1290 CurMBB->addSuccessor(B.Default);
1291 CurMBB->addSuccessor(MBB);
1292
1293 return;
1294}
1295
1296/// visitBitTestCase - this function produces one "bit test"
1297void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1298 unsigned Reg,
1299 SelectionDAGISel::BitTestCase &B) {
1300 // Emit bit tests and jumps
1301 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1302
1303 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1304 SwitchVal,
1305 DAG.getConstant(B.Mask,
1306 TLI.getPointerTy()));
1307 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1308 DAG.getConstant(0, TLI.getPointerTy()),
1309 ISD::SETNE);
1310 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1311 AndCmp, DAG.getBasicBlock(B.TargetBB));
1312
1313 // Set NextBlock to be the MBB immediately after the current one, if any.
1314 // This is used to avoid emitting unnecessary branches to the next block.
1315 MachineBasicBlock *NextBlock = 0;
1316 MachineFunction::iterator BBI = CurMBB;
1317 if (++BBI != CurMBB->getParent()->end())
1318 NextBlock = BBI;
1319
1320 if (NextMBB == NextBlock)
1321 DAG.setRoot(BrAnd);
1322 else
1323 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1324 DAG.getBasicBlock(NextMBB)));
1325
1326 CurMBB->addSuccessor(B.TargetBB);
1327 CurMBB->addSuccessor(NextMBB);
1328
1329 return;
1330}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001331
Jim Laskeyb180aa12007-02-21 22:53:45 +00001332void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001333 assert(0 && "Should never be visited directly");
1334}
1335void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001336 // Retrieve successors.
1337 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1338 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1339
Jim Laskey183f47f2007-02-25 21:43:59 +00001340 if (!AsTerminator) {
1341 // Mark landing pad so that it doesn't get deleted in branch folding.
1342 LandingPad->setIsLandingPad();
1343
1344 // Insert a label before the invoke call to mark the try range.
1345 // This can be used to detect deletion of the invoke via the
1346 // MachineModuleInfo.
1347 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1348 unsigned BeginLabel = MMI->NextLabelID();
1349 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1350 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001351
Jim Laskey183f47f2007-02-25 21:43:59 +00001352 LowerCallTo(I, I.getCalledValue()->getType(),
1353 I.getCallingConv(),
1354 false,
1355 getValue(I.getOperand(0)),
1356 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001357
Jim Laskey183f47f2007-02-25 21:43:59 +00001358 // Insert a label before the invoke call to mark the try range.
1359 // This can be used to detect deletion of the invoke via the
1360 // MachineModuleInfo.
1361 unsigned EndLabel = MMI->NextLabelID();
1362 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1363 DAG.getConstant(EndLabel, MVT::i32)));
1364
1365 // Inform MachineModuleInfo of range.
1366 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1367
1368 // Update successor info
1369 CurMBB->addSuccessor(Return);
1370 CurMBB->addSuccessor(LandingPad);
1371 } else {
1372 // Drop into normal successor.
1373 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1374 DAG.getBasicBlock(Return)));
1375 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001376}
1377
1378void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1379}
1380
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001381/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001382/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001383bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001384 CaseRecVector& WorkList,
1385 Value* SV,
1386 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001387 Case& BackCase = *(CR.Range.second-1);
1388
1389 // Size is the number of Cases represented by this range.
1390 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001391 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001392 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001393
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001394 // Get the MachineFunction which holds the current MBB. This is used when
1395 // inserting any additional MBBs necessary to represent the switch.
1396 MachineFunction *CurMF = CurMBB->getParent();
1397
1398 // Figure out which block is immediately after the current one.
1399 MachineBasicBlock *NextBlock = 0;
1400 MachineFunction::iterator BBI = CR.CaseBB;
1401
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001402 if (++BBI != CurMBB->getParent()->end())
1403 NextBlock = BBI;
1404
1405 // TODO: If any two of the cases has the same destination, and if one value
1406 // is the same as the other, but has one bit unset that the other has set,
1407 // use bit manipulation to do two compares at once. For example:
1408 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1409
1410 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001411 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001412 // The last case block won't fall through into 'NextBlock' if we emit the
1413 // branches in this order. See if rearranging a case value would help.
1414 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001415 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001416 std::swap(*I, BackCase);
1417 break;
1418 }
1419 }
1420 }
1421
1422 // Create a CaseBlock record representing a conditional branch to
1423 // the Case's target mbb if the value being switched on SV is equal
1424 // to C.
1425 MachineBasicBlock *CurBlock = CR.CaseBB;
1426 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1427 MachineBasicBlock *FallThrough;
1428 if (I != E-1) {
1429 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1430 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1431 } else {
1432 // If the last case doesn't match, go to the default block.
1433 FallThrough = Default;
1434 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001435
1436 Value *RHS, *LHS, *MHS;
1437 ISD::CondCode CC;
1438 if (I->High == I->Low) {
1439 // This is just small small case range :) containing exactly 1 case
1440 CC = ISD::SETEQ;
1441 LHS = SV; RHS = I->High; MHS = NULL;
1442 } else {
1443 CC = ISD::SETLE;
1444 LHS = I->Low; MHS = SV; RHS = I->High;
1445 }
1446 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1447 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001448
1449 // If emitting the first comparison, just call visitSwitchCase to emit the
1450 // code into the current block. Otherwise, push the CaseBlock onto the
1451 // vector to be later processed by SDISel, and insert the node's MBB
1452 // before the next MBB.
1453 if (CurBlock == CurMBB)
1454 visitSwitchCase(CB);
1455 else
1456 SwitchCases.push_back(CB);
1457
1458 CurBlock = FallThrough;
1459 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001460
1461 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001462}
1463
1464/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001465bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001466 CaseRecVector& WorkList,
1467 Value* SV,
1468 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001469 Case& FrontCase = *CR.Range.first;
1470 Case& BackCase = *(CR.Range.second-1);
1471
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001472 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1473 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1474
1475 uint64_t TSize = 0;
1476 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1477 I!=E; ++I)
1478 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001479
1480 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1481 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001482 TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001483 return false;
1484
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001485 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1486 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001487 return false;
1488
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001489 DOUT << "Lowering jump table\n"
1490 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001491 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001492
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001493 // Get the MachineFunction which holds the current MBB. This is used when
1494 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001495 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001496
1497 // Figure out which block is immediately after the current one.
1498 MachineBasicBlock *NextBlock = 0;
1499 MachineFunction::iterator BBI = CR.CaseBB;
1500
1501 if (++BBI != CurMBB->getParent()->end())
1502 NextBlock = BBI;
1503
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001504 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1505
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001506 // Create a new basic block to hold the code for loading the address
1507 // of the jump table, and jumping to it. Update successor information;
1508 // we will either branch to the default case for the switch, or the jump
1509 // table.
1510 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1511 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1512 CR.CaseBB->addSuccessor(Default);
1513 CR.CaseBB->addSuccessor(JumpTableBB);
1514
1515 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001516 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001517 // a case statement, push the case's BB onto the vector, otherwise, push
1518 // the default BB.
1519 std::vector<MachineBasicBlock*> DestBBs;
1520 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001521 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1522 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1523 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1524
1525 if ((Low <= TEI) && (TEI <= High)) {
1526 DestBBs.push_back(I->BB);
1527 if (TEI==High)
1528 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001529 } else {
1530 DestBBs.push_back(Default);
1531 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001532 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001533
1534 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001535 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001536 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1537 E = DestBBs.end(); I != E; ++I) {
1538 if (!SuccsHandled[(*I)->getNumber()]) {
1539 SuccsHandled[(*I)->getNumber()] = true;
1540 JumpTableBB->addSuccessor(*I);
1541 }
1542 }
1543
1544 // Create a jump table index for this jump table, or return an existing
1545 // one.
1546 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1547
1548 // Set the jump table information so that we can codegen it as a second
1549 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001550 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001551 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1552 (CR.CaseBB == CurMBB));
1553 if (CR.CaseBB == CurMBB)
1554 visitJumpTableHeader(JT, JTH);
1555
1556 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001557
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001558 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001559}
1560
1561/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1562/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001563bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001564 CaseRecVector& WorkList,
1565 Value* SV,
1566 MachineBasicBlock* Default) {
1567 // Get the MachineFunction which holds the current MBB. This is used when
1568 // inserting any additional MBBs necessary to represent the switch.
1569 MachineFunction *CurMF = CurMBB->getParent();
1570
1571 // Figure out which block is immediately after the current one.
1572 MachineBasicBlock *NextBlock = 0;
1573 MachineFunction::iterator BBI = CR.CaseBB;
1574
1575 if (++BBI != CurMBB->getParent()->end())
1576 NextBlock = BBI;
1577
1578 Case& FrontCase = *CR.Range.first;
1579 Case& BackCase = *(CR.Range.second-1);
1580 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1581
1582 // Size is the number of Cases represented by this range.
1583 unsigned Size = CR.Range.second - CR.Range.first;
1584
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001585 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1586 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001587 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001588 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001589
1590 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1591 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001592 uint64_t TSize = 0;
1593 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1594 I!=E; ++I)
1595 TSize += I->size();
1596
1597 uint64_t LSize = FrontCase.size();
1598 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001599 DOUT << "Selecting best pivot: \n"
1600 << "First: " << First << ", Last: " << Last <<"\n"
1601 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001602 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001603 J!=E; ++I, ++J) {
1604 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1605 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001606 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001607 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1608 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001609 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001610 // Should always split in some non-trivial place
1611 DOUT <<"=>Step\n"
1612 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1613 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1614 << "Metric: " << Metric << "\n";
1615 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001616 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001617 FMetric = Metric;
1618 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001619 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001620
1621 LSize += J->size();
1622 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001623 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001624 // If our case is dense we *really* should handle it earlier!
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001625 assert((FMetric > 0) && "Should handle dense range earlier!");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001626
1627 CaseRange LHSR(CR.Range.first, Pivot);
1628 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001629 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001630 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1631
1632 // We know that we branch to the LHS if the Value being switched on is
1633 // less than the Pivot value, C. We use this to optimize our binary
1634 // tree a bit, by recognizing that if SV is greater than or equal to the
1635 // LHS's Case Value, and that Case Value is exactly one less than the
1636 // Pivot's Value, then we can branch directly to the LHS's Target,
1637 // rather than creating a leaf node for it.
1638 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001639 LHSR.first->High == CR.GE &&
1640 cast<ConstantInt>(C)->getSExtValue() ==
1641 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1642 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001643 } else {
1644 TrueBB = new MachineBasicBlock(LLVMBB);
1645 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1646 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1647 }
1648
1649 // Similar to the optimization above, if the Value being switched on is
1650 // known to be less than the Constant CR.LT, and the current Case Value
1651 // is CR.LT - 1, then we can branch directly to the target block for
1652 // the current Case Value, rather than emitting a RHS leaf node for it.
1653 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001654 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1655 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1656 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001657 } else {
1658 FalseBB = new MachineBasicBlock(LLVMBB);
1659 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1660 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1661 }
1662
1663 // Create a CaseBlock record representing a conditional branch to
1664 // the LHS node if the value being switched on SV is less than C.
1665 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001666 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1667 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001668
1669 if (CR.CaseBB == CurMBB)
1670 visitSwitchCase(CB);
1671 else
1672 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001673
1674 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001675}
1676
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001677/// handleBitTestsSwitchCase - if current case range has few destination and
1678/// range span less, than machine word bitwidth, encode case range into series
1679/// of masks and emit bit tests with these masks.
1680bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1681 CaseRecVector& WorkList,
1682 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001683 MachineBasicBlock* Default){
Chris Lattner1c359682007-04-14 19:39:41 +00001684 return false;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001685 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1686
1687 Case& FrontCase = *CR.Range.first;
1688 Case& BackCase = *(CR.Range.second-1);
1689
1690 // Get the MachineFunction which holds the current MBB. This is used when
1691 // inserting any additional MBBs necessary to represent the switch.
1692 MachineFunction *CurMF = CurMBB->getParent();
1693
1694 unsigned numCmps = 0;
1695 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1696 I!=E; ++I) {
1697 // Single case counts one, case range - two.
1698 if (I->Low == I->High)
1699 numCmps +=1;
1700 else
1701 numCmps +=2;
1702 }
1703
1704 // Count unique destinations
1705 SmallSet<MachineBasicBlock*, 4> Dests;
1706 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1707 Dests.insert(I->BB);
1708 if (Dests.size() > 3)
1709 // Don't bother the code below, if there are too much unique destinations
1710 return false;
1711 }
1712 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1713 << "Total number of comparisons: " << numCmps << "\n";
1714
1715 // Compute span of values.
1716 Constant* minValue = FrontCase.Low;
1717 Constant* maxValue = BackCase.High;
1718 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1719 cast<ConstantInt>(minValue)->getSExtValue();
1720 DOUT << "Compare range: " << range << "\n"
1721 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1722 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1723
1724 if (range>IntPtrBits ||
1725 (!(Dests.size() == 1 && numCmps >= 3) &&
1726 !(Dests.size() == 2 && numCmps >= 5) &&
1727 !(Dests.size() >= 3 && numCmps >= 6)))
1728 return false;
1729
1730 DOUT << "Emitting bit tests\n";
1731 int64_t lowBound = 0;
1732
1733 // Optimize the case where all the case values fit in a
1734 // word without having to subtract minValue. In this case,
1735 // we can optimize away the subtraction.
1736 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001737 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001738 range = cast<ConstantInt>(maxValue)->getSExtValue();
1739 } else {
1740 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1741 }
1742
1743 CaseBitsVector CasesBits;
1744 unsigned i, count = 0;
1745
1746 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1747 MachineBasicBlock* Dest = I->BB;
1748 for (i = 0; i < count; ++i)
1749 if (Dest == CasesBits[i].BB)
1750 break;
1751
1752 if (i == count) {
1753 assert((count < 3) && "Too much destinations to test!");
1754 CasesBits.push_back(CaseBits(0, Dest, 0));
1755 count++;
1756 }
1757
1758 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1759 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1760
1761 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001762 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001763 CasesBits[i].Bits++;
1764 }
1765
1766 }
1767 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1768
1769 SelectionDAGISel::BitTestInfo BTC;
1770
1771 // Figure out which block is immediately after the current one.
1772 MachineFunction::iterator BBI = CR.CaseBB;
1773 ++BBI;
1774
1775 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1776
1777 DOUT << "Cases:\n";
1778 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1779 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1780 << ", BB: " << CasesBits[i].BB << "\n";
1781
1782 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1783 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1784 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1785 CaseBB,
1786 CasesBits[i].BB));
1787 }
1788
1789 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00001790 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001791 CR.CaseBB, Default, BTC);
1792
1793 if (CR.CaseBB == CurMBB)
1794 visitBitTestHeader(BTB);
1795
1796 BitTestCases.push_back(BTB);
1797
1798 return true;
1799}
1800
1801
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001802// Clusterify - Transform simple list of Cases into list of CaseRange's
1803unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1804 const SwitchInst& SI) {
1805 unsigned numCmps = 0;
1806
1807 // Start with "simple" cases
1808 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1809 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1810 Cases.push_back(Case(SI.getSuccessorValue(i),
1811 SI.getSuccessorValue(i),
1812 SMBB));
1813 }
1814 sort(Cases.begin(), Cases.end(), CaseCmp());
1815
1816 // Merge case into clusters
1817 if (Cases.size()>=2)
1818 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1819 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1820 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1821 MachineBasicBlock* nextBB = J->BB;
1822 MachineBasicBlock* currentBB = I->BB;
1823
1824 // If the two neighboring cases go to the same destination, merge them
1825 // into a single case.
1826 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1827 I->High = J->High;
1828 J = Cases.erase(J);
1829 } else {
1830 I = J++;
1831 }
1832 }
1833
1834 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1835 if (I->Low != I->High)
1836 // A range counts double, since it requires two compares.
1837 ++numCmps;
1838 }
1839
1840 return numCmps;
1841}
1842
1843void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001844 // Figure out which block is immediately after the current one.
1845 MachineBasicBlock *NextBlock = 0;
1846 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001847
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001848 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001849
Nate Begemanf15485a2006-03-27 01:32:24 +00001850 // If there is only the default destination, branch to it if it is not the
1851 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001852 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001853 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001854
Nate Begemanf15485a2006-03-27 01:32:24 +00001855 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001856 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001857 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001858 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001859
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001860 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001861 return;
1862 }
1863
1864 // If there are any non-default case statements, create a vector of Cases
1865 // representing each one, and sort the vector so that we can efficiently
1866 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001867 CaseVector Cases;
1868 unsigned numCmps = Clusterify(Cases, SI);
1869 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1870 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001871
Nate Begemanf15485a2006-03-27 01:32:24 +00001872 // Get the Value to be switched on and default basic blocks, which will be
1873 // inserted into CaseBlock records, representing basic blocks in the binary
1874 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001875 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001876
Nate Begemanf15485a2006-03-27 01:32:24 +00001877 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001878 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001879 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1880
1881 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001882 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001883 CaseRec CR = WorkList.back();
1884 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001885
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001886 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1887 continue;
1888
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001889 // If the range has few cases (two or less) emit a series of specific
1890 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001891 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1892 continue;
1893
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001894 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001895 // target supports indirect branches, then emit a jump table rather than
1896 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001897 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1898 continue;
1899
1900 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1901 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1902 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001903 }
1904}
1905
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001906
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001907void SelectionDAGLowering::visitSub(User &I) {
1908 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001909 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001910 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001911 visitVectorBinary(I, ISD::VSUB);
1912 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001913 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1914 if (CFP->isExactlyValue(-0.0)) {
1915 SDOperand Op2 = getValue(I.getOperand(1));
1916 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1917 return;
1918 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001919 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001920 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001921 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001922}
1923
Reid Spencer24d6da52007-01-21 00:29:26 +00001924void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001925 SDOperand Op1 = getValue(I.getOperand(0));
1926 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001927
1928 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001929}
1930
Reid Spencer24d6da52007-01-21 00:29:26 +00001931void
1932SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001933 assert(isa<VectorType>(I.getType()));
1934 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001935 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001936
Reid Spencer24d6da52007-01-21 00:29:26 +00001937 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1938 getValue(I.getOperand(0)),
1939 getValue(I.getOperand(1)),
1940 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1941 Typ));
1942}
1943
1944void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1945 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001946 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001947 visitVectorBinary(I, VectorOp);
1948 else
1949 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001950}
Chris Lattner2c49f272005-01-19 22:31:21 +00001951
Nate Begemane21ea612005-11-18 07:42:56 +00001952void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1953 SDOperand Op1 = getValue(I.getOperand(0));
1954 SDOperand Op2 = getValue(I.getOperand(1));
1955
Reid Spencer832254e2007-02-02 02:16:23 +00001956 if (TLI.getShiftAmountTy() < Op2.getValueType())
1957 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1958 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1959 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001960
Chris Lattner1c08c712005-01-07 07:47:53 +00001961 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1962}
1963
Reid Spencer45fb3f32006-11-20 01:22:35 +00001964void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001965 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1966 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1967 predicate = IC->getPredicate();
1968 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1969 predicate = ICmpInst::Predicate(IC->getPredicate());
1970 SDOperand Op1 = getValue(I.getOperand(0));
1971 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001972 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001973 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001974 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1975 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1976 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1977 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1978 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1979 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1980 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1981 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1982 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1983 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1984 default:
1985 assert(!"Invalid ICmp predicate value");
1986 Opcode = ISD::SETEQ;
1987 break;
1988 }
1989 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1990}
1991
1992void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001993 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1994 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1995 predicate = FC->getPredicate();
1996 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1997 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001998 SDOperand Op1 = getValue(I.getOperand(0));
1999 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000 ISD::CondCode Condition, FOC, FPC;
2001 switch (predicate) {
2002 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2003 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2004 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2005 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2006 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2007 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2008 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2009 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2010 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2011 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2012 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2013 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2014 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2015 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2016 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2017 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2018 default:
2019 assert(!"Invalid FCmp predicate value");
2020 FOC = FPC = ISD::SETFALSE;
2021 break;
2022 }
2023 if (FiniteOnlyFPMath())
2024 Condition = FOC;
2025 else
2026 Condition = FPC;
2027 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002028}
2029
2030void SelectionDAGLowering::visitSelect(User &I) {
2031 SDOperand Cond = getValue(I.getOperand(0));
2032 SDOperand TrueVal = getValue(I.getOperand(1));
2033 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00002034 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00002035 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2036 TrueVal, FalseVal));
2037 } else {
2038 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2039 *(TrueVal.Val->op_end()-2),
2040 *(TrueVal.Val->op_end()-1)));
2041 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002042}
2043
Reid Spencer3da59db2006-11-27 01:05:10 +00002044
2045void SelectionDAGLowering::visitTrunc(User &I) {
2046 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2047 SDOperand N = getValue(I.getOperand(0));
2048 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2049 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2050}
2051
2052void SelectionDAGLowering::visitZExt(User &I) {
2053 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2054 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2055 SDOperand N = getValue(I.getOperand(0));
2056 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2057 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2058}
2059
2060void SelectionDAGLowering::visitSExt(User &I) {
2061 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2062 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2063 SDOperand N = getValue(I.getOperand(0));
2064 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2065 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2066}
2067
2068void SelectionDAGLowering::visitFPTrunc(User &I) {
2069 // FPTrunc is never a no-op cast, no need to check
2070 SDOperand N = getValue(I.getOperand(0));
2071 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2072 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2073}
2074
2075void SelectionDAGLowering::visitFPExt(User &I){
2076 // FPTrunc is never a no-op cast, no need to check
2077 SDOperand N = getValue(I.getOperand(0));
2078 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2079 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2080}
2081
2082void SelectionDAGLowering::visitFPToUI(User &I) {
2083 // FPToUI is never a no-op cast, no need to check
2084 SDOperand N = getValue(I.getOperand(0));
2085 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2086 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2087}
2088
2089void SelectionDAGLowering::visitFPToSI(User &I) {
2090 // FPToSI is never a no-op cast, no need to check
2091 SDOperand N = getValue(I.getOperand(0));
2092 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2093 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2094}
2095
2096void SelectionDAGLowering::visitUIToFP(User &I) {
2097 // UIToFP is never a no-op cast, no need to check
2098 SDOperand N = getValue(I.getOperand(0));
2099 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2100 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2101}
2102
2103void SelectionDAGLowering::visitSIToFP(User &I){
2104 // UIToFP is never a no-op cast, no need to check
2105 SDOperand N = getValue(I.getOperand(0));
2106 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2107 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2108}
2109
2110void SelectionDAGLowering::visitPtrToInt(User &I) {
2111 // What to do depends on the size of the integer and the size of the pointer.
2112 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002113 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002114 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002115 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002116 SDOperand Result;
2117 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2118 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2119 else
2120 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2121 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2122 setValue(&I, Result);
2123}
Chris Lattner1c08c712005-01-07 07:47:53 +00002124
Reid Spencer3da59db2006-11-27 01:05:10 +00002125void SelectionDAGLowering::visitIntToPtr(User &I) {
2126 // What to do depends on the size of the integer and the size of the pointer.
2127 // We can either truncate, zero extend, or no-op, accordingly.
2128 SDOperand N = getValue(I.getOperand(0));
2129 MVT::ValueType SrcVT = N.getValueType();
2130 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2131 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2132 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2133 else
2134 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2135 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2136}
2137
2138void SelectionDAGLowering::visitBitCast(User &I) {
2139 SDOperand N = getValue(I.getOperand(0));
2140 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002141 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002142 // This is a cast to a vector from something else.
2143 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002144 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002145 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2146 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2147 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2148 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002149 return;
2150 }
2151 MVT::ValueType SrcVT = N.getValueType();
2152 if (SrcVT == MVT::Vector) {
2153 // This is a cast from a vctor to something else.
2154 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00002155 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00002156 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002157 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002158
2159 // BitCast assures us that source and destination are the same size so this
2160 // is either a BIT_CONVERT or a no-op.
2161 if (DestVT != N.getValueType())
2162 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2163 else
2164 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002165}
2166
Chris Lattner2bbd8102006-03-29 00:11:43 +00002167void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002168 SDOperand InVec = getValue(I.getOperand(0));
2169 SDOperand InVal = getValue(I.getOperand(1));
2170 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2171 getValue(I.getOperand(2)));
2172
Chris Lattner2332b9f2006-03-19 01:17:20 +00002173 SDOperand Num = *(InVec.Val->op_end()-2);
2174 SDOperand Typ = *(InVec.Val->op_end()-1);
2175 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2176 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00002177}
2178
Chris Lattner2bbd8102006-03-29 00:11:43 +00002179void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002180 SDOperand InVec = getValue(I.getOperand(0));
2181 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2182 getValue(I.getOperand(1)));
2183 SDOperand Typ = *(InVec.Val->op_end()-1);
2184 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2185 TLI.getValueType(I.getType()), InVec, InIdx));
2186}
Chris Lattnerc7029802006-03-18 01:44:44 +00002187
Chris Lattner3e104b12006-04-08 04:15:24 +00002188void SelectionDAGLowering::visitShuffleVector(User &I) {
2189 SDOperand V1 = getValue(I.getOperand(0));
2190 SDOperand V2 = getValue(I.getOperand(1));
2191 SDOperand Mask = getValue(I.getOperand(2));
2192
2193 SDOperand Num = *(V1.Val->op_end()-2);
2194 SDOperand Typ = *(V2.Val->op_end()-1);
2195 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2196 V1, V2, Mask, Num, Typ));
2197}
2198
2199
Chris Lattner1c08c712005-01-07 07:47:53 +00002200void SelectionDAGLowering::visitGetElementPtr(User &I) {
2201 SDOperand N = getValue(I.getOperand(0));
2202 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002203
2204 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2205 OI != E; ++OI) {
2206 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002207 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002208 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002209 if (Field) {
2210 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002211 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002212 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00002213 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002214 }
2215 Ty = StTy->getElementType(Field);
2216 } else {
2217 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002218
Chris Lattner7c0104b2005-11-09 04:45:33 +00002219 // If this is a constant subscript, handle it quickly.
2220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002221 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002222 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00002223 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00002224 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2225 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002226 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002227
2228 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00002229 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002230 SDOperand IdxN = getValue(Idx);
2231
2232 // If the index is smaller or larger than intptr_t, truncate or extend
2233 // it.
2234 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002235 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002236 } else if (IdxN.getValueType() > N.getValueType())
2237 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2238
2239 // If this is a multiply by a power of two, turn it into a shl
2240 // immediately. This is a very common case.
2241 if (isPowerOf2_64(ElementSize)) {
2242 unsigned Amt = Log2_64(ElementSize);
2243 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002244 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002245 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2246 continue;
2247 }
2248
2249 SDOperand Scale = getIntPtrConstant(ElementSize);
2250 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2251 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002252 }
2253 }
2254 setValue(&I, N);
2255}
2256
2257void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2258 // If this is a fixed sized alloca in the entry block of the function,
2259 // allocate it statically on the stack.
2260 if (FuncInfo.StaticAllocaMap.count(&I))
2261 return; // getValue will auto-populate this.
2262
2263 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00002264 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002265 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002266 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002267 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002268
2269 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002270 MVT::ValueType IntPtr = TLI.getPointerTy();
2271 if (IntPtr < AllocSize.getValueType())
2272 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2273 else if (IntPtr > AllocSize.getValueType())
2274 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002275
Chris Lattner68cd65e2005-01-22 23:04:37 +00002276 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00002277 getIntPtrConstant(TySize));
2278
2279 // Handle alignment. If the requested alignment is less than or equal to the
2280 // stack alignment, ignore it and round the size of the allocation up to the
2281 // stack alignment size. If the size is greater than the stack alignment, we
2282 // note this in the DYNAMIC_STACKALLOC node.
2283 unsigned StackAlign =
2284 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2285 if (Align <= StackAlign) {
2286 Align = 0;
2287 // Add SA-1 to the size.
2288 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2289 getIntPtrConstant(StackAlign-1));
2290 // Mask out the low bits for alignment purposes.
2291 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2292 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2293 }
2294
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002295 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002296 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2297 MVT::Other);
2298 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002299 setValue(&I, DSA);
2300 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002301
2302 // Inform the Frame Information that we have just allocated a variable-sized
2303 // object.
2304 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2305}
2306
Chris Lattner1c08c712005-01-07 07:47:53 +00002307void SelectionDAGLowering::visitLoad(LoadInst &I) {
2308 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002309
Chris Lattnerd3948112005-01-17 22:19:26 +00002310 SDOperand Root;
2311 if (I.isVolatile())
2312 Root = getRoot();
2313 else {
2314 // Do not serialize non-volatile loads against each other.
2315 Root = DAG.getRoot();
2316 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002317
Evan Cheng466685d2006-10-09 20:57:25 +00002318 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002319 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002320}
2321
2322SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002323 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002324 bool isVolatile,
2325 unsigned Alignment) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002326 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002327 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00002328 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00002329 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2330 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002331 } else {
Christopher Lamb95c218a2007-04-22 23:15:30 +00002332 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2333 isVolatile, Alignment);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002334 }
Chris Lattnerd3948112005-01-17 22:19:26 +00002335
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002336 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002337 DAG.setRoot(L.getValue(1));
2338 else
2339 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002340
2341 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002342}
2343
2344
2345void SelectionDAGLowering::visitStore(StoreInst &I) {
2346 Value *SrcV = I.getOperand(0);
2347 SDOperand Src = getValue(SrcV);
2348 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002349 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002350 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002351}
2352
Chris Lattner0eade312006-03-24 02:22:33 +00002353/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2354/// access memory and has no other side effects at all.
2355static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2356#define GET_NO_MEMORY_INTRINSICS
2357#include "llvm/Intrinsics.gen"
2358#undef GET_NO_MEMORY_INTRINSICS
2359 return false;
2360}
2361
Chris Lattnere58a7802006-04-02 03:41:14 +00002362// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2363// have any side-effects or if it only reads memory.
2364static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2365#define GET_SIDE_EFFECT_INFO
2366#include "llvm/Intrinsics.gen"
2367#undef GET_SIDE_EFFECT_INFO
2368 return false;
2369}
2370
Chris Lattner0eade312006-03-24 02:22:33 +00002371/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2372/// node.
2373void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2374 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00002375 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002376 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002377
2378 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002379 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002380 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2381 if (OnlyLoad) {
2382 // We don't need to serialize loads against other loads.
2383 Ops.push_back(DAG.getRoot());
2384 } else {
2385 Ops.push_back(getRoot());
2386 }
2387 }
Chris Lattner0eade312006-03-24 02:22:33 +00002388
2389 // Add the intrinsic ID as an integer operand.
2390 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2391
2392 // Add all operands of the call to the operand list.
2393 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2394 SDOperand Op = getValue(I.getOperand(i));
2395
Reid Spencerac9dcb92007-02-15 03:39:18 +00002396 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00002397 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002398 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002399 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2400
2401 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2402 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2403 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2404 }
2405
2406 assert(TLI.isTypeLegal(Op.getValueType()) &&
2407 "Intrinsic uses a non-legal type?");
2408 Ops.push_back(Op);
2409 }
2410
2411 std::vector<MVT::ValueType> VTs;
2412 if (I.getType() != Type::VoidTy) {
2413 MVT::ValueType VT = TLI.getValueType(I.getType());
2414 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002415 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002416 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2417
2418 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2419 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2420 }
2421
2422 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2423 VTs.push_back(VT);
2424 }
2425 if (HasChain)
2426 VTs.push_back(MVT::Other);
2427
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002428 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2429
Chris Lattner0eade312006-03-24 02:22:33 +00002430 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002431 SDOperand Result;
2432 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002433 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2434 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002435 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002436 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2437 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002438 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002439 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2440 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002441
Chris Lattnere58a7802006-04-02 03:41:14 +00002442 if (HasChain) {
2443 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2444 if (OnlyLoad)
2445 PendingLoads.push_back(Chain);
2446 else
2447 DAG.setRoot(Chain);
2448 }
Chris Lattner0eade312006-03-24 02:22:33 +00002449 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002450 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00002451 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2452 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2453 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2454 DAG.getValueType(EVT));
2455 }
2456 setValue(&I, Result);
2457 }
2458}
2459
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002460/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2461/// we want to emit this as a call to a named external function, return the name
2462/// otherwise lower it and return null.
2463const char *
2464SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2465 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002466 default:
2467 // By default, turn this into a target intrinsic node.
2468 visitTargetIntrinsic(I, Intrinsic);
2469 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002470 case Intrinsic::vastart: visitVAStart(I); return 0;
2471 case Intrinsic::vaend: visitVAEnd(I); return 0;
2472 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002473 case Intrinsic::returnaddress:
2474 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2475 getValue(I.getOperand(1))));
2476 return 0;
2477 case Intrinsic::frameaddress:
2478 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2479 getValue(I.getOperand(1))));
2480 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002481 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002482 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002483 break;
2484 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002485 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002486 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002487 case Intrinsic::memcpy_i32:
2488 case Intrinsic::memcpy_i64:
2489 visitMemIntrinsic(I, ISD::MEMCPY);
2490 return 0;
2491 case Intrinsic::memset_i32:
2492 case Intrinsic::memset_i64:
2493 visitMemIntrinsic(I, ISD::MEMSET);
2494 return 0;
2495 case Intrinsic::memmove_i32:
2496 case Intrinsic::memmove_i64:
2497 visitMemIntrinsic(I, ISD::MEMMOVE);
2498 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002499
Chris Lattner86cb6432005-12-13 17:40:33 +00002500 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002501 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002502 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002503 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002504 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002505
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002506 Ops[0] = getRoot();
2507 Ops[1] = getValue(SPI.getLineValue());
2508 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002509
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002510 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002511 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002512 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2513
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002514 Ops[3] = DAG.getString(CompileUnit->getFileName());
2515 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002516
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002517 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002518 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002519
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002520 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002521 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002522 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002523 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002524 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002525 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2526 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002527 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002528 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002529 }
2530
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002531 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002532 }
2533 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002534 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002535 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002536 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2537 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002538 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002539 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002540 }
2541
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002542 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002543 }
2544 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002545 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002546 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002547 if (MMI && FSI.getSubprogram() &&
2548 MMI->Verify(FSI.getSubprogram())) {
2549 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002550 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002551 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002552 }
2553
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002554 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002555 }
2556 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002557 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002558 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002559 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002560 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002561 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002562 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002563 }
2564
2565 return 0;
2566 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002567
Jim Laskeyb180aa12007-02-21 22:53:45 +00002568 case Intrinsic::eh_exception: {
2569 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2570
Jim Laskey735b6f82007-02-22 15:38:06 +00002571 if (MMI) {
2572 // Add a label to mark the beginning of the landing pad. Deletion of the
2573 // landing pad can thus be detected via the MachineModuleInfo.
2574 unsigned LabelID = MMI->addLandingPad(CurMBB);
2575 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2576 DAG.getConstant(LabelID, MVT::i32)));
2577
2578 // Mark exception register as live in.
2579 unsigned Reg = TLI.getExceptionAddressRegister();
2580 if (Reg) CurMBB->addLiveIn(Reg);
2581
2582 // Insert the EXCEPTIONADDR instruction.
2583 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2584 SDOperand Ops[1];
2585 Ops[0] = DAG.getRoot();
2586 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2587 setValue(&I, Op);
2588 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002589 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002590 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002591 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002592 return 0;
2593 }
2594
Jim Laskey0b4711b2007-03-01 20:24:30 +00002595 case Intrinsic::eh_selector:
2596 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002597 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2598
Jim Laskey735b6f82007-02-22 15:38:06 +00002599 if (MMI) {
2600 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002601 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2602 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2603 isa<Function>(CE->getOperand(0)) &&
2604 "Personality should be a function");
2605 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey0b4711b2007-03-01 20:24:30 +00002606 if (Intrinsic == Intrinsic::eh_filter)
2607 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002608
Jim Laskey735b6f82007-02-22 15:38:06 +00002609 // Gather all the type infos for this landing pad and pass them along to
2610 // MachineModuleInfo.
2611 std::vector<GlobalVariable *> TyInfo;
2612 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002613 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2614 if (CE && CE->getOpcode() == Instruction::BitCast &&
2615 isa<GlobalVariable>(CE->getOperand(0))) {
2616 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2617 } else {
2618 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2619 assert(CI && CI->getZExtValue() == 0 &&
2620 "TypeInfo must be a global variable typeinfo or NULL");
2621 TyInfo.push_back(NULL);
Jim Laskey735b6f82007-02-22 15:38:06 +00002622 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002623 }
2624 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2625
2626 // Mark exception selector register as live in.
2627 unsigned Reg = TLI.getExceptionSelectorRegister();
2628 if (Reg) CurMBB->addLiveIn(Reg);
2629
2630 // Insert the EHSELECTION instruction.
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002631 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002632 SDOperand Ops[2];
2633 Ops[0] = getValue(I.getOperand(1));
2634 Ops[1] = getRoot();
2635 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2636 setValue(&I, Op);
2637 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002638 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002639 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002640 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002641
2642 return 0;
2643 }
2644
2645 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002646 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002647
Jim Laskey735b6f82007-02-22 15:38:06 +00002648 if (MMI) {
2649 // Find the type id for the given typeinfo.
2650 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002651 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2652 if (CE && CE->getOpcode() == Instruction::BitCast &&
2653 isa<GlobalVariable>(CE->getOperand(0))) {
2654 GV = cast<GlobalVariable>(CE->getOperand(0));
2655 } else {
2656 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2657 assert(CI && CI->getZExtValue() == 0 &&
2658 "TypeInfo must be a global variable typeinfo or NULL");
2659 GV = NULL;
Jim Laskey735b6f82007-02-22 15:38:06 +00002660 }
2661
2662 unsigned TypeID = MMI->getTypeIDFor(GV);
2663 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002664 } else {
2665 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002666 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002667
2668 return 0;
2669 }
2670
Reid Spencer0b118202006-01-16 21:12:35 +00002671 case Intrinsic::sqrt_f32:
2672 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002673 setValue(&I, DAG.getNode(ISD::FSQRT,
2674 getValue(I.getOperand(1)).getValueType(),
2675 getValue(I.getOperand(1))));
2676 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002677 case Intrinsic::powi_f32:
2678 case Intrinsic::powi_f64:
2679 setValue(&I, DAG.getNode(ISD::FPOWI,
2680 getValue(I.getOperand(1)).getValueType(),
2681 getValue(I.getOperand(1)),
2682 getValue(I.getOperand(2))));
2683 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002684 case Intrinsic::pcmarker: {
2685 SDOperand Tmp = getValue(I.getOperand(1));
2686 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2687 return 0;
2688 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002689 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002690 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002691 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2692 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2693 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002694 setValue(&I, Tmp);
2695 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002696 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002697 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00002698 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002699 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00002700 assert(0 && "part_select intrinsic not implemented");
2701 abort();
2702 }
2703 case Intrinsic::part_set: {
2704 // Currently not implemented: just abort
2705 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00002706 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002707 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002708 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002709 setValue(&I, DAG.getNode(ISD::BSWAP,
2710 getValue(I.getOperand(1)).getValueType(),
2711 getValue(I.getOperand(1))));
2712 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002713 case Intrinsic::cttz: {
2714 SDOperand Arg = getValue(I.getOperand(1));
2715 MVT::ValueType Ty = Arg.getValueType();
2716 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2717 if (Ty < MVT::i32)
2718 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2719 else if (Ty > MVT::i32)
2720 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2721 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002722 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002723 }
2724 case Intrinsic::ctlz: {
2725 SDOperand Arg = getValue(I.getOperand(1));
2726 MVT::ValueType Ty = Arg.getValueType();
2727 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2728 if (Ty < MVT::i32)
2729 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2730 else if (Ty > MVT::i32)
2731 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2732 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002733 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002734 }
2735 case Intrinsic::ctpop: {
2736 SDOperand Arg = getValue(I.getOperand(1));
2737 MVT::ValueType Ty = Arg.getValueType();
2738 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2739 if (Ty < MVT::i32)
2740 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2741 else if (Ty > MVT::i32)
2742 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2743 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002744 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002745 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002746 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002747 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002748 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2749 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002750 setValue(&I, Tmp);
2751 DAG.setRoot(Tmp.getValue(1));
2752 return 0;
2753 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002754 case Intrinsic::stackrestore: {
2755 SDOperand Tmp = getValue(I.getOperand(1));
2756 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002757 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002758 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002759 case Intrinsic::prefetch:
2760 // FIXME: Currently discarding prefetches.
2761 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002762 }
2763}
2764
2765
Jim Laskey1da20a72007-02-23 21:45:01 +00002766void SelectionDAGLowering::LowerCallTo(Instruction &I,
2767 const Type *CalledValueTy,
2768 unsigned CallingConv,
2769 bool IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002770 SDOperand Callee, unsigned OpIdx) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002771 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002772 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer5694b6e2007-04-09 06:17:21 +00002773 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey735b6f82007-02-22 15:38:06 +00002774
2775 TargetLowering::ArgListTy Args;
2776 TargetLowering::ArgListEntry Entry;
2777 Args.reserve(I.getNumOperands());
2778 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2779 Value *Arg = I.getOperand(i);
2780 SDOperand ArgNode = getValue(Arg);
2781 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencer18da0722007-04-11 02:44:20 +00002782 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2783 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2784 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2785 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
Jim Laskey735b6f82007-02-22 15:38:06 +00002786 Args.push_back(Entry);
2787 }
2788
2789 std::pair<SDOperand,SDOperand> Result =
2790 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer18da0722007-04-11 02:44:20 +00002791 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey1da20a72007-02-23 21:45:01 +00002792 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002793 Callee, Args, DAG);
2794 if (I.getType() != Type::VoidTy)
2795 setValue(&I, Result.first);
2796 DAG.setRoot(Result.second);
2797}
2798
2799
Chris Lattner1c08c712005-01-07 07:47:53 +00002800void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002801 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002802 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002803 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002804 if (unsigned IID = F->getIntrinsicID()) {
2805 RenameFn = visitIntrinsicCall(I, IID);
2806 if (!RenameFn)
2807 return;
2808 } else { // Not an LLVM intrinsic.
2809 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002810 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2811 if (I.getNumOperands() == 3 && // Basic sanity checks.
2812 I.getOperand(1)->getType()->isFloatingPoint() &&
2813 I.getType() == I.getOperand(1)->getType() &&
2814 I.getType() == I.getOperand(2)->getType()) {
2815 SDOperand LHS = getValue(I.getOperand(1));
2816 SDOperand RHS = getValue(I.getOperand(2));
2817 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2818 LHS, RHS));
2819 return;
2820 }
2821 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002822 if (I.getNumOperands() == 2 && // Basic sanity checks.
2823 I.getOperand(1)->getType()->isFloatingPoint() &&
2824 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002825 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002826 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2827 return;
2828 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002829 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002830 if (I.getNumOperands() == 2 && // Basic sanity checks.
2831 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002832 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002833 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002834 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2835 return;
2836 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002837 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002838 if (I.getNumOperands() == 2 && // Basic sanity checks.
2839 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002840 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002841 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002842 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2843 return;
2844 }
2845 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002846 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002847 } else if (isa<InlineAsm>(I.getOperand(0))) {
2848 visitInlineAsm(I);
2849 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002850 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002851
Chris Lattner64e14b12005-01-08 22:48:57 +00002852 SDOperand Callee;
2853 if (!RenameFn)
2854 Callee = getValue(I.getOperand(0));
2855 else
2856 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002857
Jim Laskey1da20a72007-02-23 21:45:01 +00002858 LowerCallTo(I, I.getCalledValue()->getType(),
2859 I.getCallingConv(),
2860 I.isTailCall(),
2861 Callee,
2862 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002863}
2864
Jim Laskey735b6f82007-02-22 15:38:06 +00002865
Chris Lattner864635a2006-02-22 22:37:12 +00002866SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002867 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002868 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2869 Chain = Val.getValue(1);
2870 Flag = Val.getValue(2);
2871
2872 // If the result was expanded, copy from the top part.
2873 if (Regs.size() > 1) {
2874 assert(Regs.size() == 2 &&
2875 "Cannot expand to more than 2 elts yet!");
2876 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002877 Chain = Hi.getValue(1);
2878 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002879 if (DAG.getTargetLoweringInfo().isLittleEndian())
2880 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2881 else
2882 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002883 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002884
Chris Lattnercf752aa2006-06-08 18:22:48 +00002885 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002886 // appropriate type.
2887 if (RegVT == ValueVT)
2888 return Val;
2889
Chris Lattner5df99b32007-03-25 05:00:54 +00002890 if (MVT::isVector(RegVT)) {
2891 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2892 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2893 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2894 MVT::i32),
2895 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2896 }
2897
Chris Lattnercf752aa2006-06-08 18:22:48 +00002898 if (MVT::isInteger(RegVT)) {
2899 if (ValueVT < RegVT)
2900 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2901 else
2902 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002903 }
Chris Lattner5df99b32007-03-25 05:00:54 +00002904
2905 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2906 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002907}
2908
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002909/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2910/// specified value into the registers specified by this object. This uses
2911/// Chain/Flag as the input and updates them for the output Chain/Flag.
2912void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002913 SDOperand &Chain, SDOperand &Flag,
2914 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002915 if (Regs.size() == 1) {
2916 // If there is a single register and the types differ, this must be
2917 // a promotion.
2918 if (RegVT != ValueVT) {
Chris Lattner5df99b32007-03-25 05:00:54 +00002919 if (MVT::isVector(RegVT)) {
2920 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2921 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002922 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002923 if (RegVT < ValueVT)
2924 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2925 else
2926 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002927 } else if (MVT::isFloatingPoint(RegVT) &&
2928 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002929 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002930 } else if (MVT::getSizeInBits(RegVT) ==
2931 MVT::getSizeInBits(Val.getValueType())) {
2932 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2933 } else {
2934 assert(0 && "Unknown mismatch!");
2935 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002936 }
2937 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2938 Flag = Chain.getValue(1);
2939 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002940 std::vector<unsigned> R(Regs);
2941 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2942 std::reverse(R.begin(), R.end());
2943
2944 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002945 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002946 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002947 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002948 Flag = Chain.getValue(1);
2949 }
2950 }
2951}
Chris Lattner864635a2006-02-22 22:37:12 +00002952
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002953/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2954/// operand list. This adds the code marker and includes the number of
2955/// values added into it.
2956void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002957 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00002958 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2959 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002960 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2961 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2962}
Chris Lattner864635a2006-02-22 22:37:12 +00002963
2964/// isAllocatableRegister - If the specified register is safe to allocate,
2965/// i.e. it isn't a stack pointer or some other special register, return the
2966/// register class for the register. Otherwise, return null.
2967static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002968isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2969 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002970 MVT::ValueType FoundVT = MVT::Other;
2971 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002972 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2973 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002974 MVT::ValueType ThisVT = MVT::Other;
2975
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002976 const TargetRegisterClass *RC = *RCI;
2977 // If none of the the value types for this register class are valid, we
2978 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002979 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2980 I != E; ++I) {
2981 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002982 // If we have already found this register in a different register class,
2983 // choose the one with the largest VT specified. For example, on
2984 // PowerPC, we favor f64 register classes over f32.
2985 if (FoundVT == MVT::Other ||
2986 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2987 ThisVT = *I;
2988 break;
2989 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002990 }
2991 }
2992
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002993 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002994
Chris Lattner864635a2006-02-22 22:37:12 +00002995 // NOTE: This isn't ideal. In particular, this might allocate the
2996 // frame pointer in functions that need it (due to them not being taken
2997 // out of allocation, because a variable sized allocation hasn't been seen
2998 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002999 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3000 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003001 if (*I == Reg) {
3002 // We found a matching register class. Keep looking at others in case
3003 // we find one with larger registers that this physreg is also in.
3004 FoundRC = RC;
3005 FoundVT = ThisVT;
3006 break;
3007 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003008 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003009 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003010}
3011
3012RegsForValue SelectionDAGLowering::
3013GetRegistersForValue(const std::string &ConstrCode,
3014 MVT::ValueType VT, bool isOutReg, bool isInReg,
3015 std::set<unsigned> &OutputRegs,
3016 std::set<unsigned> &InputRegs) {
3017 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3018 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
3019 std::vector<unsigned> Regs;
3020
3021 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
3022 MVT::ValueType RegVT;
3023 MVT::ValueType ValueVT = VT;
3024
Chris Lattner2a821602006-11-02 01:41:49 +00003025 // If this is a constraint for a specific physical register, like {r17},
3026 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00003027 if (PhysReg.first) {
3028 if (VT == MVT::Other)
3029 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00003030
3031 // Get the actual register value type. This is important, because the user
3032 // may have asked for (e.g.) the AX register in i32 type. We need to
3033 // remember that AX is actually i16 to get the right extension.
3034 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00003035
3036 // This is a explicit reference to a physical register.
3037 Regs.push_back(PhysReg.first);
3038
3039 // If this is an expanded reference, add the rest of the regs to Regs.
3040 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00003041 TargetRegisterClass::iterator I = PhysReg.second->begin();
3042 TargetRegisterClass::iterator E = PhysReg.second->end();
3043 for (; *I != PhysReg.first; ++I)
3044 assert(I != E && "Didn't find reg!");
3045
3046 // Already added the first reg.
3047 --NumRegs; ++I;
3048 for (; NumRegs; --NumRegs, ++I) {
3049 assert(I != E && "Ran out of registers to allocate!");
3050 Regs.push_back(*I);
3051 }
3052 }
3053 return RegsForValue(Regs, RegVT, ValueVT);
3054 }
3055
Chris Lattner2a821602006-11-02 01:41:49 +00003056 // Otherwise, if this was a reference to an LLVM register class, create vregs
3057 // for this reference.
3058 std::vector<unsigned> RegClassRegs;
3059 if (PhysReg.second) {
3060 // If this is an early clobber or tied register, our regalloc doesn't know
3061 // how to maintain the constraint. If it isn't, go ahead and create vreg
3062 // and let the regalloc do the right thing.
3063 if (!isOutReg || !isInReg) {
Chris Lattner2a821602006-11-02 01:41:49 +00003064 RegVT = *PhysReg.second->vt_begin();
Chris Lattner3a508c92007-04-12 06:00:20 +00003065
3066 if (VT == MVT::Other)
3067 ValueVT = RegVT;
Chris Lattner2a821602006-11-02 01:41:49 +00003068
3069 // Create the appropriate number of virtual registers.
3070 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
3071 for (; NumRegs; --NumRegs)
3072 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3073
3074 return RegsForValue(Regs, RegVT, ValueVT);
3075 }
3076
3077 // Otherwise, we can't allocate it. Let the code below figure out how to
3078 // maintain these constraints.
3079 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3080
3081 } else {
3082 // This is a reference to a register class that doesn't directly correspond
3083 // to an LLVM register class. Allocate NumRegs consecutive, available,
3084 // registers from the class.
3085 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
3086 }
Chris Lattner864635a2006-02-22 22:37:12 +00003087
3088 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3089 MachineFunction &MF = *CurMBB->getParent();
3090 unsigned NumAllocated = 0;
3091 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3092 unsigned Reg = RegClassRegs[i];
3093 // See if this register is available.
3094 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3095 (isInReg && InputRegs.count(Reg))) { // Already used.
3096 // Make sure we find consecutive registers.
3097 NumAllocated = 0;
3098 continue;
3099 }
3100
3101 // Check to see if this register is allocatable (i.e. don't give out the
3102 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003103 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00003104 if (!RC) {
3105 // Make sure we find consecutive registers.
3106 NumAllocated = 0;
3107 continue;
3108 }
3109
3110 // Okay, this register is good, we can use it.
3111 ++NumAllocated;
3112
Chris Lattnere303ac92007-04-06 17:47:14 +00003113 // If we allocated enough consecutive registers, succeed.
Chris Lattner864635a2006-02-22 22:37:12 +00003114 if (NumAllocated == NumRegs) {
3115 unsigned RegStart = (i-NumAllocated)+1;
3116 unsigned RegEnd = i+1;
3117 // Mark all of the allocated registers used.
3118 for (unsigned i = RegStart; i != RegEnd; ++i) {
3119 unsigned Reg = RegClassRegs[i];
3120 Regs.push_back(Reg);
3121 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3122 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3123 }
3124
3125 return RegsForValue(Regs, *RC->vt_begin(), VT);
3126 }
3127 }
3128
3129 // Otherwise, we couldn't allocate enough registers for this.
3130 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00003131}
3132
Chris Lattner367f1092007-01-29 23:45:14 +00003133/// getConstraintGenerality - Return an integer indicating how general CT is.
3134static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3135 switch (CT) {
3136 default: assert(0 && "Unknown constraint type!");
3137 case TargetLowering::C_Other:
3138 case TargetLowering::C_Unknown:
3139 return 0;
3140 case TargetLowering::C_Register:
3141 return 1;
3142 case TargetLowering::C_RegisterClass:
3143 return 2;
3144 case TargetLowering::C_Memory:
3145 return 3;
3146 }
3147}
3148
3149static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
3150 const TargetLowering &TLI) {
3151 assert(!C.empty() && "Must have at least one constraint");
3152 if (C.size() == 1) return C[0];
3153
3154 std::string *Current = &C[0];
3155 // If we have multiple constraints, try to pick the most general one ahead
3156 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattner4234f572007-03-25 02:14:49 +00003157 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattner367f1092007-01-29 23:45:14 +00003158 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattner4234f572007-03-25 02:14:49 +00003159 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattner367f1092007-01-29 23:45:14 +00003160 if (getConstraintGenerality(ThisFlavor) >
3161 getConstraintGenerality(Flavor)) {
3162 // This constraint letter is more general than the previous one,
3163 // use it.
3164 Flavor = ThisFlavor;
3165 Current = &C[j];
3166 }
3167 }
3168 return *Current;
3169}
3170
Chris Lattner864635a2006-02-22 22:37:12 +00003171
Chris Lattnerce7518c2006-01-26 22:24:51 +00003172/// visitInlineAsm - Handle a call to an InlineAsm object.
3173///
3174void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3175 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3176
3177 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
3178 MVT::Other);
3179
Chris Lattner2cc2f662006-02-01 01:28:23 +00003180 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00003181 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003182
3183 /// AsmNodeOperands - A list of pairs. The first element is a register, the
3184 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
3185 /// if it is a def of that register.
3186 std::vector<SDOperand> AsmNodeOperands;
3187 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3188 AsmNodeOperands.push_back(AsmStr);
3189
3190 SDOperand Chain = getRoot();
3191 SDOperand Flag;
3192
Chris Lattner4e4b5762006-02-01 18:59:47 +00003193 // We fully assign registers here at isel time. This is not optimal, but
3194 // should work. For register classes that correspond to LLVM classes, we
3195 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
3196 // over the constraints, collecting fixed registers that we know we can't use.
3197 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003198 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003199 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00003200 std::string ConstraintCode =
3201 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00003202
Chris Lattner1efa40f2006-02-22 00:56:39 +00003203 MVT::ValueType OpVT;
3204
3205 // Compute the value type for each operand and add it to ConstraintVTs.
3206 switch (Constraints[i].Type) {
3207 case InlineAsm::isOutput:
3208 if (!Constraints[i].isIndirectOutput) {
3209 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3210 OpVT = TLI.getValueType(I.getType());
3211 } else {
Chris Lattner22873462006-02-27 23:45:39 +00003212 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00003213 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
3214 OpNum++; // Consumes a call operand.
3215 }
3216 break;
3217 case InlineAsm::isInput:
3218 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
3219 OpNum++; // Consumes a call operand.
3220 break;
3221 case InlineAsm::isClobber:
3222 OpVT = MVT::Other;
3223 break;
3224 }
3225
3226 ConstraintVTs.push_back(OpVT);
3227
Chris Lattner864635a2006-02-22 22:37:12 +00003228 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
3229 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003230
Chris Lattner864635a2006-02-22 22:37:12 +00003231 // Build a list of regs that this operand uses. This always has a single
3232 // element for promoted/expanded operands.
3233 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
3234 false, false,
3235 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00003236
3237 switch (Constraints[i].Type) {
3238 case InlineAsm::isOutput:
3239 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00003240 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003241 // If this is an early-clobber output, it cannot be assigned to the same
3242 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00003243 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00003244 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003245 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003246 case InlineAsm::isInput:
3247 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00003248 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00003249 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003250 case InlineAsm::isClobber:
3251 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00003252 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3253 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003254 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003255 }
3256 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00003257
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003258 // Loop over all of the inputs, copying the operand values into the
3259 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003260 RegsForValue RetValRegs;
3261 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003262 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003263
Chris Lattner6656dd12006-01-31 02:03:41 +00003264 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00003265 std::string ConstraintCode =
3266 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003267
Chris Lattner2cc2f662006-02-01 01:28:23 +00003268 switch (Constraints[i].Type) {
3269 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00003270 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3271 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003272 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner22873462006-02-27 23:45:39 +00003273
3274 if (CTy == TargetLowering::C_Memory) {
3275 // Memory output.
3276 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3277
3278 // Check that the operand (the address to store to) isn't a float.
3279 if (!MVT::isInteger(InOperandVal.getValueType()))
3280 assert(0 && "MATCH FAIL!");
3281
3282 if (!Constraints[i].isIndirectOutput)
3283 assert(0 && "MATCH FAIL!");
3284
3285 OpNum++; // Consumes a call operand.
3286
3287 // Extend/truncate to the right pointer type if needed.
3288 MVT::ValueType PtrType = TLI.getPointerTy();
3289 if (InOperandVal.getValueType() < PtrType)
3290 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3291 else if (InOperandVal.getValueType() > PtrType)
3292 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3293
3294 // Add information to the INLINEASM node to know about this output.
3295 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3296 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3297 AsmNodeOperands.push_back(InOperandVal);
3298 break;
3299 }
3300
3301 // Otherwise, this is a register output.
3302 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3303
Chris Lattner864635a2006-02-22 22:37:12 +00003304 // If this is an early-clobber output, or if there is an input
3305 // constraint that matches this, we need to reserve the input register
3306 // so no other inputs allocate to it.
3307 bool UsesInputRegister = false;
3308 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3309 UsesInputRegister = true;
3310
3311 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003312 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00003313 RegsForValue Regs =
3314 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3315 true, UsesInputRegister,
3316 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00003317 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003318 cerr << "Couldn't allocate output reg for contraint '"
3319 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003320 exit(1);
3321 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003322
Chris Lattner2cc2f662006-02-01 01:28:23 +00003323 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00003324 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003325 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003326 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00003327 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003328 } else {
Chris Lattner22873462006-02-27 23:45:39 +00003329 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3330 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003331 OpNum++; // Consumes a call operand.
3332 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003333
3334 // Add information to the INLINEASM node to know that this register is
3335 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003336 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003337 break;
3338 }
3339 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00003340 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00003341 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00003342
Chris Lattner2223aea2006-02-02 00:25:23 +00003343 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3344 // If this is required to match an output register we have already set,
3345 // just use its register.
3346 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003347
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003348 // Scan until we find the definition we already emitted of this operand.
3349 // When we find it, create a RegsForValue operand.
3350 unsigned CurOp = 2; // The first operand.
3351 for (; OperandNo; --OperandNo) {
3352 // Advance to the next operand.
3353 unsigned NumOps =
3354 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003355 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3356 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003357 "Skipped past definitions?");
3358 CurOp += (NumOps>>3)+1;
3359 }
3360
3361 unsigned NumOps =
3362 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003363 if ((NumOps & 7) == 2 /*REGDEF*/) {
3364 // Add NumOps>>3 registers to MatchedRegs.
3365 RegsForValue MatchedRegs;
3366 MatchedRegs.ValueVT = InOperandVal.getValueType();
3367 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3368 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3369 unsigned Reg =
3370 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3371 MatchedRegs.Regs.push_back(Reg);
3372 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003373
Chris Lattner527fae12007-02-01 01:21:12 +00003374 // Use the produced MatchedRegs object to
3375 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3376 TLI.getPointerTy());
3377 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3378 break;
3379 } else {
3380 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3381 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003382 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003383 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003384
3385 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3386 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003387 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003388
3389 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00003390 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3391 ConstraintCode[0], DAG);
3392 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00003393 cerr << "Invalid operand for inline asm constraint '"
3394 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003395 exit(1);
3396 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003397
3398 // Add information to the INLINEASM node to know about this input.
3399 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3400 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3401 AsmNodeOperands.push_back(InOperandVal);
3402 break;
3403 } else if (CTy == TargetLowering::C_Memory) {
3404 // Memory input.
3405
Chris Lattner6dfc6802007-03-08 22:29:47 +00003406 // If the operand is a float, spill to a constant pool entry to get its
3407 // address.
3408 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3409 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3410
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003411 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattner6dfc6802007-03-08 22:29:47 +00003412 cerr << "Match failed, cannot handle this yet!\n";
3413 InOperandVal.Val->dump();
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003414 exit(1);
3415 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003416
3417 // Extend/truncate to the right pointer type if needed.
3418 MVT::ValueType PtrType = TLI.getPointerTy();
3419 if (InOperandVal.getValueType() < PtrType)
3420 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3421 else if (InOperandVal.getValueType() > PtrType)
3422 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3423
3424 // Add information to the INLINEASM node to know about this input.
3425 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3426 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3427 AsmNodeOperands.push_back(InOperandVal);
3428 break;
3429 }
3430
3431 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3432
3433 // Copy the input into the appropriate registers.
3434 RegsForValue InRegs =
3435 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3436 false, true, OutputRegs, InputRegs);
3437 // FIXME: should be match fail.
3438 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3439
Evan Chenga8441262006-06-15 08:11:54 +00003440 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003441
3442 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003443 break;
3444 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003445 case InlineAsm::isClobber: {
3446 RegsForValue ClobberedRegs =
3447 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3448 OutputRegs, InputRegs);
3449 // Add the clobbered value to the operand list, so that the register
3450 // allocator is aware that the physreg got clobbered.
3451 if (!ClobberedRegs.Regs.empty())
3452 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003453 break;
3454 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003455 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003456 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003457
3458 // Finish up input operands.
3459 AsmNodeOperands[0] = Chain;
3460 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3461
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003462 Chain = DAG.getNode(ISD::INLINEASM,
3463 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003464 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003465 Flag = Chain.getValue(1);
3466
Chris Lattner6656dd12006-01-31 02:03:41 +00003467 // If this asm returns a register value, copy the result from that register
3468 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003469 if (!RetValRegs.Regs.empty()) {
3470 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3471
3472 // If the result of the inline asm is a vector, it may have the wrong
3473 // width/num elts. Make sure to convert it to the right type with
3474 // vbit_convert.
3475 if (Val.getValueType() == MVT::Vector) {
3476 const VectorType *VTy = cast<VectorType>(I.getType());
3477 unsigned DesiredNumElts = VTy->getNumElements();
3478 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3479
3480 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3481 DAG.getConstant(DesiredNumElts, MVT::i32),
3482 DAG.getValueType(DesiredEltVT));
3483 }
3484
3485 setValue(&I, Val);
3486 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003487
Chris Lattner6656dd12006-01-31 02:03:41 +00003488 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3489
3490 // Process indirect outputs, first output all of the flagged copies out of
3491 // physregs.
3492 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003493 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003494 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00003495 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3496 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003497 }
3498
3499 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003500 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003501 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00003502 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003503 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003504 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003505 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003506 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3507 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003508 DAG.setRoot(Chain);
3509}
3510
3511
Chris Lattner1c08c712005-01-07 07:47:53 +00003512void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3513 SDOperand Src = getValue(I.getOperand(0));
3514
3515 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003516
3517 if (IntPtr < Src.getValueType())
3518 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3519 else if (IntPtr > Src.getValueType())
3520 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003521
3522 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003523 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003524 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3525 Src, getIntPtrConstant(ElementSize));
3526
Reid Spencer47857812006-12-31 05:55:36 +00003527 TargetLowering::ArgListTy Args;
3528 TargetLowering::ArgListEntry Entry;
3529 Entry.Node = Src;
3530 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003531 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003532
3533 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003534 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003535 DAG.getExternalSymbol("malloc", IntPtr),
3536 Args, DAG);
3537 setValue(&I, Result.first); // Pointers always fit in registers
3538 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003539}
3540
3541void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003542 TargetLowering::ArgListTy Args;
3543 TargetLowering::ArgListEntry Entry;
3544 Entry.Node = getValue(I.getOperand(0));
3545 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003546 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003547 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003548 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003549 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003550 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3551 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003552}
3553
Chris Lattner025c39b2005-08-26 20:54:47 +00003554// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3555// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3556// instructions are special in various ways, which require special support to
3557// insert. The specified MachineInstr is created but not inserted into any
3558// basic blocks, and the scheduler passes ownership of it to this method.
3559MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3560 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003561 cerr << "If a target marks an instruction with "
3562 << "'usesCustomDAGSchedInserter', it must implement "
3563 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003564 abort();
3565 return 0;
3566}
3567
Chris Lattner39ae3622005-01-09 00:00:49 +00003568void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003569 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3570 getValue(I.getOperand(1)),
3571 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003572}
3573
3574void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003575 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3576 getValue(I.getOperand(0)),
3577 DAG.getSrcValue(I.getOperand(0)));
3578 setValue(&I, V);
3579 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003580}
3581
3582void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003583 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3584 getValue(I.getOperand(1)),
3585 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003586}
3587
3588void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003589 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3590 getValue(I.getOperand(1)),
3591 getValue(I.getOperand(2)),
3592 DAG.getSrcValue(I.getOperand(1)),
3593 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003594}
3595
Evan Chengb15974a2006-12-12 07:27:38 +00003596/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3597/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3598static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3599 unsigned &i, SelectionDAG &DAG,
3600 TargetLowering &TLI) {
3601 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3602 return SDOperand(Arg, i++);
3603
3604 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3605 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3606 if (NumVals == 1) {
3607 return DAG.getNode(ISD::BIT_CONVERT, VT,
3608 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3609 } else if (NumVals == 2) {
3610 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3611 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3612 if (!TLI.isLittleEndian())
3613 std::swap(Lo, Hi);
3614 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3615 } else {
3616 // Value scalarized into many values. Unimp for now.
3617 assert(0 && "Cannot expand i64 -> i16 yet!");
3618 }
3619 return SDOperand();
3620}
3621
Chris Lattnerfdfded52006-04-12 16:20:43 +00003622/// TargetLowering::LowerArguments - This is the default LowerArguments
3623/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003624/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3625/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003626std::vector<SDOperand>
3627TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003628 const FunctionType *FTy = F.getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +00003629 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003630 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3631 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003632 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003633 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3634 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3635
3636 // Add one result value for each formal argument.
3637 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003638 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003639 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3640 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003641 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003642 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003643 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003644 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003645
Chris Lattnerddf53e42007-02-26 02:56:58 +00003646 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3647 // that is zero extended!
Reid Spencer18da0722007-04-11 02:44:20 +00003648 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003649 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer18da0722007-04-11 02:44:20 +00003650 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003651 Flags |= ISD::ParamFlags::SExt;
Reid Spencer18da0722007-04-11 02:44:20 +00003652 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003653 Flags |= ISD::ParamFlags::InReg;
Reid Spencer18da0722007-04-11 02:44:20 +00003654 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003655 Flags |= ISD::ParamFlags::StructReturn;
3656 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003657
Chris Lattnerfdfded52006-04-12 16:20:43 +00003658 switch (getTypeAction(VT)) {
3659 default: assert(0 && "Unknown type action!");
3660 case Legal:
3661 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003662 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003663 break;
3664 case Promote:
3665 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003666 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003667 break;
3668 case Expand:
3669 if (VT != MVT::Vector) {
3670 // If this is a large integer, it needs to be broken up into small
3671 // integers. Figure out what the destination type is and how many small
3672 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003673 MVT::ValueType NVT = getTypeToExpandTo(VT);
3674 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003675 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003676 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003677 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003678 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003679 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3680 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003681 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3682 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003683 } else {
3684 // Otherwise, this is a vector type. We only support legal vectors
3685 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003686 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3687 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003688
Chris Lattnerfdfded52006-04-12 16:20:43 +00003689 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003690 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003691 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3692 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3693 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003694 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003695 } else {
3696 assert(0 && "Don't support illegal by-val vector arguments yet!");
3697 }
3698 }
3699 break;
3700 }
3701 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003702
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003703 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003704
3705 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003706 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3707 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003708 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003709
3710 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003711
3712 // Set up the return result vector.
3713 Ops.clear();
3714 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003715 unsigned Idx = 1;
3716 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3717 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003718 MVT::ValueType VT = getValueType(I->getType());
3719
3720 switch (getTypeAction(VT)) {
3721 default: assert(0 && "Unknown type action!");
3722 case Legal:
3723 Ops.push_back(SDOperand(Result, i++));
3724 break;
3725 case Promote: {
3726 SDOperand Op(Result, i++);
3727 if (MVT::isInteger(VT)) {
Reid Spencer18da0722007-04-11 02:44:20 +00003728 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003729 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3730 DAG.getValueType(VT));
Reid Spencer18da0722007-04-11 02:44:20 +00003731 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003732 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3733 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003734 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3735 } else {
3736 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3737 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3738 }
3739 Ops.push_back(Op);
3740 break;
3741 }
3742 case Expand:
3743 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003744 // If this is a large integer or a floating point node that needs to be
3745 // expanded, it needs to be reassembled from small integers. Figure out
3746 // what the source elt type is and how many small integers it is.
3747 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003748 } else {
3749 // Otherwise, this is a vector type. We only support legal vectors
3750 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003751 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003752 unsigned NumElems = PTy->getNumElements();
3753 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003754
Chris Lattnerfdfded52006-04-12 16:20:43 +00003755 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003756 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003757 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003758 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003759 SDOperand N = SDOperand(Result, i++);
3760 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003761 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3762 DAG.getConstant(NumElems, MVT::i32),
3763 DAG.getValueType(getValueType(EltTy)));
3764 Ops.push_back(N);
3765 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003766 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003767 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003768 }
3769 }
3770 break;
3771 }
3772 }
3773 return Ops;
3774}
3775
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003776
Evan Chengb15974a2006-12-12 07:27:38 +00003777/// ExpandScalarCallArgs - Recursively expand call argument node by
3778/// bit_converting it or extract a pair of elements from the larger node.
3779static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003780 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003781 SmallVector<SDOperand, 32> &Ops,
3782 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003783 TargetLowering &TLI,
3784 bool isFirst = true) {
3785
Evan Chengb15974a2006-12-12 07:27:38 +00003786 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003787 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003788 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003789 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3790 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003791 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003792 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003793 return;
3794 }
3795
3796 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3797 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3798 if (NumVals == 1) {
3799 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003800 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003801 } else if (NumVals == 2) {
3802 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3803 DAG.getConstant(0, TLI.getPointerTy()));
3804 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3805 DAG.getConstant(1, TLI.getPointerTy()));
3806 if (!TLI.isLittleEndian())
3807 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003808 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3809 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003810 } else {
3811 // Value scalarized into many values. Unimp for now.
3812 assert(0 && "Cannot expand i64 -> i16 yet!");
3813 }
3814}
3815
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003816/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3817/// implementation, which just inserts an ISD::CALL node, which is later custom
3818/// lowered by the target to something concrete. FIXME: When all targets are
3819/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3820std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003821TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3822 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003823 unsigned CallingConv, bool isTailCall,
3824 SDOperand Callee,
3825 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003826 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003827 Ops.push_back(Chain); // Op#0 - Chain
3828 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3829 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3830 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3831 Ops.push_back(Callee);
3832
3833 // Handle all of the outgoing arguments.
3834 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003835 MVT::ValueType VT = getValueType(Args[i].Ty);
3836 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003837 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003838 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003839 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003840
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003841 if (Args[i].isSExt)
3842 Flags |= ISD::ParamFlags::SExt;
3843 if (Args[i].isZExt)
3844 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003845 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003846 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003847 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003848 Flags |= ISD::ParamFlags::StructReturn;
3849 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003850
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003851 switch (getTypeAction(VT)) {
3852 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003853 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003854 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003855 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003856 break;
3857 case Promote:
3858 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003859 unsigned ExtOp;
3860 if (Args[i].isSExt)
3861 ExtOp = ISD::SIGN_EXTEND;
3862 else if (Args[i].isZExt)
3863 ExtOp = ISD::ZERO_EXTEND;
3864 else
3865 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003866 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3867 } else {
3868 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3869 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3870 }
3871 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003872 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003873 break;
3874 case Expand:
3875 if (VT != MVT::Vector) {
3876 // If this is a large integer, it needs to be broken down into small
3877 // integers. Figure out what the source elt type is and how many small
3878 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003879 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003880 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003881 // Otherwise, this is a vector type. We only support legal vectors
3882 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003883 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003884 unsigned NumElems = PTy->getNumElements();
3885 const Type *EltTy = PTy->getElementType();
3886
3887 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003888 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003889 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003890 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003891 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003892 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3893 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003894 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003895 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003896 assert(0 && "Don't support illegal by-val vector call args yet!");
3897 abort();
3898 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003899 }
3900 break;
3901 }
3902 }
3903
3904 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003905 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003906
3907 if (RetTy != Type::VoidTy) {
3908 MVT::ValueType VT = getValueType(RetTy);
3909 switch (getTypeAction(VT)) {
3910 default: assert(0 && "Unknown type action!");
3911 case Legal:
3912 RetTys.push_back(VT);
3913 break;
3914 case Promote:
3915 RetTys.push_back(getTypeToTransformTo(VT));
3916 break;
3917 case Expand:
3918 if (VT != MVT::Vector) {
3919 // If this is a large integer, it needs to be reassembled from small
3920 // integers. Figure out what the source elt type is and how many small
3921 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003922 MVT::ValueType NVT = getTypeToExpandTo(VT);
3923 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003924 for (unsigned i = 0; i != NumVals; ++i)
3925 RetTys.push_back(NVT);
3926 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003927 // Otherwise, this is a vector type. We only support legal vectors
3928 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003929 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003930 unsigned NumElems = PTy->getNumElements();
3931 const Type *EltTy = PTy->getElementType();
3932
3933 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003934 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003935 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3936 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3937 RetTys.push_back(TVT);
3938 } else {
3939 assert(0 && "Don't support illegal by-val vector call results yet!");
3940 abort();
3941 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003942 }
3943 }
3944 }
3945
3946 RetTys.push_back(MVT::Other); // Always has a chain.
3947
3948 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003949 SDOperand Res = DAG.getNode(ISD::CALL,
3950 DAG.getVTList(&RetTys[0], RetTys.size()),
3951 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003952
3953 // This returns a pair of operands. The first element is the
3954 // return value for the function (if RetTy is not VoidTy). The second
3955 // element is the outgoing token chain.
3956 SDOperand ResVal;
3957 if (RetTys.size() != 1) {
3958 MVT::ValueType VT = getValueType(RetTy);
3959 if (RetTys.size() == 2) {
3960 ResVal = Res;
3961
3962 // If this value was promoted, truncate it down.
3963 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003964 if (VT == MVT::Vector) {
Chris Lattner5df99b32007-03-25 05:00:54 +00003965 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerda098e72006-05-16 23:39:44 +00003966 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003967 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3968 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003969
3970 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003971 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003972 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003973 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003974 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3975 // "N x PTyElementVT" MVT::Vector type.
3976 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003977 DAG.getConstant(NumElems, MVT::i32),
3978 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003979 } else {
3980 abort();
3981 }
3982 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003983 unsigned AssertOp = ISD::AssertSext;
3984 if (!RetTyIsSigned)
3985 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003986 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3987 DAG.getValueType(VT));
3988 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3989 } else {
3990 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003991 if (getTypeAction(VT) == Expand)
3992 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3993 else
3994 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003995 }
3996 }
3997 } else if (RetTys.size() == 3) {
3998 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3999 Res.getValue(0), Res.getValue(1));
4000
4001 } else {
4002 assert(0 && "Case not handled yet!");
4003 }
4004 }
4005
4006 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4007}
4008
Chris Lattner50381b62005-05-14 05:50:48 +00004009SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004010 assert(0 && "LowerOperation not implemented for this target!");
4011 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004012 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004013}
4014
Nate Begeman0aed7842006-01-28 03:14:31 +00004015SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4016 SelectionDAG &DAG) {
4017 assert(0 && "CustomPromoteOperation not implemented for this target!");
4018 abort();
4019 return SDOperand();
4020}
4021
Evan Cheng74d0aa92006-02-15 21:59:04 +00004022/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004023/// operand.
4024static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004025 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004026 MVT::ValueType CurVT = VT;
4027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4028 uint64_t Val = C->getValue() & 255;
4029 unsigned Shift = 8;
4030 while (CurVT != MVT::i8) {
4031 Val = (Val << Shift) | Val;
4032 Shift <<= 1;
4033 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004034 }
4035 return DAG.getConstant(Val, VT);
4036 } else {
4037 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4038 unsigned Shift = 8;
4039 while (CurVT != MVT::i8) {
4040 Value =
4041 DAG.getNode(ISD::OR, VT,
4042 DAG.getNode(ISD::SHL, VT, Value,
4043 DAG.getConstant(Shift, MVT::i8)), Value);
4044 Shift <<= 1;
4045 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004046 }
4047
4048 return Value;
4049 }
4050}
4051
Evan Cheng74d0aa92006-02-15 21:59:04 +00004052/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4053/// used when a memcpy is turned into a memset when the source is a constant
4054/// string ptr.
4055static SDOperand getMemsetStringVal(MVT::ValueType VT,
4056 SelectionDAG &DAG, TargetLowering &TLI,
4057 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004058 uint64_t Val = 0;
4059 unsigned MSB = getSizeInBits(VT) / 8;
4060 if (TLI.isLittleEndian())
4061 Offset = Offset + MSB - 1;
4062 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004063 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004064 Offset += TLI.isLittleEndian() ? -1 : 1;
4065 }
4066 return DAG.getConstant(Val, VT);
4067}
4068
Evan Cheng1db92f92006-02-14 08:22:34 +00004069/// getMemBasePlusOffset - Returns base and offset node for the
4070static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4071 SelectionDAG &DAG, TargetLowering &TLI) {
4072 MVT::ValueType VT = Base.getValueType();
4073 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4074}
4075
Evan Chengc4f8eee2006-02-14 20:12:38 +00004076/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004077/// to replace the memset / memcpy is below the threshold. It also returns the
4078/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004079static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4080 unsigned Limit, uint64_t Size,
4081 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004082 MVT::ValueType VT;
4083
4084 if (TLI.allowsUnalignedMemoryAccesses()) {
4085 VT = MVT::i64;
4086 } else {
4087 switch (Align & 7) {
4088 case 0:
4089 VT = MVT::i64;
4090 break;
4091 case 4:
4092 VT = MVT::i32;
4093 break;
4094 case 2:
4095 VT = MVT::i16;
4096 break;
4097 default:
4098 VT = MVT::i8;
4099 break;
4100 }
4101 }
4102
Evan Cheng80e89d72006-02-14 09:11:59 +00004103 MVT::ValueType LVT = MVT::i64;
4104 while (!TLI.isTypeLegal(LVT))
4105 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4106 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004107
Evan Cheng80e89d72006-02-14 09:11:59 +00004108 if (VT > LVT)
4109 VT = LVT;
4110
Evan Chengdea72452006-02-14 23:05:54 +00004111 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004112 while (Size != 0) {
4113 unsigned VTSize = getSizeInBits(VT) / 8;
4114 while (VTSize > Size) {
4115 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004116 VTSize >>= 1;
4117 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004118 assert(MVT::isInteger(VT));
4119
4120 if (++NumMemOps > Limit)
4121 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004122 MemOps.push_back(VT);
4123 Size -= VTSize;
4124 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004125
4126 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004127}
4128
Chris Lattner7041ee32005-01-11 05:56:49 +00004129void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004130 SDOperand Op1 = getValue(I.getOperand(1));
4131 SDOperand Op2 = getValue(I.getOperand(2));
4132 SDOperand Op3 = getValue(I.getOperand(3));
4133 SDOperand Op4 = getValue(I.getOperand(4));
4134 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4135 if (Align == 0) Align = 1;
4136
4137 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4138 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004139
4140 // Expand memset / memcpy to a series of load / store ops
4141 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004142 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004143 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004144 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004145 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004146 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4147 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004148 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004149 unsigned Offset = 0;
4150 for (unsigned i = 0; i < NumMemOps; i++) {
4151 MVT::ValueType VT = MemOps[i];
4152 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004153 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004154 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004155 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004156 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004157 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004158 Offset += VTSize;
4159 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004160 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004161 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004162 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004163 case ISD::MEMCPY: {
4164 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4165 Size->getValue(), Align, TLI)) {
4166 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004167 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004168 GlobalAddressSDNode *G = NULL;
4169 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004170 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004171
4172 if (Op2.getOpcode() == ISD::GlobalAddress)
4173 G = cast<GlobalAddressSDNode>(Op2);
4174 else if (Op2.getOpcode() == ISD::ADD &&
4175 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4176 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4177 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004178 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004179 }
4180 if (G) {
4181 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004182 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004183 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004184 if (!Str.empty()) {
4185 CopyFromStr = true;
4186 SrcOff += SrcDelta;
4187 }
4188 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004189 }
4190
Evan Chengc080d6f2006-02-15 01:54:51 +00004191 for (unsigned i = 0; i < NumMemOps; i++) {
4192 MVT::ValueType VT = MemOps[i];
4193 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004194 SDOperand Value, Chain, Store;
4195
Evan Chengcffbb512006-02-16 23:11:42 +00004196 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004197 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4198 Chain = getRoot();
4199 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004200 DAG.getStore(Chain, Value,
4201 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004202 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004203 } else {
4204 Value = DAG.getLoad(VT, getRoot(),
4205 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00004206 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004207 Chain = Value.getValue(1);
4208 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004209 DAG.getStore(Chain, Value,
4210 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004211 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004212 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004213 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004214 SrcOff += VTSize;
4215 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004216 }
4217 }
4218 break;
4219 }
4220 }
4221
4222 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004223 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4224 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004225 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004226 }
4227 }
4228
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004229 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00004230}
4231
Chris Lattner7041ee32005-01-11 05:56:49 +00004232//===----------------------------------------------------------------------===//
4233// SelectionDAGISel code
4234//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004235
4236unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4237 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4238}
4239
Chris Lattner495a0b52005-08-17 06:37:43 +00004240void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004241 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004242 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004243}
Chris Lattner1c08c712005-01-07 07:47:53 +00004244
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004245
Chris Lattnerbad7f482006-10-28 19:22:10 +00004246
Chris Lattner1c08c712005-01-07 07:47:53 +00004247bool SelectionDAGISel::runOnFunction(Function &Fn) {
4248 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4249 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004250 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004251
4252 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4253
4254 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4255 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004256
Evan Chengad2070c2007-02-10 02:43:39 +00004257 // Add function live-ins to entry block live-in set.
4258 BasicBlock *EntryBB = &Fn.getEntryBlock();
4259 BB = FuncInfo.MBBMap[EntryBB];
4260 if (!MF.livein_empty())
4261 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4262 E = MF.livein_end(); I != E; ++I)
4263 BB->addLiveIn(I->first);
4264
Chris Lattner1c08c712005-01-07 07:47:53 +00004265 return true;
4266}
4267
Chris Lattner571e4342006-10-27 21:36:01 +00004268SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4269 unsigned Reg) {
4270 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004271 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004272 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004273 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004274
4275 // If this type is not legal, we must make sure to not create an invalid
4276 // register use.
4277 MVT::ValueType SrcVT = Op.getValueType();
4278 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004279 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004280 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004281 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004282 // Handle copies from generic vectors to registers.
4283 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004284 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004285 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004286
Chris Lattner70c2a612006-03-31 02:06:56 +00004287 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4288 // MVT::Vector type.
4289 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4290 DAG.getConstant(NE, MVT::i32),
4291 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004292
Chris Lattner70c2a612006-03-31 02:06:56 +00004293 // Loop over all of the elements of the resultant vector,
4294 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4295 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004296 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004297 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004298 for (unsigned i = 0; i != NE; ++i) {
4299 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004300 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004301 if (PTyElementVT == PTyLegalElementVT) {
4302 // Elements are legal.
4303 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4304 } else if (PTyLegalElementVT > PTyElementVT) {
4305 // Elements are promoted.
4306 if (MVT::isFloatingPoint(PTyLegalElementVT))
4307 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4308 else
4309 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4310 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4311 } else {
4312 // Elements are expanded.
4313 // The src value is expanded into multiple registers.
4314 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004315 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004316 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004317 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004318 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4319 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4320 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004321 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004322 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4323 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004324 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004325 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004326 if (MVT::isFloatingPoint(SrcVT))
4327 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4328 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004329 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004330 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004331 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004332 DestVT = TLI.getTypeToExpandTo(SrcVT);
4333 unsigned NumVals = TLI.getNumElements(SrcVT);
4334 if (NumVals == 1)
4335 return DAG.getCopyToReg(getRoot(), Reg,
4336 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4337 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004338 // The src value is expanded into multiple registers.
4339 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004340 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004341 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004342 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004343 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004344 return DAG.getCopyToReg(Op, Reg+1, Hi);
4345 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004346}
4347
Chris Lattner068a81e2005-01-17 17:15:02 +00004348void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004349LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004350 std::vector<SDOperand> &UnorderedChains) {
4351 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004352 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004353 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004354 SDOperand OldRoot = SDL.DAG.getRoot();
4355 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004356
Chris Lattnerbf209482005-10-30 19:42:35 +00004357 unsigned a = 0;
4358 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4359 AI != E; ++AI, ++a)
4360 if (!AI->use_empty()) {
4361 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004362
Chris Lattnerbf209482005-10-30 19:42:35 +00004363 // If this argument is live outside of the entry block, insert a copy from
4364 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004365 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4366 if (VMI != FuncInfo.ValueMap.end()) {
4367 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004368 UnorderedChains.push_back(Copy);
4369 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004370 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004371
Chris Lattnerbf209482005-10-30 19:42:35 +00004372 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004373 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004374 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004375}
4376
Chris Lattner1c08c712005-01-07 07:47:53 +00004377void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4378 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004379 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004380 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004381
4382 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004383
Chris Lattnerbf209482005-10-30 19:42:35 +00004384 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004385 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004386 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004387
4388 BB = FuncInfo.MBBMap[LLVMBB];
4389 SDL.setCurrentBasicBlock(BB);
4390
4391 // Lower all of the non-terminator instructions.
4392 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4393 I != E; ++I)
4394 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004395
4396 // Lower call part of invoke.
4397 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4398 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004399
Chris Lattner1c08c712005-01-07 07:47:53 +00004400 // Ensure that all instructions which are used outside of their defining
4401 // blocks are available as virtual registers.
4402 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004403 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004404 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004405 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004406 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004407 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004408 }
4409
4410 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4411 // ensure constants are generated when needed. Remember the virtual registers
4412 // that need to be added to the Machine PHI nodes as input. We cannot just
4413 // directly add them, because expansion might result in multiple MBB's for one
4414 // BB. As such, the start of the BB might correspond to a different MBB than
4415 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004416 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004417 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004418
4419 // Emit constants only once even if used by multiple PHI nodes.
4420 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004421
Chris Lattner8c494ab2006-10-27 23:50:33 +00004422 // Vector bool would be better, but vector<bool> is really slow.
4423 std::vector<unsigned char> SuccsHandled;
4424 if (TI->getNumSuccessors())
4425 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4426
Chris Lattner1c08c712005-01-07 07:47:53 +00004427 // Check successor nodes PHI nodes that expect a constant to be available from
4428 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004429 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4430 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004431 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004432 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004433
Chris Lattner8c494ab2006-10-27 23:50:33 +00004434 // If this terminator has multiple identical successors (common for
4435 // switches), only handle each succ once.
4436 unsigned SuccMBBNo = SuccMBB->getNumber();
4437 if (SuccsHandled[SuccMBBNo]) continue;
4438 SuccsHandled[SuccMBBNo] = true;
4439
4440 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004441 PHINode *PN;
4442
4443 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4444 // nodes and Machine PHI nodes, but the incoming operands have not been
4445 // emitted yet.
4446 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004447 (PN = dyn_cast<PHINode>(I)); ++I) {
4448 // Ignore dead phi's.
4449 if (PN->use_empty()) continue;
4450
4451 unsigned Reg;
4452 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004453
Chris Lattner8c494ab2006-10-27 23:50:33 +00004454 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4455 unsigned &RegOut = ConstantsOut[C];
4456 if (RegOut == 0) {
4457 RegOut = FuncInfo.CreateRegForValue(C);
4458 UnorderedChains.push_back(
4459 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004460 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004461 Reg = RegOut;
4462 } else {
4463 Reg = FuncInfo.ValueMap[PHIOp];
4464 if (Reg == 0) {
4465 assert(isa<AllocaInst>(PHIOp) &&
4466 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4467 "Didn't codegen value into a register!??");
4468 Reg = FuncInfo.CreateRegForValue(PHIOp);
4469 UnorderedChains.push_back(
4470 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004471 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004472 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004473
4474 // Remember that this register needs to added to the machine PHI node as
4475 // the input for this MBB.
4476 MVT::ValueType VT = TLI.getValueType(PN->getType());
4477 unsigned NumElements;
4478 if (VT != MVT::Vector)
4479 NumElements = TLI.getNumElements(VT);
4480 else {
4481 MVT::ValueType VT1,VT2;
4482 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004483 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004484 VT1, VT2);
4485 }
4486 for (unsigned i = 0, e = NumElements; i != e; ++i)
4487 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4488 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004489 }
4490 ConstantsOut.clear();
4491
Chris Lattnerddb870b2005-01-13 17:59:43 +00004492 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004493 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004494 SDOperand Root = SDL.getRoot();
4495 if (Root.getOpcode() != ISD::EntryToken) {
4496 unsigned i = 0, e = UnorderedChains.size();
4497 for (; i != e; ++i) {
4498 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4499 if (UnorderedChains[i].Val->getOperand(0) == Root)
4500 break; // Don't add the root if we already indirectly depend on it.
4501 }
4502
4503 if (i == e)
4504 UnorderedChains.push_back(Root);
4505 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004506 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4507 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004508 }
4509
Chris Lattner1c08c712005-01-07 07:47:53 +00004510 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004511 if (Invoke) {
4512 // Just the branch part of invoke.
4513 SDL.visitInvoke(*Invoke, true);
4514 } else {
4515 SDL.visit(*LLVMBB->getTerminator());
4516 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004517
Nate Begemanf15485a2006-03-27 01:32:24 +00004518 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004519 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004520 SwitchCases.clear();
4521 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004522 JTCases.clear();
4523 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004524 BitTestCases.clear();
4525 BitTestCases = SDL.BitTestCases;
4526
Chris Lattnera651cf62005-01-17 19:43:36 +00004527 // Make sure the root of the DAG is up-to-date.
4528 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004529}
4530
Nate Begemanf15485a2006-03-27 01:32:24 +00004531void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004532 // Get alias analysis for load/store combining.
4533 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4534
Chris Lattneraf21d552005-10-10 16:47:10 +00004535 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004536 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004537
Bill Wendling832171c2006-12-07 20:04:42 +00004538 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004539 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004540
Chris Lattner1c08c712005-01-07 07:47:53 +00004541 // Second step, hack on the DAG until it only uses operations and types that
4542 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004543 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004544
Bill Wendling832171c2006-12-07 20:04:42 +00004545 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004546 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004547
Chris Lattneraf21d552005-10-10 16:47:10 +00004548 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004549 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004550
Evan Chenga9c20912006-01-21 02:32:06 +00004551 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004552
Chris Lattnera33ef482005-03-30 01:10:47 +00004553 // Third, instruction select all of the operations to machine code, adding the
4554 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004555 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004556
Bill Wendling832171c2006-12-07 20:04:42 +00004557 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004558 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004559}
Chris Lattner1c08c712005-01-07 07:47:53 +00004560
Nate Begemanf15485a2006-03-27 01:32:24 +00004561void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4562 FunctionLoweringInfo &FuncInfo) {
4563 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4564 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004565 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004566 CurDAG = &DAG;
4567
4568 // First step, lower LLVM code to some DAG. This DAG may use operations and
4569 // types that are not supported by the target.
4570 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4571
4572 // Second step, emit the lowered DAG as machine code.
4573 CodeGenAndEmitDAG(DAG);
4574 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004575
4576 DOUT << "Total amount of phi nodes to update: "
4577 << PHINodesToUpdate.size() << "\n";
4578 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4579 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4580 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004581
Chris Lattnera33ef482005-03-30 01:10:47 +00004582 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004583 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004584 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004585 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4586 MachineInstr *PHI = PHINodesToUpdate[i].first;
4587 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4588 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004589 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004590 PHI->addMachineBasicBlockOperand(BB);
4591 }
4592 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004593 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004594
4595 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4596 // Lower header first, if it wasn't already lowered
4597 if (!BitTestCases[i].Emitted) {
4598 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4599 CurDAG = &HSDAG;
4600 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4601 // Set the current basic block to the mbb we wish to insert the code into
4602 BB = BitTestCases[i].Parent;
4603 HSDL.setCurrentBasicBlock(BB);
4604 // Emit the code
4605 HSDL.visitBitTestHeader(BitTestCases[i]);
4606 HSDAG.setRoot(HSDL.getRoot());
4607 CodeGenAndEmitDAG(HSDAG);
4608 }
4609
4610 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4611 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4612 CurDAG = &BSDAG;
4613 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4614 // Set the current basic block to the mbb we wish to insert the code into
4615 BB = BitTestCases[i].Cases[j].ThisBB;
4616 BSDL.setCurrentBasicBlock(BB);
4617 // Emit the code
4618 if (j+1 != ej)
4619 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4620 BitTestCases[i].Reg,
4621 BitTestCases[i].Cases[j]);
4622 else
4623 BSDL.visitBitTestCase(BitTestCases[i].Default,
4624 BitTestCases[i].Reg,
4625 BitTestCases[i].Cases[j]);
4626
4627
4628 BSDAG.setRoot(BSDL.getRoot());
4629 CodeGenAndEmitDAG(BSDAG);
4630 }
4631
4632 // Update PHI Nodes
4633 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4634 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4635 MachineBasicBlock *PHIBB = PHI->getParent();
4636 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4637 "This is not a machine PHI node that we are updating!");
4638 // This is "default" BB. We have two jumps to it. From "header" BB and
4639 // from last "case" BB.
4640 if (PHIBB == BitTestCases[i].Default) {
4641 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4642 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikov8085bcf2007-04-13 06:53:51 +00004643 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004644 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4645 }
4646 // One of "cases" BB.
4647 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4648 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4649 if (cBB->succ_end() !=
4650 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4651 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4652 PHI->addMachineBasicBlockOperand(cBB);
4653 }
4654 }
4655 }
4656 }
4657
Nate Begeman9453eea2006-04-23 06:26:20 +00004658 // If the JumpTable record is filled in, then we need to emit a jump table.
4659 // Updating the PHI nodes is tricky in this case, since we need to determine
4660 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004661 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4662 // Lower header first, if it wasn't already lowered
4663 if (!JTCases[i].first.Emitted) {
4664 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4665 CurDAG = &HSDAG;
4666 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4667 // Set the current basic block to the mbb we wish to insert the code into
4668 BB = JTCases[i].first.HeaderBB;
4669 HSDL.setCurrentBasicBlock(BB);
4670 // Emit the code
4671 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4672 HSDAG.setRoot(HSDL.getRoot());
4673 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004674 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004675
4676 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4677 CurDAG = &JSDAG;
4678 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004679 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004680 BB = JTCases[i].second.MBB;
4681 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004682 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004683 JSDL.visitJumpTable(JTCases[i].second);
4684 JSDAG.setRoot(JSDL.getRoot());
4685 CodeGenAndEmitDAG(JSDAG);
4686
Nate Begeman37efe672006-04-22 18:53:45 +00004687 // Update PHI Nodes
4688 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4689 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4690 MachineBasicBlock *PHIBB = PHI->getParent();
4691 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4692 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004693 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004694 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004695 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004696 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004697 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004698 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004699 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004700 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004701 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004702 }
4703 }
Nate Begeman37efe672006-04-22 18:53:45 +00004704 }
4705
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004706 // If the switch block involved a branch to one of the actual successors, we
4707 // need to update PHI nodes in that block.
4708 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4709 MachineInstr *PHI = PHINodesToUpdate[i].first;
4710 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4711 "This is not a machine PHI node that we are updating!");
4712 if (BB->isSuccessor(PHI->getParent())) {
4713 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4714 PHI->addMachineBasicBlockOperand(BB);
4715 }
4716 }
4717
Nate Begemanf15485a2006-03-27 01:32:24 +00004718 // If we generated any switch lowering information, build and codegen any
4719 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004720 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004721 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004722 CurDAG = &SDAG;
4723 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004724
Nate Begemanf15485a2006-03-27 01:32:24 +00004725 // Set the current basic block to the mbb we wish to insert the code into
4726 BB = SwitchCases[i].ThisBB;
4727 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004728
Nate Begemanf15485a2006-03-27 01:32:24 +00004729 // Emit the code
4730 SDL.visitSwitchCase(SwitchCases[i]);
4731 SDAG.setRoot(SDL.getRoot());
4732 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004733
4734 // Handle any PHI nodes in successors of this chunk, as if we were coming
4735 // from the original BB before switch expansion. Note that PHI nodes can
4736 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4737 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004738 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004739 for (MachineBasicBlock::iterator Phi = BB->begin();
4740 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4741 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4742 for (unsigned pn = 0; ; ++pn) {
4743 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4744 if (PHINodesToUpdate[pn].first == Phi) {
4745 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4746 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4747 break;
4748 }
4749 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004750 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004751
4752 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004753 if (BB == SwitchCases[i].FalseBB)
4754 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004755
4756 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004757 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004758 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004759 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004760 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004761 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004762}
Evan Chenga9c20912006-01-21 02:32:06 +00004763
Jim Laskey13ec7022006-08-01 14:21:23 +00004764
Evan Chenga9c20912006-01-21 02:32:06 +00004765//===----------------------------------------------------------------------===//
4766/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4767/// target node in the graph.
4768void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4769 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004770
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004771 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004772
4773 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004774 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004775 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004776 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004777
Jim Laskey9ff542f2006-08-01 18:29:48 +00004778 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004779 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004780 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004781}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004782
Chris Lattner03fc53c2006-03-06 00:22:00 +00004783
Jim Laskey9ff542f2006-08-01 18:29:48 +00004784HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4785 return new HazardRecognizer();
4786}
4787
Chris Lattner75548062006-10-11 03:58:02 +00004788//===----------------------------------------------------------------------===//
4789// Helper functions used by the generated instruction selector.
4790//===----------------------------------------------------------------------===//
4791// Calls to these methods are generated by tblgen.
4792
4793/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4794/// the dag combiner simplified the 255, we still want to match. RHS is the
4795/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4796/// specified in the .td file (e.g. 255).
4797bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4798 int64_t DesiredMaskS) {
4799 uint64_t ActualMask = RHS->getValue();
4800 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4801
4802 // If the actual mask exactly matches, success!
4803 if (ActualMask == DesiredMask)
4804 return true;
4805
4806 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4807 if (ActualMask & ~DesiredMask)
4808 return false;
4809
4810 // Otherwise, the DAG Combiner may have proven that the value coming in is
4811 // either already zero or is not demanded. Check for known zero input bits.
4812 uint64_t NeededMask = DesiredMask & ~ActualMask;
4813 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4814 return true;
4815
4816 // TODO: check to see if missing bits are just not demanded.
4817
4818 // Otherwise, this pattern doesn't match.
4819 return false;
4820}
4821
4822/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4823/// the dag combiner simplified the 255, we still want to match. RHS is the
4824/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4825/// specified in the .td file (e.g. 255).
4826bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4827 int64_t DesiredMaskS) {
4828 uint64_t ActualMask = RHS->getValue();
4829 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4830
4831 // If the actual mask exactly matches, success!
4832 if (ActualMask == DesiredMask)
4833 return true;
4834
4835 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4836 if (ActualMask & ~DesiredMask)
4837 return false;
4838
4839 // Otherwise, the DAG Combiner may have proven that the value coming in is
4840 // either already zero or is not demanded. Check for known zero input bits.
4841 uint64_t NeededMask = DesiredMask & ~ActualMask;
4842
4843 uint64_t KnownZero, KnownOne;
4844 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4845
4846 // If all the missing bits in the or are already known to be set, match!
4847 if ((NeededMask & KnownOne) == NeededMask)
4848 return true;
4849
4850 // TODO: check to see if missing bits are just not demanded.
4851
4852 // Otherwise, this pattern doesn't match.
4853 return false;
4854}
4855
Jim Laskey9ff542f2006-08-01 18:29:48 +00004856
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004857/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4858/// by tblgen. Others should not call it.
4859void SelectionDAGISel::
4860SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4861 std::vector<SDOperand> InOps;
4862 std::swap(InOps, Ops);
4863
4864 Ops.push_back(InOps[0]); // input chain.
4865 Ops.push_back(InOps[1]); // input asm string.
4866
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004867 unsigned i = 2, e = InOps.size();
4868 if (InOps[e-1].getValueType() == MVT::Flag)
4869 --e; // Don't process a flag operand if it is here.
4870
4871 while (i != e) {
4872 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4873 if ((Flags & 7) != 4 /*MEM*/) {
4874 // Just skip over this operand, copying the operands verbatim.
4875 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4876 i += (Flags >> 3) + 1;
4877 } else {
4878 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4879 // Otherwise, this is a memory operand. Ask the target to select it.
4880 std::vector<SDOperand> SelOps;
4881 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004882 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004883 exit(1);
4884 }
4885
4886 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00004887 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00004888 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00004889 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004890 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4891 i += 2;
4892 }
4893 }
4894
4895 // Add the flag input back if present.
4896 if (e != InOps.size())
4897 Ops.push_back(InOps.back());
4898}