blob: 103a00a25c2507f50ba85836ff72dc5e78d558ca [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"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/SelectionDAG.h"
28#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000029#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/Target/TargetData.h"
31#include "llvm/Target/TargetFrameInfo.h"
32#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
34#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000036#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000037#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000038#include "llvm/Support/Debug.h"
39#include <map>
40#include <iostream>
41using namespace llvm;
42
Chris Lattnerda8abb02005-09-01 18:44:10 +000043#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000044static cl::opt<bool>
45ViewDAGs("view-isel-dags", cl::Hidden,
46 cl::desc("Pop up a window to show isel dags as they are selected"));
47#else
Chris Lattnera639a432005-09-02 07:09:28 +000048static const bool ViewDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000049#endif
50
Chris Lattner1c08c712005-01-07 07:47:53 +000051namespace llvm {
52 //===--------------------------------------------------------------------===//
53 /// FunctionLoweringInfo - This contains information that is global to a
54 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000055 class FunctionLoweringInfo {
56 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000057 TargetLowering &TLI;
58 Function &Fn;
59 MachineFunction &MF;
60 SSARegMap *RegMap;
61
62 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
63
64 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
65 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
66
67 /// ValueMap - Since we emit code for the function a basic block at a time,
68 /// we must remember which virtual registers hold the values for
69 /// cross-basic-block values.
70 std::map<const Value*, unsigned> ValueMap;
71
72 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
73 /// the entry block. This allows the allocas to be efficiently referenced
74 /// anywhere in the function.
75 std::map<const AllocaInst*, int> StaticAllocaMap;
76
77 unsigned MakeReg(MVT::ValueType VT) {
78 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
79 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000080
Chris Lattner1c08c712005-01-07 07:47:53 +000081 unsigned CreateRegForValue(const Value *V) {
82 MVT::ValueType VT = TLI.getValueType(V->getType());
83 // The common case is that we will only create one register for this
84 // value. If we have that case, create and return the virtual register.
85 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +000086 if (NV == 1) {
87 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000088 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000089 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000090
Chris Lattner1c08c712005-01-07 07:47:53 +000091 // If this value is represented with multiple target registers, make sure
92 // to create enough consequtive registers of the right (smaller) type.
93 unsigned NT = VT-1; // Find the type to use.
94 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
95 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +000096
Chris Lattner1c08c712005-01-07 07:47:53 +000097 unsigned R = MakeReg((MVT::ValueType)NT);
98 for (unsigned i = 1; i != NV; ++i)
99 MakeReg((MVT::ValueType)NT);
100 return R;
101 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000102
Chris Lattner1c08c712005-01-07 07:47:53 +0000103 unsigned InitializeRegForValue(const Value *V) {
104 unsigned &R = ValueMap[V];
105 assert(R == 0 && "Already initialized this value register!");
106 return R = CreateRegForValue(V);
107 }
108 };
109}
110
111/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
112/// PHI nodes or outside of the basic block that defines it.
113static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
114 if (isa<PHINode>(I)) return true;
115 BasicBlock *BB = I->getParent();
116 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
117 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
118 return true;
119 return false;
120}
121
Chris Lattnerbf209482005-10-30 19:42:35 +0000122/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
123/// entry block, return true.
124static bool isOnlyUsedInEntryBlock(Argument *A) {
125 BasicBlock *Entry = A->getParent()->begin();
126 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
127 if (cast<Instruction>(*UI)->getParent() != Entry)
128 return false; // Use not in entry block.
129 return true;
130}
131
Chris Lattner1c08c712005-01-07 07:47:53 +0000132FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000133 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000134 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
135
Chris Lattnerbf209482005-10-30 19:42:35 +0000136 // Create a vreg for each argument register that is not dead and is used
137 // outside of the entry block for the function.
138 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
139 AI != E; ++AI)
140 if (!isOnlyUsedInEntryBlock(AI))
141 InitializeRegForValue(AI);
142
Chris Lattner1c08c712005-01-07 07:47:53 +0000143 // Initialize the mapping of values to registers. This is only set up for
144 // instruction values that are used outside of the block that defines
145 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000146 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000147 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
148 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
149 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
150 const Type *Ty = AI->getAllocatedType();
151 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000152 unsigned Align =
153 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
154 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000155
156 // If the alignment of the value is smaller than the size of the value,
157 // and if the size of the value is particularly small (<= 8 bytes),
158 // round up to the size of the value for potentially better performance.
159 //
160 // FIXME: This could be made better with a preferred alignment hook in
161 // TargetData. It serves primarily to 8-byte align doubles for X86.
162 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000163 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000164 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000165 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000166 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000167 }
168
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000169 for (; BB != EB; ++BB)
170 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000171 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
172 if (!isa<AllocaInst>(I) ||
173 !StaticAllocaMap.count(cast<AllocaInst>(I)))
174 InitializeRegForValue(I);
175
176 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
177 // also creates the initial PHI MachineInstrs, though none of the input
178 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000179 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000180 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
181 MBBMap[BB] = MBB;
182 MF.getBasicBlockList().push_back(MBB);
183
184 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
185 // appropriate.
186 PHINode *PN;
187 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000188 (PN = dyn_cast<PHINode>(I)); ++I)
189 if (!PN->use_empty()) {
190 unsigned NumElements =
191 TLI.getNumElements(TLI.getValueType(PN->getType()));
192 unsigned PHIReg = ValueMap[PN];
193 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
194 for (unsigned i = 0; i != NumElements; ++i)
195 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
196 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000197 }
198}
199
200
201
202//===----------------------------------------------------------------------===//
203/// SelectionDAGLowering - This is the common target-independent lowering
204/// implementation that is parameterized by a TargetLowering object.
205/// Also, targets can overload any lowering method.
206///
207namespace llvm {
208class SelectionDAGLowering {
209 MachineBasicBlock *CurMBB;
210
211 std::map<const Value*, SDOperand> NodeMap;
212
Chris Lattnerd3948112005-01-17 22:19:26 +0000213 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
214 /// them up and then emit token factor nodes when possible. This allows us to
215 /// get simple disambiguation between loads without worrying about alias
216 /// analysis.
217 std::vector<SDOperand> PendingLoads;
218
Chris Lattner1c08c712005-01-07 07:47:53 +0000219public:
220 // TLI - This is information that describes the available target features we
221 // need for lowering. This indicates when operations are unavailable,
222 // implemented with a libcall, etc.
223 TargetLowering &TLI;
224 SelectionDAG &DAG;
225 const TargetData &TD;
226
227 /// FuncInfo - Information about the function as a whole.
228 ///
229 FunctionLoweringInfo &FuncInfo;
230
231 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000232 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000233 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
234 FuncInfo(funcinfo) {
235 }
236
Chris Lattnera651cf62005-01-17 19:43:36 +0000237 /// getRoot - Return the current virtual root of the Selection DAG.
238 ///
239 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000240 if (PendingLoads.empty())
241 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000242
Chris Lattnerd3948112005-01-17 22:19:26 +0000243 if (PendingLoads.size() == 1) {
244 SDOperand Root = PendingLoads[0];
245 DAG.setRoot(Root);
246 PendingLoads.clear();
247 return Root;
248 }
249
250 // Otherwise, we have to make a token factor node.
251 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
252 PendingLoads.clear();
253 DAG.setRoot(Root);
254 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000255 }
256
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 void visit(Instruction &I) { visit(I.getOpcode(), I); }
258
259 void visit(unsigned Opcode, User &I) {
260 switch (Opcode) {
261 default: assert(0 && "Unknown instruction type encountered!");
262 abort();
263 // Build the switch statement using the Instruction.def file.
264#define HANDLE_INST(NUM, OPCODE, CLASS) \
265 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
266#include "llvm/Instruction.def"
267 }
268 }
269
270 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
271
272
273 SDOperand getIntPtrConstant(uint64_t Val) {
274 return DAG.getConstant(Val, TLI.getPointerTy());
275 }
276
277 SDOperand getValue(const Value *V) {
278 SDOperand &N = NodeMap[V];
279 if (N.Val) return N;
280
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000281 const Type *VTy = V->getType();
282 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000283 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
284 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
285 visit(CE->getOpcode(), *CE);
286 assert(N.Val && "visit didn't populate the ValueMap!");
287 return N;
288 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
289 return N = DAG.getGlobalAddress(GV, VT);
290 } else if (isa<ConstantPointerNull>(C)) {
291 return N = DAG.getConstant(0, TLI.getPointerTy());
292 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000293 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000294 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
295 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000296 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
297 unsigned NumElements = PTy->getNumElements();
298 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
299 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
300
301 // Now that we know the number and type of the elements, push a
302 // Constant or ConstantFP node onto the ops list for each element of
303 // the packed constant.
304 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000305 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
306 if (MVT::isFloatingPoint(PVT)) {
307 for (unsigned i = 0; i != NumElements; ++i) {
308 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
309 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
310 }
311 } else {
312 for (unsigned i = 0; i != NumElements; ++i) {
313 const ConstantIntegral *El =
314 cast<ConstantIntegral>(CP->getOperand(i));
315 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
316 }
317 }
318 } else {
319 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
320 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000321 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000322 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000323 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000324 Op = DAG.getConstant(0, PVT);
325 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000326 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000327
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000328 // Handle the case where we have a 1-element vector, in which
329 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000330 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000331 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000332 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
333 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
334 } else {
335 // If the packed type isn't legal, then create a ConstantVec node with
336 // generic Vector type instead.
337 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
338 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 } else {
340 // Canonicalize all constant ints to be unsigned.
341 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
342 }
343
344 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
345 std::map<const AllocaInst*, int>::iterator SI =
346 FuncInfo.StaticAllocaMap.find(AI);
347 if (SI != FuncInfo.StaticAllocaMap.end())
348 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
349 }
350
351 std::map<const Value*, unsigned>::const_iterator VMI =
352 FuncInfo.ValueMap.find(V);
353 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000354
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000355 unsigned InReg = VMI->second;
356
357 // If this type is not legal, make it so now.
358 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
359
360 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
361 if (DestVT < VT) {
362 // Source must be expanded. This input value is actually coming from the
363 // register pair VMI->second and VMI->second+1.
364 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
365 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
366 } else {
367 if (DestVT > VT) { // Promotion case
368 if (MVT::isFloatingPoint(VT))
369 N = DAG.getNode(ISD::FP_ROUND, VT, N);
370 else
371 N = DAG.getNode(ISD::TRUNCATE, VT, N);
372 }
373 }
374
375 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000376 }
377
378 const SDOperand &setValue(const Value *V, SDOperand NewN) {
379 SDOperand &N = NodeMap[V];
380 assert(N.Val == 0 && "Already set a value for this node!");
381 return N = NewN;
382 }
383
384 // Terminator instructions.
385 void visitRet(ReturnInst &I);
386 void visitBr(BranchInst &I);
387 void visitUnreachable(UnreachableInst &I) { /* noop */ }
388
389 // These all get lowered before this pass.
390 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
391 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
392 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
393
394 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000395 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000396 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000397 void visitAdd(User &I) {
398 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000399 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000400 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000401 void visitMul(User &I) {
402 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000403 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000404 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000405 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000406 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000407 }
408 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000409 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000410 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000411 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000412 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
413 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
414 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000415 void visitShl(User &I) { visitShift(I, ISD::SHL); }
416 void visitShr(User &I) {
417 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 }
419
420 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
421 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
422 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
423 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
424 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
425 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
426 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
427
428 void visitGetElementPtr(User &I);
429 void visitCast(User &I);
430 void visitSelect(User &I);
431 //
432
433 void visitMalloc(MallocInst &I);
434 void visitFree(FreeInst &I);
435 void visitAlloca(AllocaInst &I);
436 void visitLoad(LoadInst &I);
437 void visitStore(StoreInst &I);
438 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
439 void visitCall(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000440 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000441
Chris Lattner1c08c712005-01-07 07:47:53 +0000442 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 void visitVAArg(VAArgInst &I);
444 void visitVAEnd(CallInst &I);
445 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000446 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000447
Chris Lattner7041ee32005-01-11 05:56:49 +0000448 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000449
450 void visitUserOp1(Instruction &I) {
451 assert(0 && "UserOp1 should not exist at instruction selection time!");
452 abort();
453 }
454 void visitUserOp2(Instruction &I) {
455 assert(0 && "UserOp2 should not exist at instruction selection time!");
456 abort();
457 }
458};
459} // end namespace llvm
460
461void SelectionDAGLowering::visitRet(ReturnInst &I) {
462 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000463 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000464 return;
465 }
466
467 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000468 MVT::ValueType TmpVT;
469
Chris Lattner1c08c712005-01-07 07:47:53 +0000470 switch (Op1.getValueType()) {
471 default: assert(0 && "Unknown value type!");
472 case MVT::i1:
473 case MVT::i8:
474 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000475 case MVT::i32:
476 // If this is a machine where 32-bits is legal or expanded, promote to
477 // 32-bits, otherwise, promote to 64-bits.
478 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
479 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000480 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000481 TmpVT = MVT::i32;
482
483 // Extend integer types to result type.
484 if (I.getOperand(0)->getType()->isSigned())
485 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
486 else
487 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 break;
489 case MVT::f32:
Chris Lattner1c08c712005-01-07 07:47:53 +0000490 case MVT::i64:
491 case MVT::f64:
492 break; // No extension needed!
493 }
Nate Begeman4a959452005-10-18 23:23:37 +0000494 // Allow targets to lower this further to meet ABI requirements
495 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000496}
497
498void SelectionDAGLowering::visitBr(BranchInst &I) {
499 // Update machine-CFG edges.
500 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000501
502 // Figure out which block is immediately after the current one.
503 MachineBasicBlock *NextBlock = 0;
504 MachineFunction::iterator BBI = CurMBB;
505 if (++BBI != CurMBB->getParent()->end())
506 NextBlock = BBI;
507
508 if (I.isUnconditional()) {
509 // If this is not a fall-through branch, emit the branch.
510 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000511 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000512 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 } else {
514 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000515
516 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000517 if (Succ1MBB == NextBlock) {
518 // If the condition is false, fall through. This means we should branch
519 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000520 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000521 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000522 } else if (Succ0MBB == NextBlock) {
523 // If the condition is true, fall through. This means we should branch if
524 // the condition is false to Succ #1. Invert the condition first.
525 SDOperand True = DAG.getConstant(1, Cond.getValueType());
526 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
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(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000529 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000530 std::vector<SDOperand> Ops;
531 Ops.push_back(getRoot());
532 Ops.push_back(Cond);
533 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
534 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
535 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000536 }
537 }
538}
539
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000540void SelectionDAGLowering::visitSub(User &I) {
541 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000542 if (I.getType()->isFloatingPoint()) {
543 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
544 if (CFP->isExactlyValue(-0.0)) {
545 SDOperand Op2 = getValue(I.getOperand(1));
546 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
547 return;
548 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000549 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000550 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000551}
552
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000553void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
554 unsigned VecOp) {
555 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000556 SDOperand Op1 = getValue(I.getOperand(0));
557 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000558
Chris Lattnerb67eb912005-11-19 18:40:42 +0000559 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000560 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
561 } else if (Ty->isFloatingPoint()) {
562 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
563 } else {
564 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000565 unsigned NumElements = PTy->getNumElements();
566 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000567 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000568
569 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000570 // the Legalize pass does not have to deal with them. Similarly, if the
571 // abstract vector is going to turn into one that the target natively
572 // supports, generate that type now so that Legalize doesn't have to deal
573 // with that either. These steps ensure that Legalize only has to handle
574 // vector types in its Expand case.
575 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000576 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000577 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000578 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
579 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000580 } else {
581 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
582 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000583 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000584 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000585 }
Nate Begemane21ea612005-11-18 07:42:56 +0000586}
Chris Lattner2c49f272005-01-19 22:31:21 +0000587
Nate Begemane21ea612005-11-18 07:42:56 +0000588void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
589 SDOperand Op1 = getValue(I.getOperand(0));
590 SDOperand Op2 = getValue(I.getOperand(1));
591
592 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
593
Chris Lattner1c08c712005-01-07 07:47:53 +0000594 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
595}
596
597void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
598 ISD::CondCode UnsignedOpcode) {
599 SDOperand Op1 = getValue(I.getOperand(0));
600 SDOperand Op2 = getValue(I.getOperand(1));
601 ISD::CondCode Opcode = SignedOpcode;
602 if (I.getOperand(0)->getType()->isUnsigned())
603 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000604 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000605}
606
607void SelectionDAGLowering::visitSelect(User &I) {
608 SDOperand Cond = getValue(I.getOperand(0));
609 SDOperand TrueVal = getValue(I.getOperand(1));
610 SDOperand FalseVal = getValue(I.getOperand(2));
611 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
612 TrueVal, FalseVal));
613}
614
615void SelectionDAGLowering::visitCast(User &I) {
616 SDOperand N = getValue(I.getOperand(0));
617 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
618 MVT::ValueType DestTy = TLI.getValueType(I.getType());
619
620 if (N.getValueType() == DestTy) {
621 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000622 } else if (DestTy == MVT::i1) {
623 // Cast to bool is a comparison against zero, not truncation to zero.
624 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
625 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000626 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000627 } else if (isInteger(SrcTy)) {
628 if (isInteger(DestTy)) { // Int -> Int cast
629 if (DestTy < SrcTy) // Truncating cast?
630 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
631 else if (I.getOperand(0)->getType()->isSigned())
632 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
633 else
634 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
635 } else { // Int -> FP cast
636 if (I.getOperand(0)->getType()->isSigned())
637 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
638 else
639 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
640 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000641 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000642 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
643 if (isFloatingPoint(DestTy)) { // FP -> FP cast
644 if (DestTy < SrcTy) // Rounding cast?
645 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
646 else
647 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
648 } else { // FP -> Int cast.
649 if (I.getType()->isSigned())
650 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
651 else
652 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
653 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000654 }
655}
656
657void SelectionDAGLowering::visitGetElementPtr(User &I) {
658 SDOperand N = getValue(I.getOperand(0));
659 const Type *Ty = I.getOperand(0)->getType();
660 const Type *UIntPtrTy = TD.getIntPtrType();
661
662 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
663 OI != E; ++OI) {
664 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000665 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000666 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
667 if (Field) {
668 // N = N + Offset
669 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
670 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000671 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000672 }
673 Ty = StTy->getElementType(Field);
674 } else {
675 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000676
Chris Lattner7c0104b2005-11-09 04:45:33 +0000677 // If this is a constant subscript, handle it quickly.
678 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
679 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000680
Chris Lattner7c0104b2005-11-09 04:45:33 +0000681 uint64_t Offs;
682 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
683 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
684 else
685 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
686 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
687 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000688 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000689
690 // N = N + Idx * ElementSize;
691 uint64_t ElementSize = TD.getTypeSize(Ty);
692 SDOperand IdxN = getValue(Idx);
693
694 // If the index is smaller or larger than intptr_t, truncate or extend
695 // it.
696 if (IdxN.getValueType() < N.getValueType()) {
697 if (Idx->getType()->isSigned())
698 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
699 else
700 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
701 } else if (IdxN.getValueType() > N.getValueType())
702 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
703
704 // If this is a multiply by a power of two, turn it into a shl
705 // immediately. This is a very common case.
706 if (isPowerOf2_64(ElementSize)) {
707 unsigned Amt = Log2_64(ElementSize);
708 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000709 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000710 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
711 continue;
712 }
713
714 SDOperand Scale = getIntPtrConstant(ElementSize);
715 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
716 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000717 }
718 }
719 setValue(&I, N);
720}
721
722void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
723 // If this is a fixed sized alloca in the entry block of the function,
724 // allocate it statically on the stack.
725 if (FuncInfo.StaticAllocaMap.count(&I))
726 return; // getValue will auto-populate this.
727
728 const Type *Ty = I.getAllocatedType();
729 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000730 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
731 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000732
733 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000734 MVT::ValueType IntPtr = TLI.getPointerTy();
735 if (IntPtr < AllocSize.getValueType())
736 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
737 else if (IntPtr > AllocSize.getValueType())
738 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000739
Chris Lattner68cd65e2005-01-22 23:04:37 +0000740 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000741 getIntPtrConstant(TySize));
742
743 // Handle alignment. If the requested alignment is less than or equal to the
744 // stack alignment, ignore it and round the size of the allocation up to the
745 // stack alignment size. If the size is greater than the stack alignment, we
746 // note this in the DYNAMIC_STACKALLOC node.
747 unsigned StackAlign =
748 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
749 if (Align <= StackAlign) {
750 Align = 0;
751 // Add SA-1 to the size.
752 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
753 getIntPtrConstant(StackAlign-1));
754 // Mask out the low bits for alignment purposes.
755 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
756 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
757 }
758
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000759 std::vector<MVT::ValueType> VTs;
760 VTs.push_back(AllocSize.getValueType());
761 VTs.push_back(MVT::Other);
762 std::vector<SDOperand> Ops;
763 Ops.push_back(getRoot());
764 Ops.push_back(AllocSize);
765 Ops.push_back(getIntPtrConstant(Align));
766 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000767 DAG.setRoot(setValue(&I, DSA).getValue(1));
768
769 // Inform the Frame Information that we have just allocated a variable-sized
770 // object.
771 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
772}
773
Chris Lattner36ce6912005-11-29 06:21:05 +0000774/// getStringValue - Turn an LLVM constant pointer that eventually points to a
775/// global into a string value. Return an empty string if we can't do it.
776///
777static std::string getStringValue(Value *V, unsigned Offset = 0) {
778 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
779 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
780 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
781 if (Init->isString()) {
782 std::string Result = Init->getAsString();
783 if (Offset < Result.size()) {
784 // If we are pointing INTO The string, erase the beginning...
785 Result.erase(Result.begin(), Result.begin()+Offset);
786
787 // Take off the null terminator, and any string fragments after it.
788 std::string::size_type NullPos = Result.find_first_of((char)0);
789 if (NullPos != std::string::npos)
790 Result.erase(Result.begin()+NullPos, Result.end());
791 return Result;
792 }
793 }
794 }
795 } else if (Constant *C = dyn_cast<Constant>(V)) {
796 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
797 return getStringValue(GV, Offset);
798 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
799 if (CE->getOpcode() == Instruction::GetElementPtr) {
800 // Turn a gep into the specified offset.
801 if (CE->getNumOperands() == 3 &&
802 cast<Constant>(CE->getOperand(1))->isNullValue() &&
803 isa<ConstantInt>(CE->getOperand(2))) {
804 return getStringValue(CE->getOperand(0),
805 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
806 }
807 }
808 }
809 }
810 return "";
811}
Chris Lattner1c08c712005-01-07 07:47:53 +0000812
813void SelectionDAGLowering::visitLoad(LoadInst &I) {
814 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000815
Chris Lattnerd3948112005-01-17 22:19:26 +0000816 SDOperand Root;
817 if (I.isVolatile())
818 Root = getRoot();
819 else {
820 // Do not serialize non-volatile loads against each other.
821 Root = DAG.getRoot();
822 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000823
824 const Type *Ty = I.getType();
825 SDOperand L;
826
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000827 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000828 unsigned NumElements = PTy->getNumElements();
829 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000830 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000831
832 // Immediately scalarize packed types containing only one element, so that
833 // the Legalize pass does not have to deal with them.
834 if (NumElements == 1) {
835 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000836 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
837 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000838 } else {
839 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
840 DAG.getSrcValue(I.getOperand(0)));
841 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000842 } else {
843 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
844 DAG.getSrcValue(I.getOperand(0)));
845 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000846 setValue(&I, L);
847
848 if (I.isVolatile())
849 DAG.setRoot(L.getValue(1));
850 else
851 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000852}
853
854
855void SelectionDAGLowering::visitStore(StoreInst &I) {
856 Value *SrcV = I.getOperand(0);
857 SDOperand Src = getValue(SrcV);
858 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000859 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000860 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000861}
862
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000863/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
864/// we want to emit this as a call to a named external function, return the name
865/// otherwise lower it and return null.
866const char *
867SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
868 switch (Intrinsic) {
869 case Intrinsic::vastart: visitVAStart(I); return 0;
870 case Intrinsic::vaend: visitVAEnd(I); return 0;
871 case Intrinsic::vacopy: visitVACopy(I); return 0;
872 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
873 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
874 case Intrinsic::setjmp:
875 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
876 break;
877 case Intrinsic::longjmp:
878 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
879 break;
880 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
881 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
882 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
883
884 case Intrinsic::readport:
885 case Intrinsic::readio: {
886 std::vector<MVT::ValueType> VTs;
887 VTs.push_back(TLI.getValueType(I.getType()));
888 VTs.push_back(MVT::Other);
889 std::vector<SDOperand> Ops;
890 Ops.push_back(getRoot());
891 Ops.push_back(getValue(I.getOperand(1)));
892 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
893 ISD::READPORT : ISD::READIO, VTs, Ops);
894
895 setValue(&I, Tmp);
896 DAG.setRoot(Tmp.getValue(1));
897 return 0;
898 }
899 case Intrinsic::writeport:
900 case Intrinsic::writeio:
901 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
902 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
903 getRoot(), getValue(I.getOperand(1)),
904 getValue(I.getOperand(2))));
905 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000906
Chris Lattner86cb6432005-12-13 17:40:33 +0000907 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000908 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
909 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000910
911 std::string fname = "<unknown>";
912 std::vector<SDOperand> Ops;
913
Chris Lattner36ce6912005-11-29 06:21:05 +0000914 // Input Chain
915 Ops.push_back(getRoot());
916
917 // line number
918 Ops.push_back(getValue(I.getOperand(2)));
919
920 // column
921 Ops.push_back(getValue(I.getOperand(3)));
922
Chris Lattner86cb6432005-12-13 17:40:33 +0000923 // filename/working dir
924 // Pull the filename out of the the compilation unit.
925 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
926 if (cunit && cunit->hasInitializer()) {
927 if (ConstantStruct *CS =
928 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
929 if (CS->getNumOperands() > 0) {
Chris Lattner86cb6432005-12-13 17:40:33 +0000930 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskeyf5395ce2005-12-16 22:45:29 +0000931 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner86cb6432005-12-13 17:40:33 +0000932 }
933 }
934 }
935
936 if (Ops.size() == 5) // Found filename/workingdir.
937 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000938 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000939 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000940 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000941 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000942 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
943 return "llvm_dbg_region_start";
944 if (I.getType() != Type::VoidTy)
945 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
946 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000947 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000948 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
949 return "llvm_dbg_region_end";
950 if (I.getType() != Type::VoidTy)
951 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
952 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000953 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000954 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
955 return "llvm_dbg_subprogram";
956 if (I.getType() != Type::VoidTy)
957 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
958 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000959 case Intrinsic::dbg_declare:
960 if (I.getType() != Type::VoidTy)
961 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
962 return 0;
963
964 case Intrinsic::isunordered:
965 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
966 getValue(I.getOperand(2)), ISD::SETUO));
967 return 0;
968
969 case Intrinsic::sqrt:
970 setValue(&I, DAG.getNode(ISD::FSQRT,
971 getValue(I.getOperand(1)).getValueType(),
972 getValue(I.getOperand(1))));
973 return 0;
974 case Intrinsic::pcmarker: {
975 SDOperand Tmp = getValue(I.getOperand(1));
976 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
977 return 0;
978 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +0000979 case Intrinsic::readcyclecounter: {
980 std::vector<MVT::ValueType> VTs;
981 VTs.push_back(MVT::i64);
982 VTs.push_back(MVT::Other);
983 std::vector<SDOperand> Ops;
984 Ops.push_back(getRoot());
985 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
986 setValue(&I, Tmp);
987 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +0000988 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +0000989 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000990 case Intrinsic::cttz:
991 setValue(&I, DAG.getNode(ISD::CTTZ,
992 getValue(I.getOperand(1)).getValueType(),
993 getValue(I.getOperand(1))));
994 return 0;
995 case Intrinsic::ctlz:
996 setValue(&I, DAG.getNode(ISD::CTLZ,
997 getValue(I.getOperand(1)).getValueType(),
998 getValue(I.getOperand(1))));
999 return 0;
1000 case Intrinsic::ctpop:
1001 setValue(&I, DAG.getNode(ISD::CTPOP,
1002 getValue(I.getOperand(1)).getValueType(),
1003 getValue(I.getOperand(1))));
1004 return 0;
Chris Lattnerac22c832005-12-12 22:51:16 +00001005 case Intrinsic::prefetch:
1006 // FIXME: Currently discarding prefetches.
1007 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001008 default:
1009 std::cerr << I;
1010 assert(0 && "This intrinsic is not implemented yet!");
1011 return 0;
1012 }
1013}
1014
1015
Chris Lattner1c08c712005-01-07 07:47:53 +00001016void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001017 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001018 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001019 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001020 if (unsigned IID = F->getIntrinsicID()) {
1021 RenameFn = visitIntrinsicCall(I, IID);
1022 if (!RenameFn)
1023 return;
1024 } else { // Not an LLVM intrinsic.
1025 const std::string &Name = F->getName();
1026 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001027 if (I.getNumOperands() == 2 && // Basic sanity checks.
1028 I.getOperand(1)->getType()->isFloatingPoint() &&
1029 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001030 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001031 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1032 return;
1033 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001034 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001035 if (I.getNumOperands() == 2 && // Basic sanity checks.
1036 I.getOperand(1)->getType()->isFloatingPoint() &&
1037 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001038 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001039 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1040 return;
1041 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001042 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001043 if (I.getNumOperands() == 2 && // Basic sanity checks.
1044 I.getOperand(1)->getType()->isFloatingPoint() &&
1045 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001046 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001047 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1048 return;
1049 }
1050 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001051 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001052 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001053
Chris Lattner64e14b12005-01-08 22:48:57 +00001054 SDOperand Callee;
1055 if (!RenameFn)
1056 Callee = getValue(I.getOperand(0));
1057 else
1058 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001059 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001060 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001061 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1062 Value *Arg = I.getOperand(i);
1063 SDOperand ArgNode = getValue(Arg);
1064 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1065 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001066
Nate Begeman8e21e712005-03-26 01:29:23 +00001067 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1068 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001069
Chris Lattnercf5734d2005-01-08 19:26:18 +00001070 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001071 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001072 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001073 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001074 setValue(&I, Result.first);
1075 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001076}
1077
1078void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1079 SDOperand Src = getValue(I.getOperand(0));
1080
1081 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001082
1083 if (IntPtr < Src.getValueType())
1084 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1085 else if (IntPtr > Src.getValueType())
1086 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001087
1088 // Scale the source by the type size.
1089 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1090 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1091 Src, getIntPtrConstant(ElementSize));
1092
1093 std::vector<std::pair<SDOperand, const Type*> > Args;
1094 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001095
1096 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001097 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001098 DAG.getExternalSymbol("malloc", IntPtr),
1099 Args, DAG);
1100 setValue(&I, Result.first); // Pointers always fit in registers
1101 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001102}
1103
1104void SelectionDAGLowering::visitFree(FreeInst &I) {
1105 std::vector<std::pair<SDOperand, const Type*> > Args;
1106 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1107 TLI.getTargetData().getIntPtrType()));
1108 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001109 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001110 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001111 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1112 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001113}
1114
Chris Lattner025c39b2005-08-26 20:54:47 +00001115// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1116// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1117// instructions are special in various ways, which require special support to
1118// insert. The specified MachineInstr is created but not inserted into any
1119// basic blocks, and the scheduler passes ownership of it to this method.
1120MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1121 MachineBasicBlock *MBB) {
1122 std::cerr << "If a target marks an instruction with "
1123 "'usesCustomDAGSchedInserter', it must implement "
1124 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1125 abort();
1126 return 0;
1127}
1128
Nate Begeman4a959452005-10-18 23:23:37 +00001129SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1130 SelectionDAG &DAG) {
1131 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1132}
1133
Chris Lattnere64e72b2005-07-05 19:57:53 +00001134SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1135 SDOperand VAListP, Value *VAListV,
1136 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001137 // We have no sane default behavior, just emit a useful error message and bail
1138 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +00001139 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00001140 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +00001141 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +00001142}
1143
Chris Lattnere64e72b2005-07-05 19:57:53 +00001144SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +00001145 SelectionDAG &DAG) {
1146 // Default to a noop.
1147 return Chain;
1148}
1149
Chris Lattnere64e72b2005-07-05 19:57:53 +00001150SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1151 SDOperand SrcP, Value *SrcV,
1152 SDOperand DestP, Value *DestV,
1153 SelectionDAG &DAG) {
1154 // Default to copying the input list.
1155 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1156 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001157 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001158 Val, DestP, DAG.getSrcValue(DestV));
1159 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +00001160}
1161
1162std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +00001163TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1164 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +00001165 // We have no sane default behavior, just emit a useful error message and bail
1166 // out.
1167 std::cerr << "Variable arguments handling not implemented on this target!\n";
1168 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001169 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +00001170}
1171
1172
1173void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001174 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1175 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +00001176}
1177
1178void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1179 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +00001180 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +00001181 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001182 setValue(&I, Result.first);
1183 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001184}
1185
1186void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001187 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001188 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +00001189}
1190
1191void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001192 SDOperand Result =
1193 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1194 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1195 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +00001196}
1197
Chris Lattner39ae3622005-01-09 00:00:49 +00001198
1199// It is always conservatively correct for llvm.returnaddress and
1200// llvm.frameaddress to return 0.
1201std::pair<SDOperand, SDOperand>
1202TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1203 unsigned Depth, SelectionDAG &DAG) {
1204 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001205}
1206
Chris Lattner50381b62005-05-14 05:50:48 +00001207SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001208 assert(0 && "LowerOperation not implemented for this target!");
1209 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001210 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001211}
1212
Chris Lattner39ae3622005-01-09 00:00:49 +00001213void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1214 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1215 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001216 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001217 setValue(&I, Result.first);
1218 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001219}
1220
Chris Lattner7041ee32005-01-11 05:56:49 +00001221void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer6ff72402005-11-30 05:21:10 +00001222#if 0
1223 // If the size of the cpy/move/set is constant (known)
1224 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1225 uint64_t size = op3->getValue();
1226 switch (Op) {
1227 case ISD::MEMSET:
1228 if (size <= TLI.getMaxStoresPerMemSet()) {
1229 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1230 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1231 uint64_t align = op4.getValue();
1232 while (size > align) {
1233 size -=align;
1234 }
1235 Value *SrcV = I.getOperand(0);
1236 SDOperand Src = getValue(SrcV);
1237 SDOperand Ptr = getValue(I.getOperand(1));
1238 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1239 DAG.getSrcValue(I.getOperand(1))));
1240 }
1241 break;
1242 }
1243 break; // don't do this optimization, use a normal memset
1244 case ISD::MEMMOVE:
1245 case ISD::MEMCPY:
1246 break; // FIXME: not implemented yet
1247 }
1248 }
1249#endif
1250
1251 // Non-optimized version
Chris Lattner7041ee32005-01-11 05:56:49 +00001252 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001253 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +00001254 Ops.push_back(getValue(I.getOperand(1)));
1255 Ops.push_back(getValue(I.getOperand(2)));
1256 Ops.push_back(getValue(I.getOperand(3)));
1257 Ops.push_back(getValue(I.getOperand(4)));
1258 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001259}
1260
Chris Lattner7041ee32005-01-11 05:56:49 +00001261//===----------------------------------------------------------------------===//
1262// SelectionDAGISel code
1263//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001264
1265unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1266 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1267}
1268
Chris Lattner495a0b52005-08-17 06:37:43 +00001269void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001270 // FIXME: we only modify the CFG to split critical edges. This
1271 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001272}
Chris Lattner1c08c712005-01-07 07:47:53 +00001273
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001274
1275/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1276/// casting to the type of GEPI.
1277static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1278 Value *Ptr, Value *PtrOffset) {
1279 if (V) return V; // Already computed.
1280
1281 BasicBlock::iterator InsertPt;
1282 if (BB == GEPI->getParent()) {
1283 // If insert into the GEP's block, insert right after the GEP.
1284 InsertPt = GEPI;
1285 ++InsertPt;
1286 } else {
1287 // Otherwise, insert at the top of BB, after any PHI nodes
1288 InsertPt = BB->begin();
1289 while (isa<PHINode>(InsertPt)) ++InsertPt;
1290 }
1291
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001292 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1293 // BB so that there is only one value live across basic blocks (the cast
1294 // operand).
1295 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1296 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1297 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1298
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001299 // Add the offset, cast it to the right type.
1300 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1301 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1302 return V = Ptr;
1303}
1304
1305
1306/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1307/// selection, we want to be a bit careful about some things. In particular, if
1308/// we have a GEP instruction that is used in a different block than it is
1309/// defined, the addressing expression of the GEP cannot be folded into loads or
1310/// stores that use it. In this case, decompose the GEP and move constant
1311/// indices into blocks that use it.
1312static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1313 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001314 // If this GEP is only used inside the block it is defined in, there is no
1315 // need to rewrite it.
1316 bool isUsedOutsideDefBB = false;
1317 BasicBlock *DefBB = GEPI->getParent();
1318 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1319 UI != E; ++UI) {
1320 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1321 isUsedOutsideDefBB = true;
1322 break;
1323 }
1324 }
1325 if (!isUsedOutsideDefBB) return;
1326
1327 // If this GEP has no non-zero constant indices, there is nothing we can do,
1328 // ignore it.
1329 bool hasConstantIndex = false;
1330 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1331 E = GEPI->op_end(); OI != E; ++OI) {
1332 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1333 if (CI->getRawValue()) {
1334 hasConstantIndex = true;
1335 break;
1336 }
1337 }
Chris Lattner3802c252005-12-11 09:05:13 +00001338 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1339 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001340
1341 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1342 // constant offset (which we now know is non-zero) and deal with it later.
1343 uint64_t ConstantOffset = 0;
1344 const Type *UIntPtrTy = TD.getIntPtrType();
1345 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1346 const Type *Ty = GEPI->getOperand(0)->getType();
1347
1348 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1349 E = GEPI->op_end(); OI != E; ++OI) {
1350 Value *Idx = *OI;
1351 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1352 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1353 if (Field)
1354 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1355 Ty = StTy->getElementType(Field);
1356 } else {
1357 Ty = cast<SequentialType>(Ty)->getElementType();
1358
1359 // Handle constant subscripts.
1360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1361 if (CI->getRawValue() == 0) continue;
1362
1363 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1364 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1365 else
1366 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1367 continue;
1368 }
1369
1370 // Ptr = Ptr + Idx * ElementSize;
1371
1372 // Cast Idx to UIntPtrTy if needed.
1373 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1374
1375 uint64_t ElementSize = TD.getTypeSize(Ty);
1376 // Mask off bits that should not be set.
1377 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1378 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1379
1380 // Multiply by the element size and add to the base.
1381 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1382 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1383 }
1384 }
1385
1386 // Make sure that the offset fits in uintptr_t.
1387 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1388 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1389
1390 // Okay, we have now emitted all of the variable index parts to the BB that
1391 // the GEP is defined in. Loop over all of the using instructions, inserting
1392 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001393 // instruction to use the newly computed value, making GEPI dead. When the
1394 // user is a load or store instruction address, we emit the add into the user
1395 // block, otherwise we use a canonical version right next to the gep (these
1396 // won't be foldable as addresses, so we might as well share the computation).
1397
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001398 std::map<BasicBlock*,Value*> InsertedExprs;
1399 while (!GEPI->use_empty()) {
1400 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001401
1402 // If this use is not foldable into the addressing mode, use a version
1403 // emitted in the GEP block.
1404 Value *NewVal;
1405 if (!isa<LoadInst>(User) &&
1406 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1407 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1408 Ptr, PtrOffset);
1409 } else {
1410 // Otherwise, insert the code in the User's block so it can be folded into
1411 // any users in that block.
1412 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001413 User->getParent(), GEPI,
1414 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001415 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001416 User->replaceUsesOfWith(GEPI, NewVal);
1417 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001418
1419 // Finally, the GEP is dead, remove it.
1420 GEPI->eraseFromParent();
1421}
1422
Chris Lattner1c08c712005-01-07 07:47:53 +00001423bool SelectionDAGISel::runOnFunction(Function &Fn) {
1424 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1425 RegMap = MF.getSSARegMap();
1426 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1427
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001428 // First, split all critical edges for PHI nodes with incoming values that are
1429 // constants, this way the load of the constant into a vreg will not be placed
1430 // into MBBs that are used some other way.
1431 //
1432 // In this pass we also look for GEP instructions that are used across basic
1433 // blocks and rewrites them to improve basic-block-at-a-time selection.
1434 //
Chris Lattner36b708f2005-08-18 17:35:14 +00001435 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1436 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001437 BasicBlock::iterator BBI;
1438 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00001439 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1440 if (isa<Constant>(PN->getIncomingValue(i)))
1441 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001442
1443 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1444 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1445 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00001446 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001447
Chris Lattner1c08c712005-01-07 07:47:53 +00001448 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1449
1450 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1451 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001452
Chris Lattner1c08c712005-01-07 07:47:53 +00001453 return true;
1454}
1455
1456
Chris Lattnerddb870b2005-01-13 17:59:43 +00001457SDOperand SelectionDAGISel::
1458CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001459 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001460 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001461 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001462 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001463
1464 // If this type is not legal, we must make sure to not create an invalid
1465 // register use.
1466 MVT::ValueType SrcVT = Op.getValueType();
1467 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1468 SelectionDAG &DAG = SDL.DAG;
1469 if (SrcVT == DestVT) {
1470 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1471 } else if (SrcVT < DestVT) {
1472 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001473 if (MVT::isFloatingPoint(SrcVT))
1474 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1475 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001476 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001477 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1478 } else {
1479 // The src value is expanded into multiple registers.
1480 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1481 Op, DAG.getConstant(0, MVT::i32));
1482 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1483 Op, DAG.getConstant(1, MVT::i32));
1484 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1485 return DAG.getCopyToReg(Op, Reg+1, Hi);
1486 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001487}
1488
Chris Lattner068a81e2005-01-17 17:15:02 +00001489void SelectionDAGISel::
1490LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1491 std::vector<SDOperand> &UnorderedChains) {
1492 // If this is the entry block, emit arguments.
1493 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001494 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00001495 SDOperand OldRoot = SDL.DAG.getRoot();
1496 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00001497
Chris Lattnerbf209482005-10-30 19:42:35 +00001498 unsigned a = 0;
1499 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1500 AI != E; ++AI, ++a)
1501 if (!AI->use_empty()) {
1502 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00001503
Chris Lattnerbf209482005-10-30 19:42:35 +00001504 // If this argument is live outside of the entry block, insert a copy from
1505 // whereever we got it to the vreg that other BB's will reference it as.
1506 if (FuncInfo.ValueMap.count(AI)) {
1507 SDOperand Copy =
1508 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1509 UnorderedChains.push_back(Copy);
1510 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00001511 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001512
1513 // Next, if the function has live ins that need to be copied into vregs,
1514 // emit the copies now, into the top of the block.
1515 MachineFunction &MF = SDL.DAG.getMachineFunction();
1516 if (MF.livein_begin() != MF.livein_end()) {
1517 SSARegMap *RegMap = MF.getSSARegMap();
1518 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1519 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1520 E = MF.livein_end(); LI != E; ++LI)
1521 if (LI->second)
1522 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1523 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00001524 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001525
1526 // Finally, if the target has anything special to do, allow it to do so.
1527 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00001528}
1529
1530
Chris Lattner1c08c712005-01-07 07:47:53 +00001531void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1532 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1533 FunctionLoweringInfo &FuncInfo) {
1534 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001535
1536 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001537
Chris Lattnerbf209482005-10-30 19:42:35 +00001538 // Lower any arguments needed in this block if this is the entry block.
1539 if (LLVMBB == &LLVMBB->getParent()->front())
1540 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001541
1542 BB = FuncInfo.MBBMap[LLVMBB];
1543 SDL.setCurrentBasicBlock(BB);
1544
1545 // Lower all of the non-terminator instructions.
1546 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1547 I != E; ++I)
1548 SDL.visit(*I);
1549
1550 // Ensure that all instructions which are used outside of their defining
1551 // blocks are available as virtual registers.
1552 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001553 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001554 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001555 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001556 UnorderedChains.push_back(
1557 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001558 }
1559
1560 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1561 // ensure constants are generated when needed. Remember the virtual registers
1562 // that need to be added to the Machine PHI nodes as input. We cannot just
1563 // directly add them, because expansion might result in multiple MBB's for one
1564 // BB. As such, the start of the BB might correspond to a different MBB than
1565 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001566 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001567
1568 // Emit constants only once even if used by multiple PHI nodes.
1569 std::map<Constant*, unsigned> ConstantsOut;
1570
1571 // Check successor nodes PHI nodes that expect a constant to be available from
1572 // this block.
1573 TerminatorInst *TI = LLVMBB->getTerminator();
1574 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1575 BasicBlock *SuccBB = TI->getSuccessor(succ);
1576 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1577 PHINode *PN;
1578
1579 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1580 // nodes and Machine PHI nodes, but the incoming operands have not been
1581 // emitted yet.
1582 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001583 (PN = dyn_cast<PHINode>(I)); ++I)
1584 if (!PN->use_empty()) {
1585 unsigned Reg;
1586 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1587 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1588 unsigned &RegOut = ConstantsOut[C];
1589 if (RegOut == 0) {
1590 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001591 UnorderedChains.push_back(
1592 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001593 }
1594 Reg = RegOut;
1595 } else {
1596 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001597 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001598 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001599 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1600 "Didn't codegen value into a register!??");
1601 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001602 UnorderedChains.push_back(
1603 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001604 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001605 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001606
Chris Lattnerf44fd882005-01-07 21:34:19 +00001607 // Remember that this register needs to added to the machine PHI node as
1608 // the input for this MBB.
1609 unsigned NumElements =
1610 TLI.getNumElements(TLI.getValueType(PN->getType()));
1611 for (unsigned i = 0, e = NumElements; i != e; ++i)
1612 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001613 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001614 }
1615 ConstantsOut.clear();
1616
Chris Lattnerddb870b2005-01-13 17:59:43 +00001617 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001618 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00001619 SDOperand Root = SDL.getRoot();
1620 if (Root.getOpcode() != ISD::EntryToken) {
1621 unsigned i = 0, e = UnorderedChains.size();
1622 for (; i != e; ++i) {
1623 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1624 if (UnorderedChains[i].Val->getOperand(0) == Root)
1625 break; // Don't add the root if we already indirectly depend on it.
1626 }
1627
1628 if (i == e)
1629 UnorderedChains.push_back(Root);
1630 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00001631 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1632 }
1633
Chris Lattner1c08c712005-01-07 07:47:53 +00001634 // Lower the terminator after the copies are emitted.
1635 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001636
1637 // Make sure the root of the DAG is up-to-date.
1638 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001639}
1640
1641void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1642 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001643 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001644 CurDAG = &DAG;
1645 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1646
1647 // First step, lower LLVM code to some DAG. This DAG may use operations and
1648 // types that are not supported by the target.
1649 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1650
Chris Lattneraf21d552005-10-10 16:47:10 +00001651 // Run the DAG combiner in pre-legalize mode.
1652 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00001653
Chris Lattner1c08c712005-01-07 07:47:53 +00001654 DEBUG(std::cerr << "Lowered selection DAG:\n");
1655 DEBUG(DAG.dump());
1656
1657 // Second step, hack on the DAG until it only uses operations and types that
1658 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001659 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001660
1661 DEBUG(std::cerr << "Legalized selection DAG:\n");
1662 DEBUG(DAG.dump());
1663
Chris Lattneraf21d552005-10-10 16:47:10 +00001664 // Run the DAG combiner in post-legalize mode.
1665 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00001666
Chris Lattnerd48050a2005-10-05 06:09:10 +00001667 if (ViewDAGs) DAG.viewGraph();
1668
Chris Lattnera33ef482005-03-30 01:10:47 +00001669 // Third, instruction select all of the operations to machine code, adding the
1670 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001671 InstructionSelectBasicBlock(DAG);
1672
Chris Lattner1c08c712005-01-07 07:47:53 +00001673 DEBUG(std::cerr << "Selected machine code:\n");
1674 DEBUG(BB->dump());
1675
Chris Lattnera33ef482005-03-30 01:10:47 +00001676 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001677 // PHI nodes in successors.
1678 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1679 MachineInstr *PHI = PHINodesToUpdate[i].first;
1680 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1681 "This is not a machine PHI node that we are updating!");
1682 PHI->addRegOperand(PHINodesToUpdate[i].second);
1683 PHI->addMachineBasicBlockOperand(BB);
1684 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001685
1686 // Finally, add the CFG edges from the last selected MBB to the successor
1687 // MBBs.
1688 TerminatorInst *TI = LLVMBB->getTerminator();
1689 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1690 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1691 BB->addSuccessor(Succ0MBB);
1692 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001693}