blob: 10053acaab9a87281f63b8083121f08e12feb2b0 [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"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.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///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000074namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey9ff542f2006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner864635a2006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000134 };
135}
Evan Cheng4ef10862006-01-23 07:01:07 +0000136
Chris Lattner1c08c712005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattner571e4342006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000190
Chris Lattner3c384492006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattnerbf209482005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner1c08c712005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000249
Reid Spencerb83eb642006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000254 }
255
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000286 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000292 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner3c384492006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencerac9dcb92007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
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.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner1c08c712005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner0da331f2007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000358
Chris Lattnerd3948112005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemanf15485a2006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattnerae4f99d2007-02-13 20:09:07 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner1c08c712005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000404
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000409
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 }
419
Chris Lattnera651cf62005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000425
Chris Lattnerd3948112005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000439 }
440
Chris Lattner571e4342006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner199862b2006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000469
Chris Lattner0da331f2007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000475
Chris Lattner864635a2006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000481
Chris Lattner571e4342006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
487
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemanf15485a2006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000497
Chris Lattner1c08c712005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000499 void visitInvoke(InvokeInst &I);
500 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000501
Reid Spencer24d6da52007-01-21 00:29:26 +0000502 void visitScalarBinary(User &I, unsigned OpCode);
503 void visitVectorBinary(User &I, unsigned OpCode);
504 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000505 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000506 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000507 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000508 visitVectorBinary(I, ISD::VADD);
509 else if (I.getType()->isFloatingPoint())
510 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000511 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000512 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000513 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000514 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000515 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000516 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000517 visitVectorBinary(I, ISD::VMUL);
518 else if (I.getType()->isFloatingPoint())
519 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000521 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000522 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000523 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
524 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
525 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
526 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
527 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
528 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
529 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
530 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
531 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
532 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000533 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
534 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000535 void visitICmp(User &I);
536 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000537 // Visit the conversion instructions
538 void visitTrunc(User &I);
539 void visitZExt(User &I);
540 void visitSExt(User &I);
541 void visitFPTrunc(User &I);
542 void visitFPExt(User &I);
543 void visitFPToUI(User &I);
544 void visitFPToSI(User &I);
545 void visitUIToFP(User &I);
546 void visitSIToFP(User &I);
547 void visitPtrToInt(User &I);
548 void visitIntToPtr(User &I);
549 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000550
Chris Lattner2bbd8102006-03-29 00:11:43 +0000551 void visitExtractElement(User &I);
552 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000553 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000554
Chris Lattner1c08c712005-01-07 07:47:53 +0000555 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000556 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557
558 void visitMalloc(MallocInst &I);
559 void visitFree(FreeInst &I);
560 void visitAlloca(AllocaInst &I);
561 void visitLoad(LoadInst &I);
562 void visitStore(StoreInst &I);
563 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
564 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000565 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000566 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000567 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000568
Chris Lattner1c08c712005-01-07 07:47:53 +0000569 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 void visitVAArg(VAArgInst &I);
571 void visitVAEnd(CallInst &I);
572 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000573
Chris Lattner7041ee32005-01-11 05:56:49 +0000574 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000575
576 void visitUserOp1(Instruction &I) {
577 assert(0 && "UserOp1 should not exist at instruction selection time!");
578 abort();
579 }
580 void visitUserOp2(Instruction &I) {
581 assert(0 && "UserOp2 should not exist at instruction selection time!");
582 abort();
583 }
584};
585} // end namespace llvm
586
Chris Lattner199862b2006-03-16 19:57:50 +0000587SDOperand SelectionDAGLowering::getValue(const Value *V) {
588 SDOperand &N = NodeMap[V];
589 if (N.Val) return N;
590
591 const Type *VTy = V->getType();
592 MVT::ValueType VT = TLI.getValueType(VTy);
593 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
595 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000596 SDOperand N1 = NodeMap[V];
597 assert(N1.Val && "visit didn't populate the ValueMap!");
598 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000599 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
600 return N = DAG.getGlobalAddress(GV, VT);
601 } else if (isa<ConstantPointerNull>(C)) {
602 return N = DAG.getConstant(0, TLI.getPointerTy());
603 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000604 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000605 return N = DAG.getNode(ISD::UNDEF, VT);
606
Chris Lattnerb2827b02006-03-19 00:52:58 +0000607 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000608 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000609 unsigned NumElements = PTy->getNumElements();
610 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
611
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000612 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000613 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
614
615 // Create a VConstant node with generic Vector type.
616 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
617 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000618 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
619 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000620 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
621 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000622 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000623 unsigned NumElements = PTy->getNumElements();
624 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000625
626 // Now that we know the number and type of the elements, push a
627 // Constant or ConstantFP node onto the ops list for each element of
628 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000629 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000630 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000631 for (unsigned i = 0; i != NumElements; ++i)
632 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000633 } else {
634 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
635 SDOperand Op;
636 if (MVT::isFloatingPoint(PVT))
637 Op = DAG.getConstantFP(0, PVT);
638 else
639 Op = DAG.getConstant(0, PVT);
640 Ops.assign(NumElements, Op);
641 }
642
Chris Lattnerb2827b02006-03-19 00:52:58 +0000643 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000644 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
645 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000646 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
647 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000648 } else {
649 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000650 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000651 }
652 }
653
654 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
655 std::map<const AllocaInst*, int>::iterator SI =
656 FuncInfo.StaticAllocaMap.find(AI);
657 if (SI != FuncInfo.StaticAllocaMap.end())
658 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
659 }
660
Chris Lattner9f24ad72007-02-04 01:35:11 +0000661 DenseMap<const Value*, unsigned>::iterator VMI =
Chris Lattner199862b2006-03-16 19:57:50 +0000662 FuncInfo.ValueMap.find(V);
663 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
664
665 unsigned InReg = VMI->second;
666
667 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000668 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000669 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000670 // Source must be expanded. This input value is actually coming from the
671 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000672 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
673 unsigned NumVals = TLI.getNumElements(VT);
674 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
675 if (NumVals == 1)
676 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
677 else {
678 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
679 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
680 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
681 }
682 } else {
683 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
684 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
685 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
686 N = MVT::isFloatingPoint(VT)
687 ? DAG.getNode(ISD::FP_ROUND, VT, N)
688 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000689 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000690 } else {
691 // Otherwise, if this is a vector, make it available as a generic vector
692 // here.
693 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000694 const VectorType *PTy = cast<VectorType>(VTy);
695 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000696 PTyLegalElementVT);
697
698 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000699 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000700 if (PTyElementVT == PTyLegalElementVT) {
701 // If the value types are legal, just VBUILD the CopyFromReg nodes.
702 for (unsigned i = 0; i != NE; ++i)
703 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
704 PTyElementVT));
705 } else if (PTyElementVT < PTyLegalElementVT) {
706 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
707 for (unsigned i = 0; i != NE; ++i) {
708 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT);
710 if (MVT::isFloatingPoint(PTyElementVT))
711 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
712 else
713 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
714 Ops.push_back(Op);
715 }
716 } else {
717 // If the register was expanded, use BUILD_PAIR.
718 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
719 for (unsigned i = 0; i != NE/2; ++i) {
720 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
721 PTyElementVT);
722 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
723 PTyElementVT);
724 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
725 }
726 }
727
728 Ops.push_back(DAG.getConstant(NE, MVT::i32));
729 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000730 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000731
732 // Finally, use a VBIT_CONVERT to make this available as the appropriate
733 // vector type.
734 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
735 DAG.getConstant(PTy->getNumElements(),
736 MVT::i32),
737 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000738 }
739
740 return N;
741}
742
743
Chris Lattner1c08c712005-01-07 07:47:53 +0000744void SelectionDAGLowering::visitRet(ReturnInst &I) {
745 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000746 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000747 return;
748 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000749 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000750 NewValues.push_back(getRoot());
751 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
752 SDOperand RetOp = getValue(I.getOperand(i));
753
754 // If this is an integer return value, we need to promote it ourselves to
755 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
756 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000757 // FIXME: C calling convention requires the return type to be promoted to
758 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000759 if (MVT::isInteger(RetOp.getValueType()) &&
760 RetOp.getValueType() < MVT::i64) {
761 MVT::ValueType TmpVT;
762 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
763 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
764 else
765 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000766 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000767 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000768 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
769 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000770 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
771 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000772 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000773 }
774 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000775 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000776 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000777 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
778 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000779}
780
Chris Lattner571e4342006-10-27 21:36:01 +0000781/// ExportFromCurrentBlock - If this condition isn't known to be exported from
782/// the current basic block, add it to ValueMap now so that we'll get a
783/// CopyTo/FromReg.
784void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
785 // No need to export constants.
786 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
787
788 // Already exported?
789 if (FuncInfo.isExportedInst(V)) return;
790
791 unsigned Reg = FuncInfo.InitializeRegForValue(V);
792 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
793}
794
Chris Lattner8c494ab2006-10-27 23:50:33 +0000795bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
796 const BasicBlock *FromBB) {
797 // The operands of the setcc have to be in this block. We don't know
798 // how to export them from some other block.
799 if (Instruction *VI = dyn_cast<Instruction>(V)) {
800 // Can export from current BB.
801 if (VI->getParent() == FromBB)
802 return true;
803
804 // Is already exported, noop.
805 return FuncInfo.isExportedInst(V);
806 }
807
808 // If this is an argument, we can export it if the BB is the entry block or
809 // if it is already exported.
810 if (isa<Argument>(V)) {
811 if (FromBB == &FromBB->getParent()->getEntryBlock())
812 return true;
813
814 // Otherwise, can only export this if it is already exported.
815 return FuncInfo.isExportedInst(V);
816 }
817
818 // Otherwise, constants can always be exported.
819 return true;
820}
821
Chris Lattner6a586c82006-10-29 21:01:20 +0000822static bool InBlock(const Value *V, const BasicBlock *BB) {
823 if (const Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() == BB;
825 return true;
826}
827
Chris Lattner571e4342006-10-27 21:36:01 +0000828/// FindMergedConditions - If Cond is an expression like
829void SelectionDAGLowering::FindMergedConditions(Value *Cond,
830 MachineBasicBlock *TBB,
831 MachineBasicBlock *FBB,
832 MachineBasicBlock *CurBB,
833 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000834 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000835 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000836
Reid Spencere4d87aa2006-12-23 06:05:41 +0000837 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
838 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000839 BOp->getParent() != CurBB->getBasicBlock() ||
840 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
841 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000842 const BasicBlock *BB = CurBB->getBasicBlock();
843
Reid Spencere4d87aa2006-12-23 06:05:41 +0000844 // If the leaf of the tree is a comparison, merge the condition into
845 // the caseblock.
846 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
847 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000848 // how to export them from some other block. If this is the first block
849 // of the sequence, no exporting is needed.
850 (CurBB == CurMBB ||
851 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
852 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000853 BOp = cast<Instruction>(Cond);
854 ISD::CondCode Condition;
855 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
856 switch (IC->getPredicate()) {
857 default: assert(0 && "Unknown icmp predicate opcode!");
858 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
859 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
860 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
861 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
862 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
863 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
864 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
865 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
866 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
867 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
868 }
869 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
870 ISD::CondCode FPC, FOC;
871 switch (FC->getPredicate()) {
872 default: assert(0 && "Unknown fcmp predicate opcode!");
873 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
874 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
875 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
876 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
877 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
878 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
879 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
880 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
881 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
882 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
883 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
884 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
885 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
886 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
887 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
888 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
889 }
890 if (FiniteOnlyFPMath())
891 Condition = FOC;
892 else
893 Condition = FPC;
894 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000895 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000896 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000897 }
898
Chris Lattner571e4342006-10-27 21:36:01 +0000899 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
900 BOp->getOperand(1), TBB, FBB, CurBB);
901 SwitchCases.push_back(CB);
902 return;
903 }
904
905 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000906 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000907 TBB, FBB, CurBB);
908 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000909 return;
910 }
911
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000912
913 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000914 MachineFunction::iterator BBI = CurBB;
915 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
916 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
917
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000918 if (Opc == Instruction::Or) {
919 // Codegen X | Y as:
920 // jmp_if_X TBB
921 // jmp TmpBB
922 // TmpBB:
923 // jmp_if_Y TBB
924 // jmp FBB
925 //
Chris Lattner571e4342006-10-27 21:36:01 +0000926
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000927 // Emit the LHS condition.
928 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
929
930 // Emit the RHS condition into TmpBB.
931 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
932 } else {
933 assert(Opc == Instruction::And && "Unknown merge op!");
934 // Codegen X & Y as:
935 // jmp_if_X TmpBB
936 // jmp FBB
937 // TmpBB:
938 // jmp_if_Y TBB
939 // jmp FBB
940 //
941 // This requires creation of TmpBB after CurBB.
942
943 // Emit the LHS condition.
944 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
945
946 // Emit the RHS condition into TmpBB.
947 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
948 }
Chris Lattner571e4342006-10-27 21:36:01 +0000949}
950
Chris Lattnerdf19f272006-10-31 22:37:42 +0000951/// If the set of cases should be emitted as a series of branches, return true.
952/// If we should emit this as a bunch of and/or'd together conditions, return
953/// false.
954static bool
955ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
956 if (Cases.size() != 2) return true;
957
Chris Lattner0ccb5002006-10-31 23:06:00 +0000958 // If this is two comparisons of the same values or'd or and'd together, they
959 // will get folded into a single comparison, so don't emit two blocks.
960 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
961 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
962 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
963 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
964 return false;
965 }
966
Chris Lattnerdf19f272006-10-31 22:37:42 +0000967 return true;
968}
969
Chris Lattner1c08c712005-01-07 07:47:53 +0000970void SelectionDAGLowering::visitBr(BranchInst &I) {
971 // Update machine-CFG edges.
972 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000973
974 // Figure out which block is immediately after the current one.
975 MachineBasicBlock *NextBlock = 0;
976 MachineFunction::iterator BBI = CurMBB;
977 if (++BBI != CurMBB->getParent()->end())
978 NextBlock = BBI;
979
980 if (I.isUnconditional()) {
981 // If this is not a fall-through branch, emit the branch.
982 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000983 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000984 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000985
Chris Lattner57ab6592006-10-24 17:57:59 +0000986 // Update machine-CFG edges.
987 CurMBB->addSuccessor(Succ0MBB);
988
989 return;
990 }
991
992 // If this condition is one of the special cases we handle, do special stuff
993 // now.
994 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000995 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000996
997 // If this is a series of conditions that are or'd or and'd together, emit
998 // this as a sequence of branches instead of setcc's with and/or operations.
999 // For example, instead of something like:
1000 // cmp A, B
1001 // C = seteq
1002 // cmp D, E
1003 // F = setle
1004 // or C, F
1005 // jnz foo
1006 // Emit:
1007 // cmp A, B
1008 // je foo
1009 // cmp D, E
1010 // jle foo
1011 //
1012 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1013 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001014 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001015 BOp->getOpcode() == Instruction::Or)) {
1016 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001017 // If the compares in later blocks need to use values not currently
1018 // exported from this block, export them now. This block should always
1019 // be the first entry.
1020 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1021
Chris Lattnerdf19f272006-10-31 22:37:42 +00001022 // Allow some cases to be rejected.
1023 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001024 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1025 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1026 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1027 }
1028
1029 // Emit the branch for this block.
1030 visitSwitchCase(SwitchCases[0]);
1031 SwitchCases.erase(SwitchCases.begin());
1032 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001033 }
1034
Chris Lattner0ccb5002006-10-31 23:06:00 +00001035 // Okay, we decided not to do this, remove any inserted MBB's and clear
1036 // SwitchCases.
1037 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1038 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1039
Chris Lattnerdf19f272006-10-31 22:37:42 +00001040 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001041 }
1042 }
Chris Lattner24525952006-10-24 18:07:37 +00001043
1044 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001045 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001046 Succ0MBB, Succ1MBB, CurMBB);
1047 // Use visitSwitchCase to actually insert the fast branch sequence for this
1048 // cond branch.
1049 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001050}
1051
Nate Begemanf15485a2006-03-27 01:32:24 +00001052/// visitSwitchCase - Emits the necessary code to represent a single node in
1053/// the binary search tree resulting from lowering a switch instruction.
1054void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001055 SDOperand Cond;
1056 SDOperand CondLHS = getValue(CB.CmpLHS);
1057
Chris Lattner571e4342006-10-27 21:36:01 +00001058 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1059 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001060 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001061 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001062 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001063 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1064 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1065 } else
1066 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001067
1068 // Set NextBlock to be the MBB immediately after the current one, if any.
1069 // This is used to avoid emitting unnecessary branches to the next block.
1070 MachineBasicBlock *NextBlock = 0;
1071 MachineFunction::iterator BBI = CurMBB;
1072 if (++BBI != CurMBB->getParent()->end())
1073 NextBlock = BBI;
1074
1075 // If the lhs block is the next block, invert the condition so that we can
1076 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001077 if (CB.TrueBB == NextBlock) {
1078 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001079 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1080 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1081 }
1082 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001083 DAG.getBasicBlock(CB.TrueBB));
1084 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001085 DAG.setRoot(BrCond);
1086 else
1087 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001088 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001089 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001090 CurMBB->addSuccessor(CB.TrueBB);
1091 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001092}
1093
Nate Begeman37efe672006-04-22 18:53:45 +00001094void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001095 // Emit the code for the jump table
1096 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001097 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1098 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1099 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1100 Table, Index));
1101 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001102}
1103
Jim Laskeyb180aa12007-02-21 22:53:45 +00001104void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1105 // Retrieve successors.
1106 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1107 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1108
1109 // Mark landing pad so that it doesn't get deleted in branch folding.
1110 LandingPad->setIsLandingPad();
1111
1112 // Insert a label before the invoke call to mark the try range.
1113 // This can be used to detect deletion of the invoke via the
1114 // MachineModuleInfo.
1115 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1116 unsigned BeginLabel = MMI->NextLabelID();
1117 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1118 DAG.getConstant(BeginLabel, MVT::i32)));
1119
1120 // Insert a normal call instruction.
1121 std::vector<Value*> Args;
1122 for (InvokeInst::op_iterator OI = I.op_begin() + 3, E = I.op_end();
1123 OI != E; ++OI) {
1124 Args.push_back(*OI);
1125 }
1126 CallInst *NewCall = new CallInst(I.getCalledValue(), &Args[0], Args.size(),
1127 I.getName(), &I);
1128 NewCall->setCallingConv(I.getCallingConv());
1129 I.replaceAllUsesWith(NewCall);
1130 visitCall(*NewCall);
1131
1132 // Insert a label before the invoke call to mark the try range.
1133 // This can be used to detect deletion of the invoke via the
1134 // MachineModuleInfo.
1135 unsigned EndLabel = MMI->NextLabelID();
1136 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1137 DAG.getConstant(EndLabel, MVT::i32)));
1138
1139 // Inform MachineModuleInfo of range.
1140 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1141
1142 // Drop into normal successor.
1143 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1144 DAG.getBasicBlock(Return)));
1145
1146 // Update successor info
1147 CurMBB->addSuccessor(Return);
1148 CurMBB->addSuccessor(LandingPad);
1149}
1150
1151void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1152}
1153
Nate Begemanf15485a2006-03-27 01:32:24 +00001154void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1155 // Figure out which block is immediately after the current one.
1156 MachineBasicBlock *NextBlock = 0;
1157 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001158
Nate Begemanf15485a2006-03-27 01:32:24 +00001159 if (++BBI != CurMBB->getParent()->end())
1160 NextBlock = BBI;
1161
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001162 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1163
Nate Begemanf15485a2006-03-27 01:32:24 +00001164 // If there is only the default destination, branch to it if it is not the
1165 // next basic block. Otherwise, just fall through.
1166 if (I.getNumOperands() == 2) {
1167 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001168
Nate Begemanf15485a2006-03-27 01:32:24 +00001169 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001170 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001171 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001172 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001173
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001174 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001175 return;
1176 }
1177
1178 // If there are any non-default case statements, create a vector of Cases
1179 // representing each one, and sort the vector so that we can efficiently
1180 // create a binary search tree from them.
1181 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001182
Nate Begemanf15485a2006-03-27 01:32:24 +00001183 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1184 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1185 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1186 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001187
Nate Begemanf15485a2006-03-27 01:32:24 +00001188 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1189
1190 // Get the Value to be switched on and default basic blocks, which will be
1191 // inserted into CaseBlock records, representing basic blocks in the binary
1192 // search tree.
1193 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001194
1195 // Get the MachineFunction which holds the current MBB. This is used during
1196 // emission of jump tables, and when inserting any additional MBBs necessary
1197 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001198 MachineFunction *CurMF = CurMBB->getParent();
1199 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001200
1201 // If the switch has few cases (two or less) emit a series of specific
1202 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001203 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001204 // TODO: If any two of the cases has the same destination, and if one value
1205 // is the same as the other, but has one bit unset that the other has set,
1206 // use bit manipulation to do two compares at once. For example:
1207 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1208
Chris Lattnerb3543432006-10-23 18:38:22 +00001209 // Rearrange the case blocks so that the last one falls through if possible.
1210 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1211 // The last case block won't fall through into 'NextBlock' if we emit the
1212 // branches in this order. See if rearranging a case value would help.
1213 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1214 if (Cases[i].second == NextBlock) {
1215 std::swap(Cases[i], Cases.back());
1216 break;
1217 }
1218 }
1219 }
1220
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001221 // Create a CaseBlock record representing a conditional branch to
1222 // the Case's target mbb if the value being switched on SV is equal
1223 // to C.
1224 MachineBasicBlock *CurBlock = CurMBB;
1225 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1226 MachineBasicBlock *FallThrough;
1227 if (i != e-1) {
1228 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1229 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1230 } else {
1231 // If the last case doesn't match, go to the default block.
1232 FallThrough = Default;
1233 }
1234
1235 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1236 Cases[i].second, FallThrough, CurBlock);
1237
1238 // If emitting the first comparison, just call visitSwitchCase to emit the
1239 // code into the current block. Otherwise, push the CaseBlock onto the
1240 // vector to be later processed by SDISel, and insert the node's MBB
1241 // before the next MBB.
1242 if (CurBlock == CurMBB)
1243 visitSwitchCase(CB);
1244 else
1245 SwitchCases.push_back(CB);
1246
1247 CurBlock = FallThrough;
1248 }
1249 return;
1250 }
Nate Begeman37efe672006-04-22 18:53:45 +00001251
Nate Begeman17c275f2006-05-08 16:51:36 +00001252 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1253 // target supports indirect branches, then emit a jump table rather than
1254 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001255 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1256 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001257 Cases.size() > 5) {
Chris Lattner21840b12007-02-14 07:18:16 +00001258 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1259 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001260 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1261
Nate Begeman17c275f2006-05-08 16:51:36 +00001262 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001263 // Create a new basic block to hold the code for loading the address
1264 // of the jump table, and jumping to it. Update successor information;
1265 // we will either branch to the default case for the switch, or the jump
1266 // table.
1267 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1268 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1269 CurMBB->addSuccessor(Default);
1270 CurMBB->addSuccessor(JumpTableBB);
1271
1272 // Subtract the lowest switch case value from the value being switched on
1273 // and conditional branch to default mbb if the result is greater than the
1274 // difference between smallest and largest cases.
1275 SDOperand SwitchOp = getValue(SV);
1276 MVT::ValueType VT = SwitchOp.getValueType();
1277 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1278 DAG.getConstant(First, VT));
1279
1280 // The SDNode we just created, which holds the value being switched on
1281 // minus the the smallest case value, needs to be copied to a virtual
1282 // register so it can be used as an index into the jump table in a
1283 // subsequent basic block. This value may be smaller or larger than the
1284 // target's pointer type, and therefore require extension or truncating.
1285 if (VT > TLI.getPointerTy())
1286 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1287 else
1288 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001289
Nate Begeman37efe672006-04-22 18:53:45 +00001290 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1291 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1292
1293 // Emit the range check for the jump table, and branch to the default
1294 // block for the switch statement if the value being switched on exceeds
1295 // the largest case in the switch.
1296 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1297 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1298 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1299 DAG.getBasicBlock(Default)));
1300
Nate Begemanf4360a42006-05-03 03:48:02 +00001301 // Build a vector of destination BBs, corresponding to each target
1302 // of the jump table. If the value of the jump table slot corresponds to
1303 // a case statement, push the case's BB onto the vector, otherwise, push
1304 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001305 std::vector<MachineBasicBlock*> DestBBs;
Chris Lattnerc661d612007-02-14 07:34:56 +00001306 int64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001307 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Chris Lattner21840b12007-02-14 07:18:16 +00001308 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001309 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001310 ++ii;
1311 } else {
1312 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001313 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001314
Chris Lattner8c494ab2006-10-27 23:50:33 +00001315 // Update successor info. Add one edge to each unique successor.
1316 // Vector bool would be better, but vector<bool> is really slow.
1317 std::vector<unsigned char> SuccsHandled;
1318 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1319
Chris Lattnerc66764c2006-09-10 06:36:57 +00001320 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001321 E = DestBBs.end(); I != E; ++I) {
1322 if (!SuccsHandled[(*I)->getNumber()]) {
1323 SuccsHandled[(*I)->getNumber()] = true;
1324 JumpTableBB->addSuccessor(*I);
1325 }
1326 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001327
1328 // Create a jump table index for this jump table, or return an existing
1329 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001330 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1331
1332 // Set the jump table information so that we can codegen it as a second
1333 // MachineBasicBlock
1334 JT.Reg = JumpTableReg;
1335 JT.JTI = JTI;
1336 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001337 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001338 return;
1339 }
1340 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001341
1342 // Push the initial CaseRec onto the worklist
1343 std::vector<CaseRec> CaseVec;
1344 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1345
1346 while (!CaseVec.empty()) {
1347 // Grab a record representing a case range to process off the worklist
1348 CaseRec CR = CaseVec.back();
1349 CaseVec.pop_back();
1350
1351 // Size is the number of Cases represented by this range. If Size is 1,
1352 // then we are processing a leaf of the binary search tree. Otherwise,
1353 // we need to pick a pivot, and push left and right ranges onto the
1354 // worklist.
1355 unsigned Size = CR.Range.second - CR.Range.first;
1356
1357 if (Size == 1) {
1358 // Create a CaseBlock record representing a conditional branch to
1359 // the Case's target mbb if the value being switched on SV is equal
1360 // to C. Otherwise, branch to default.
1361 Constant *C = CR.Range.first->first;
1362 MachineBasicBlock *Target = CR.Range.first->second;
1363 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1364 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001365
Nate Begemanf15485a2006-03-27 01:32:24 +00001366 // If the MBB representing the leaf node is the current MBB, then just
1367 // call visitSwitchCase to emit the code into the current block.
1368 // Otherwise, push the CaseBlock onto the vector to be later processed
1369 // by SDISel, and insert the node's MBB before the next MBB.
1370 if (CR.CaseBB == CurMBB)
1371 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001372 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001373 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001374 } else {
1375 // split case range at pivot
1376 CaseItr Pivot = CR.Range.first + (Size / 2);
1377 CaseRange LHSR(CR.Range.first, Pivot);
1378 CaseRange RHSR(Pivot, CR.Range.second);
1379 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001380 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001381
Nate Begemanf15485a2006-03-27 01:32:24 +00001382 // We know that we branch to the LHS if the Value being switched on is
1383 // less than the Pivot value, C. We use this to optimize our binary
1384 // tree a bit, by recognizing that if SV is greater than or equal to the
1385 // LHS's Case Value, and that Case Value is exactly one less than the
1386 // Pivot's Value, then we can branch directly to the LHS's Target,
1387 // rather than creating a leaf node for it.
1388 if ((LHSR.second - LHSR.first) == 1 &&
1389 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001390 cast<ConstantInt>(C)->getZExtValue() ==
1391 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001392 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001393 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001394 TrueBB = new MachineBasicBlock(LLVMBB);
1395 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1396 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001397 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001398
Nate Begemanf15485a2006-03-27 01:32:24 +00001399 // Similar to the optimization above, if the Value being switched on is
1400 // known to be less than the Constant CR.LT, and the current Case Value
1401 // is CR.LT - 1, then we can branch directly to the target block for
1402 // the current Case Value, rather than emitting a RHS leaf node for it.
1403 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001404 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1405 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001406 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001407 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001408 FalseBB = new MachineBasicBlock(LLVMBB);
1409 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1410 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001411 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001412
Nate Begemanf15485a2006-03-27 01:32:24 +00001413 // Create a CaseBlock record representing a conditional branch to
1414 // the LHS node if the value being switched on SV is less than C.
1415 // Otherwise, branch to LHS.
Chris Lattner21840b12007-02-14 07:18:16 +00001416 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1417 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001418
Nate Begemanf15485a2006-03-27 01:32:24 +00001419 if (CR.CaseBB == CurMBB)
1420 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001421 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001422 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001423 }
1424 }
1425}
1426
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001427void SelectionDAGLowering::visitSub(User &I) {
1428 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001429 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001430 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001431 visitVectorBinary(I, ISD::VSUB);
1432 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001433 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1434 if (CFP->isExactlyValue(-0.0)) {
1435 SDOperand Op2 = getValue(I.getOperand(1));
1436 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1437 return;
1438 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001439 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001440 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001441 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001442}
1443
Reid Spencer24d6da52007-01-21 00:29:26 +00001444void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001445 SDOperand Op1 = getValue(I.getOperand(0));
1446 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001447
1448 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001449}
1450
Reid Spencer24d6da52007-01-21 00:29:26 +00001451void
1452SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 assert(isa<VectorType>(I.getType()));
1454 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001455 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001456
Reid Spencer24d6da52007-01-21 00:29:26 +00001457 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1458 getValue(I.getOperand(0)),
1459 getValue(I.getOperand(1)),
1460 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1461 Typ));
1462}
1463
1464void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1465 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001467 visitVectorBinary(I, VectorOp);
1468 else
1469 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001470}
Chris Lattner2c49f272005-01-19 22:31:21 +00001471
Nate Begemane21ea612005-11-18 07:42:56 +00001472void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1473 SDOperand Op1 = getValue(I.getOperand(0));
1474 SDOperand Op2 = getValue(I.getOperand(1));
1475
Reid Spencer832254e2007-02-02 02:16:23 +00001476 if (TLI.getShiftAmountTy() < Op2.getValueType())
1477 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1478 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1479 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001480
Chris Lattner1c08c712005-01-07 07:47:53 +00001481 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1482}
1483
Reid Spencer45fb3f32006-11-20 01:22:35 +00001484void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001485 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1486 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1487 predicate = IC->getPredicate();
1488 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1489 predicate = ICmpInst::Predicate(IC->getPredicate());
1490 SDOperand Op1 = getValue(I.getOperand(0));
1491 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001492 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001493 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001494 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1495 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1496 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1497 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1498 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1499 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1500 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1501 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1502 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1503 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1504 default:
1505 assert(!"Invalid ICmp predicate value");
1506 Opcode = ISD::SETEQ;
1507 break;
1508 }
1509 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1510}
1511
1512void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001513 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1514 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1515 predicate = FC->getPredicate();
1516 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1517 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001518 SDOperand Op1 = getValue(I.getOperand(0));
1519 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001520 ISD::CondCode Condition, FOC, FPC;
1521 switch (predicate) {
1522 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1523 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1524 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1525 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1526 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1527 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1528 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1529 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1530 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1531 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1532 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1533 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1534 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1535 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1536 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1537 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1538 default:
1539 assert(!"Invalid FCmp predicate value");
1540 FOC = FPC = ISD::SETFALSE;
1541 break;
1542 }
1543 if (FiniteOnlyFPMath())
1544 Condition = FOC;
1545 else
1546 Condition = FPC;
1547 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001548}
1549
1550void SelectionDAGLowering::visitSelect(User &I) {
1551 SDOperand Cond = getValue(I.getOperand(0));
1552 SDOperand TrueVal = getValue(I.getOperand(1));
1553 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001554 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001555 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1556 TrueVal, FalseVal));
1557 } else {
1558 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1559 *(TrueVal.Val->op_end()-2),
1560 *(TrueVal.Val->op_end()-1)));
1561 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001562}
1563
Reid Spencer3da59db2006-11-27 01:05:10 +00001564
1565void SelectionDAGLowering::visitTrunc(User &I) {
1566 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1567 SDOperand N = getValue(I.getOperand(0));
1568 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1569 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1570}
1571
1572void SelectionDAGLowering::visitZExt(User &I) {
1573 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1574 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1575 SDOperand N = getValue(I.getOperand(0));
1576 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1577 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1578}
1579
1580void SelectionDAGLowering::visitSExt(User &I) {
1581 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1582 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1583 SDOperand N = getValue(I.getOperand(0));
1584 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1585 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1586}
1587
1588void SelectionDAGLowering::visitFPTrunc(User &I) {
1589 // FPTrunc is never a no-op cast, no need to check
1590 SDOperand N = getValue(I.getOperand(0));
1591 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1592 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1593}
1594
1595void SelectionDAGLowering::visitFPExt(User &I){
1596 // FPTrunc is never a no-op cast, no need to check
1597 SDOperand N = getValue(I.getOperand(0));
1598 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1599 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1600}
1601
1602void SelectionDAGLowering::visitFPToUI(User &I) {
1603 // FPToUI is never a no-op cast, no need to check
1604 SDOperand N = getValue(I.getOperand(0));
1605 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1606 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1607}
1608
1609void SelectionDAGLowering::visitFPToSI(User &I) {
1610 // FPToSI is never a no-op cast, no need to check
1611 SDOperand N = getValue(I.getOperand(0));
1612 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1613 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1614}
1615
1616void SelectionDAGLowering::visitUIToFP(User &I) {
1617 // UIToFP is never a no-op cast, no need to check
1618 SDOperand N = getValue(I.getOperand(0));
1619 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1620 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1621}
1622
1623void SelectionDAGLowering::visitSIToFP(User &I){
1624 // UIToFP is never a no-op cast, no need to check
1625 SDOperand N = getValue(I.getOperand(0));
1626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1627 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1628}
1629
1630void SelectionDAGLowering::visitPtrToInt(User &I) {
1631 // What to do depends on the size of the integer and the size of the pointer.
1632 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001633 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001634 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001635 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001636 SDOperand Result;
1637 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1638 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1639 else
1640 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1641 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1642 setValue(&I, Result);
1643}
Chris Lattner1c08c712005-01-07 07:47:53 +00001644
Reid Spencer3da59db2006-11-27 01:05:10 +00001645void SelectionDAGLowering::visitIntToPtr(User &I) {
1646 // What to do depends on the size of the integer and the size of the pointer.
1647 // We can either truncate, zero extend, or no-op, accordingly.
1648 SDOperand N = getValue(I.getOperand(0));
1649 MVT::ValueType SrcVT = N.getValueType();
1650 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1651 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1652 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1653 else
1654 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1655 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1656}
1657
1658void SelectionDAGLowering::visitBitCast(User &I) {
1659 SDOperand N = getValue(I.getOperand(0));
1660 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001661 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001662 // This is a cast to a vector from something else.
1663 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001664 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001665 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1666 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1667 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1668 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001669 return;
1670 }
1671 MVT::ValueType SrcVT = N.getValueType();
1672 if (SrcVT == MVT::Vector) {
1673 // This is a cast from a vctor to something else.
1674 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001675 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001676 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001677 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001678
1679 // BitCast assures us that source and destination are the same size so this
1680 // is either a BIT_CONVERT or a no-op.
1681 if (DestVT != N.getValueType())
1682 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1683 else
1684 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001685}
1686
Chris Lattner2bbd8102006-03-29 00:11:43 +00001687void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001688 SDOperand InVec = getValue(I.getOperand(0));
1689 SDOperand InVal = getValue(I.getOperand(1));
1690 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1691 getValue(I.getOperand(2)));
1692
Chris Lattner2332b9f2006-03-19 01:17:20 +00001693 SDOperand Num = *(InVec.Val->op_end()-2);
1694 SDOperand Typ = *(InVec.Val->op_end()-1);
1695 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1696 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001697}
1698
Chris Lattner2bbd8102006-03-29 00:11:43 +00001699void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001700 SDOperand InVec = getValue(I.getOperand(0));
1701 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1702 getValue(I.getOperand(1)));
1703 SDOperand Typ = *(InVec.Val->op_end()-1);
1704 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1705 TLI.getValueType(I.getType()), InVec, InIdx));
1706}
Chris Lattnerc7029802006-03-18 01:44:44 +00001707
Chris Lattner3e104b12006-04-08 04:15:24 +00001708void SelectionDAGLowering::visitShuffleVector(User &I) {
1709 SDOperand V1 = getValue(I.getOperand(0));
1710 SDOperand V2 = getValue(I.getOperand(1));
1711 SDOperand Mask = getValue(I.getOperand(2));
1712
1713 SDOperand Num = *(V1.Val->op_end()-2);
1714 SDOperand Typ = *(V2.Val->op_end()-1);
1715 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1716 V1, V2, Mask, Num, Typ));
1717}
1718
1719
Chris Lattner1c08c712005-01-07 07:47:53 +00001720void SelectionDAGLowering::visitGetElementPtr(User &I) {
1721 SDOperand N = getValue(I.getOperand(0));
1722 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001723
1724 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1725 OI != E; ++OI) {
1726 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001727 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001728 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001729 if (Field) {
1730 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00001731 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00001732 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001733 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001734 }
1735 Ty = StTy->getElementType(Field);
1736 } else {
1737 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001738
Chris Lattner7c0104b2005-11-09 04:45:33 +00001739 // If this is a constant subscript, handle it quickly.
1740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001741 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001742 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001743 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001744 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1745 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001746 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001747
1748 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001749 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001750 SDOperand IdxN = getValue(Idx);
1751
1752 // If the index is smaller or larger than intptr_t, truncate or extend
1753 // it.
1754 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001755 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001756 } else if (IdxN.getValueType() > N.getValueType())
1757 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1758
1759 // If this is a multiply by a power of two, turn it into a shl
1760 // immediately. This is a very common case.
1761 if (isPowerOf2_64(ElementSize)) {
1762 unsigned Amt = Log2_64(ElementSize);
1763 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001764 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001765 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1766 continue;
1767 }
1768
1769 SDOperand Scale = getIntPtrConstant(ElementSize);
1770 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1771 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001772 }
1773 }
1774 setValue(&I, N);
1775}
1776
1777void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1778 // If this is a fixed sized alloca in the entry block of the function,
1779 // allocate it statically on the stack.
1780 if (FuncInfo.StaticAllocaMap.count(&I))
1781 return; // getValue will auto-populate this.
1782
1783 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001784 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001785 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00001786 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00001787 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001788
1789 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001790 MVT::ValueType IntPtr = TLI.getPointerTy();
1791 if (IntPtr < AllocSize.getValueType())
1792 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1793 else if (IntPtr > AllocSize.getValueType())
1794 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001795
Chris Lattner68cd65e2005-01-22 23:04:37 +00001796 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001797 getIntPtrConstant(TySize));
1798
1799 // Handle alignment. If the requested alignment is less than or equal to the
1800 // stack alignment, ignore it and round the size of the allocation up to the
1801 // stack alignment size. If the size is greater than the stack alignment, we
1802 // note this in the DYNAMIC_STACKALLOC node.
1803 unsigned StackAlign =
1804 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1805 if (Align <= StackAlign) {
1806 Align = 0;
1807 // Add SA-1 to the size.
1808 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1809 getIntPtrConstant(StackAlign-1));
1810 // Mask out the low bits for alignment purposes.
1811 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1812 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1813 }
1814
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001815 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001816 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1817 MVT::Other);
1818 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00001819 setValue(&I, DSA);
1820 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001821
1822 // Inform the Frame Information that we have just allocated a variable-sized
1823 // object.
1824 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1825}
1826
Chris Lattner1c08c712005-01-07 07:47:53 +00001827void SelectionDAGLowering::visitLoad(LoadInst &I) {
1828 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001829
Chris Lattnerd3948112005-01-17 22:19:26 +00001830 SDOperand Root;
1831 if (I.isVolatile())
1832 Root = getRoot();
1833 else {
1834 // Do not serialize non-volatile loads against each other.
1835 Root = DAG.getRoot();
1836 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001837
Evan Cheng466685d2006-10-09 20:57:25 +00001838 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001839 Root, I.isVolatile()));
1840}
1841
1842SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001843 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001844 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001845 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001846 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001847 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001848 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1849 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001850 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001851 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001852 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001853
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001854 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001855 DAG.setRoot(L.getValue(1));
1856 else
1857 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001858
1859 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001860}
1861
1862
1863void SelectionDAGLowering::visitStore(StoreInst &I) {
1864 Value *SrcV = I.getOperand(0);
1865 SDOperand Src = getValue(SrcV);
1866 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001867 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001868 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001869}
1870
Chris Lattner0eade312006-03-24 02:22:33 +00001871/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1872/// access memory and has no other side effects at all.
1873static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1874#define GET_NO_MEMORY_INTRINSICS
1875#include "llvm/Intrinsics.gen"
1876#undef GET_NO_MEMORY_INTRINSICS
1877 return false;
1878}
1879
Chris Lattnere58a7802006-04-02 03:41:14 +00001880// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1881// have any side-effects or if it only reads memory.
1882static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1883#define GET_SIDE_EFFECT_INFO
1884#include "llvm/Intrinsics.gen"
1885#undef GET_SIDE_EFFECT_INFO
1886 return false;
1887}
1888
Chris Lattner0eade312006-03-24 02:22:33 +00001889/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1890/// node.
1891void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1892 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001893 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001894 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001895
1896 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001897 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001898 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1899 if (OnlyLoad) {
1900 // We don't need to serialize loads against other loads.
1901 Ops.push_back(DAG.getRoot());
1902 } else {
1903 Ops.push_back(getRoot());
1904 }
1905 }
Chris Lattner0eade312006-03-24 02:22:33 +00001906
1907 // Add the intrinsic ID as an integer operand.
1908 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1909
1910 // Add all operands of the call to the operand list.
1911 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1912 SDOperand Op = getValue(I.getOperand(i));
1913
Reid Spencerac9dcb92007-02-15 03:39:18 +00001914 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00001915 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001916 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001917 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1918
1919 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1920 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1921 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1922 }
1923
1924 assert(TLI.isTypeLegal(Op.getValueType()) &&
1925 "Intrinsic uses a non-legal type?");
1926 Ops.push_back(Op);
1927 }
1928
1929 std::vector<MVT::ValueType> VTs;
1930 if (I.getType() != Type::VoidTy) {
1931 MVT::ValueType VT = TLI.getValueType(I.getType());
1932 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001933 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001934 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1935
1936 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1937 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1938 }
1939
1940 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1941 VTs.push_back(VT);
1942 }
1943 if (HasChain)
1944 VTs.push_back(MVT::Other);
1945
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001946 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1947
Chris Lattner0eade312006-03-24 02:22:33 +00001948 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001949 SDOperand Result;
1950 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001951 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1952 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001953 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001954 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1955 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001956 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001957 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1958 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001959
Chris Lattnere58a7802006-04-02 03:41:14 +00001960 if (HasChain) {
1961 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1962 if (OnlyLoad)
1963 PendingLoads.push_back(Chain);
1964 else
1965 DAG.setRoot(Chain);
1966 }
Chris Lattner0eade312006-03-24 02:22:33 +00001967 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001968 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00001969 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1970 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1971 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1972 DAG.getValueType(EVT));
1973 }
1974 setValue(&I, Result);
1975 }
1976}
1977
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001978/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1979/// we want to emit this as a call to a named external function, return the name
1980/// otherwise lower it and return null.
1981const char *
1982SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1983 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001984 default:
1985 // By default, turn this into a target intrinsic node.
1986 visitTargetIntrinsic(I, Intrinsic);
1987 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001988 case Intrinsic::vastart: visitVAStart(I); return 0;
1989 case Intrinsic::vaend: visitVAEnd(I); return 0;
1990 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00001991 case Intrinsic::returnaddress:
1992 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1993 getValue(I.getOperand(1))));
1994 return 0;
1995 case Intrinsic::frameaddress:
1996 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1997 getValue(I.getOperand(1))));
1998 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001999 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002000 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002001 break;
2002 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002003 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002004 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002005 case Intrinsic::memcpy_i32:
2006 case Intrinsic::memcpy_i64:
2007 visitMemIntrinsic(I, ISD::MEMCPY);
2008 return 0;
2009 case Intrinsic::memset_i32:
2010 case Intrinsic::memset_i64:
2011 visitMemIntrinsic(I, ISD::MEMSET);
2012 return 0;
2013 case Intrinsic::memmove_i32:
2014 case Intrinsic::memmove_i64:
2015 visitMemIntrinsic(I, ISD::MEMMOVE);
2016 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002017
Chris Lattner86cb6432005-12-13 17:40:33 +00002018 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002019 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002020 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002021 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002022 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002023
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002024 Ops[0] = getRoot();
2025 Ops[1] = getValue(SPI.getLineValue());
2026 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002027
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002028 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002029 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002030 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2031
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002032 Ops[3] = DAG.getString(CompileUnit->getFileName());
2033 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002034
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002035 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002036 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002037
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002038 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002039 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002040 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002041 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002042 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002043 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2044 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002045 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002046 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002047 }
2048
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002049 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002050 }
2051 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002052 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002053 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002054 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2055 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002056 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002057 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002058 }
2059
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002060 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002061 }
2062 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002063 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002064 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002065 if (MMI && FSI.getSubprogram() &&
2066 MMI->Verify(FSI.getSubprogram())) {
2067 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002068 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002069 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002070 }
2071
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002072 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002073 }
2074 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002075 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002076 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002077 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002078 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002079 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002080 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002081 }
2082
2083 return 0;
2084 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002085
Jim Laskeyb180aa12007-02-21 22:53:45 +00002086 case Intrinsic::eh_exception: {
2087 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2088
2089 // Add a label to mark the beginning of the landing pad. Deletion of the
2090 // landing pad can thus be detected via the MachineModuleInfo.
2091 unsigned LabelID = MMI->addLandingPad(CurMBB);
2092 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2093 DAG.getConstant(LabelID, MVT::i32)));
2094
2095 // Mark exception register as live in.
2096 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2097 unsigned Reg = MRI->getEHExceptionRegister();
2098 if (Reg) CurMBB->addLiveIn(Reg);
2099
2100 // Insert the EXCEPTIONADDR instruction.
2101 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2102 SDOperand Ops[1];
2103 Ops[0] = DAG.getRoot();
2104 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2105 setValue(&I, Op);
2106 DAG.setRoot(Op.getValue(1));
2107
2108 return 0;
2109 }
2110
2111 case Intrinsic::eh_handlers: {
2112 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2113
2114 // Inform the MachineModuleInfo of the personality for this landing pad.
2115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2))) {
2116 if (CE->getOpcode() == Instruction::BitCast) {
2117 MMI->addPersonality(CurMBB,
2118 cast<Function>(CE->getOperand(0)));
2119 }
2120 }
2121
2122 // Gather all the type infos for this landing pad and pass them along to
2123 // MachineModuleInfo.
2124 std::vector<GlobalVariable *> TyInfo;
2125 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2126 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2127 if (CE->getOpcode() == Instruction::BitCast) {
2128 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2129 continue;
2130 }
2131 }
2132
2133 TyInfo.push_back(NULL);
2134 }
2135 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2136
2137 // Mark exception selector register as live in.
2138 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2139 unsigned Reg = MRI->getEHHandlerRegister();
2140 if (Reg) CurMBB->addLiveIn(Reg);
2141
2142 // Insert the EHSELECTION instruction.
2143 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2144 SDOperand Ops[2];
2145 Ops[0] = getValue(I.getOperand(1));
2146 Ops[1] = getRoot();
2147 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2148 setValue(&I, Op);
2149 DAG.setRoot(Op.getValue(1));
2150
2151 return 0;
2152 }
2153
2154 case Intrinsic::eh_typeid_for: {
2155 GlobalVariable *GV = NULL;
2156
2157 // Find the type id for the given typeinfo.
2158 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1))) {
2160 if (CE->getOpcode() == Instruction::BitCast) {
2161 GV = cast<GlobalVariable>(CE->getOperand(0));
2162 }
2163 }
2164
2165 unsigned TypeID = MMI->getTypeIDFor(GV);
2166 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2167
2168 return 0;
2169 }
2170
Reid Spencer0b118202006-01-16 21:12:35 +00002171 case Intrinsic::sqrt_f32:
2172 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002173 setValue(&I, DAG.getNode(ISD::FSQRT,
2174 getValue(I.getOperand(1)).getValueType(),
2175 getValue(I.getOperand(1))));
2176 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002177 case Intrinsic::powi_f32:
2178 case Intrinsic::powi_f64:
2179 setValue(&I, DAG.getNode(ISD::FPOWI,
2180 getValue(I.getOperand(1)).getValueType(),
2181 getValue(I.getOperand(1)),
2182 getValue(I.getOperand(2))));
2183 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002184 case Intrinsic::pcmarker: {
2185 SDOperand Tmp = getValue(I.getOperand(1));
2186 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2187 return 0;
2188 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002189 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002190 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002191 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2192 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2193 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002194 setValue(&I, Tmp);
2195 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002196 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002197 }
Nate Begemand88fc032006-01-14 03:14:10 +00002198 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002199 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002200 case Intrinsic::bswap_i64:
2201 setValue(&I, DAG.getNode(ISD::BSWAP,
2202 getValue(I.getOperand(1)).getValueType(),
2203 getValue(I.getOperand(1))));
2204 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002205 case Intrinsic::cttz_i8:
2206 case Intrinsic::cttz_i16:
2207 case Intrinsic::cttz_i32:
2208 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002209 setValue(&I, DAG.getNode(ISD::CTTZ,
2210 getValue(I.getOperand(1)).getValueType(),
2211 getValue(I.getOperand(1))));
2212 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002213 case Intrinsic::ctlz_i8:
2214 case Intrinsic::ctlz_i16:
2215 case Intrinsic::ctlz_i32:
2216 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002217 setValue(&I, DAG.getNode(ISD::CTLZ,
2218 getValue(I.getOperand(1)).getValueType(),
2219 getValue(I.getOperand(1))));
2220 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002221 case Intrinsic::ctpop_i8:
2222 case Intrinsic::ctpop_i16:
2223 case Intrinsic::ctpop_i32:
2224 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002225 setValue(&I, DAG.getNode(ISD::CTPOP,
2226 getValue(I.getOperand(1)).getValueType(),
2227 getValue(I.getOperand(1))));
2228 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002229 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002230 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002231 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2232 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002233 setValue(&I, Tmp);
2234 DAG.setRoot(Tmp.getValue(1));
2235 return 0;
2236 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002237 case Intrinsic::stackrestore: {
2238 SDOperand Tmp = getValue(I.getOperand(1));
2239 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002240 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002241 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002242 case Intrinsic::prefetch:
2243 // FIXME: Currently discarding prefetches.
2244 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002245 }
2246}
2247
2248
Chris Lattner1c08c712005-01-07 07:47:53 +00002249void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002250 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002251 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002252 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002253 if (unsigned IID = F->getIntrinsicID()) {
2254 RenameFn = visitIntrinsicCall(I, IID);
2255 if (!RenameFn)
2256 return;
2257 } else { // Not an LLVM intrinsic.
2258 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002259 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2260 if (I.getNumOperands() == 3 && // Basic sanity checks.
2261 I.getOperand(1)->getType()->isFloatingPoint() &&
2262 I.getType() == I.getOperand(1)->getType() &&
2263 I.getType() == I.getOperand(2)->getType()) {
2264 SDOperand LHS = getValue(I.getOperand(1));
2265 SDOperand RHS = getValue(I.getOperand(2));
2266 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2267 LHS, RHS));
2268 return;
2269 }
2270 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002271 if (I.getNumOperands() == 2 && // Basic sanity checks.
2272 I.getOperand(1)->getType()->isFloatingPoint() &&
2273 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002274 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002275 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2276 return;
2277 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002278 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002279 if (I.getNumOperands() == 2 && // Basic sanity checks.
2280 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002281 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002282 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002283 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2284 return;
2285 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002286 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002287 if (I.getNumOperands() == 2 && // Basic sanity checks.
2288 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002289 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002290 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002291 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2292 return;
2293 }
2294 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002295 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002296 } else if (isa<InlineAsm>(I.getOperand(0))) {
2297 visitInlineAsm(I);
2298 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002299 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002300
Reid Spencer47857812006-12-31 05:55:36 +00002301 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2302 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2303
Chris Lattner64e14b12005-01-08 22:48:57 +00002304 SDOperand Callee;
2305 if (!RenameFn)
2306 Callee = getValue(I.getOperand(0));
2307 else
2308 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencer47857812006-12-31 05:55:36 +00002309 TargetLowering::ArgListTy Args;
2310 TargetLowering::ArgListEntry Entry;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002311 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002312 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2313 Value *Arg = I.getOperand(i);
2314 SDOperand ArgNode = getValue(Arg);
Reid Spencer47857812006-12-31 05:55:36 +00002315 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2316 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002317 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2318 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
Reid Spencer47857812006-12-31 05:55:36 +00002319 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002320 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002321
Chris Lattnercf5734d2005-01-08 19:26:18 +00002322 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002323 TLI.LowerCallTo(getRoot(), I.getType(),
2324 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2325 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2326 Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002327 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002328 setValue(&I, Result.first);
2329 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002330}
2331
Chris Lattner864635a2006-02-22 22:37:12 +00002332SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002333 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002334 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2335 Chain = Val.getValue(1);
2336 Flag = Val.getValue(2);
2337
2338 // If the result was expanded, copy from the top part.
2339 if (Regs.size() > 1) {
2340 assert(Regs.size() == 2 &&
2341 "Cannot expand to more than 2 elts yet!");
2342 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002343 Chain = Hi.getValue(1);
2344 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002345 if (DAG.getTargetLoweringInfo().isLittleEndian())
2346 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2347 else
2348 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002349 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002350
Chris Lattnercf752aa2006-06-08 18:22:48 +00002351 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002352 // appropriate type.
2353 if (RegVT == ValueVT)
2354 return Val;
2355
Chris Lattnercf752aa2006-06-08 18:22:48 +00002356 if (MVT::isInteger(RegVT)) {
2357 if (ValueVT < RegVT)
2358 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2359 else
2360 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2361 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002362 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002363 }
Chris Lattner864635a2006-02-22 22:37:12 +00002364}
2365
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002366/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2367/// specified value into the registers specified by this object. This uses
2368/// Chain/Flag as the input and updates them for the output Chain/Flag.
2369void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002370 SDOperand &Chain, SDOperand &Flag,
2371 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002372 if (Regs.size() == 1) {
2373 // If there is a single register and the types differ, this must be
2374 // a promotion.
2375 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002376 if (MVT::isInteger(RegVT)) {
2377 if (RegVT < ValueVT)
2378 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2379 else
2380 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2381 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002382 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2383 }
2384 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2385 Flag = Chain.getValue(1);
2386 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002387 std::vector<unsigned> R(Regs);
2388 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2389 std::reverse(R.begin(), R.end());
2390
2391 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002392 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002393 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002394 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002395 Flag = Chain.getValue(1);
2396 }
2397 }
2398}
Chris Lattner864635a2006-02-22 22:37:12 +00002399
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002400/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2401/// operand list. This adds the code marker and includes the number of
2402/// values added into it.
2403void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002404 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002405 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2406 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2407 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2408}
Chris Lattner864635a2006-02-22 22:37:12 +00002409
2410/// isAllocatableRegister - If the specified register is safe to allocate,
2411/// i.e. it isn't a stack pointer or some other special register, return the
2412/// register class for the register. Otherwise, return null.
2413static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002414isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2415 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002416 MVT::ValueType FoundVT = MVT::Other;
2417 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002418 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2419 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002420 MVT::ValueType ThisVT = MVT::Other;
2421
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002422 const TargetRegisterClass *RC = *RCI;
2423 // If none of the the value types for this register class are valid, we
2424 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002425 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2426 I != E; ++I) {
2427 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002428 // If we have already found this register in a different register class,
2429 // choose the one with the largest VT specified. For example, on
2430 // PowerPC, we favor f64 register classes over f32.
2431 if (FoundVT == MVT::Other ||
2432 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2433 ThisVT = *I;
2434 break;
2435 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002436 }
2437 }
2438
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002439 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002440
Chris Lattner864635a2006-02-22 22:37:12 +00002441 // NOTE: This isn't ideal. In particular, this might allocate the
2442 // frame pointer in functions that need it (due to them not being taken
2443 // out of allocation, because a variable sized allocation hasn't been seen
2444 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002445 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2446 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002447 if (*I == Reg) {
2448 // We found a matching register class. Keep looking at others in case
2449 // we find one with larger registers that this physreg is also in.
2450 FoundRC = RC;
2451 FoundVT = ThisVT;
2452 break;
2453 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002454 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002455 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002456}
2457
2458RegsForValue SelectionDAGLowering::
2459GetRegistersForValue(const std::string &ConstrCode,
2460 MVT::ValueType VT, bool isOutReg, bool isInReg,
2461 std::set<unsigned> &OutputRegs,
2462 std::set<unsigned> &InputRegs) {
2463 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2464 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2465 std::vector<unsigned> Regs;
2466
2467 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2468 MVT::ValueType RegVT;
2469 MVT::ValueType ValueVT = VT;
2470
Chris Lattner2a821602006-11-02 01:41:49 +00002471 // If this is a constraint for a specific physical register, like {r17},
2472 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002473 if (PhysReg.first) {
2474 if (VT == MVT::Other)
2475 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002476
2477 // Get the actual register value type. This is important, because the user
2478 // may have asked for (e.g.) the AX register in i32 type. We need to
2479 // remember that AX is actually i16 to get the right extension.
2480 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002481
2482 // This is a explicit reference to a physical register.
2483 Regs.push_back(PhysReg.first);
2484
2485 // If this is an expanded reference, add the rest of the regs to Regs.
2486 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002487 TargetRegisterClass::iterator I = PhysReg.second->begin();
2488 TargetRegisterClass::iterator E = PhysReg.second->end();
2489 for (; *I != PhysReg.first; ++I)
2490 assert(I != E && "Didn't find reg!");
2491
2492 // Already added the first reg.
2493 --NumRegs; ++I;
2494 for (; NumRegs; --NumRegs, ++I) {
2495 assert(I != E && "Ran out of registers to allocate!");
2496 Regs.push_back(*I);
2497 }
2498 }
2499 return RegsForValue(Regs, RegVT, ValueVT);
2500 }
2501
Chris Lattner2a821602006-11-02 01:41:49 +00002502 // Otherwise, if this was a reference to an LLVM register class, create vregs
2503 // for this reference.
2504 std::vector<unsigned> RegClassRegs;
2505 if (PhysReg.second) {
2506 // If this is an early clobber or tied register, our regalloc doesn't know
2507 // how to maintain the constraint. If it isn't, go ahead and create vreg
2508 // and let the regalloc do the right thing.
2509 if (!isOutReg || !isInReg) {
2510 if (VT == MVT::Other)
2511 ValueVT = *PhysReg.second->vt_begin();
2512 RegVT = *PhysReg.second->vt_begin();
2513
2514 // Create the appropriate number of virtual registers.
2515 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2516 for (; NumRegs; --NumRegs)
2517 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2518
2519 return RegsForValue(Regs, RegVT, ValueVT);
2520 }
2521
2522 // Otherwise, we can't allocate it. Let the code below figure out how to
2523 // maintain these constraints.
2524 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2525
2526 } else {
2527 // This is a reference to a register class that doesn't directly correspond
2528 // to an LLVM register class. Allocate NumRegs consecutive, available,
2529 // registers from the class.
2530 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2531 }
Chris Lattner864635a2006-02-22 22:37:12 +00002532
2533 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2534 MachineFunction &MF = *CurMBB->getParent();
2535 unsigned NumAllocated = 0;
2536 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2537 unsigned Reg = RegClassRegs[i];
2538 // See if this register is available.
2539 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2540 (isInReg && InputRegs.count(Reg))) { // Already used.
2541 // Make sure we find consecutive registers.
2542 NumAllocated = 0;
2543 continue;
2544 }
2545
2546 // Check to see if this register is allocatable (i.e. don't give out the
2547 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002548 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002549 if (!RC) {
2550 // Make sure we find consecutive registers.
2551 NumAllocated = 0;
2552 continue;
2553 }
2554
2555 // Okay, this register is good, we can use it.
2556 ++NumAllocated;
2557
2558 // If we allocated enough consecutive
2559 if (NumAllocated == NumRegs) {
2560 unsigned RegStart = (i-NumAllocated)+1;
2561 unsigned RegEnd = i+1;
2562 // Mark all of the allocated registers used.
2563 for (unsigned i = RegStart; i != RegEnd; ++i) {
2564 unsigned Reg = RegClassRegs[i];
2565 Regs.push_back(Reg);
2566 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2567 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2568 }
2569
2570 return RegsForValue(Regs, *RC->vt_begin(), VT);
2571 }
2572 }
2573
2574 // Otherwise, we couldn't allocate enough registers for this.
2575 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002576}
2577
Chris Lattner367f1092007-01-29 23:45:14 +00002578/// getConstraintGenerality - Return an integer indicating how general CT is.
2579static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2580 switch (CT) {
2581 default: assert(0 && "Unknown constraint type!");
2582 case TargetLowering::C_Other:
2583 case TargetLowering::C_Unknown:
2584 return 0;
2585 case TargetLowering::C_Register:
2586 return 1;
2587 case TargetLowering::C_RegisterClass:
2588 return 2;
2589 case TargetLowering::C_Memory:
2590 return 3;
2591 }
2592}
2593
2594static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2595 const TargetLowering &TLI) {
2596 assert(!C.empty() && "Must have at least one constraint");
2597 if (C.size() == 1) return C[0];
2598
2599 std::string *Current = &C[0];
2600 // If we have multiple constraints, try to pick the most general one ahead
2601 // of time. This isn't a wonderful solution, but handles common cases.
2602 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2603 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2604 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2605 if (getConstraintGenerality(ThisFlavor) >
2606 getConstraintGenerality(Flavor)) {
2607 // This constraint letter is more general than the previous one,
2608 // use it.
2609 Flavor = ThisFlavor;
2610 Current = &C[j];
2611 }
2612 }
2613 return *Current;
2614}
2615
Chris Lattner864635a2006-02-22 22:37:12 +00002616
Chris Lattnerce7518c2006-01-26 22:24:51 +00002617/// visitInlineAsm - Handle a call to an InlineAsm object.
2618///
2619void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2620 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2621
2622 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2623 MVT::Other);
2624
Chris Lattner2cc2f662006-02-01 01:28:23 +00002625 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002626 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002627
2628 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2629 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2630 /// if it is a def of that register.
2631 std::vector<SDOperand> AsmNodeOperands;
2632 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2633 AsmNodeOperands.push_back(AsmStr);
2634
2635 SDOperand Chain = getRoot();
2636 SDOperand Flag;
2637
Chris Lattner4e4b5762006-02-01 18:59:47 +00002638 // We fully assign registers here at isel time. This is not optimal, but
2639 // should work. For register classes that correspond to LLVM classes, we
2640 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2641 // over the constraints, collecting fixed registers that we know we can't use.
2642 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002643 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002644 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002645 std::string ConstraintCode =
2646 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002647
Chris Lattner1efa40f2006-02-22 00:56:39 +00002648 MVT::ValueType OpVT;
2649
2650 // Compute the value type for each operand and add it to ConstraintVTs.
2651 switch (Constraints[i].Type) {
2652 case InlineAsm::isOutput:
2653 if (!Constraints[i].isIndirectOutput) {
2654 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2655 OpVT = TLI.getValueType(I.getType());
2656 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002657 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002658 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2659 OpNum++; // Consumes a call operand.
2660 }
2661 break;
2662 case InlineAsm::isInput:
2663 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2664 OpNum++; // Consumes a call operand.
2665 break;
2666 case InlineAsm::isClobber:
2667 OpVT = MVT::Other;
2668 break;
2669 }
2670
2671 ConstraintVTs.push_back(OpVT);
2672
Chris Lattner864635a2006-02-22 22:37:12 +00002673 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2674 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002675
Chris Lattner864635a2006-02-22 22:37:12 +00002676 // Build a list of regs that this operand uses. This always has a single
2677 // element for promoted/expanded operands.
2678 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2679 false, false,
2680 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002681
2682 switch (Constraints[i].Type) {
2683 case InlineAsm::isOutput:
2684 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002685 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002686 // If this is an early-clobber output, it cannot be assigned to the same
2687 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002688 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002689 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002690 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002691 case InlineAsm::isInput:
2692 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002693 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002694 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002695 case InlineAsm::isClobber:
2696 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002697 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2698 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002699 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002700 }
2701 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002702
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002703 // Loop over all of the inputs, copying the operand values into the
2704 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002705 RegsForValue RetValRegs;
2706 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002707 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002708
Chris Lattner6656dd12006-01-31 02:03:41 +00002709 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002710 std::string ConstraintCode =
2711 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002712
Chris Lattner2cc2f662006-02-01 01:28:23 +00002713 switch (Constraints[i].Type) {
2714 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002715 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2716 if (ConstraintCode.size() == 1) // not a physreg name.
2717 CTy = TLI.getConstraintType(ConstraintCode[0]);
2718
2719 if (CTy == TargetLowering::C_Memory) {
2720 // Memory output.
2721 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2722
2723 // Check that the operand (the address to store to) isn't a float.
2724 if (!MVT::isInteger(InOperandVal.getValueType()))
2725 assert(0 && "MATCH FAIL!");
2726
2727 if (!Constraints[i].isIndirectOutput)
2728 assert(0 && "MATCH FAIL!");
2729
2730 OpNum++; // Consumes a call operand.
2731
2732 // Extend/truncate to the right pointer type if needed.
2733 MVT::ValueType PtrType = TLI.getPointerTy();
2734 if (InOperandVal.getValueType() < PtrType)
2735 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2736 else if (InOperandVal.getValueType() > PtrType)
2737 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2738
2739 // Add information to the INLINEASM node to know about this output.
2740 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2741 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2742 AsmNodeOperands.push_back(InOperandVal);
2743 break;
2744 }
2745
2746 // Otherwise, this is a register output.
2747 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2748
Chris Lattner864635a2006-02-22 22:37:12 +00002749 // If this is an early-clobber output, or if there is an input
2750 // constraint that matches this, we need to reserve the input register
2751 // so no other inputs allocate to it.
2752 bool UsesInputRegister = false;
2753 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2754 UsesInputRegister = true;
2755
2756 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002757 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002758 RegsForValue Regs =
2759 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2760 true, UsesInputRegister,
2761 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002762 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002763 cerr << "Couldn't allocate output reg for contraint '"
2764 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002765 exit(1);
2766 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002767
Chris Lattner2cc2f662006-02-01 01:28:23 +00002768 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002769 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002770 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002771 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002772 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002773 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002774 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2775 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002776 OpNum++; // Consumes a call operand.
2777 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002778
2779 // Add information to the INLINEASM node to know that this register is
2780 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002781 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002782 break;
2783 }
2784 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002785 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002786 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002787
Chris Lattner2223aea2006-02-02 00:25:23 +00002788 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2789 // If this is required to match an output register we have already set,
2790 // just use its register.
2791 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002792
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002793 // Scan until we find the definition we already emitted of this operand.
2794 // When we find it, create a RegsForValue operand.
2795 unsigned CurOp = 2; // The first operand.
2796 for (; OperandNo; --OperandNo) {
2797 // Advance to the next operand.
2798 unsigned NumOps =
2799 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002800 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2801 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002802 "Skipped past definitions?");
2803 CurOp += (NumOps>>3)+1;
2804 }
2805
2806 unsigned NumOps =
2807 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00002808 if ((NumOps & 7) == 2 /*REGDEF*/) {
2809 // Add NumOps>>3 registers to MatchedRegs.
2810 RegsForValue MatchedRegs;
2811 MatchedRegs.ValueVT = InOperandVal.getValueType();
2812 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2813 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2814 unsigned Reg =
2815 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2816 MatchedRegs.Regs.push_back(Reg);
2817 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002818
Chris Lattner527fae12007-02-01 01:21:12 +00002819 // Use the produced MatchedRegs object to
2820 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2821 TLI.getPointerTy());
2822 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2823 break;
2824 } else {
2825 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2826 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002827 }
Chris Lattner2223aea2006-02-02 00:25:23 +00002828 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002829
2830 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2831 if (ConstraintCode.size() == 1) // not a physreg name.
2832 CTy = TLI.getConstraintType(ConstraintCode[0]);
2833
2834 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002835 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2836 ConstraintCode[0], DAG);
2837 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002838 cerr << "Invalid operand for inline asm constraint '"
2839 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002840 exit(1);
2841 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002842
2843 // Add information to the INLINEASM node to know about this input.
2844 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2845 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2846 AsmNodeOperands.push_back(InOperandVal);
2847 break;
2848 } else if (CTy == TargetLowering::C_Memory) {
2849 // Memory input.
2850
2851 // Check that the operand isn't a float.
2852 if (!MVT::isInteger(InOperandVal.getValueType()))
2853 assert(0 && "MATCH FAIL!");
2854
2855 // Extend/truncate to the right pointer type if needed.
2856 MVT::ValueType PtrType = TLI.getPointerTy();
2857 if (InOperandVal.getValueType() < PtrType)
2858 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2859 else if (InOperandVal.getValueType() > PtrType)
2860 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2861
2862 // Add information to the INLINEASM node to know about this input.
2863 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2864 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2865 AsmNodeOperands.push_back(InOperandVal);
2866 break;
2867 }
2868
2869 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2870
2871 // Copy the input into the appropriate registers.
2872 RegsForValue InRegs =
2873 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2874 false, true, OutputRegs, InputRegs);
2875 // FIXME: should be match fail.
2876 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2877
Evan Chenga8441262006-06-15 08:11:54 +00002878 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002879
2880 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002881 break;
2882 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002883 case InlineAsm::isClobber: {
2884 RegsForValue ClobberedRegs =
2885 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2886 OutputRegs, InputRegs);
2887 // Add the clobbered value to the operand list, so that the register
2888 // allocator is aware that the physreg got clobbered.
2889 if (!ClobberedRegs.Regs.empty())
2890 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002891 break;
2892 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002893 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002894 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002895
2896 // Finish up input operands.
2897 AsmNodeOperands[0] = Chain;
2898 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2899
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002900 Chain = DAG.getNode(ISD::INLINEASM,
2901 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002902 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002903 Flag = Chain.getValue(1);
2904
Chris Lattner6656dd12006-01-31 02:03:41 +00002905 // If this asm returns a register value, copy the result from that register
2906 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002907 if (!RetValRegs.Regs.empty())
2908 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002909
Chris Lattner6656dd12006-01-31 02:03:41 +00002910 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2911
2912 // Process indirect outputs, first output all of the flagged copies out of
2913 // physregs.
2914 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002915 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002916 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002917 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2918 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002919 }
2920
2921 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002922 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002923 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002924 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002925 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002926 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002927 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002928 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2929 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002930 DAG.setRoot(Chain);
2931}
2932
2933
Chris Lattner1c08c712005-01-07 07:47:53 +00002934void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2935 SDOperand Src = getValue(I.getOperand(0));
2936
2937 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002938
2939 if (IntPtr < Src.getValueType())
2940 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2941 else if (IntPtr > Src.getValueType())
2942 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002943
2944 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002945 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002946 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2947 Src, getIntPtrConstant(ElementSize));
2948
Reid Spencer47857812006-12-31 05:55:36 +00002949 TargetLowering::ArgListTy Args;
2950 TargetLowering::ArgListEntry Entry;
2951 Entry.Node = Src;
2952 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2953 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002954 Entry.isInReg = false;
2955 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002956 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002957
2958 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002959 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002960 DAG.getExternalSymbol("malloc", IntPtr),
2961 Args, DAG);
2962 setValue(&I, Result.first); // Pointers always fit in registers
2963 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002964}
2965
2966void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002967 TargetLowering::ArgListTy Args;
2968 TargetLowering::ArgListEntry Entry;
2969 Entry.Node = getValue(I.getOperand(0));
2970 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2971 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002972 Entry.isInReg = false;
2973 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002974 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002975 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002976 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002977 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002978 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2979 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002980}
2981
Chris Lattner025c39b2005-08-26 20:54:47 +00002982// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2983// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2984// instructions are special in various ways, which require special support to
2985// insert. The specified MachineInstr is created but not inserted into any
2986// basic blocks, and the scheduler passes ownership of it to this method.
2987MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2988 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002989 cerr << "If a target marks an instruction with "
2990 << "'usesCustomDAGSchedInserter', it must implement "
2991 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002992 abort();
2993 return 0;
2994}
2995
Chris Lattner39ae3622005-01-09 00:00:49 +00002996void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002997 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2998 getValue(I.getOperand(1)),
2999 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003000}
3001
3002void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003003 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3004 getValue(I.getOperand(0)),
3005 DAG.getSrcValue(I.getOperand(0)));
3006 setValue(&I, V);
3007 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003008}
3009
3010void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003011 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3012 getValue(I.getOperand(1)),
3013 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003014}
3015
3016void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003017 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3018 getValue(I.getOperand(1)),
3019 getValue(I.getOperand(2)),
3020 DAG.getSrcValue(I.getOperand(1)),
3021 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003022}
3023
Evan Chengb15974a2006-12-12 07:27:38 +00003024/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3025/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3026static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3027 unsigned &i, SelectionDAG &DAG,
3028 TargetLowering &TLI) {
3029 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3030 return SDOperand(Arg, i++);
3031
3032 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3033 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3034 if (NumVals == 1) {
3035 return DAG.getNode(ISD::BIT_CONVERT, VT,
3036 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3037 } else if (NumVals == 2) {
3038 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3039 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3040 if (!TLI.isLittleEndian())
3041 std::swap(Lo, Hi);
3042 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3043 } else {
3044 // Value scalarized into many values. Unimp for now.
3045 assert(0 && "Cannot expand i64 -> i16 yet!");
3046 }
3047 return SDOperand();
3048}
3049
Chris Lattnerfdfded52006-04-12 16:20:43 +00003050/// TargetLowering::LowerArguments - This is the default LowerArguments
3051/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003052/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3053/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003054std::vector<SDOperand>
3055TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003056 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003057 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3058 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003059 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003060 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3061 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3062
3063 // Add one result value for each formal argument.
3064 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003065 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003066 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3067 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003068 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003069 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003070 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003071 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003072 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003073 // Flags[31:27] -> OriginalAlignment
3074 // Flags[2] -> isSRet
3075 // Flags[1] -> isInReg
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003076 unsigned Flags = (isInReg << 1) | (isSRet << 2) | (OriginalAlignment << 27);
3077
Chris Lattnerfdfded52006-04-12 16:20:43 +00003078 switch (getTypeAction(VT)) {
3079 default: assert(0 && "Unknown type action!");
3080 case Legal:
3081 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003082 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003083 break;
3084 case Promote:
3085 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003086 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003087 break;
3088 case Expand:
3089 if (VT != MVT::Vector) {
3090 // If this is a large integer, it needs to be broken up into small
3091 // integers. Figure out what the destination type is and how many small
3092 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003093 MVT::ValueType NVT = getTypeToExpandTo(VT);
3094 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003095 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003096 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003097 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003098 if (i == 1) Flags = (Flags & 0x07ffffff) | (1 << 27);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003099 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3100 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003101 } else {
3102 // Otherwise, this is a vector type. We only support legal vectors
3103 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003104 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3105 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003106
Chris Lattnerfdfded52006-04-12 16:20:43 +00003107 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003108 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003109 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3110 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3111 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003112 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003113 } else {
3114 assert(0 && "Don't support illegal by-val vector arguments yet!");
3115 }
3116 }
3117 break;
3118 }
3119 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003120
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003121 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003122
3123 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003124 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3125 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003126 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003127
3128 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003129
3130 // Set up the return result vector.
3131 Ops.clear();
3132 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003133 unsigned Idx = 1;
3134 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3135 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003136 MVT::ValueType VT = getValueType(I->getType());
3137
3138 switch (getTypeAction(VT)) {
3139 default: assert(0 && "Unknown type action!");
3140 case Legal:
3141 Ops.push_back(SDOperand(Result, i++));
3142 break;
3143 case Promote: {
3144 SDOperand Op(Result, i++);
3145 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003146 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3147 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3148 DAG.getValueType(VT));
3149 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3150 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3151 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003152 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3153 } else {
3154 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3155 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3156 }
3157 Ops.push_back(Op);
3158 break;
3159 }
3160 case Expand:
3161 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003162 // If this is a large integer or a floating point node that needs to be
3163 // expanded, it needs to be reassembled from small integers. Figure out
3164 // what the source elt type is and how many small integers it is.
3165 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003166 } else {
3167 // Otherwise, this is a vector type. We only support legal vectors
3168 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003169 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003170 unsigned NumElems = PTy->getNumElements();
3171 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003172
Chris Lattnerfdfded52006-04-12 16:20:43 +00003173 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003174 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003175 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003176 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003177 SDOperand N = SDOperand(Result, i++);
3178 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003179 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3180 DAG.getConstant(NumElems, MVT::i32),
3181 DAG.getValueType(getValueType(EltTy)));
3182 Ops.push_back(N);
3183 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003184 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003185 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003186 }
3187 }
3188 break;
3189 }
3190 }
3191 return Ops;
3192}
3193
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003194
Evan Chengb15974a2006-12-12 07:27:38 +00003195/// ExpandScalarCallArgs - Recursively expand call argument node by
3196/// bit_converting it or extract a pair of elements from the larger node.
3197static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003198 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003199 SmallVector<SDOperand, 32> &Ops,
3200 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003201 TargetLowering &TLI,
3202 bool isFirst = true) {
3203
Evan Chengb15974a2006-12-12 07:27:38 +00003204 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003205 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003206 if (!isFirst)
3207 Flags = (Flags & 0x07ffffff) | (1 << 27);
Evan Chengb15974a2006-12-12 07:27:38 +00003208 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003209 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003210 return;
3211 }
3212
3213 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3214 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3215 if (NumVals == 1) {
3216 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003217 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003218 } else if (NumVals == 2) {
3219 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3220 DAG.getConstant(0, TLI.getPointerTy()));
3221 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3222 DAG.getConstant(1, TLI.getPointerTy()));
3223 if (!TLI.isLittleEndian())
3224 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003225 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3226 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003227 } else {
3228 // Value scalarized into many values. Unimp for now.
3229 assert(0 && "Cannot expand i64 -> i16 yet!");
3230 }
3231}
3232
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003233/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3234/// implementation, which just inserts an ISD::CALL node, which is later custom
3235/// lowered by the target to something concrete. FIXME: When all targets are
3236/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3237std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003238TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3239 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003240 unsigned CallingConv, bool isTailCall,
3241 SDOperand Callee,
3242 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003243 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003244 Ops.push_back(Chain); // Op#0 - Chain
3245 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3246 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3247 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3248 Ops.push_back(Callee);
3249
3250 // Handle all of the outgoing arguments.
3251 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003252 MVT::ValueType VT = getValueType(Args[i].Ty);
3253 SDOperand Op = Args[i].Node;
3254 bool isSigned = Args[i].isSigned;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003255 bool isInReg = Args[i].isInReg;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003256 bool isSRet = Args[i].isSRet;
3257 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003258 getTargetData()->getABITypeAlignment(Args[i].Ty);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003259 // Flags[31:27] -> OriginalAlignment
3260 // Flags[2] -> isSRet
3261 // Flags[1] -> isInReg
3262 // Flags[0] -> isSigned
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003263 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned |
3264 (OriginalAlignment << 27);
3265
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003266 switch (getTypeAction(VT)) {
3267 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003268 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003269 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003270 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003271 break;
3272 case Promote:
3273 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003274 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003275 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3276 } else {
3277 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3278 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3279 }
3280 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003281 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003282 break;
3283 case Expand:
3284 if (VT != MVT::Vector) {
3285 // If this is a large integer, it needs to be broken down into small
3286 // integers. Figure out what the source elt type is and how many small
3287 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003288 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003289 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003290 // Otherwise, this is a vector type. We only support legal vectors
3291 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003292 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003293 unsigned NumElems = PTy->getNumElements();
3294 const Type *EltTy = PTy->getElementType();
3295
3296 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003297 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003298 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003299 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003300 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003301 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3302 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003303 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003304 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003305 assert(0 && "Don't support illegal by-val vector call args yet!");
3306 abort();
3307 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003308 }
3309 break;
3310 }
3311 }
3312
3313 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003314 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003315
3316 if (RetTy != Type::VoidTy) {
3317 MVT::ValueType VT = getValueType(RetTy);
3318 switch (getTypeAction(VT)) {
3319 default: assert(0 && "Unknown type action!");
3320 case Legal:
3321 RetTys.push_back(VT);
3322 break;
3323 case Promote:
3324 RetTys.push_back(getTypeToTransformTo(VT));
3325 break;
3326 case Expand:
3327 if (VT != MVT::Vector) {
3328 // If this is a large integer, it needs to be reassembled from small
3329 // integers. Figure out what the source elt type is and how many small
3330 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003331 MVT::ValueType NVT = getTypeToExpandTo(VT);
3332 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003333 for (unsigned i = 0; i != NumVals; ++i)
3334 RetTys.push_back(NVT);
3335 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003336 // Otherwise, this is a vector type. We only support legal vectors
3337 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003338 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003339 unsigned NumElems = PTy->getNumElements();
3340 const Type *EltTy = PTy->getElementType();
3341
3342 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003343 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003344 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3345 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3346 RetTys.push_back(TVT);
3347 } else {
3348 assert(0 && "Don't support illegal by-val vector call results yet!");
3349 abort();
3350 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003351 }
3352 }
3353 }
3354
3355 RetTys.push_back(MVT::Other); // Always has a chain.
3356
3357 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003358 SDOperand Res = DAG.getNode(ISD::CALL,
3359 DAG.getVTList(&RetTys[0], RetTys.size()),
3360 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003361
3362 // This returns a pair of operands. The first element is the
3363 // return value for the function (if RetTy is not VoidTy). The second
3364 // element is the outgoing token chain.
3365 SDOperand ResVal;
3366 if (RetTys.size() != 1) {
3367 MVT::ValueType VT = getValueType(RetTy);
3368 if (RetTys.size() == 2) {
3369 ResVal = Res;
3370
3371 // If this value was promoted, truncate it down.
3372 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003373 if (VT == MVT::Vector) {
3374 // Insert a VBITCONVERT to convert from the packed result type to the
3375 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003376 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3377 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003378
3379 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003380 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003381 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003382 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003383 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3384 // "N x PTyElementVT" MVT::Vector type.
3385 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003386 DAG.getConstant(NumElems, MVT::i32),
3387 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003388 } else {
3389 abort();
3390 }
3391 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003392 unsigned AssertOp = ISD::AssertSext;
3393 if (!RetTyIsSigned)
3394 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003395 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3396 DAG.getValueType(VT));
3397 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3398 } else {
3399 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003400 if (getTypeAction(VT) == Expand)
3401 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3402 else
3403 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003404 }
3405 }
3406 } else if (RetTys.size() == 3) {
3407 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3408 Res.getValue(0), Res.getValue(1));
3409
3410 } else {
3411 assert(0 && "Case not handled yet!");
3412 }
3413 }
3414
3415 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3416}
3417
Chris Lattner50381b62005-05-14 05:50:48 +00003418SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003419 assert(0 && "LowerOperation not implemented for this target!");
3420 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003421 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003422}
3423
Nate Begeman0aed7842006-01-28 03:14:31 +00003424SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3425 SelectionDAG &DAG) {
3426 assert(0 && "CustomPromoteOperation not implemented for this target!");
3427 abort();
3428 return SDOperand();
3429}
3430
Evan Cheng74d0aa92006-02-15 21:59:04 +00003431/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003432/// operand.
3433static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003434 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003435 MVT::ValueType CurVT = VT;
3436 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3437 uint64_t Val = C->getValue() & 255;
3438 unsigned Shift = 8;
3439 while (CurVT != MVT::i8) {
3440 Val = (Val << Shift) | Val;
3441 Shift <<= 1;
3442 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003443 }
3444 return DAG.getConstant(Val, VT);
3445 } else {
3446 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3447 unsigned Shift = 8;
3448 while (CurVT != MVT::i8) {
3449 Value =
3450 DAG.getNode(ISD::OR, VT,
3451 DAG.getNode(ISD::SHL, VT, Value,
3452 DAG.getConstant(Shift, MVT::i8)), Value);
3453 Shift <<= 1;
3454 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003455 }
3456
3457 return Value;
3458 }
3459}
3460
Evan Cheng74d0aa92006-02-15 21:59:04 +00003461/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3462/// used when a memcpy is turned into a memset when the source is a constant
3463/// string ptr.
3464static SDOperand getMemsetStringVal(MVT::ValueType VT,
3465 SelectionDAG &DAG, TargetLowering &TLI,
3466 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003467 uint64_t Val = 0;
3468 unsigned MSB = getSizeInBits(VT) / 8;
3469 if (TLI.isLittleEndian())
3470 Offset = Offset + MSB - 1;
3471 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003472 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003473 Offset += TLI.isLittleEndian() ? -1 : 1;
3474 }
3475 return DAG.getConstant(Val, VT);
3476}
3477
Evan Cheng1db92f92006-02-14 08:22:34 +00003478/// getMemBasePlusOffset - Returns base and offset node for the
3479static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3480 SelectionDAG &DAG, TargetLowering &TLI) {
3481 MVT::ValueType VT = Base.getValueType();
3482 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3483}
3484
Evan Chengc4f8eee2006-02-14 20:12:38 +00003485/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003486/// to replace the memset / memcpy is below the threshold. It also returns the
3487/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003488static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3489 unsigned Limit, uint64_t Size,
3490 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003491 MVT::ValueType VT;
3492
3493 if (TLI.allowsUnalignedMemoryAccesses()) {
3494 VT = MVT::i64;
3495 } else {
3496 switch (Align & 7) {
3497 case 0:
3498 VT = MVT::i64;
3499 break;
3500 case 4:
3501 VT = MVT::i32;
3502 break;
3503 case 2:
3504 VT = MVT::i16;
3505 break;
3506 default:
3507 VT = MVT::i8;
3508 break;
3509 }
3510 }
3511
Evan Cheng80e89d72006-02-14 09:11:59 +00003512 MVT::ValueType LVT = MVT::i64;
3513 while (!TLI.isTypeLegal(LVT))
3514 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3515 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003516
Evan Cheng80e89d72006-02-14 09:11:59 +00003517 if (VT > LVT)
3518 VT = LVT;
3519
Evan Chengdea72452006-02-14 23:05:54 +00003520 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003521 while (Size != 0) {
3522 unsigned VTSize = getSizeInBits(VT) / 8;
3523 while (VTSize > Size) {
3524 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003525 VTSize >>= 1;
3526 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003527 assert(MVT::isInteger(VT));
3528
3529 if (++NumMemOps > Limit)
3530 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003531 MemOps.push_back(VT);
3532 Size -= VTSize;
3533 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003534
3535 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003536}
3537
Chris Lattner7041ee32005-01-11 05:56:49 +00003538void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003539 SDOperand Op1 = getValue(I.getOperand(1));
3540 SDOperand Op2 = getValue(I.getOperand(2));
3541 SDOperand Op3 = getValue(I.getOperand(3));
3542 SDOperand Op4 = getValue(I.getOperand(4));
3543 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3544 if (Align == 0) Align = 1;
3545
3546 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3547 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003548
3549 // Expand memset / memcpy to a series of load / store ops
3550 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003551 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003552 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003553 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003554 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003555 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3556 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003557 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003558 unsigned Offset = 0;
3559 for (unsigned i = 0; i < NumMemOps; i++) {
3560 MVT::ValueType VT = MemOps[i];
3561 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003562 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003563 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003564 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003565 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003566 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003567 Offset += VTSize;
3568 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003569 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003570 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003571 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003572 case ISD::MEMCPY: {
3573 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3574 Size->getValue(), Align, TLI)) {
3575 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003576 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003577 GlobalAddressSDNode *G = NULL;
3578 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003579 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003580
3581 if (Op2.getOpcode() == ISD::GlobalAddress)
3582 G = cast<GlobalAddressSDNode>(Op2);
3583 else if (Op2.getOpcode() == ISD::ADD &&
3584 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3585 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3586 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003587 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003588 }
3589 if (G) {
3590 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003591 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003592 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003593 if (!Str.empty()) {
3594 CopyFromStr = true;
3595 SrcOff += SrcDelta;
3596 }
3597 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003598 }
3599
Evan Chengc080d6f2006-02-15 01:54:51 +00003600 for (unsigned i = 0; i < NumMemOps; i++) {
3601 MVT::ValueType VT = MemOps[i];
3602 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003603 SDOperand Value, Chain, Store;
3604
Evan Chengcffbb512006-02-16 23:11:42 +00003605 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003606 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3607 Chain = getRoot();
3608 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003609 DAG.getStore(Chain, Value,
3610 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003611 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003612 } else {
3613 Value = DAG.getLoad(VT, getRoot(),
3614 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003615 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003616 Chain = Value.getValue(1);
3617 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003618 DAG.getStore(Chain, Value,
3619 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003620 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003621 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003622 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003623 SrcOff += VTSize;
3624 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003625 }
3626 }
3627 break;
3628 }
3629 }
3630
3631 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003632 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3633 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003634 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003635 }
3636 }
3637
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003638 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003639}
3640
Chris Lattner7041ee32005-01-11 05:56:49 +00003641//===----------------------------------------------------------------------===//
3642// SelectionDAGISel code
3643//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003644
3645unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3646 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3647}
3648
Chris Lattner495a0b52005-08-17 06:37:43 +00003649void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003650 // FIXME: we only modify the CFG to split critical edges. This
3651 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003652 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003653}
Chris Lattner1c08c712005-01-07 07:47:53 +00003654
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003655
Chris Lattner90323642006-05-05 21:17:49 +00003656/// OptimizeNoopCopyExpression - We have determined that the specified cast
3657/// instruction is a noop copy (e.g. it's casting from one pointer type to
3658/// another, int->uint, or int->sbyte on PPC.
3659///
3660/// Return true if any changes are made.
3661static bool OptimizeNoopCopyExpression(CastInst *CI) {
3662 BasicBlock *DefBB = CI->getParent();
3663
3664 /// InsertedCasts - Only insert a cast in each block once.
3665 std::map<BasicBlock*, CastInst*> InsertedCasts;
3666
3667 bool MadeChange = false;
3668 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3669 UI != E; ) {
3670 Use &TheUse = UI.getUse();
3671 Instruction *User = cast<Instruction>(*UI);
3672
3673 // Figure out which BB this cast is used in. For PHI's this is the
3674 // appropriate predecessor block.
3675 BasicBlock *UserBB = User->getParent();
3676 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3677 unsigned OpVal = UI.getOperandNo()/2;
3678 UserBB = PN->getIncomingBlock(OpVal);
3679 }
3680
3681 // Preincrement use iterator so we don't invalidate it.
3682 ++UI;
3683
3684 // If this user is in the same block as the cast, don't change the cast.
3685 if (UserBB == DefBB) continue;
3686
3687 // If we have already inserted a cast into this block, use it.
3688 CastInst *&InsertedCast = InsertedCasts[UserBB];
3689
3690 if (!InsertedCast) {
3691 BasicBlock::iterator InsertPt = UserBB->begin();
3692 while (isa<PHINode>(InsertPt)) ++InsertPt;
3693
3694 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003695 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3696 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003697 MadeChange = true;
3698 }
3699
3700 // Replace a use of the cast with a use of the new casat.
3701 TheUse = InsertedCast;
3702 }
3703
3704 // If we removed all uses, nuke the cast.
3705 if (CI->use_empty())
3706 CI->eraseFromParent();
3707
3708 return MadeChange;
3709}
3710
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003711/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3712/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003713static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3714 Instruction *GEPI, Value *Ptr,
3715 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003716 if (V) return V; // Already computed.
3717
Reid Spencer3da59db2006-11-27 01:05:10 +00003718 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003719 BasicBlock::iterator InsertPt;
3720 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003721 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003722 InsertPt = GEPI;
3723 ++InsertPt;
3724 } else {
3725 // Otherwise, insert at the top of BB, after any PHI nodes
3726 InsertPt = BB->begin();
3727 while (isa<PHINode>(InsertPt)) ++InsertPt;
3728 }
3729
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003730 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3731 // BB so that there is only one value live across basic blocks (the cast
3732 // operand).
3733 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3734 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003735 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3736 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003737
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003738 // Add the offset, cast it to the right type.
3739 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003740 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3741 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3742 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003743}
3744
Chris Lattner90323642006-05-05 21:17:49 +00003745/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3746/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3747/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3748/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3749/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3750/// the constant add into a load or store instruction. Additionally, if a user
3751/// is a pointer-pointer cast, we look through it to find its users.
3752static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3753 Constant *PtrOffset, BasicBlock *DefBB,
3754 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003755 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003756 while (!RepPtr->use_empty()) {
3757 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003758
Reid Spencer3da59db2006-11-27 01:05:10 +00003759 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3760 // used for a Pointer-Pointer cast.
3761 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003762 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003763
Chris Lattner90323642006-05-05 21:17:49 +00003764 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3765 // could invalidate an iterator.
3766 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3767 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003768 }
3769
Chris Lattner90323642006-05-05 21:17:49 +00003770 // If this is a load of the pointer, or a store through the pointer, emit
3771 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003772 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003773 if (isa<LoadInst>(User) ||
3774 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3775 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3776 User->getParent(), GEPI,
3777 Ptr, PtrOffset);
3778 } else {
3779 // If this use is not foldable into the addressing mode, use a version
3780 // emitted in the GEP block.
3781 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3782 Ptr, PtrOffset);
3783 }
3784
Chris Lattnerf0df8822006-05-06 09:10:37 +00003785 if (GEPI->getType() != RepPtr->getType()) {
3786 BasicBlock::iterator IP = NewVal;
3787 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003788 // NewVal must be a GEP which must be pointer type, so BitCast
3789 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003790 }
Chris Lattner90323642006-05-05 21:17:49 +00003791 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003792 }
3793}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003794
Chris Lattner90323642006-05-05 21:17:49 +00003795
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003796/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3797/// selection, we want to be a bit careful about some things. In particular, if
3798/// we have a GEP instruction that is used in a different block than it is
3799/// defined, the addressing expression of the GEP cannot be folded into loads or
3800/// stores that use it. In this case, decompose the GEP and move constant
3801/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003802static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003803 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003804 // If this GEP is only used inside the block it is defined in, there is no
3805 // need to rewrite it.
3806 bool isUsedOutsideDefBB = false;
3807 BasicBlock *DefBB = GEPI->getParent();
3808 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3809 UI != E; ++UI) {
3810 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3811 isUsedOutsideDefBB = true;
3812 break;
3813 }
3814 }
Chris Lattner90323642006-05-05 21:17:49 +00003815 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003816
3817 // If this GEP has no non-zero constant indices, there is nothing we can do,
3818 // ignore it.
3819 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003820 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003821 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3822 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003823 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003824 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003825 hasConstantIndex = true;
3826 break;
3827 }
Chris Lattner90323642006-05-05 21:17:49 +00003828 } else {
3829 hasVariableIndex = true;
3830 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003831 }
Chris Lattner90323642006-05-05 21:17:49 +00003832
3833 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3834 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003835 /// The GEP operand must be a pointer, so must its result -> BitCast
3836 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003837 GEPI->getName(), GEPI);
3838 GEPI->replaceAllUsesWith(NC);
3839 GEPI->eraseFromParent();
3840 return true;
3841 }
3842
Chris Lattner3802c252005-12-11 09:05:13 +00003843 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003844 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3845 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003846
3847 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3848 // constant offset (which we now know is non-zero) and deal with it later.
3849 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003850 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003851 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003852 const Type *Ty = GEPI->getOperand(0)->getType();
3853
3854 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3855 E = GEPI->op_end(); OI != E; ++OI) {
3856 Value *Idx = *OI;
3857 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003858 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003859 if (Field)
Chris Lattnerb1919e22007-02-10 19:55:17 +00003860 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003861 Ty = StTy->getElementType(Field);
3862 } else {
3863 Ty = cast<SequentialType>(Ty)->getElementType();
3864
3865 // Handle constant subscripts.
3866 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003867 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003868 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003869 continue;
3870 }
3871
3872 // Ptr = Ptr + Idx * ElementSize;
3873
3874 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003875 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003876
Owen Andersona69571c2006-05-03 01:29:57 +00003877 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003878 // Mask off bits that should not be set.
3879 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003880 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003881
3882 // Multiply by the element size and add to the base.
3883 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3884 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3885 }
3886 }
3887
3888 // Make sure that the offset fits in uintptr_t.
3889 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003890 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003891
3892 // Okay, we have now emitted all of the variable index parts to the BB that
3893 // the GEP is defined in. Loop over all of the using instructions, inserting
3894 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003895 // instruction to use the newly computed value, making GEPI dead. When the
3896 // user is a load or store instruction address, we emit the add into the user
3897 // block, otherwise we use a canonical version right next to the gep (these
3898 // won't be foldable as addresses, so we might as well share the computation).
3899
Chris Lattnerf0df8822006-05-06 09:10:37 +00003900 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003901 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003902
3903 // Finally, the GEP is dead, remove it.
3904 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003905
3906 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003907}
3908
Chris Lattnerbad7f482006-10-28 19:22:10 +00003909
3910/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3911/// successor if it will improve codegen. We only do this if the successor has
3912/// phi nodes (otherwise critical edges are ok). If there is already another
3913/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3914/// instead of introducing a new block.
3915static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3916 BasicBlock *TIBB = TI->getParent();
3917 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3918 assert(isa<PHINode>(Dest->begin()) &&
3919 "This should only be called if Dest has a PHI!");
3920
3921 /// TIPHIValues - This array is lazily computed to determine the values of
3922 /// PHIs in Dest that TI would provide.
3923 std::vector<Value*> TIPHIValues;
3924
3925 // Check to see if Dest has any blocks that can be used as a split edge for
3926 // this terminator.
3927 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3928 BasicBlock *Pred = *PI;
3929 // To be usable, the pred has to end with an uncond branch to the dest.
3930 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3931 if (!PredBr || !PredBr->isUnconditional() ||
3932 // Must be empty other than the branch.
3933 &Pred->front() != PredBr)
3934 continue;
3935
3936 // Finally, since we know that Dest has phi nodes in it, we have to make
3937 // sure that jumping to Pred will have the same affect as going to Dest in
3938 // terms of PHI values.
3939 PHINode *PN;
3940 unsigned PHINo = 0;
3941 bool FoundMatch = true;
3942 for (BasicBlock::iterator I = Dest->begin();
3943 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3944 if (PHINo == TIPHIValues.size())
3945 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3946
3947 // If the PHI entry doesn't work, we can't use this pred.
3948 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3949 FoundMatch = false;
3950 break;
3951 }
3952 }
3953
3954 // If we found a workable predecessor, change TI to branch to Succ.
3955 if (FoundMatch) {
3956 Dest->removePredecessor(TIBB);
3957 TI->setSuccessor(SuccNum, Pred);
3958 return;
3959 }
3960 }
3961
3962 SplitCriticalEdge(TI, SuccNum, P, true);
3963}
3964
3965
Chris Lattner1c08c712005-01-07 07:47:53 +00003966bool SelectionDAGISel::runOnFunction(Function &Fn) {
3967 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3968 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003969 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003970
Chris Lattner47e32e62006-10-28 17:04:37 +00003971 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003972 //
Chris Lattner7e598092006-05-05 01:04:50 +00003973 // In this pass we also look for GEP and cast instructions that are used
3974 // across basic blocks and rewrite them to improve basic-block-at-a-time
3975 // selection.
3976 //
Chris Lattner90323642006-05-05 21:17:49 +00003977 bool MadeChange = true;
3978 while (MadeChange) {
3979 MadeChange = false;
Evan Cheng15699fc2007-02-10 01:08:18 +00003980 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003981 // Split all critical edges where the dest block has a PHI.
Evan Cheng15699fc2007-02-10 01:08:18 +00003982 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner47e32e62006-10-28 17:04:37 +00003983 if (BBTI->getNumSuccessors() > 1) {
3984 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003985 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3986 isCriticalEdge(BBTI, i, true))
3987 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003988 }
3989
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003990
Evan Cheng15699fc2007-02-10 01:08:18 +00003991 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003992 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003993
3994 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3995 // If we found an inline asm expession, and if the target knows how to
3996 // lower it to normal LLVM code, do so now.
3997 if (isa<InlineAsm>(CI->getCalledValue()))
3998 if (const TargetAsmInfo *TAI =
3999 TLI.getTargetMachine().getTargetAsmInfo()) {
4000 if (TAI->ExpandInlineAsm(CI))
Evan Cheng15699fc2007-02-10 01:08:18 +00004001 BBI = FNI->begin();
Chris Lattner3f7927c2006-11-29 01:12:32 +00004002 }
4003 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00004004 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00004005 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00004006 // If the source of the cast is a constant, then this should have
4007 // already been constant folded. The only reason NOT to constant fold
4008 // it is if something (e.g. LSR) was careful to place the constant
4009 // evaluation in a block other than then one that uses it (e.g. to hoist
4010 // the address of globals out of a loop). If this is the case, we don't
4011 // want to forward-subst the cast.
4012 if (isa<Constant>(CI->getOperand(0)))
4013 continue;
4014
Chris Lattner7e598092006-05-05 01:04:50 +00004015 // If this is a noop copy, sink it into user blocks to reduce the number
4016 // of virtual registers that must be created and coallesced.
4017 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4018 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4019
4020 // This is an fp<->int conversion?
4021 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4022 continue;
4023
4024 // If this is an extension, it will be a zero or sign extension, which
4025 // isn't a noop.
4026 if (SrcVT < DstVT) continue;
4027
4028 // If these values will be promoted, find out what they will be promoted
4029 // to. This helps us consider truncates on PPC as noop copies when they
4030 // are.
4031 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4032 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4033 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4034 DstVT = TLI.getTypeToTransformTo(DstVT);
4035
4036 // If, after promotion, these are the same types, this is a noop copy.
4037 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00004038 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00004039 }
4040 }
Chris Lattner36b708f2005-08-18 17:35:14 +00004041 }
Chris Lattner90323642006-05-05 21:17:49 +00004042 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00004043
Chris Lattner1c08c712005-01-07 07:47:53 +00004044 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4045
4046 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4047 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004048
Evan Chengad2070c2007-02-10 02:43:39 +00004049 // Add function live-ins to entry block live-in set.
4050 BasicBlock *EntryBB = &Fn.getEntryBlock();
4051 BB = FuncInfo.MBBMap[EntryBB];
4052 if (!MF.livein_empty())
4053 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4054 E = MF.livein_end(); I != E; ++I)
4055 BB->addLiveIn(I->first);
4056
Chris Lattner1c08c712005-01-07 07:47:53 +00004057 return true;
4058}
4059
Chris Lattner571e4342006-10-27 21:36:01 +00004060SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4061 unsigned Reg) {
4062 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004063 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004064 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004065 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004066
4067 // If this type is not legal, we must make sure to not create an invalid
4068 // register use.
4069 MVT::ValueType SrcVT = Op.getValueType();
4070 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004071 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004072 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004073 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004074 // Handle copies from generic vectors to registers.
4075 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004076 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004077 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004078
Chris Lattner70c2a612006-03-31 02:06:56 +00004079 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4080 // MVT::Vector type.
4081 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4082 DAG.getConstant(NE, MVT::i32),
4083 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004084
Chris Lattner70c2a612006-03-31 02:06:56 +00004085 // Loop over all of the elements of the resultant vector,
4086 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4087 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004088 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004089 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004090 for (unsigned i = 0; i != NE; ++i) {
4091 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004092 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004093 if (PTyElementVT == PTyLegalElementVT) {
4094 // Elements are legal.
4095 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4096 } else if (PTyLegalElementVT > PTyElementVT) {
4097 // Elements are promoted.
4098 if (MVT::isFloatingPoint(PTyLegalElementVT))
4099 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4100 else
4101 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4102 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4103 } else {
4104 // Elements are expanded.
4105 // The src value is expanded into multiple registers.
4106 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004107 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004108 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004109 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004110 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4111 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4112 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004113 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004114 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4115 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004116 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004117 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004118 if (MVT::isFloatingPoint(SrcVT))
4119 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4120 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004121 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004122 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004123 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004124 DestVT = TLI.getTypeToExpandTo(SrcVT);
4125 unsigned NumVals = TLI.getNumElements(SrcVT);
4126 if (NumVals == 1)
4127 return DAG.getCopyToReg(getRoot(), Reg,
4128 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4129 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004130 // The src value is expanded into multiple registers.
4131 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004132 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004133 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004134 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004135 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004136 return DAG.getCopyToReg(Op, Reg+1, Hi);
4137 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004138}
4139
Chris Lattner068a81e2005-01-17 17:15:02 +00004140void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004141LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004142 std::vector<SDOperand> &UnorderedChains) {
4143 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004144 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004145 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004146 SDOperand OldRoot = SDL.DAG.getRoot();
4147 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004148
Chris Lattnerbf209482005-10-30 19:42:35 +00004149 unsigned a = 0;
4150 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4151 AI != E; ++AI, ++a)
4152 if (!AI->use_empty()) {
4153 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004154
Chris Lattnerbf209482005-10-30 19:42:35 +00004155 // If this argument is live outside of the entry block, insert a copy from
4156 // whereever we got it to the vreg that other BB's will reference it as.
4157 if (FuncInfo.ValueMap.count(AI)) {
4158 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00004159 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00004160 UnorderedChains.push_back(Copy);
4161 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004162 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004163
Chris Lattnerbf209482005-10-30 19:42:35 +00004164 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004165 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004166 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004167}
4168
Chris Lattner1c08c712005-01-07 07:47:53 +00004169void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4170 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004171 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004172 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004173
4174 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004175
Chris Lattnerbf209482005-10-30 19:42:35 +00004176 // Lower any arguments needed in this block if this is the entry block.
4177 if (LLVMBB == &LLVMBB->getParent()->front())
4178 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004179
4180 BB = FuncInfo.MBBMap[LLVMBB];
4181 SDL.setCurrentBasicBlock(BB);
4182
4183 // Lower all of the non-terminator instructions.
4184 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4185 I != E; ++I)
4186 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00004187
Chris Lattner1c08c712005-01-07 07:47:53 +00004188 // Ensure that all instructions which are used outside of their defining
4189 // blocks are available as virtual registers.
4190 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004191 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004192 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004193 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004194 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004195 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004196 }
4197
4198 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4199 // ensure constants are generated when needed. Remember the virtual registers
4200 // that need to be added to the Machine PHI nodes as input. We cannot just
4201 // directly add them, because expansion might result in multiple MBB's for one
4202 // BB. As such, the start of the BB might correspond to a different MBB than
4203 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004204 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004205 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004206
4207 // Emit constants only once even if used by multiple PHI nodes.
4208 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004209
Chris Lattner8c494ab2006-10-27 23:50:33 +00004210 // Vector bool would be better, but vector<bool> is really slow.
4211 std::vector<unsigned char> SuccsHandled;
4212 if (TI->getNumSuccessors())
4213 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4214
Chris Lattner1c08c712005-01-07 07:47:53 +00004215 // Check successor nodes PHI nodes that expect a constant to be available from
4216 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004217 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4218 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004219 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004220 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004221
Chris Lattner8c494ab2006-10-27 23:50:33 +00004222 // If this terminator has multiple identical successors (common for
4223 // switches), only handle each succ once.
4224 unsigned SuccMBBNo = SuccMBB->getNumber();
4225 if (SuccsHandled[SuccMBBNo]) continue;
4226 SuccsHandled[SuccMBBNo] = true;
4227
4228 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004229 PHINode *PN;
4230
4231 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4232 // nodes and Machine PHI nodes, but the incoming operands have not been
4233 // emitted yet.
4234 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004235 (PN = dyn_cast<PHINode>(I)); ++I) {
4236 // Ignore dead phi's.
4237 if (PN->use_empty()) continue;
4238
4239 unsigned Reg;
4240 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004241
Chris Lattner8c494ab2006-10-27 23:50:33 +00004242 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4243 unsigned &RegOut = ConstantsOut[C];
4244 if (RegOut == 0) {
4245 RegOut = FuncInfo.CreateRegForValue(C);
4246 UnorderedChains.push_back(
4247 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004248 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004249 Reg = RegOut;
4250 } else {
4251 Reg = FuncInfo.ValueMap[PHIOp];
4252 if (Reg == 0) {
4253 assert(isa<AllocaInst>(PHIOp) &&
4254 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4255 "Didn't codegen value into a register!??");
4256 Reg = FuncInfo.CreateRegForValue(PHIOp);
4257 UnorderedChains.push_back(
4258 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004259 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004260 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004261
4262 // Remember that this register needs to added to the machine PHI node as
4263 // the input for this MBB.
4264 MVT::ValueType VT = TLI.getValueType(PN->getType());
4265 unsigned NumElements;
4266 if (VT != MVT::Vector)
4267 NumElements = TLI.getNumElements(VT);
4268 else {
4269 MVT::ValueType VT1,VT2;
4270 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004271 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004272 VT1, VT2);
4273 }
4274 for (unsigned i = 0, e = NumElements; i != e; ++i)
4275 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4276 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004277 }
4278 ConstantsOut.clear();
4279
Chris Lattnerddb870b2005-01-13 17:59:43 +00004280 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004281 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004282 SDOperand Root = SDL.getRoot();
4283 if (Root.getOpcode() != ISD::EntryToken) {
4284 unsigned i = 0, e = UnorderedChains.size();
4285 for (; i != e; ++i) {
4286 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4287 if (UnorderedChains[i].Val->getOperand(0) == Root)
4288 break; // Don't add the root if we already indirectly depend on it.
4289 }
4290
4291 if (i == e)
4292 UnorderedChains.push_back(Root);
4293 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004294 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4295 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004296 }
4297
Chris Lattner1c08c712005-01-07 07:47:53 +00004298 // Lower the terminator after the copies are emitted.
4299 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004300
Nate Begemanf15485a2006-03-27 01:32:24 +00004301 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004302 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004303 SwitchCases.clear();
4304 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004305 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004306
Chris Lattnera651cf62005-01-17 19:43:36 +00004307 // Make sure the root of the DAG is up-to-date.
4308 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004309}
4310
Nate Begemanf15485a2006-03-27 01:32:24 +00004311void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004312 // Get alias analysis for load/store combining.
4313 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4314
Chris Lattneraf21d552005-10-10 16:47:10 +00004315 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004316 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004317
Bill Wendling832171c2006-12-07 20:04:42 +00004318 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004319 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004320
Chris Lattner1c08c712005-01-07 07:47:53 +00004321 // Second step, hack on the DAG until it only uses operations and types that
4322 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004323 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004324
Bill Wendling832171c2006-12-07 20:04:42 +00004325 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004326 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004327
Chris Lattneraf21d552005-10-10 16:47:10 +00004328 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004329 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004330
Evan Chenga9c20912006-01-21 02:32:06 +00004331 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004332
Chris Lattnera33ef482005-03-30 01:10:47 +00004333 // Third, instruction select all of the operations to machine code, adding the
4334 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004335 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004336
Bill Wendling832171c2006-12-07 20:04:42 +00004337 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004338 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004339}
Chris Lattner1c08c712005-01-07 07:47:53 +00004340
Nate Begemanf15485a2006-03-27 01:32:24 +00004341void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4342 FunctionLoweringInfo &FuncInfo) {
4343 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4344 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004345 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004346 CurDAG = &DAG;
4347
4348 // First step, lower LLVM code to some DAG. This DAG may use operations and
4349 // types that are not supported by the target.
4350 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4351
4352 // Second step, emit the lowered DAG as machine code.
4353 CodeGenAndEmitDAG(DAG);
4354 }
4355
Chris Lattnera33ef482005-03-30 01:10:47 +00004356 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004357 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004358 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004359 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4360 MachineInstr *PHI = PHINodesToUpdate[i].first;
4361 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4362 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004363 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004364 PHI->addMachineBasicBlockOperand(BB);
4365 }
4366 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004367 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004368
Nate Begeman9453eea2006-04-23 06:26:20 +00004369 // If the JumpTable record is filled in, then we need to emit a jump table.
4370 // Updating the PHI nodes is tricky in this case, since we need to determine
4371 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004372 if (JT.Reg) {
4373 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004374 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004375 CurDAG = &SDAG;
4376 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004377 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004378 // Set the current basic block to the mbb we wish to insert the code into
4379 BB = JT.MBB;
4380 SDL.setCurrentBasicBlock(BB);
4381 // Emit the code
4382 SDL.visitJumpTable(JT);
4383 SDAG.setRoot(SDL.getRoot());
4384 CodeGenAndEmitDAG(SDAG);
4385 // Update PHI Nodes
4386 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4387 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4388 MachineBasicBlock *PHIBB = PHI->getParent();
4389 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4390 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004391 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004392 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004393 PHI->addMachineBasicBlockOperand(RangeBB);
4394 }
4395 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004396 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004397 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004398 }
4399 }
4400 return;
4401 }
4402
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004403 // If the switch block involved a branch to one of the actual successors, we
4404 // need to update PHI nodes in that block.
4405 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4406 MachineInstr *PHI = PHINodesToUpdate[i].first;
4407 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4408 "This is not a machine PHI node that we are updating!");
4409 if (BB->isSuccessor(PHI->getParent())) {
4410 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4411 PHI->addMachineBasicBlockOperand(BB);
4412 }
4413 }
4414
Nate Begemanf15485a2006-03-27 01:32:24 +00004415 // If we generated any switch lowering information, build and codegen any
4416 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004417 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004418 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004419 CurDAG = &SDAG;
4420 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004421
Nate Begemanf15485a2006-03-27 01:32:24 +00004422 // Set the current basic block to the mbb we wish to insert the code into
4423 BB = SwitchCases[i].ThisBB;
4424 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004425
Nate Begemanf15485a2006-03-27 01:32:24 +00004426 // Emit the code
4427 SDL.visitSwitchCase(SwitchCases[i]);
4428 SDAG.setRoot(SDL.getRoot());
4429 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004430
4431 // Handle any PHI nodes in successors of this chunk, as if we were coming
4432 // from the original BB before switch expansion. Note that PHI nodes can
4433 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4434 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004435 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004436 for (MachineBasicBlock::iterator Phi = BB->begin();
4437 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4438 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4439 for (unsigned pn = 0; ; ++pn) {
4440 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4441 if (PHINodesToUpdate[pn].first == Phi) {
4442 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4443 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4444 break;
4445 }
4446 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004447 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004448
4449 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004450 if (BB == SwitchCases[i].FalseBB)
4451 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004452
4453 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004454 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004455 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004456 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004457 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004458 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004459}
Evan Chenga9c20912006-01-21 02:32:06 +00004460
Jim Laskey13ec7022006-08-01 14:21:23 +00004461
Evan Chenga9c20912006-01-21 02:32:06 +00004462//===----------------------------------------------------------------------===//
4463/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4464/// target node in the graph.
4465void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4466 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004467
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004468 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004469
4470 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004471 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004472 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004473 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004474
Jim Laskey9ff542f2006-08-01 18:29:48 +00004475 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004476 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004477 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004478}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004479
Chris Lattner03fc53c2006-03-06 00:22:00 +00004480
Jim Laskey9ff542f2006-08-01 18:29:48 +00004481HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4482 return new HazardRecognizer();
4483}
4484
Chris Lattner75548062006-10-11 03:58:02 +00004485//===----------------------------------------------------------------------===//
4486// Helper functions used by the generated instruction selector.
4487//===----------------------------------------------------------------------===//
4488// Calls to these methods are generated by tblgen.
4489
4490/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4491/// the dag combiner simplified the 255, we still want to match. RHS is the
4492/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4493/// specified in the .td file (e.g. 255).
4494bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4495 int64_t DesiredMaskS) {
4496 uint64_t ActualMask = RHS->getValue();
4497 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4498
4499 // If the actual mask exactly matches, success!
4500 if (ActualMask == DesiredMask)
4501 return true;
4502
4503 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4504 if (ActualMask & ~DesiredMask)
4505 return false;
4506
4507 // Otherwise, the DAG Combiner may have proven that the value coming in is
4508 // either already zero or is not demanded. Check for known zero input bits.
4509 uint64_t NeededMask = DesiredMask & ~ActualMask;
4510 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4511 return true;
4512
4513 // TODO: check to see if missing bits are just not demanded.
4514
4515 // Otherwise, this pattern doesn't match.
4516 return false;
4517}
4518
4519/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4520/// the dag combiner simplified the 255, we still want to match. RHS is the
4521/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4522/// specified in the .td file (e.g. 255).
4523bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4524 int64_t DesiredMaskS) {
4525 uint64_t ActualMask = RHS->getValue();
4526 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4527
4528 // If the actual mask exactly matches, success!
4529 if (ActualMask == DesiredMask)
4530 return true;
4531
4532 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4533 if (ActualMask & ~DesiredMask)
4534 return false;
4535
4536 // Otherwise, the DAG Combiner may have proven that the value coming in is
4537 // either already zero or is not demanded. Check for known zero input bits.
4538 uint64_t NeededMask = DesiredMask & ~ActualMask;
4539
4540 uint64_t KnownZero, KnownOne;
4541 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4542
4543 // If all the missing bits in the or are already known to be set, match!
4544 if ((NeededMask & KnownOne) == NeededMask)
4545 return true;
4546
4547 // TODO: check to see if missing bits are just not demanded.
4548
4549 // Otherwise, this pattern doesn't match.
4550 return false;
4551}
4552
Jim Laskey9ff542f2006-08-01 18:29:48 +00004553
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004554/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4555/// by tblgen. Others should not call it.
4556void SelectionDAGISel::
4557SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4558 std::vector<SDOperand> InOps;
4559 std::swap(InOps, Ops);
4560
4561 Ops.push_back(InOps[0]); // input chain.
4562 Ops.push_back(InOps[1]); // input asm string.
4563
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004564 unsigned i = 2, e = InOps.size();
4565 if (InOps[e-1].getValueType() == MVT::Flag)
4566 --e; // Don't process a flag operand if it is here.
4567
4568 while (i != e) {
4569 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4570 if ((Flags & 7) != 4 /*MEM*/) {
4571 // Just skip over this operand, copying the operands verbatim.
4572 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4573 i += (Flags >> 3) + 1;
4574 } else {
4575 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4576 // Otherwise, this is a memory operand. Ask the target to select it.
4577 std::vector<SDOperand> SelOps;
4578 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004579 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004580 exit(1);
4581 }
4582
4583 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004584 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4585 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004586 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4587 i += 2;
4588 }
4589 }
4590
4591 // Add the flag input back if present.
4592 if (e != InOps.size())
4593 Ops.push_back(InOps.back());
4594}