blob: f3e25467790c44fedbe190e871194d7e943b5c57 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-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 Lattner2e77db62005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000020#include "llvm/GlobalVariable.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/Instructions.h"
22#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000023#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000024#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-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 Lattnerd4382f02005-09-13 19:30:54 +000030#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-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 Lattnerc9950c12005-08-17 06:37:43 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000037#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000038#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000039#include "llvm/Support/Debug.h"
40#include <map>
41#include <iostream>
42using namespace llvm;
43
Chris Lattner975f5c92005-09-01 18:44:10 +000044#ifndef NDEBUG
Chris Lattnere05a4612005-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 Lattnerb6cde172005-09-02 07:09:28 +000049static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000050#endif
51
Chris Lattner7a60d912005-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 Lattnerd0061952005-01-08 19:52:31 +000056 class FunctionLoweringInfo {
57 public:
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +000081
Chris Lattner7a60d912005-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 Lattnera8d34fb2005-01-16 00:37:38 +000087 if (NV == 1) {
88 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000089 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000090 }
Misha Brukman835702a2005-04-21 22:36:52 +000091
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +000097
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000103
Chris Lattner7a60d912005-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 Lattner6871b232005-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 Lattner7a60d912005-01-07 07:47:53 +0000133FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000134 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000135 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
136
Chris Lattner6871b232005-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 Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000147 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-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 Begeman3ee3e692005-11-06 09:00:38 +0000153 unsigned Align =
154 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
155 AI->getAlignment());
Chris Lattnercbefe722005-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 Lattner8396a302005-10-18 22:11:42 +0000164 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000165 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000166 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000167 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000168 }
169
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000170 for (; BB != EB; ++BB)
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000180 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-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 Lattner8ea875f2005-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 Lattner7a60d912005-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 Lattner4d9651c2005-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 Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000233 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000234 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
235 FuncInfo(funcinfo) {
236 }
237
Chris Lattner4108bb02005-01-17 19:43:36 +0000238 /// getRoot - Return the current virtual root of the Selection DAG.
239 ///
240 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000241 if (PendingLoads.empty())
242 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000243
Chris Lattner4d9651c2005-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 Lattner4108bb02005-01-17 19:43:36 +0000256 }
257
Chris Lattner7a60d912005-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 Begeman41b1cdc2005-12-06 06:18:55 +0000282 const Type *VTy = V->getType();
283 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-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 Begemanaf1c0f72005-04-12 23:12:17 +0000294 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000295 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
296 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-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 Lattner803a5752005-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 Begeman41b1cdc2005-12-06 06:18:55 +0000322 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000323 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000324 else
Chris Lattner803a5752005-12-21 02:43:26 +0000325 Op = DAG.getConstant(0, PVT);
326 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000327 }
Chris Lattner803a5752005-12-21 02:43:26 +0000328
Nate Begeman41b1cdc2005-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 Begemanae89d862005-12-07 19:48:11 +0000331 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000332 return N = Ops[0];
Nate Begemanae89d862005-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 Lattner7a60d912005-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 Lattner209f5852005-01-16 02:23:07 +0000355
Chris Lattner33182322005-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 Lattner7a60d912005-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 Bocchino2c966e72006-01-10 19:04:57 +0000391 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000392 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-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 Begemanb2e089c2005-11-19 00:36:38 +0000398 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000399 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000400 void visitAdd(User &I) {
401 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000402 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000403 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000404 void visitMul(User &I) {
405 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000406 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000407 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000408 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000409 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000410 }
411 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000412 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000413 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000414 }
Nate Begemanb2e089c2005-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 Begeman127321b2005-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 Lattner7a60d912005-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 Lattnercd6f0f42005-11-09 19:44:01 +0000443 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000444
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000446 void visitVAArg(VAArgInst &I);
447 void visitVAEnd(CallInst &I);
448 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000449 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000450
Chris Lattner875def92005-01-11 05:56:49 +0000451 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-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 Lattner4108bb02005-01-17 19:43:36 +0000466 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000467 return;
468 }
469
470 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000471 MVT::ValueType TmpVT;
472
Chris Lattner7a60d912005-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 Lattnerdb45f7d2005-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 Lattner7a60d912005-01-07 07:47:53 +0000483 else
Chris Lattnerdb45f7d2005-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 Lattner7a60d912005-01-07 07:47:53 +0000491 break;
492 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 case MVT::i64:
494 case MVT::f64:
495 break; // No extension needed!
496 }
Nate Begeman78afac22005-10-18 23:23:37 +0000497 // Allow targets to lower this further to meet ABI requirements
498 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000499}
500
501void SelectionDAGLowering::visitBr(BranchInst &I) {
502 // Update machine-CFG edges.
503 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000504
505 // Figure out which block is immediately after the current one.
506 MachineBasicBlock *NextBlock = 0;
507 MachineFunction::iterator BBI = CurMBB;
508 if (++BBI != CurMBB->getParent()->end())
509 NextBlock = BBI;
510
511 if (I.isUnconditional()) {
512 // If this is not a fall-through branch, emit the branch.
513 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000514 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000515 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 } else {
517 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000518
519 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 if (Succ1MBB == NextBlock) {
521 // If the condition is false, fall through. This means we should branch
522 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000523 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000524 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000525 } else if (Succ0MBB == NextBlock) {
526 // If the condition is true, fall through. This means we should branch if
527 // the condition is false to Succ #1. Invert the condition first.
528 SDOperand True = DAG.getConstant(1, Cond.getValueType());
529 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000530 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000531 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000532 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000533 std::vector<SDOperand> Ops;
534 Ops.push_back(getRoot());
535 Ops.push_back(Cond);
536 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
537 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
538 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000539 }
540 }
541}
542
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000543void SelectionDAGLowering::visitSub(User &I) {
544 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000545 if (I.getType()->isFloatingPoint()) {
546 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
547 if (CFP->isExactlyValue(-0.0)) {
548 SDOperand Op2 = getValue(I.getOperand(1));
549 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
550 return;
551 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000552 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000553 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000554}
555
Nate Begemanb2e089c2005-11-19 00:36:38 +0000556void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
557 unsigned VecOp) {
558 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000559 SDOperand Op1 = getValue(I.getOperand(0));
560 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000561
Chris Lattner19baba62005-11-19 18:40:42 +0000562 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000563 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
564 } else if (Ty->isFloatingPoint()) {
565 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
566 } else {
567 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000568 unsigned NumElements = PTy->getNumElements();
569 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000570 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000571
572 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000573 // the Legalize pass does not have to deal with them. Similarly, if the
574 // abstract vector is going to turn into one that the target natively
575 // supports, generate that type now so that Legalize doesn't have to deal
576 // with that either. These steps ensure that Legalize only has to handle
577 // vector types in its Expand case.
578 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000579 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000580 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000581 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
582 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000583 } else {
584 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
585 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000586 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000587 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000588 }
Nate Begeman127321b2005-11-18 07:42:56 +0000589}
Chris Lattner96c26752005-01-19 22:31:21 +0000590
Nate Begeman127321b2005-11-18 07:42:56 +0000591void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
592 SDOperand Op1 = getValue(I.getOperand(0));
593 SDOperand Op2 = getValue(I.getOperand(1));
594
595 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
596
Chris Lattner7a60d912005-01-07 07:47:53 +0000597 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
598}
599
600void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
601 ISD::CondCode UnsignedOpcode) {
602 SDOperand Op1 = getValue(I.getOperand(0));
603 SDOperand Op2 = getValue(I.getOperand(1));
604 ISD::CondCode Opcode = SignedOpcode;
605 if (I.getOperand(0)->getType()->isUnsigned())
606 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000607 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000608}
609
610void SelectionDAGLowering::visitSelect(User &I) {
611 SDOperand Cond = getValue(I.getOperand(0));
612 SDOperand TrueVal = getValue(I.getOperand(1));
613 SDOperand FalseVal = getValue(I.getOperand(2));
614 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
615 TrueVal, FalseVal));
616}
617
618void SelectionDAGLowering::visitCast(User &I) {
619 SDOperand N = getValue(I.getOperand(0));
620 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
621 MVT::ValueType DestTy = TLI.getValueType(I.getType());
622
623 if (N.getValueType() == DestTy) {
624 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000625 } else if (DestTy == MVT::i1) {
626 // Cast to bool is a comparison against zero, not truncation to zero.
627 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
628 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000629 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000630 } else if (isInteger(SrcTy)) {
631 if (isInteger(DestTy)) { // Int -> Int cast
632 if (DestTy < SrcTy) // Truncating cast?
633 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
634 else if (I.getOperand(0)->getType()->isSigned())
635 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
636 else
637 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
638 } else { // Int -> FP cast
639 if (I.getOperand(0)->getType()->isSigned())
640 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
641 else
642 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
643 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000644 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000645 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
646 if (isFloatingPoint(DestTy)) { // FP -> FP cast
647 if (DestTy < SrcTy) // Rounding cast?
648 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
649 else
650 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
651 } else { // FP -> Int cast.
652 if (I.getType()->isSigned())
653 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
654 else
655 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
656 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000657 }
658}
659
660void SelectionDAGLowering::visitGetElementPtr(User &I) {
661 SDOperand N = getValue(I.getOperand(0));
662 const Type *Ty = I.getOperand(0)->getType();
663 const Type *UIntPtrTy = TD.getIntPtrType();
664
665 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
666 OI != E; ++OI) {
667 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000668 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000669 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
670 if (Field) {
671 // N = N + Offset
672 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
673 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000674 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000675 }
676 Ty = StTy->getElementType(Field);
677 } else {
678 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000679
Chris Lattner43535a12005-11-09 04:45:33 +0000680 // If this is a constant subscript, handle it quickly.
681 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
682 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000683
Chris Lattner43535a12005-11-09 04:45:33 +0000684 uint64_t Offs;
685 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
686 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
687 else
688 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
689 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
690 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000691 }
Chris Lattner43535a12005-11-09 04:45:33 +0000692
693 // N = N + Idx * ElementSize;
694 uint64_t ElementSize = TD.getTypeSize(Ty);
695 SDOperand IdxN = getValue(Idx);
696
697 // If the index is smaller or larger than intptr_t, truncate or extend
698 // it.
699 if (IdxN.getValueType() < N.getValueType()) {
700 if (Idx->getType()->isSigned())
701 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
702 else
703 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
704 } else if (IdxN.getValueType() > N.getValueType())
705 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
706
707 // If this is a multiply by a power of two, turn it into a shl
708 // immediately. This is a very common case.
709 if (isPowerOf2_64(ElementSize)) {
710 unsigned Amt = Log2_64(ElementSize);
711 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000712 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000713 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
714 continue;
715 }
716
717 SDOperand Scale = getIntPtrConstant(ElementSize);
718 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
719 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000720 }
721 }
722 setValue(&I, N);
723}
724
725void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
726 // If this is a fixed sized alloca in the entry block of the function,
727 // allocate it statically on the stack.
728 if (FuncInfo.StaticAllocaMap.count(&I))
729 return; // getValue will auto-populate this.
730
731 const Type *Ty = I.getAllocatedType();
732 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000733 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
734 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000735
736 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000737 MVT::ValueType IntPtr = TLI.getPointerTy();
738 if (IntPtr < AllocSize.getValueType())
739 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
740 else if (IntPtr > AllocSize.getValueType())
741 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000742
Chris Lattnereccb73d2005-01-22 23:04:37 +0000743 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000744 getIntPtrConstant(TySize));
745
746 // Handle alignment. If the requested alignment is less than or equal to the
747 // stack alignment, ignore it and round the size of the allocation up to the
748 // stack alignment size. If the size is greater than the stack alignment, we
749 // note this in the DYNAMIC_STACKALLOC node.
750 unsigned StackAlign =
751 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
752 if (Align <= StackAlign) {
753 Align = 0;
754 // Add SA-1 to the size.
755 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
756 getIntPtrConstant(StackAlign-1));
757 // Mask out the low bits for alignment purposes.
758 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
759 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
760 }
761
Chris Lattner96c262e2005-05-14 07:29:57 +0000762 std::vector<MVT::ValueType> VTs;
763 VTs.push_back(AllocSize.getValueType());
764 VTs.push_back(MVT::Other);
765 std::vector<SDOperand> Ops;
766 Ops.push_back(getRoot());
767 Ops.push_back(AllocSize);
768 Ops.push_back(getIntPtrConstant(Align));
769 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000770 DAG.setRoot(setValue(&I, DSA).getValue(1));
771
772 // Inform the Frame Information that we have just allocated a variable-sized
773 // object.
774 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
775}
776
Chris Lattner435b4022005-11-29 06:21:05 +0000777/// getStringValue - Turn an LLVM constant pointer that eventually points to a
778/// global into a string value. Return an empty string if we can't do it.
779///
780static std::string getStringValue(Value *V, unsigned Offset = 0) {
781 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
782 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
783 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
784 if (Init->isString()) {
785 std::string Result = Init->getAsString();
786 if (Offset < Result.size()) {
787 // If we are pointing INTO The string, erase the beginning...
788 Result.erase(Result.begin(), Result.begin()+Offset);
789
790 // Take off the null terminator, and any string fragments after it.
791 std::string::size_type NullPos = Result.find_first_of((char)0);
792 if (NullPos != std::string::npos)
793 Result.erase(Result.begin()+NullPos, Result.end());
794 return Result;
795 }
796 }
797 }
798 } else if (Constant *C = dyn_cast<Constant>(V)) {
799 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
800 return getStringValue(GV, Offset);
801 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
802 if (CE->getOpcode() == Instruction::GetElementPtr) {
803 // Turn a gep into the specified offset.
804 if (CE->getNumOperands() == 3 &&
805 cast<Constant>(CE->getOperand(1))->isNullValue() &&
806 isa<ConstantInt>(CE->getOperand(2))) {
807 return getStringValue(CE->getOperand(0),
808 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
809 }
810 }
811 }
812 }
813 return "";
814}
Chris Lattner7a60d912005-01-07 07:47:53 +0000815
816void SelectionDAGLowering::visitLoad(LoadInst &I) {
817 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000818
Chris Lattner4d9651c2005-01-17 22:19:26 +0000819 SDOperand Root;
820 if (I.isVolatile())
821 Root = getRoot();
822 else {
823 // Do not serialize non-volatile loads against each other.
824 Root = DAG.getRoot();
825 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000826
827 const Type *Ty = I.getType();
828 SDOperand L;
829
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000830 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000831 unsigned NumElements = PTy->getNumElements();
832 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000833 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000834
835 // Immediately scalarize packed types containing only one element, so that
836 // the Legalize pass does not have to deal with them.
837 if (NumElements == 1) {
838 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000839 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
840 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000841 } else {
842 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
843 DAG.getSrcValue(I.getOperand(0)));
844 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000845 } else {
846 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
847 DAG.getSrcValue(I.getOperand(0)));
848 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000849 setValue(&I, L);
850
851 if (I.isVolatile())
852 DAG.setRoot(L.getValue(1));
853 else
854 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000855}
856
857
858void SelectionDAGLowering::visitStore(StoreInst &I) {
859 Value *SrcV = I.getOperand(0);
860 SDOperand Src = getValue(SrcV);
861 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000862 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000863 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000864}
865
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000866/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
867/// we want to emit this as a call to a named external function, return the name
868/// otherwise lower it and return null.
869const char *
870SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
871 switch (Intrinsic) {
872 case Intrinsic::vastart: visitVAStart(I); return 0;
873 case Intrinsic::vaend: visitVAEnd(I); return 0;
874 case Intrinsic::vacopy: visitVACopy(I); return 0;
875 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
876 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
877 case Intrinsic::setjmp:
878 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
879 break;
880 case Intrinsic::longjmp:
881 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
882 break;
883 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
884 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
885 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
886
887 case Intrinsic::readport:
888 case Intrinsic::readio: {
889 std::vector<MVT::ValueType> VTs;
890 VTs.push_back(TLI.getValueType(I.getType()));
891 VTs.push_back(MVT::Other);
892 std::vector<SDOperand> Ops;
893 Ops.push_back(getRoot());
894 Ops.push_back(getValue(I.getOperand(1)));
895 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
896 ISD::READPORT : ISD::READIO, VTs, Ops);
897
898 setValue(&I, Tmp);
899 DAG.setRoot(Tmp.getValue(1));
900 return 0;
901 }
902 case Intrinsic::writeport:
903 case Intrinsic::writeio:
904 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
905 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
906 getRoot(), getValue(I.getOperand(1)),
907 getValue(I.getOperand(2))));
908 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000909
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000910 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000911 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
912 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000913
914 std::string fname = "<unknown>";
915 std::vector<SDOperand> Ops;
916
Chris Lattner435b4022005-11-29 06:21:05 +0000917 // Input Chain
918 Ops.push_back(getRoot());
919
920 // line number
921 Ops.push_back(getValue(I.getOperand(2)));
922
923 // column
924 Ops.push_back(getValue(I.getOperand(3)));
925
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000926 // filename/working dir
927 // Pull the filename out of the the compilation unit.
928 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
929 if (cunit && cunit->hasInitializer()) {
930 if (ConstantStruct *CS =
931 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
932 if (CS->getNumOperands() > 0) {
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000933 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskey7c462762005-12-16 22:45:29 +0000934 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000935 }
936 }
937 }
938
939 if (Ops.size() == 5) // Found filename/workingdir.
940 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner8782b782005-12-03 18:50:48 +0000941 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000942 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000943 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000944 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000945 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
946 return "llvm_dbg_region_start";
947 if (I.getType() != Type::VoidTy)
948 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
949 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000950 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000951 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
952 return "llvm_dbg_region_end";
953 if (I.getType() != Type::VoidTy)
954 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
955 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000956 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000957 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
958 return "llvm_dbg_subprogram";
959 if (I.getType() != Type::VoidTy)
960 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
961 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000962 case Intrinsic::dbg_declare:
963 if (I.getType() != Type::VoidTy)
964 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
965 return 0;
966
Reid Spencerb4f9a6f2006-01-16 21:12:35 +0000967 case Intrinsic::isunordered_f32:
968 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000969 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
970 getValue(I.getOperand(2)), ISD::SETUO));
971 return 0;
972
Reid Spencerb4f9a6f2006-01-16 21:12:35 +0000973 case Intrinsic::sqrt_f32:
974 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000975 setValue(&I, DAG.getNode(ISD::FSQRT,
976 getValue(I.getOperand(1)).getValueType(),
977 getValue(I.getOperand(1))));
978 return 0;
979 case Intrinsic::pcmarker: {
980 SDOperand Tmp = getValue(I.getOperand(1));
981 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
982 return 0;
983 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000984 case Intrinsic::readcyclecounter: {
985 std::vector<MVT::ValueType> VTs;
986 VTs.push_back(MVT::i64);
987 VTs.push_back(MVT::Other);
988 std::vector<SDOperand> Ops;
989 Ops.push_back(getRoot());
990 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
991 setValue(&I, Tmp);
992 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000993 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000994 }
Nate Begeman2fba8a32006-01-14 03:14:10 +0000995 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +0000996 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +0000997 case Intrinsic::bswap_i64:
998 setValue(&I, DAG.getNode(ISD::BSWAP,
999 getValue(I.getOperand(1)).getValueType(),
1000 getValue(I.getOperand(1))));
1001 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001002 case Intrinsic::cttz_i8:
1003 case Intrinsic::cttz_i16:
1004 case Intrinsic::cttz_i32:
1005 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001006 setValue(&I, DAG.getNode(ISD::CTTZ,
1007 getValue(I.getOperand(1)).getValueType(),
1008 getValue(I.getOperand(1))));
1009 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001010 case Intrinsic::ctlz_i8:
1011 case Intrinsic::ctlz_i16:
1012 case Intrinsic::ctlz_i32:
1013 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001014 setValue(&I, DAG.getNode(ISD::CTLZ,
1015 getValue(I.getOperand(1)).getValueType(),
1016 getValue(I.getOperand(1))));
1017 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001018 case Intrinsic::ctpop_i8:
1019 case Intrinsic::ctpop_i16:
1020 case Intrinsic::ctpop_i32:
1021 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001022 setValue(&I, DAG.getNode(ISD::CTPOP,
1023 getValue(I.getOperand(1)).getValueType(),
1024 getValue(I.getOperand(1))));
1025 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001026 case Intrinsic::stacksave: {
1027 std::vector<MVT::ValueType> VTs;
1028 VTs.push_back(TLI.getPointerTy());
1029 VTs.push_back(MVT::Other);
1030 std::vector<SDOperand> Ops;
1031 Ops.push_back(getRoot());
1032 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1033 setValue(&I, Tmp);
1034 DAG.setRoot(Tmp.getValue(1));
1035 return 0;
1036 }
Chris Lattner6c9c2502006-01-13 02:24:42 +00001037 case Intrinsic::stackrestore:
Chris Lattnerb3266452006-01-13 02:50:02 +00001038 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1039 getValue(I.getOperand(1))));
1040 return 0;
Chris Lattner9e8b6332005-12-12 22:51:16 +00001041 case Intrinsic::prefetch:
1042 // FIXME: Currently discarding prefetches.
1043 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001044 default:
1045 std::cerr << I;
1046 assert(0 && "This intrinsic is not implemented yet!");
1047 return 0;
1048 }
1049}
1050
1051
Chris Lattner7a60d912005-01-07 07:47:53 +00001052void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001053 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001054 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001055 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001056 if (unsigned IID = F->getIntrinsicID()) {
1057 RenameFn = visitIntrinsicCall(I, IID);
1058 if (!RenameFn)
1059 return;
1060 } else { // Not an LLVM intrinsic.
1061 const std::string &Name = F->getName();
1062 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001063 if (I.getNumOperands() == 2 && // Basic sanity checks.
1064 I.getOperand(1)->getType()->isFloatingPoint() &&
1065 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001066 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001067 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1068 return;
1069 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001070 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001071 if (I.getNumOperands() == 2 && // Basic sanity checks.
1072 I.getOperand(1)->getType()->isFloatingPoint() &&
1073 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001074 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001075 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1076 return;
1077 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001078 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001079 if (I.getNumOperands() == 2 && // Basic sanity checks.
1080 I.getOperand(1)->getType()->isFloatingPoint() &&
1081 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001082 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001083 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1084 return;
1085 }
1086 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001087 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001088 }
Misha Brukman835702a2005-04-21 22:36:52 +00001089
Chris Lattner18d2b342005-01-08 22:48:57 +00001090 SDOperand Callee;
1091 if (!RenameFn)
1092 Callee = getValue(I.getOperand(0));
1093 else
1094 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001095 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001096 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001097 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1098 Value *Arg = I.getOperand(i);
1099 SDOperand ArgNode = getValue(Arg);
1100 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1101 }
Misha Brukman835702a2005-04-21 22:36:52 +00001102
Nate Begemanf6565252005-03-26 01:29:23 +00001103 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1104 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001105
Chris Lattner1f45cd72005-01-08 19:26:18 +00001106 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001107 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001108 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001109 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001110 setValue(&I, Result.first);
1111 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001112}
1113
1114void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1115 SDOperand Src = getValue(I.getOperand(0));
1116
1117 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001118
1119 if (IntPtr < Src.getValueType())
1120 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1121 else if (IntPtr > Src.getValueType())
1122 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001123
1124 // Scale the source by the type size.
1125 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1126 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1127 Src, getIntPtrConstant(ElementSize));
1128
1129 std::vector<std::pair<SDOperand, const Type*> > Args;
1130 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001131
1132 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001133 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001134 DAG.getExternalSymbol("malloc", IntPtr),
1135 Args, DAG);
1136 setValue(&I, Result.first); // Pointers always fit in registers
1137 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001138}
1139
1140void SelectionDAGLowering::visitFree(FreeInst &I) {
1141 std::vector<std::pair<SDOperand, const Type*> > Args;
1142 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1143 TLI.getTargetData().getIntPtrType()));
1144 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001145 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001146 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001147 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1148 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001149}
1150
Chris Lattner13d7c252005-08-26 20:54:47 +00001151// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1152// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1153// instructions are special in various ways, which require special support to
1154// insert. The specified MachineInstr is created but not inserted into any
1155// basic blocks, and the scheduler passes ownership of it to this method.
1156MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1157 MachineBasicBlock *MBB) {
1158 std::cerr << "If a target marks an instruction with "
1159 "'usesCustomDAGSchedInserter', it must implement "
1160 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1161 abort();
1162 return 0;
1163}
1164
Nate Begeman78afac22005-10-18 23:23:37 +00001165SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1166 SelectionDAG &DAG) {
1167 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1168}
1169
Chris Lattnerf5473e42005-07-05 19:57:53 +00001170SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1171 SDOperand VAListP, Value *VAListV,
1172 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001173 // We have no sane default behavior, just emit a useful error message and bail
1174 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001175 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001176 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001177 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001178}
1179
Chris Lattnerf5473e42005-07-05 19:57:53 +00001180SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001181 SelectionDAG &DAG) {
1182 // Default to a noop.
1183 return Chain;
1184}
1185
Chris Lattnerf5473e42005-07-05 19:57:53 +00001186SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1187 SDOperand SrcP, Value *SrcV,
1188 SDOperand DestP, Value *DestV,
1189 SelectionDAG &DAG) {
1190 // Default to copying the input list.
1191 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1192 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001193 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001194 Val, DestP, DAG.getSrcValue(DestV));
1195 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001196}
1197
1198std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001199TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1200 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001201 // We have no sane default behavior, just emit a useful error message and bail
1202 // out.
1203 std::cerr << "Variable arguments handling not implemented on this target!\n";
1204 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001205 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001206}
1207
1208
1209void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001210 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1211 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001212}
1213
1214void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1215 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001216 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001217 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001218 setValue(&I, Result.first);
1219 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001220}
1221
1222void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001223 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001224 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001225}
1226
1227void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001228 SDOperand Result =
1229 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1230 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1231 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001232}
1233
Chris Lattner58cfd792005-01-09 00:00:49 +00001234
1235// It is always conservatively correct for llvm.returnaddress and
1236// llvm.frameaddress to return 0.
1237std::pair<SDOperand, SDOperand>
1238TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1239 unsigned Depth, SelectionDAG &DAG) {
1240 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001241}
1242
Chris Lattner29dcc712005-05-14 05:50:48 +00001243SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001244 assert(0 && "LowerOperation not implemented for this target!");
1245 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001246 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001247}
1248
Chris Lattner58cfd792005-01-09 00:00:49 +00001249void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1250 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1251 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001252 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001253 setValue(&I, Result.first);
1254 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001255}
1256
Chris Lattner875def92005-01-11 05:56:49 +00001257void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer3fd1b4c2005-11-30 05:21:10 +00001258#if 0
1259 // If the size of the cpy/move/set is constant (known)
1260 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1261 uint64_t size = op3->getValue();
1262 switch (Op) {
1263 case ISD::MEMSET:
1264 if (size <= TLI.getMaxStoresPerMemSet()) {
1265 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1266 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1267 uint64_t align = op4.getValue();
1268 while (size > align) {
1269 size -=align;
1270 }
1271 Value *SrcV = I.getOperand(0);
1272 SDOperand Src = getValue(SrcV);
1273 SDOperand Ptr = getValue(I.getOperand(1));
1274 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1275 DAG.getSrcValue(I.getOperand(1))));
1276 }
1277 break;
1278 }
1279 break; // don't do this optimization, use a normal memset
1280 case ISD::MEMMOVE:
1281 case ISD::MEMCPY:
1282 break; // FIXME: not implemented yet
1283 }
1284 }
1285#endif
1286
1287 // Non-optimized version
Chris Lattner875def92005-01-11 05:56:49 +00001288 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001289 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001290 Ops.push_back(getValue(I.getOperand(1)));
1291 Ops.push_back(getValue(I.getOperand(2)));
1292 Ops.push_back(getValue(I.getOperand(3)));
1293 Ops.push_back(getValue(I.getOperand(4)));
1294 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001295}
1296
Chris Lattner875def92005-01-11 05:56:49 +00001297//===----------------------------------------------------------------------===//
1298// SelectionDAGISel code
1299//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001300
1301unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1302 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1303}
1304
Chris Lattnerc9950c12005-08-17 06:37:43 +00001305void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001306 // FIXME: we only modify the CFG to split critical edges. This
1307 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001308}
Chris Lattner7a60d912005-01-07 07:47:53 +00001309
Chris Lattner35397782005-12-05 07:10:48 +00001310
1311/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1312/// casting to the type of GEPI.
1313static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1314 Value *Ptr, Value *PtrOffset) {
1315 if (V) return V; // Already computed.
1316
1317 BasicBlock::iterator InsertPt;
1318 if (BB == GEPI->getParent()) {
1319 // If insert into the GEP's block, insert right after the GEP.
1320 InsertPt = GEPI;
1321 ++InsertPt;
1322 } else {
1323 // Otherwise, insert at the top of BB, after any PHI nodes
1324 InsertPt = BB->begin();
1325 while (isa<PHINode>(InsertPt)) ++InsertPt;
1326 }
1327
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001328 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1329 // BB so that there is only one value live across basic blocks (the cast
1330 // operand).
1331 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1332 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1333 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1334
Chris Lattner35397782005-12-05 07:10:48 +00001335 // Add the offset, cast it to the right type.
1336 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1337 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1338 return V = Ptr;
1339}
1340
1341
1342/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1343/// selection, we want to be a bit careful about some things. In particular, if
1344/// we have a GEP instruction that is used in a different block than it is
1345/// defined, the addressing expression of the GEP cannot be folded into loads or
1346/// stores that use it. In this case, decompose the GEP and move constant
1347/// indices into blocks that use it.
1348static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1349 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00001350 // If this GEP is only used inside the block it is defined in, there is no
1351 // need to rewrite it.
1352 bool isUsedOutsideDefBB = false;
1353 BasicBlock *DefBB = GEPI->getParent();
1354 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1355 UI != E; ++UI) {
1356 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1357 isUsedOutsideDefBB = true;
1358 break;
1359 }
1360 }
1361 if (!isUsedOutsideDefBB) return;
1362
1363 // If this GEP has no non-zero constant indices, there is nothing we can do,
1364 // ignore it.
1365 bool hasConstantIndex = false;
1366 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1367 E = GEPI->op_end(); OI != E; ++OI) {
1368 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1369 if (CI->getRawValue()) {
1370 hasConstantIndex = true;
1371 break;
1372 }
1373 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00001374 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1375 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00001376
1377 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1378 // constant offset (which we now know is non-zero) and deal with it later.
1379 uint64_t ConstantOffset = 0;
1380 const Type *UIntPtrTy = TD.getIntPtrType();
1381 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1382 const Type *Ty = GEPI->getOperand(0)->getType();
1383
1384 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1385 E = GEPI->op_end(); OI != E; ++OI) {
1386 Value *Idx = *OI;
1387 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1388 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1389 if (Field)
1390 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1391 Ty = StTy->getElementType(Field);
1392 } else {
1393 Ty = cast<SequentialType>(Ty)->getElementType();
1394
1395 // Handle constant subscripts.
1396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1397 if (CI->getRawValue() == 0) continue;
1398
1399 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1400 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1401 else
1402 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1403 continue;
1404 }
1405
1406 // Ptr = Ptr + Idx * ElementSize;
1407
1408 // Cast Idx to UIntPtrTy if needed.
1409 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1410
1411 uint64_t ElementSize = TD.getTypeSize(Ty);
1412 // Mask off bits that should not be set.
1413 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1414 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1415
1416 // Multiply by the element size and add to the base.
1417 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1418 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1419 }
1420 }
1421
1422 // Make sure that the offset fits in uintptr_t.
1423 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1424 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1425
1426 // Okay, we have now emitted all of the variable index parts to the BB that
1427 // the GEP is defined in. Loop over all of the using instructions, inserting
1428 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001429 // instruction to use the newly computed value, making GEPI dead. When the
1430 // user is a load or store instruction address, we emit the add into the user
1431 // block, otherwise we use a canonical version right next to the gep (these
1432 // won't be foldable as addresses, so we might as well share the computation).
1433
Chris Lattner35397782005-12-05 07:10:48 +00001434 std::map<BasicBlock*,Value*> InsertedExprs;
1435 while (!GEPI->use_empty()) {
1436 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001437
1438 // If this use is not foldable into the addressing mode, use a version
1439 // emitted in the GEP block.
1440 Value *NewVal;
1441 if (!isa<LoadInst>(User) &&
1442 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1443 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1444 Ptr, PtrOffset);
1445 } else {
1446 // Otherwise, insert the code in the User's block so it can be folded into
1447 // any users in that block.
1448 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00001449 User->getParent(), GEPI,
1450 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00001451 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001452 User->replaceUsesOfWith(GEPI, NewVal);
1453 }
Chris Lattner35397782005-12-05 07:10:48 +00001454
1455 // Finally, the GEP is dead, remove it.
1456 GEPI->eraseFromParent();
1457}
1458
Chris Lattner7a60d912005-01-07 07:47:53 +00001459bool SelectionDAGISel::runOnFunction(Function &Fn) {
1460 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1461 RegMap = MF.getSSARegMap();
1462 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1463
Chris Lattner35397782005-12-05 07:10:48 +00001464 // First, split all critical edges for PHI nodes with incoming values that are
1465 // constants, this way the load of the constant into a vreg will not be placed
1466 // into MBBs that are used some other way.
1467 //
1468 // In this pass we also look for GEP instructions that are used across basic
1469 // blocks and rewrites them to improve basic-block-at-a-time selection.
1470 //
Chris Lattner1a908c82005-08-18 17:35:14 +00001471 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1472 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00001473 BasicBlock::iterator BBI;
1474 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00001475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1476 if (isa<Constant>(PN->getIncomingValue(i)))
1477 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00001478
1479 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1480 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1481 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00001482 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001483
Chris Lattner7a60d912005-01-07 07:47:53 +00001484 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1485
1486 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1487 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001488
Chris Lattner7a60d912005-01-07 07:47:53 +00001489 return true;
1490}
1491
1492
Chris Lattner718b5c22005-01-13 17:59:43 +00001493SDOperand SelectionDAGISel::
1494CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001495 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001496 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001497 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001498 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001499
1500 // If this type is not legal, we must make sure to not create an invalid
1501 // register use.
1502 MVT::ValueType SrcVT = Op.getValueType();
1503 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1504 SelectionDAG &DAG = SDL.DAG;
1505 if (SrcVT == DestVT) {
1506 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1507 } else if (SrcVT < DestVT) {
1508 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001509 if (MVT::isFloatingPoint(SrcVT))
1510 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1511 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001512 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001513 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1514 } else {
1515 // The src value is expanded into multiple registers.
1516 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1517 Op, DAG.getConstant(0, MVT::i32));
1518 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1519 Op, DAG.getConstant(1, MVT::i32));
1520 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1521 return DAG.getCopyToReg(Op, Reg+1, Hi);
1522 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001523}
1524
Chris Lattner16f64df2005-01-17 17:15:02 +00001525void SelectionDAGISel::
1526LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1527 std::vector<SDOperand> &UnorderedChains) {
1528 // If this is the entry block, emit arguments.
1529 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001530 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001531 SDOperand OldRoot = SDL.DAG.getRoot();
1532 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001533
Chris Lattner6871b232005-10-30 19:42:35 +00001534 unsigned a = 0;
1535 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1536 AI != E; ++AI, ++a)
1537 if (!AI->use_empty()) {
1538 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001539
Chris Lattner6871b232005-10-30 19:42:35 +00001540 // If this argument is live outside of the entry block, insert a copy from
1541 // whereever we got it to the vreg that other BB's will reference it as.
1542 if (FuncInfo.ValueMap.count(AI)) {
1543 SDOperand Copy =
1544 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1545 UnorderedChains.push_back(Copy);
1546 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001547 }
Chris Lattner6871b232005-10-30 19:42:35 +00001548
1549 // Next, if the function has live ins that need to be copied into vregs,
1550 // emit the copies now, into the top of the block.
1551 MachineFunction &MF = SDL.DAG.getMachineFunction();
1552 if (MF.livein_begin() != MF.livein_end()) {
1553 SSARegMap *RegMap = MF.getSSARegMap();
1554 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1555 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1556 E = MF.livein_end(); LI != E; ++LI)
1557 if (LI->second)
1558 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1559 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001560 }
Chris Lattner6871b232005-10-30 19:42:35 +00001561
1562 // Finally, if the target has anything special to do, allow it to do so.
1563 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001564}
1565
1566
Chris Lattner7a60d912005-01-07 07:47:53 +00001567void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1568 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1569 FunctionLoweringInfo &FuncInfo) {
1570 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001571
1572 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001573
Chris Lattner6871b232005-10-30 19:42:35 +00001574 // Lower any arguments needed in this block if this is the entry block.
1575 if (LLVMBB == &LLVMBB->getParent()->front())
1576 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001577
1578 BB = FuncInfo.MBBMap[LLVMBB];
1579 SDL.setCurrentBasicBlock(BB);
1580
1581 // Lower all of the non-terminator instructions.
1582 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1583 I != E; ++I)
1584 SDL.visit(*I);
1585
1586 // Ensure that all instructions which are used outside of their defining
1587 // blocks are available as virtual registers.
1588 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001589 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001590 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001591 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001592 UnorderedChains.push_back(
1593 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001594 }
1595
1596 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1597 // ensure constants are generated when needed. Remember the virtual registers
1598 // that need to be added to the Machine PHI nodes as input. We cannot just
1599 // directly add them, because expansion might result in multiple MBB's for one
1600 // BB. As such, the start of the BB might correspond to a different MBB than
1601 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001602 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001603
1604 // Emit constants only once even if used by multiple PHI nodes.
1605 std::map<Constant*, unsigned> ConstantsOut;
1606
1607 // Check successor nodes PHI nodes that expect a constant to be available from
1608 // this block.
1609 TerminatorInst *TI = LLVMBB->getTerminator();
1610 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1611 BasicBlock *SuccBB = TI->getSuccessor(succ);
1612 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1613 PHINode *PN;
1614
1615 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1616 // nodes and Machine PHI nodes, but the incoming operands have not been
1617 // emitted yet.
1618 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001619 (PN = dyn_cast<PHINode>(I)); ++I)
1620 if (!PN->use_empty()) {
1621 unsigned Reg;
1622 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1623 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1624 unsigned &RegOut = ConstantsOut[C];
1625 if (RegOut == 0) {
1626 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001627 UnorderedChains.push_back(
1628 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001629 }
1630 Reg = RegOut;
1631 } else {
1632 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001633 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001634 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001635 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1636 "Didn't codegen value into a register!??");
1637 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001638 UnorderedChains.push_back(
1639 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001640 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001641 }
Misha Brukman835702a2005-04-21 22:36:52 +00001642
Chris Lattner8ea875f2005-01-07 21:34:19 +00001643 // Remember that this register needs to added to the machine PHI node as
1644 // the input for this MBB.
1645 unsigned NumElements =
1646 TLI.getNumElements(TLI.getValueType(PN->getType()));
1647 for (unsigned i = 0, e = NumElements; i != e; ++i)
1648 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001649 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001650 }
1651 ConstantsOut.clear();
1652
Chris Lattner718b5c22005-01-13 17:59:43 +00001653 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001654 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001655 SDOperand Root = SDL.getRoot();
1656 if (Root.getOpcode() != ISD::EntryToken) {
1657 unsigned i = 0, e = UnorderedChains.size();
1658 for (; i != e; ++i) {
1659 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1660 if (UnorderedChains[i].Val->getOperand(0) == Root)
1661 break; // Don't add the root if we already indirectly depend on it.
1662 }
1663
1664 if (i == e)
1665 UnorderedChains.push_back(Root);
1666 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001667 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1668 }
1669
Chris Lattner7a60d912005-01-07 07:47:53 +00001670 // Lower the terminator after the copies are emitted.
1671 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001672
1673 // Make sure the root of the DAG is up-to-date.
1674 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001675}
1676
1677void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1678 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00001679 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00001680 CurDAG = &DAG;
1681 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1682
1683 // First step, lower LLVM code to some DAG. This DAG may use operations and
1684 // types that are not supported by the target.
1685 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1686
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001687 // Run the DAG combiner in pre-legalize mode.
1688 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001689
Chris Lattner7a60d912005-01-07 07:47:53 +00001690 DEBUG(std::cerr << "Lowered selection DAG:\n");
1691 DEBUG(DAG.dump());
1692
1693 // Second step, hack on the DAG until it only uses operations and types that
1694 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001695 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001696
1697 DEBUG(std::cerr << "Legalized selection DAG:\n");
1698 DEBUG(DAG.dump());
1699
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001700 // Run the DAG combiner in post-legalize mode.
1701 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001702
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001703 if (ViewDAGs) DAG.viewGraph();
1704
Chris Lattner5ca31d92005-03-30 01:10:47 +00001705 // Third, instruction select all of the operations to machine code, adding the
1706 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001707 InstructionSelectBasicBlock(DAG);
1708
Chris Lattner7a60d912005-01-07 07:47:53 +00001709 DEBUG(std::cerr << "Selected machine code:\n");
1710 DEBUG(BB->dump());
1711
Chris Lattner5ca31d92005-03-30 01:10:47 +00001712 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001713 // PHI nodes in successors.
1714 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1715 MachineInstr *PHI = PHINodesToUpdate[i].first;
1716 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1717 "This is not a machine PHI node that we are updating!");
1718 PHI->addRegOperand(PHINodesToUpdate[i].second);
1719 PHI->addMachineBasicBlockOperand(BB);
1720 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001721
1722 // Finally, add the CFG edges from the last selected MBB to the successor
1723 // MBBs.
1724 TerminatorInst *TI = LLVMBB->getTerminator();
1725 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1726 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1727 BB->addSuccessor(Succ0MBB);
1728 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001729}