blob: 02ae7108aeea8642887e3a3146904ecfc9ac8bf5 [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"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000020#include "llvm/GlobalVariable.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/Instructions.h"
22#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000023#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000024#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/SelectionDAG.h"
29#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000030#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000037#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000038#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Support/Debug.h"
40#include <map>
41#include <iostream>
42using namespace llvm;
43
Chris Lattnerda8abb02005-09-01 18:44:10 +000044#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000045static cl::opt<bool>
46ViewDAGs("view-isel-dags", cl::Hidden,
47 cl::desc("Pop up a window to show isel dags as they are selected"));
48#else
Chris Lattnera639a432005-09-02 07:09:28 +000049static const bool ViewDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000050#endif
51
Chris Lattner1c08c712005-01-07 07:47:53 +000052namespace llvm {
53 //===--------------------------------------------------------------------===//
54 /// FunctionLoweringInfo - This contains information that is global to a
55 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000056 class FunctionLoweringInfo {
57 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000058 TargetLowering &TLI;
59 Function &Fn;
60 MachineFunction &MF;
61 SSARegMap *RegMap;
62
63 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
64
65 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
66 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
67
68 /// ValueMap - Since we emit code for the function a basic block at a time,
69 /// we must remember which virtual registers hold the values for
70 /// cross-basic-block values.
71 std::map<const Value*, unsigned> ValueMap;
72
73 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
74 /// the entry block. This allows the allocas to be efficiently referenced
75 /// anywhere in the function.
76 std::map<const AllocaInst*, int> StaticAllocaMap;
77
78 unsigned MakeReg(MVT::ValueType VT) {
79 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
80 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000081
Chris Lattner1c08c712005-01-07 07:47:53 +000082 unsigned CreateRegForValue(const Value *V) {
83 MVT::ValueType VT = TLI.getValueType(V->getType());
84 // The common case is that we will only create one register for this
85 // value. If we have that case, create and return the virtual register.
86 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +000087 if (NV == 1) {
88 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000089 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000090 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000091
Chris Lattner1c08c712005-01-07 07:47:53 +000092 // If this value is represented with multiple target registers, make sure
93 // to create enough consequtive registers of the right (smaller) type.
94 unsigned NT = VT-1; // Find the type to use.
95 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
96 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +000097
Chris Lattner1c08c712005-01-07 07:47:53 +000098 unsigned R = MakeReg((MVT::ValueType)NT);
99 for (unsigned i = 1; i != NV; ++i)
100 MakeReg((MVT::ValueType)NT);
101 return R;
102 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000103
Chris Lattner1c08c712005-01-07 07:47:53 +0000104 unsigned InitializeRegForValue(const Value *V) {
105 unsigned &R = ValueMap[V];
106 assert(R == 0 && "Already initialized this value register!");
107 return R = CreateRegForValue(V);
108 }
109 };
110}
111
112/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
113/// PHI nodes or outside of the basic block that defines it.
114static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
115 if (isa<PHINode>(I)) return true;
116 BasicBlock *BB = I->getParent();
117 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
118 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
119 return true;
120 return false;
121}
122
Chris Lattnerbf209482005-10-30 19:42:35 +0000123/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
124/// entry block, return true.
125static bool isOnlyUsedInEntryBlock(Argument *A) {
126 BasicBlock *Entry = A->getParent()->begin();
127 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
128 if (cast<Instruction>(*UI)->getParent() != Entry)
129 return false; // Use not in entry block.
130 return true;
131}
132
Chris Lattner1c08c712005-01-07 07:47:53 +0000133FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000134 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000135 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
136
Chris Lattnerbf209482005-10-30 19:42:35 +0000137 // Create a vreg for each argument register that is not dead and is used
138 // outside of the entry block for the function.
139 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
140 AI != E; ++AI)
141 if (!isOnlyUsedInEntryBlock(AI))
142 InitializeRegForValue(AI);
143
Chris Lattner1c08c712005-01-07 07:47:53 +0000144 // Initialize the mapping of values to registers. This is only set up for
145 // instruction values that are used outside of the block that defines
146 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000147 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000148 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
149 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
150 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
151 const Type *Ty = AI->getAllocatedType();
152 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000153 unsigned Align =
154 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
155 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000156
157 // If the alignment of the value is smaller than the size of the value,
158 // and if the size of the value is particularly small (<= 8 bytes),
159 // round up to the size of the value for potentially better performance.
160 //
161 // FIXME: This could be made better with a preferred alignment hook in
162 // TargetData. It serves primarily to 8-byte align doubles for X86.
163 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000164 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000165 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000166 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000167 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000168 }
169
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000170 for (; BB != EB; ++BB)
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000172 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
173 if (!isa<AllocaInst>(I) ||
174 !StaticAllocaMap.count(cast<AllocaInst>(I)))
175 InitializeRegForValue(I);
176
177 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
178 // also creates the initial PHI MachineInstrs, though none of the input
179 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000180 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000181 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
182 MBBMap[BB] = MBB;
183 MF.getBasicBlockList().push_back(MBB);
184
185 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
186 // appropriate.
187 PHINode *PN;
188 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000189 (PN = dyn_cast<PHINode>(I)); ++I)
190 if (!PN->use_empty()) {
191 unsigned NumElements =
192 TLI.getNumElements(TLI.getValueType(PN->getType()));
193 unsigned PHIReg = ValueMap[PN];
194 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
195 for (unsigned i = 0; i != NumElements; ++i)
196 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
197 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000198 }
199}
200
201
202
203//===----------------------------------------------------------------------===//
204/// SelectionDAGLowering - This is the common target-independent lowering
205/// implementation that is parameterized by a TargetLowering object.
206/// Also, targets can overload any lowering method.
207///
208namespace llvm {
209class SelectionDAGLowering {
210 MachineBasicBlock *CurMBB;
211
212 std::map<const Value*, SDOperand> NodeMap;
213
Chris Lattnerd3948112005-01-17 22:19:26 +0000214 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
215 /// them up and then emit token factor nodes when possible. This allows us to
216 /// get simple disambiguation between loads without worrying about alias
217 /// analysis.
218 std::vector<SDOperand> PendingLoads;
219
Chris Lattner1c08c712005-01-07 07:47:53 +0000220public:
221 // TLI - This is information that describes the available target features we
222 // need for lowering. This indicates when operations are unavailable,
223 // implemented with a libcall, etc.
224 TargetLowering &TLI;
225 SelectionDAG &DAG;
226 const TargetData &TD;
227
228 /// FuncInfo - Information about the function as a whole.
229 ///
230 FunctionLoweringInfo &FuncInfo;
231
232 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000233 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000234 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
235 FuncInfo(funcinfo) {
236 }
237
Chris Lattnera651cf62005-01-17 19:43:36 +0000238 /// getRoot - Return the current virtual root of the Selection DAG.
239 ///
240 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000241 if (PendingLoads.empty())
242 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000243
Chris Lattnerd3948112005-01-17 22:19:26 +0000244 if (PendingLoads.size() == 1) {
245 SDOperand Root = PendingLoads[0];
246 DAG.setRoot(Root);
247 PendingLoads.clear();
248 return Root;
249 }
250
251 // Otherwise, we have to make a token factor node.
252 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
253 PendingLoads.clear();
254 DAG.setRoot(Root);
255 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000256 }
257
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 void visit(Instruction &I) { visit(I.getOpcode(), I); }
259
260 void visit(unsigned Opcode, User &I) {
261 switch (Opcode) {
262 default: assert(0 && "Unknown instruction type encountered!");
263 abort();
264 // Build the switch statement using the Instruction.def file.
265#define HANDLE_INST(NUM, OPCODE, CLASS) \
266 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
267#include "llvm/Instruction.def"
268 }
269 }
270
271 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
272
273
274 SDOperand getIntPtrConstant(uint64_t Val) {
275 return DAG.getConstant(Val, TLI.getPointerTy());
276 }
277
278 SDOperand getValue(const Value *V) {
279 SDOperand &N = NodeMap[V];
280 if (N.Val) return N;
281
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000282 const Type *VTy = V->getType();
283 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000284 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
286 visit(CE->getOpcode(), *CE);
287 assert(N.Val && "visit didn't populate the ValueMap!");
288 return N;
289 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
290 return N = DAG.getGlobalAddress(GV, VT);
291 } else if (isa<ConstantPointerNull>(C)) {
292 return N = DAG.getConstant(0, TLI.getPointerTy());
293 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000294 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000295 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
296 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000297 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
298 unsigned NumElements = PTy->getNumElements();
299 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
300 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
301
302 // Now that we know the number and type of the elements, push a
303 // Constant or ConstantFP node onto the ops list for each element of
304 // the packed constant.
305 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000306 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
307 if (MVT::isFloatingPoint(PVT)) {
308 for (unsigned i = 0; i != NumElements; ++i) {
309 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
310 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
311 }
312 } else {
313 for (unsigned i = 0; i != NumElements; ++i) {
314 const ConstantIntegral *El =
315 cast<ConstantIntegral>(CP->getOperand(i));
316 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
317 }
318 }
319 } else {
320 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
321 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000322 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000323 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000324 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000325 Op = DAG.getConstant(0, PVT);
326 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000327 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000328
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000329 // Handle the case where we have a 1-element vector, in which
330 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000331 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000332 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000333 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
334 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
335 } else {
336 // If the packed type isn't legal, then create a ConstantVec node with
337 // generic Vector type instead.
338 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
339 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000340 } else {
341 // Canonicalize all constant ints to be unsigned.
342 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
343 }
344
345 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
346 std::map<const AllocaInst*, int>::iterator SI =
347 FuncInfo.StaticAllocaMap.find(AI);
348 if (SI != FuncInfo.StaticAllocaMap.end())
349 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
350 }
351
352 std::map<const Value*, unsigned>::const_iterator VMI =
353 FuncInfo.ValueMap.find(V);
354 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000355
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000356 unsigned InReg = VMI->second;
357
358 // If this type is not legal, make it so now.
359 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
360
361 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
362 if (DestVT < VT) {
363 // Source must be expanded. This input value is actually coming from the
364 // register pair VMI->second and VMI->second+1.
365 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
366 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
367 } else {
368 if (DestVT > VT) { // Promotion case
369 if (MVT::isFloatingPoint(VT))
370 N = DAG.getNode(ISD::FP_ROUND, VT, N);
371 else
372 N = DAG.getNode(ISD::TRUNCATE, VT, N);
373 }
374 }
375
376 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000377 }
378
379 const SDOperand &setValue(const Value *V, SDOperand NewN) {
380 SDOperand &N = NodeMap[V];
381 assert(N.Val == 0 && "Already set a value for this node!");
382 return N = NewN;
383 }
384
385 // Terminator instructions.
386 void visitRet(ReturnInst &I);
387 void visitBr(BranchInst &I);
388 void visitUnreachable(UnreachableInst &I) { /* noop */ }
389
390 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000391 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000392 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000393 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
394 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
395 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
396
397 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000398 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000399 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000400 void visitAdd(User &I) {
401 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000402 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000403 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000404 void visitMul(User &I) {
405 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000406 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000407 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000408 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000409 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 }
411 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000412 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000413 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000414 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000415 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
416 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
417 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000418 void visitShl(User &I) { visitShift(I, ISD::SHL); }
419 void visitShr(User &I) {
420 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000421 }
422
423 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
424 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
425 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
426 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
427 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
428 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
429 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
430
431 void visitGetElementPtr(User &I);
432 void visitCast(User &I);
433 void visitSelect(User &I);
434 //
435
436 void visitMalloc(MallocInst &I);
437 void visitFree(FreeInst &I);
438 void visitAlloca(AllocaInst &I);
439 void visitLoad(LoadInst &I);
440 void visitStore(StoreInst &I);
441 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
442 void visitCall(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000443 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000444
Chris Lattner1c08c712005-01-07 07:47:53 +0000445 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000446 void visitVAArg(VAArgInst &I);
447 void visitVAEnd(CallInst &I);
448 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000449 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000450
Chris Lattner7041ee32005-01-11 05:56:49 +0000451 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000452
453 void visitUserOp1(Instruction &I) {
454 assert(0 && "UserOp1 should not exist at instruction selection time!");
455 abort();
456 }
457 void visitUserOp2(Instruction &I) {
458 assert(0 && "UserOp2 should not exist at instruction selection time!");
459 abort();
460 }
461};
462} // end namespace llvm
463
464void SelectionDAGLowering::visitRet(ReturnInst &I) {
465 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000466 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000467 return;
468 }
469
470 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000471 MVT::ValueType TmpVT;
472
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 switch (Op1.getValueType()) {
474 default: assert(0 && "Unknown value type!");
475 case MVT::i1:
476 case MVT::i8:
477 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000478 case MVT::i32:
479 // If this is a machine where 32-bits is legal or expanded, promote to
480 // 32-bits, otherwise, promote to 64-bits.
481 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
482 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000483 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000484 TmpVT = MVT::i32;
485
486 // Extend integer types to result type.
487 if (I.getOperand(0)->getType()->isSigned())
488 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
489 else
490 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000491 break;
492 case MVT::f32:
Chris Lattner4eebb602006-01-20 18:38:32 +0000493 // If this is a machine where f32 is promoted to f64, do so now.
494 if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
495 Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
496 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000497 case MVT::i64:
498 case MVT::f64:
499 break; // No extension needed!
500 }
Nate Begeman4a959452005-10-18 23:23:37 +0000501 // Allow targets to lower this further to meet ABI requirements
502 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000503}
504
505void SelectionDAGLowering::visitBr(BranchInst &I) {
506 // Update machine-CFG edges.
507 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000508
509 // Figure out which block is immediately after the current one.
510 MachineBasicBlock *NextBlock = 0;
511 MachineFunction::iterator BBI = CurMBB;
512 if (++BBI != CurMBB->getParent()->end())
513 NextBlock = BBI;
514
515 if (I.isUnconditional()) {
516 // If this is not a fall-through branch, emit the branch.
517 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000518 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000519 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000520 } else {
521 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000522
523 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000524 if (Succ1MBB == NextBlock) {
525 // If the condition is false, fall through. This means we should branch
526 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000528 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000529 } else if (Succ0MBB == NextBlock) {
530 // If the condition is true, fall through. This means we should branch if
531 // the condition is false to Succ #1. Invert the condition first.
532 SDOperand True = DAG.getConstant(1, Cond.getValueType());
533 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000534 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000535 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000536 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000537 std::vector<SDOperand> Ops;
538 Ops.push_back(getRoot());
539 Ops.push_back(Cond);
540 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
541 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
542 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000543 }
544 }
545}
546
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000547void SelectionDAGLowering::visitSub(User &I) {
548 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000549 if (I.getType()->isFloatingPoint()) {
550 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
551 if (CFP->isExactlyValue(-0.0)) {
552 SDOperand Op2 = getValue(I.getOperand(1));
553 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
554 return;
555 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000556 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000557 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000558}
559
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000560void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
561 unsigned VecOp) {
562 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000563 SDOperand Op1 = getValue(I.getOperand(0));
564 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000565
Chris Lattnerb67eb912005-11-19 18:40:42 +0000566 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000567 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
568 } else if (Ty->isFloatingPoint()) {
569 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
570 } else {
571 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000572 unsigned NumElements = PTy->getNumElements();
573 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000574 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000575
576 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000577 // the Legalize pass does not have to deal with them. Similarly, if the
578 // abstract vector is going to turn into one that the target natively
579 // supports, generate that type now so that Legalize doesn't have to deal
580 // with that either. These steps ensure that Legalize only has to handle
581 // vector types in its Expand case.
582 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000583 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000584 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000585 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
586 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000587 } else {
588 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
589 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000590 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000591 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000592 }
Nate Begemane21ea612005-11-18 07:42:56 +0000593}
Chris Lattner2c49f272005-01-19 22:31:21 +0000594
Nate Begemane21ea612005-11-18 07:42:56 +0000595void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
596 SDOperand Op1 = getValue(I.getOperand(0));
597 SDOperand Op2 = getValue(I.getOperand(1));
598
599 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
600
Chris Lattner1c08c712005-01-07 07:47:53 +0000601 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
602}
603
604void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
605 ISD::CondCode UnsignedOpcode) {
606 SDOperand Op1 = getValue(I.getOperand(0));
607 SDOperand Op2 = getValue(I.getOperand(1));
608 ISD::CondCode Opcode = SignedOpcode;
609 if (I.getOperand(0)->getType()->isUnsigned())
610 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000611 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000612}
613
614void SelectionDAGLowering::visitSelect(User &I) {
615 SDOperand Cond = getValue(I.getOperand(0));
616 SDOperand TrueVal = getValue(I.getOperand(1));
617 SDOperand FalseVal = getValue(I.getOperand(2));
618 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
619 TrueVal, FalseVal));
620}
621
622void SelectionDAGLowering::visitCast(User &I) {
623 SDOperand N = getValue(I.getOperand(0));
624 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
625 MVT::ValueType DestTy = TLI.getValueType(I.getType());
626
627 if (N.getValueType() == DestTy) {
628 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000629 } else if (DestTy == MVT::i1) {
630 // Cast to bool is a comparison against zero, not truncation to zero.
631 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
632 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000633 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000634 } else if (isInteger(SrcTy)) {
635 if (isInteger(DestTy)) { // Int -> Int cast
636 if (DestTy < SrcTy) // Truncating cast?
637 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
638 else if (I.getOperand(0)->getType()->isSigned())
639 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
640 else
641 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
642 } else { // Int -> FP cast
643 if (I.getOperand(0)->getType()->isSigned())
644 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
645 else
646 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
647 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000648 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000649 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
650 if (isFloatingPoint(DestTy)) { // FP -> FP cast
651 if (DestTy < SrcTy) // Rounding cast?
652 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
653 else
654 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
655 } else { // FP -> Int cast.
656 if (I.getType()->isSigned())
657 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
658 else
659 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
660 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000661 }
662}
663
664void SelectionDAGLowering::visitGetElementPtr(User &I) {
665 SDOperand N = getValue(I.getOperand(0));
666 const Type *Ty = I.getOperand(0)->getType();
667 const Type *UIntPtrTy = TD.getIntPtrType();
668
669 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
670 OI != E; ++OI) {
671 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000672 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000673 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
674 if (Field) {
675 // N = N + Offset
676 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
677 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000678 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000679 }
680 Ty = StTy->getElementType(Field);
681 } else {
682 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000683
Chris Lattner7c0104b2005-11-09 04:45:33 +0000684 // If this is a constant subscript, handle it quickly.
685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
686 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000687
Chris Lattner7c0104b2005-11-09 04:45:33 +0000688 uint64_t Offs;
689 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
690 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
691 else
692 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
693 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
694 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000695 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000696
697 // N = N + Idx * ElementSize;
698 uint64_t ElementSize = TD.getTypeSize(Ty);
699 SDOperand IdxN = getValue(Idx);
700
701 // If the index is smaller or larger than intptr_t, truncate or extend
702 // it.
703 if (IdxN.getValueType() < N.getValueType()) {
704 if (Idx->getType()->isSigned())
705 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
706 else
707 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
708 } else if (IdxN.getValueType() > N.getValueType())
709 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
710
711 // If this is a multiply by a power of two, turn it into a shl
712 // immediately. This is a very common case.
713 if (isPowerOf2_64(ElementSize)) {
714 unsigned Amt = Log2_64(ElementSize);
715 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000716 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000717 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
718 continue;
719 }
720
721 SDOperand Scale = getIntPtrConstant(ElementSize);
722 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
723 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724 }
725 }
726 setValue(&I, N);
727}
728
729void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
730 // If this is a fixed sized alloca in the entry block of the function,
731 // allocate it statically on the stack.
732 if (FuncInfo.StaticAllocaMap.count(&I))
733 return; // getValue will auto-populate this.
734
735 const Type *Ty = I.getAllocatedType();
736 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000737 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
738 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000739
740 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000741 MVT::ValueType IntPtr = TLI.getPointerTy();
742 if (IntPtr < AllocSize.getValueType())
743 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
744 else if (IntPtr > AllocSize.getValueType())
745 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000746
Chris Lattner68cd65e2005-01-22 23:04:37 +0000747 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000748 getIntPtrConstant(TySize));
749
750 // Handle alignment. If the requested alignment is less than or equal to the
751 // stack alignment, ignore it and round the size of the allocation up to the
752 // stack alignment size. If the size is greater than the stack alignment, we
753 // note this in the DYNAMIC_STACKALLOC node.
754 unsigned StackAlign =
755 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
756 if (Align <= StackAlign) {
757 Align = 0;
758 // Add SA-1 to the size.
759 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
760 getIntPtrConstant(StackAlign-1));
761 // Mask out the low bits for alignment purposes.
762 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
763 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
764 }
765
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000766 std::vector<MVT::ValueType> VTs;
767 VTs.push_back(AllocSize.getValueType());
768 VTs.push_back(MVT::Other);
769 std::vector<SDOperand> Ops;
770 Ops.push_back(getRoot());
771 Ops.push_back(AllocSize);
772 Ops.push_back(getIntPtrConstant(Align));
773 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000774 DAG.setRoot(setValue(&I, DSA).getValue(1));
775
776 // Inform the Frame Information that we have just allocated a variable-sized
777 // object.
778 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
779}
780
Chris Lattner36ce6912005-11-29 06:21:05 +0000781/// getStringValue - Turn an LLVM constant pointer that eventually points to a
782/// global into a string value. Return an empty string if we can't do it.
783///
784static std::string getStringValue(Value *V, unsigned Offset = 0) {
785 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
786 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
787 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
788 if (Init->isString()) {
789 std::string Result = Init->getAsString();
790 if (Offset < Result.size()) {
791 // If we are pointing INTO The string, erase the beginning...
792 Result.erase(Result.begin(), Result.begin()+Offset);
793
794 // Take off the null terminator, and any string fragments after it.
795 std::string::size_type NullPos = Result.find_first_of((char)0);
796 if (NullPos != std::string::npos)
797 Result.erase(Result.begin()+NullPos, Result.end());
798 return Result;
799 }
800 }
801 }
802 } else if (Constant *C = dyn_cast<Constant>(V)) {
803 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
804 return getStringValue(GV, Offset);
805 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
806 if (CE->getOpcode() == Instruction::GetElementPtr) {
807 // Turn a gep into the specified offset.
808 if (CE->getNumOperands() == 3 &&
809 cast<Constant>(CE->getOperand(1))->isNullValue() &&
810 isa<ConstantInt>(CE->getOperand(2))) {
811 return getStringValue(CE->getOperand(0),
812 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
813 }
814 }
815 }
816 }
817 return "";
818}
Chris Lattner1c08c712005-01-07 07:47:53 +0000819
820void SelectionDAGLowering::visitLoad(LoadInst &I) {
821 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000822
Chris Lattnerd3948112005-01-17 22:19:26 +0000823 SDOperand Root;
824 if (I.isVolatile())
825 Root = getRoot();
826 else {
827 // Do not serialize non-volatile loads against each other.
828 Root = DAG.getRoot();
829 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000830
831 const Type *Ty = I.getType();
832 SDOperand L;
833
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000834 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000835 unsigned NumElements = PTy->getNumElements();
836 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000837 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000838
839 // Immediately scalarize packed types containing only one element, so that
840 // the Legalize pass does not have to deal with them.
841 if (NumElements == 1) {
842 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000843 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
844 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000845 } else {
846 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
847 DAG.getSrcValue(I.getOperand(0)));
848 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000849 } else {
850 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
851 DAG.getSrcValue(I.getOperand(0)));
852 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000853 setValue(&I, L);
854
855 if (I.isVolatile())
856 DAG.setRoot(L.getValue(1));
857 else
858 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000859}
860
861
862void SelectionDAGLowering::visitStore(StoreInst &I) {
863 Value *SrcV = I.getOperand(0);
864 SDOperand Src = getValue(SrcV);
865 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000866 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000867 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000868}
869
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000870/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
871/// we want to emit this as a call to a named external function, return the name
872/// otherwise lower it and return null.
873const char *
874SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
875 switch (Intrinsic) {
876 case Intrinsic::vastart: visitVAStart(I); return 0;
877 case Intrinsic::vaend: visitVAEnd(I); return 0;
878 case Intrinsic::vacopy: visitVACopy(I); return 0;
879 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
880 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
881 case Intrinsic::setjmp:
882 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
883 break;
884 case Intrinsic::longjmp:
885 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
886 break;
887 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
888 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
889 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
890
891 case Intrinsic::readport:
892 case Intrinsic::readio: {
893 std::vector<MVT::ValueType> VTs;
894 VTs.push_back(TLI.getValueType(I.getType()));
895 VTs.push_back(MVT::Other);
896 std::vector<SDOperand> Ops;
897 Ops.push_back(getRoot());
898 Ops.push_back(getValue(I.getOperand(1)));
899 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
900 ISD::READPORT : ISD::READIO, VTs, Ops);
901
902 setValue(&I, Tmp);
903 DAG.setRoot(Tmp.getValue(1));
904 return 0;
905 }
906 case Intrinsic::writeport:
907 case Intrinsic::writeio:
908 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
909 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
910 getRoot(), getValue(I.getOperand(1)),
911 getValue(I.getOperand(2))));
912 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000913
Chris Lattner86cb6432005-12-13 17:40:33 +0000914 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000915 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
916 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000917
918 std::string fname = "<unknown>";
919 std::vector<SDOperand> Ops;
920
Chris Lattner36ce6912005-11-29 06:21:05 +0000921 // Input Chain
922 Ops.push_back(getRoot());
923
924 // line number
925 Ops.push_back(getValue(I.getOperand(2)));
926
927 // column
928 Ops.push_back(getValue(I.getOperand(3)));
929
Chris Lattner86cb6432005-12-13 17:40:33 +0000930 // filename/working dir
931 // Pull the filename out of the the compilation unit.
932 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
933 if (cunit && cunit->hasInitializer()) {
934 if (ConstantStruct *CS =
935 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
936 if (CS->getNumOperands() > 0) {
Chris Lattner86cb6432005-12-13 17:40:33 +0000937 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskeyf5395ce2005-12-16 22:45:29 +0000938 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner86cb6432005-12-13 17:40:33 +0000939 }
940 }
941 }
942
943 if (Ops.size() == 5) // Found filename/workingdir.
944 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000945 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000946 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000947 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000948 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000949 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
950 return "llvm_dbg_region_start";
951 if (I.getType() != Type::VoidTy)
952 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
953 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000954 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000955 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
956 return "llvm_dbg_region_end";
957 if (I.getType() != Type::VoidTy)
958 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
959 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000960 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000961 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
962 return "llvm_dbg_subprogram";
963 if (I.getType() != Type::VoidTy)
964 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
965 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000966 case Intrinsic::dbg_declare:
967 if (I.getType() != Type::VoidTy)
968 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
969 return 0;
970
Reid Spencer0b118202006-01-16 21:12:35 +0000971 case Intrinsic::isunordered_f32:
972 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000973 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
974 getValue(I.getOperand(2)), ISD::SETUO));
975 return 0;
976
Reid Spencer0b118202006-01-16 21:12:35 +0000977 case Intrinsic::sqrt_f32:
978 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000979 setValue(&I, DAG.getNode(ISD::FSQRT,
980 getValue(I.getOperand(1)).getValueType(),
981 getValue(I.getOperand(1))));
982 return 0;
983 case Intrinsic::pcmarker: {
984 SDOperand Tmp = getValue(I.getOperand(1));
985 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
986 return 0;
987 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +0000988 case Intrinsic::readcyclecounter: {
989 std::vector<MVT::ValueType> VTs;
990 VTs.push_back(MVT::i64);
991 VTs.push_back(MVT::Other);
992 std::vector<SDOperand> Ops;
993 Ops.push_back(getRoot());
994 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
995 setValue(&I, Tmp);
996 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +0000997 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +0000998 }
Nate Begemand88fc032006-01-14 03:14:10 +0000999 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001000 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001001 case Intrinsic::bswap_i64:
1002 setValue(&I, DAG.getNode(ISD::BSWAP,
1003 getValue(I.getOperand(1)).getValueType(),
1004 getValue(I.getOperand(1))));
1005 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001006 case Intrinsic::cttz_i8:
1007 case Intrinsic::cttz_i16:
1008 case Intrinsic::cttz_i32:
1009 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001010 setValue(&I, DAG.getNode(ISD::CTTZ,
1011 getValue(I.getOperand(1)).getValueType(),
1012 getValue(I.getOperand(1))));
1013 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001014 case Intrinsic::ctlz_i8:
1015 case Intrinsic::ctlz_i16:
1016 case Intrinsic::ctlz_i32:
1017 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001018 setValue(&I, DAG.getNode(ISD::CTLZ,
1019 getValue(I.getOperand(1)).getValueType(),
1020 getValue(I.getOperand(1))));
1021 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001022 case Intrinsic::ctpop_i8:
1023 case Intrinsic::ctpop_i16:
1024 case Intrinsic::ctpop_i32:
1025 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001026 setValue(&I, DAG.getNode(ISD::CTPOP,
1027 getValue(I.getOperand(1)).getValueType(),
1028 getValue(I.getOperand(1))));
1029 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001030 case Intrinsic::stacksave: {
1031 std::vector<MVT::ValueType> VTs;
1032 VTs.push_back(TLI.getPointerTy());
1033 VTs.push_back(MVT::Other);
1034 std::vector<SDOperand> Ops;
1035 Ops.push_back(getRoot());
1036 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1037 setValue(&I, Tmp);
1038 DAG.setRoot(Tmp.getValue(1));
1039 return 0;
1040 }
Chris Lattnere8f7a4b2006-01-13 02:24:42 +00001041 case Intrinsic::stackrestore:
Chris Lattner140d53c2006-01-13 02:50:02 +00001042 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1043 getValue(I.getOperand(1))));
1044 return 0;
Chris Lattnerac22c832005-12-12 22:51:16 +00001045 case Intrinsic::prefetch:
1046 // FIXME: Currently discarding prefetches.
1047 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001048 default:
1049 std::cerr << I;
1050 assert(0 && "This intrinsic is not implemented yet!");
1051 return 0;
1052 }
1053}
1054
1055
Chris Lattner1c08c712005-01-07 07:47:53 +00001056void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001057 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001058 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001059 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001060 if (unsigned IID = F->getIntrinsicID()) {
1061 RenameFn = visitIntrinsicCall(I, IID);
1062 if (!RenameFn)
1063 return;
1064 } else { // Not an LLVM intrinsic.
1065 const std::string &Name = F->getName();
1066 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001067 if (I.getNumOperands() == 2 && // Basic sanity checks.
1068 I.getOperand(1)->getType()->isFloatingPoint() &&
1069 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001070 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001071 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1072 return;
1073 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001074 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001075 if (I.getNumOperands() == 2 && // Basic sanity checks.
1076 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001077 I.getType() == I.getOperand(1)->getType() &&
1078 TLI.isOperationLegal(ISD::FSIN,
1079 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001080 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001081 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1082 return;
1083 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001084 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001085 if (I.getNumOperands() == 2 && // Basic sanity checks.
1086 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001087 I.getType() == I.getOperand(1)->getType() &&
1088 TLI.isOperationLegal(ISD::FCOS,
1089 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001090 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001091 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1092 return;
1093 }
1094 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001095 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001096 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001097
Chris Lattner64e14b12005-01-08 22:48:57 +00001098 SDOperand Callee;
1099 if (!RenameFn)
1100 Callee = getValue(I.getOperand(0));
1101 else
1102 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001103 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001104 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001105 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1106 Value *Arg = I.getOperand(i);
1107 SDOperand ArgNode = getValue(Arg);
1108 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1109 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001110
Nate Begeman8e21e712005-03-26 01:29:23 +00001111 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1112 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001113
Chris Lattnercf5734d2005-01-08 19:26:18 +00001114 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001115 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001116 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001117 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001118 setValue(&I, Result.first);
1119 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001120}
1121
1122void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1123 SDOperand Src = getValue(I.getOperand(0));
1124
1125 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001126
1127 if (IntPtr < Src.getValueType())
1128 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1129 else if (IntPtr > Src.getValueType())
1130 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001131
1132 // Scale the source by the type size.
1133 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1134 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1135 Src, getIntPtrConstant(ElementSize));
1136
1137 std::vector<std::pair<SDOperand, const Type*> > Args;
1138 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001139
1140 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001141 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001142 DAG.getExternalSymbol("malloc", IntPtr),
1143 Args, DAG);
1144 setValue(&I, Result.first); // Pointers always fit in registers
1145 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001146}
1147
1148void SelectionDAGLowering::visitFree(FreeInst &I) {
1149 std::vector<std::pair<SDOperand, const Type*> > Args;
1150 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1151 TLI.getTargetData().getIntPtrType()));
1152 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001153 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001154 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001155 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1156 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001157}
1158
Chris Lattner025c39b2005-08-26 20:54:47 +00001159// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1160// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1161// instructions are special in various ways, which require special support to
1162// insert. The specified MachineInstr is created but not inserted into any
1163// basic blocks, and the scheduler passes ownership of it to this method.
1164MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1165 MachineBasicBlock *MBB) {
1166 std::cerr << "If a target marks an instruction with "
1167 "'usesCustomDAGSchedInserter', it must implement "
1168 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1169 abort();
1170 return 0;
1171}
1172
Nate Begeman4a959452005-10-18 23:23:37 +00001173SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1174 SelectionDAG &DAG) {
1175 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1176}
1177
Chris Lattnere64e72b2005-07-05 19:57:53 +00001178SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1179 SDOperand VAListP, Value *VAListV,
1180 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001181 // We have no sane default behavior, just emit a useful error message and bail
1182 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +00001183 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00001184 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +00001185 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +00001186}
1187
Chris Lattnere64e72b2005-07-05 19:57:53 +00001188SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +00001189 SelectionDAG &DAG) {
1190 // Default to a noop.
1191 return Chain;
1192}
1193
Chris Lattnere64e72b2005-07-05 19:57:53 +00001194SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1195 SDOperand SrcP, Value *SrcV,
1196 SDOperand DestP, Value *DestV,
1197 SelectionDAG &DAG) {
1198 // Default to copying the input list.
1199 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1200 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001201 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001202 Val, DestP, DAG.getSrcValue(DestV));
1203 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +00001204}
1205
1206std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +00001207TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1208 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +00001209 // We have no sane default behavior, just emit a useful error message and bail
1210 // out.
1211 std::cerr << "Variable arguments handling not implemented on this target!\n";
1212 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001213 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +00001214}
1215
1216
1217void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001218 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1219 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +00001220}
1221
1222void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1223 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +00001224 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +00001225 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001226 setValue(&I, Result.first);
1227 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001228}
1229
1230void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001231 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001232 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +00001233}
1234
1235void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001236 SDOperand Result =
1237 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1238 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1239 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +00001240}
1241
Chris Lattner39ae3622005-01-09 00:00:49 +00001242
1243// It is always conservatively correct for llvm.returnaddress and
1244// llvm.frameaddress to return 0.
1245std::pair<SDOperand, SDOperand>
1246TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1247 unsigned Depth, SelectionDAG &DAG) {
1248 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001249}
1250
Chris Lattner50381b62005-05-14 05:50:48 +00001251SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001252 assert(0 && "LowerOperation not implemented for this target!");
1253 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001254 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001255}
1256
Chris Lattner39ae3622005-01-09 00:00:49 +00001257void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1258 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1259 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001260 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001261 setValue(&I, Result.first);
1262 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001263}
1264
Chris Lattner7041ee32005-01-11 05:56:49 +00001265void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer6ff72402005-11-30 05:21:10 +00001266#if 0
1267 // If the size of the cpy/move/set is constant (known)
1268 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1269 uint64_t size = op3->getValue();
1270 switch (Op) {
1271 case ISD::MEMSET:
1272 if (size <= TLI.getMaxStoresPerMemSet()) {
1273 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1274 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1275 uint64_t align = op4.getValue();
1276 while (size > align) {
1277 size -=align;
1278 }
1279 Value *SrcV = I.getOperand(0);
1280 SDOperand Src = getValue(SrcV);
1281 SDOperand Ptr = getValue(I.getOperand(1));
1282 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1283 DAG.getSrcValue(I.getOperand(1))));
1284 }
1285 break;
1286 }
1287 break; // don't do this optimization, use a normal memset
1288 case ISD::MEMMOVE:
1289 case ISD::MEMCPY:
1290 break; // FIXME: not implemented yet
1291 }
1292 }
1293#endif
1294
1295 // Non-optimized version
Chris Lattner7041ee32005-01-11 05:56:49 +00001296 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001297 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +00001298 Ops.push_back(getValue(I.getOperand(1)));
1299 Ops.push_back(getValue(I.getOperand(2)));
1300 Ops.push_back(getValue(I.getOperand(3)));
1301 Ops.push_back(getValue(I.getOperand(4)));
1302 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001303}
1304
Chris Lattner7041ee32005-01-11 05:56:49 +00001305//===----------------------------------------------------------------------===//
1306// SelectionDAGISel code
1307//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001308
1309unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1310 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1311}
1312
Chris Lattner495a0b52005-08-17 06:37:43 +00001313void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001314 // FIXME: we only modify the CFG to split critical edges. This
1315 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001316}
Chris Lattner1c08c712005-01-07 07:47:53 +00001317
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001318
1319/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1320/// casting to the type of GEPI.
1321static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1322 Value *Ptr, Value *PtrOffset) {
1323 if (V) return V; // Already computed.
1324
1325 BasicBlock::iterator InsertPt;
1326 if (BB == GEPI->getParent()) {
1327 // If insert into the GEP's block, insert right after the GEP.
1328 InsertPt = GEPI;
1329 ++InsertPt;
1330 } else {
1331 // Otherwise, insert at the top of BB, after any PHI nodes
1332 InsertPt = BB->begin();
1333 while (isa<PHINode>(InsertPt)) ++InsertPt;
1334 }
1335
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001336 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1337 // BB so that there is only one value live across basic blocks (the cast
1338 // operand).
1339 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1340 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1341 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1342
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001343 // Add the offset, cast it to the right type.
1344 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1345 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1346 return V = Ptr;
1347}
1348
1349
1350/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1351/// selection, we want to be a bit careful about some things. In particular, if
1352/// we have a GEP instruction that is used in a different block than it is
1353/// defined, the addressing expression of the GEP cannot be folded into loads or
1354/// stores that use it. In this case, decompose the GEP and move constant
1355/// indices into blocks that use it.
1356static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1357 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001358 // If this GEP is only used inside the block it is defined in, there is no
1359 // need to rewrite it.
1360 bool isUsedOutsideDefBB = false;
1361 BasicBlock *DefBB = GEPI->getParent();
1362 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1363 UI != E; ++UI) {
1364 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1365 isUsedOutsideDefBB = true;
1366 break;
1367 }
1368 }
1369 if (!isUsedOutsideDefBB) return;
1370
1371 // If this GEP has no non-zero constant indices, there is nothing we can do,
1372 // ignore it.
1373 bool hasConstantIndex = false;
1374 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1375 E = GEPI->op_end(); OI != E; ++OI) {
1376 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1377 if (CI->getRawValue()) {
1378 hasConstantIndex = true;
1379 break;
1380 }
1381 }
Chris Lattner3802c252005-12-11 09:05:13 +00001382 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1383 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001384
1385 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1386 // constant offset (which we now know is non-zero) and deal with it later.
1387 uint64_t ConstantOffset = 0;
1388 const Type *UIntPtrTy = TD.getIntPtrType();
1389 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1390 const Type *Ty = GEPI->getOperand(0)->getType();
1391
1392 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1393 E = GEPI->op_end(); OI != E; ++OI) {
1394 Value *Idx = *OI;
1395 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1396 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1397 if (Field)
1398 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1399 Ty = StTy->getElementType(Field);
1400 } else {
1401 Ty = cast<SequentialType>(Ty)->getElementType();
1402
1403 // Handle constant subscripts.
1404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1405 if (CI->getRawValue() == 0) continue;
1406
1407 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1408 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1409 else
1410 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1411 continue;
1412 }
1413
1414 // Ptr = Ptr + Idx * ElementSize;
1415
1416 // Cast Idx to UIntPtrTy if needed.
1417 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1418
1419 uint64_t ElementSize = TD.getTypeSize(Ty);
1420 // Mask off bits that should not be set.
1421 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1422 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1423
1424 // Multiply by the element size and add to the base.
1425 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1426 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1427 }
1428 }
1429
1430 // Make sure that the offset fits in uintptr_t.
1431 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1432 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1433
1434 // Okay, we have now emitted all of the variable index parts to the BB that
1435 // the GEP is defined in. Loop over all of the using instructions, inserting
1436 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001437 // instruction to use the newly computed value, making GEPI dead. When the
1438 // user is a load or store instruction address, we emit the add into the user
1439 // block, otherwise we use a canonical version right next to the gep (these
1440 // won't be foldable as addresses, so we might as well share the computation).
1441
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001442 std::map<BasicBlock*,Value*> InsertedExprs;
1443 while (!GEPI->use_empty()) {
1444 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001445
1446 // If this use is not foldable into the addressing mode, use a version
1447 // emitted in the GEP block.
1448 Value *NewVal;
1449 if (!isa<LoadInst>(User) &&
1450 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1451 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1452 Ptr, PtrOffset);
1453 } else {
1454 // Otherwise, insert the code in the User's block so it can be folded into
1455 // any users in that block.
1456 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001457 User->getParent(), GEPI,
1458 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001459 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001460 User->replaceUsesOfWith(GEPI, NewVal);
1461 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001462
1463 // Finally, the GEP is dead, remove it.
1464 GEPI->eraseFromParent();
1465}
1466
Chris Lattner1c08c712005-01-07 07:47:53 +00001467bool SelectionDAGISel::runOnFunction(Function &Fn) {
1468 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1469 RegMap = MF.getSSARegMap();
1470 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1471
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001472 // First, split all critical edges for PHI nodes with incoming values that are
1473 // constants, this way the load of the constant into a vreg will not be placed
1474 // into MBBs that are used some other way.
1475 //
1476 // In this pass we also look for GEP instructions that are used across basic
1477 // blocks and rewrites them to improve basic-block-at-a-time selection.
1478 //
Chris Lattner36b708f2005-08-18 17:35:14 +00001479 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1480 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001481 BasicBlock::iterator BBI;
1482 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00001483 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1484 if (isa<Constant>(PN->getIncomingValue(i)))
1485 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001486
1487 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1488 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1489 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00001490 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001491
Chris Lattner1c08c712005-01-07 07:47:53 +00001492 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1493
1494 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1495 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001496
Chris Lattner1c08c712005-01-07 07:47:53 +00001497 return true;
1498}
1499
1500
Chris Lattnerddb870b2005-01-13 17:59:43 +00001501SDOperand SelectionDAGISel::
1502CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001503 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001504 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001505 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001506 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001507
1508 // If this type is not legal, we must make sure to not create an invalid
1509 // register use.
1510 MVT::ValueType SrcVT = Op.getValueType();
1511 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1512 SelectionDAG &DAG = SDL.DAG;
1513 if (SrcVT == DestVT) {
1514 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1515 } else if (SrcVT < DestVT) {
1516 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001517 if (MVT::isFloatingPoint(SrcVT))
1518 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1519 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001520 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001521 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1522 } else {
1523 // The src value is expanded into multiple registers.
1524 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1525 Op, DAG.getConstant(0, MVT::i32));
1526 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1527 Op, DAG.getConstant(1, MVT::i32));
1528 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1529 return DAG.getCopyToReg(Op, Reg+1, Hi);
1530 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001531}
1532
Chris Lattner068a81e2005-01-17 17:15:02 +00001533void SelectionDAGISel::
1534LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1535 std::vector<SDOperand> &UnorderedChains) {
1536 // If this is the entry block, emit arguments.
1537 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001538 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00001539 SDOperand OldRoot = SDL.DAG.getRoot();
1540 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00001541
Chris Lattnerbf209482005-10-30 19:42:35 +00001542 unsigned a = 0;
1543 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1544 AI != E; ++AI, ++a)
1545 if (!AI->use_empty()) {
1546 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00001547
Chris Lattnerbf209482005-10-30 19:42:35 +00001548 // If this argument is live outside of the entry block, insert a copy from
1549 // whereever we got it to the vreg that other BB's will reference it as.
1550 if (FuncInfo.ValueMap.count(AI)) {
1551 SDOperand Copy =
1552 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1553 UnorderedChains.push_back(Copy);
1554 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00001555 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001556
1557 // Next, if the function has live ins that need to be copied into vregs,
1558 // emit the copies now, into the top of the block.
1559 MachineFunction &MF = SDL.DAG.getMachineFunction();
1560 if (MF.livein_begin() != MF.livein_end()) {
1561 SSARegMap *RegMap = MF.getSSARegMap();
1562 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1563 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1564 E = MF.livein_end(); LI != E; ++LI)
1565 if (LI->second)
1566 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1567 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00001568 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001569
1570 // Finally, if the target has anything special to do, allow it to do so.
1571 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00001572}
1573
1574
Chris Lattner1c08c712005-01-07 07:47:53 +00001575void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1576 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1577 FunctionLoweringInfo &FuncInfo) {
1578 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001579
1580 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001581
Chris Lattnerbf209482005-10-30 19:42:35 +00001582 // Lower any arguments needed in this block if this is the entry block.
1583 if (LLVMBB == &LLVMBB->getParent()->front())
1584 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001585
1586 BB = FuncInfo.MBBMap[LLVMBB];
1587 SDL.setCurrentBasicBlock(BB);
1588
1589 // Lower all of the non-terminator instructions.
1590 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1591 I != E; ++I)
1592 SDL.visit(*I);
1593
1594 // Ensure that all instructions which are used outside of their defining
1595 // blocks are available as virtual registers.
1596 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001597 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001598 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001599 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001600 UnorderedChains.push_back(
1601 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001602 }
1603
1604 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1605 // ensure constants are generated when needed. Remember the virtual registers
1606 // that need to be added to the Machine PHI nodes as input. We cannot just
1607 // directly add them, because expansion might result in multiple MBB's for one
1608 // BB. As such, the start of the BB might correspond to a different MBB than
1609 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001610 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001611
1612 // Emit constants only once even if used by multiple PHI nodes.
1613 std::map<Constant*, unsigned> ConstantsOut;
1614
1615 // Check successor nodes PHI nodes that expect a constant to be available from
1616 // this block.
1617 TerminatorInst *TI = LLVMBB->getTerminator();
1618 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1619 BasicBlock *SuccBB = TI->getSuccessor(succ);
1620 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1621 PHINode *PN;
1622
1623 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1624 // nodes and Machine PHI nodes, but the incoming operands have not been
1625 // emitted yet.
1626 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001627 (PN = dyn_cast<PHINode>(I)); ++I)
1628 if (!PN->use_empty()) {
1629 unsigned Reg;
1630 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1631 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1632 unsigned &RegOut = ConstantsOut[C];
1633 if (RegOut == 0) {
1634 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001635 UnorderedChains.push_back(
1636 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001637 }
1638 Reg = RegOut;
1639 } else {
1640 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001641 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001642 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001643 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1644 "Didn't codegen value into a register!??");
1645 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001646 UnorderedChains.push_back(
1647 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001648 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001649 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001650
Chris Lattnerf44fd882005-01-07 21:34:19 +00001651 // Remember that this register needs to added to the machine PHI node as
1652 // the input for this MBB.
1653 unsigned NumElements =
1654 TLI.getNumElements(TLI.getValueType(PN->getType()));
1655 for (unsigned i = 0, e = NumElements; i != e; ++i)
1656 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001657 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001658 }
1659 ConstantsOut.clear();
1660
Chris Lattnerddb870b2005-01-13 17:59:43 +00001661 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001662 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00001663 SDOperand Root = SDL.getRoot();
1664 if (Root.getOpcode() != ISD::EntryToken) {
1665 unsigned i = 0, e = UnorderedChains.size();
1666 for (; i != e; ++i) {
1667 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1668 if (UnorderedChains[i].Val->getOperand(0) == Root)
1669 break; // Don't add the root if we already indirectly depend on it.
1670 }
1671
1672 if (i == e)
1673 UnorderedChains.push_back(Root);
1674 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00001675 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1676 }
1677
Chris Lattner1c08c712005-01-07 07:47:53 +00001678 // Lower the terminator after the copies are emitted.
1679 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001680
1681 // Make sure the root of the DAG is up-to-date.
1682 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001683}
1684
1685void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1686 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00001687 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00001688 CurDAG = &DAG;
1689 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1690
1691 // First step, lower LLVM code to some DAG. This DAG may use operations and
1692 // types that are not supported by the target.
1693 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1694
Chris Lattneraf21d552005-10-10 16:47:10 +00001695 // Run the DAG combiner in pre-legalize mode.
1696 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00001697
Chris Lattner1c08c712005-01-07 07:47:53 +00001698 DEBUG(std::cerr << "Lowered selection DAG:\n");
1699 DEBUG(DAG.dump());
1700
1701 // Second step, hack on the DAG until it only uses operations and types that
1702 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001703 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001704
1705 DEBUG(std::cerr << "Legalized selection DAG:\n");
1706 DEBUG(DAG.dump());
1707
Chris Lattneraf21d552005-10-10 16:47:10 +00001708 // Run the DAG combiner in post-legalize mode.
1709 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00001710
Chris Lattnerd48050a2005-10-05 06:09:10 +00001711 if (ViewDAGs) DAG.viewGraph();
1712
Chris Lattnera33ef482005-03-30 01:10:47 +00001713 // Third, instruction select all of the operations to machine code, adding the
1714 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001715 InstructionSelectBasicBlock(DAG);
1716
Chris Lattner1c08c712005-01-07 07:47:53 +00001717 DEBUG(std::cerr << "Selected machine code:\n");
1718 DEBUG(BB->dump());
1719
Chris Lattnera33ef482005-03-30 01:10:47 +00001720 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001721 // PHI nodes in successors.
1722 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1723 MachineInstr *PHI = PHINodesToUpdate[i].first;
1724 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1725 "This is not a machine PHI node that we are updating!");
1726 PHI->addRegOperand(PHINodesToUpdate[i].second);
1727 PHI->addMachineBasicBlockOperand(BB);
1728 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001729
1730 // Finally, add the CFG edges from the last selected MBB to the successor
1731 // MBBs.
1732 TerminatorInst *TI = LLVMBB->getTerminator();
1733 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1734 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1735 BB->addSuccessor(Succ0MBB);
1736 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001737}