blob: d75e5013d55ddd460f6c2ca30a4b368d6d4199fe [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"
Chris Lattner7a60d912005-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 Lattnerd4382f02005-09-13 19:30:54 +000029#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-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 Lattnerc9950c12005-08-17 06:37:43 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000036#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000037#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Support/Debug.h"
39#include <map>
40#include <iostream>
41using namespace llvm;
42
Chris Lattner35397782005-12-05 07:10:48 +000043static cl::opt<bool>
44GEPISelTest("enable-gep-isel-opt", cl::Hidden,
45 cl::desc("temporary for testing"));
46
Chris Lattner975f5c92005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000048static cl::opt<bool>
49ViewDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000052static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000053#endif
54
Chris Lattner7a60d912005-01-07 07:47:53 +000055namespace llvm {
56 //===--------------------------------------------------------------------===//
57 /// FunctionLoweringInfo - This contains information that is global to a
58 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000059 class FunctionLoweringInfo {
60 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000061 TargetLowering &TLI;
62 Function &Fn;
63 MachineFunction &MF;
64 SSARegMap *RegMap;
65
66 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
67
68 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
69 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
70
71 /// ValueMap - Since we emit code for the function a basic block at a time,
72 /// we must remember which virtual registers hold the values for
73 /// cross-basic-block values.
74 std::map<const Value*, unsigned> ValueMap;
75
76 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
77 /// the entry block. This allows the allocas to be efficiently referenced
78 /// anywhere in the function.
79 std::map<const AllocaInst*, int> StaticAllocaMap;
80
81 unsigned MakeReg(MVT::ValueType VT) {
82 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
83 }
Misha Brukman835702a2005-04-21 22:36:52 +000084
Chris Lattner7a60d912005-01-07 07:47:53 +000085 unsigned CreateRegForValue(const Value *V) {
86 MVT::ValueType VT = TLI.getValueType(V->getType());
87 // The common case is that we will only create one register for this
88 // value. If we have that case, create and return the virtual register.
89 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000090 if (NV == 1) {
91 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000092 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000093 }
Misha Brukman835702a2005-04-21 22:36:52 +000094
Chris Lattner7a60d912005-01-07 07:47:53 +000095 // If this value is represented with multiple target registers, make sure
96 // to create enough consequtive registers of the right (smaller) type.
97 unsigned NT = VT-1; // Find the type to use.
98 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
99 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000100
Chris Lattner7a60d912005-01-07 07:47:53 +0000101 unsigned R = MakeReg((MVT::ValueType)NT);
102 for (unsigned i = 1; i != NV; ++i)
103 MakeReg((MVT::ValueType)NT);
104 return R;
105 }
Misha Brukman835702a2005-04-21 22:36:52 +0000106
Chris Lattner7a60d912005-01-07 07:47:53 +0000107 unsigned InitializeRegForValue(const Value *V) {
108 unsigned &R = ValueMap[V];
109 assert(R == 0 && "Already initialized this value register!");
110 return R = CreateRegForValue(V);
111 }
112 };
113}
114
115/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
116/// PHI nodes or outside of the basic block that defines it.
117static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
118 if (isa<PHINode>(I)) return true;
119 BasicBlock *BB = I->getParent();
120 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
121 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
122 return true;
123 return false;
124}
125
Chris Lattner6871b232005-10-30 19:42:35 +0000126/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
127/// entry block, return true.
128static bool isOnlyUsedInEntryBlock(Argument *A) {
129 BasicBlock *Entry = A->getParent()->begin();
130 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
131 if (cast<Instruction>(*UI)->getParent() != Entry)
132 return false; // Use not in entry block.
133 return true;
134}
135
Chris Lattner7a60d912005-01-07 07:47:53 +0000136FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000137 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000138 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
139
Chris Lattner6871b232005-10-30 19:42:35 +0000140 // Create a vreg for each argument register that is not dead and is used
141 // outside of the entry block for the function.
142 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
143 AI != E; ++AI)
144 if (!isOnlyUsedInEntryBlock(AI))
145 InitializeRegForValue(AI);
146
Chris Lattner7a60d912005-01-07 07:47:53 +0000147 // Initialize the mapping of values to registers. This is only set up for
148 // instruction values that are used outside of the block that defines
149 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000150 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000151 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
152 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
153 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
154 const Type *Ty = AI->getAllocatedType();
155 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000156 unsigned Align =
157 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
158 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000159
160 // If the alignment of the value is smaller than the size of the value,
161 // and if the size of the value is particularly small (<= 8 bytes),
162 // round up to the size of the value for potentially better performance.
163 //
164 // FIXME: This could be made better with a preferred alignment hook in
165 // TargetData. It serves primarily to 8-byte align doubles for X86.
166 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000167 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000168 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000169 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000170 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000171 }
172
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000173 for (; BB != EB; ++BB)
174 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000175 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
176 if (!isa<AllocaInst>(I) ||
177 !StaticAllocaMap.count(cast<AllocaInst>(I)))
178 InitializeRegForValue(I);
179
180 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
181 // also creates the initial PHI MachineInstrs, though none of the input
182 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000183 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
185 MBBMap[BB] = MBB;
186 MF.getBasicBlockList().push_back(MBB);
187
188 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
189 // appropriate.
190 PHINode *PN;
191 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000192 (PN = dyn_cast<PHINode>(I)); ++I)
193 if (!PN->use_empty()) {
194 unsigned NumElements =
195 TLI.getNumElements(TLI.getValueType(PN->getType()));
196 unsigned PHIReg = ValueMap[PN];
197 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
198 for (unsigned i = 0; i != NumElements; ++i)
199 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
200 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000201 }
202}
203
204
205
206//===----------------------------------------------------------------------===//
207/// SelectionDAGLowering - This is the common target-independent lowering
208/// implementation that is parameterized by a TargetLowering object.
209/// Also, targets can overload any lowering method.
210///
211namespace llvm {
212class SelectionDAGLowering {
213 MachineBasicBlock *CurMBB;
214
215 std::map<const Value*, SDOperand> NodeMap;
216
Chris Lattner4d9651c2005-01-17 22:19:26 +0000217 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
218 /// them up and then emit token factor nodes when possible. This allows us to
219 /// get simple disambiguation between loads without worrying about alias
220 /// analysis.
221 std::vector<SDOperand> PendingLoads;
222
Chris Lattner7a60d912005-01-07 07:47:53 +0000223public:
224 // TLI - This is information that describes the available target features we
225 // need for lowering. This indicates when operations are unavailable,
226 // implemented with a libcall, etc.
227 TargetLowering &TLI;
228 SelectionDAG &DAG;
229 const TargetData &TD;
230
231 /// FuncInfo - Information about the function as a whole.
232 ///
233 FunctionLoweringInfo &FuncInfo;
234
235 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000236 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
238 FuncInfo(funcinfo) {
239 }
240
Chris Lattner4108bb02005-01-17 19:43:36 +0000241 /// getRoot - Return the current virtual root of the Selection DAG.
242 ///
243 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000244 if (PendingLoads.empty())
245 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000246
Chris Lattner4d9651c2005-01-17 22:19:26 +0000247 if (PendingLoads.size() == 1) {
248 SDOperand Root = PendingLoads[0];
249 DAG.setRoot(Root);
250 PendingLoads.clear();
251 return Root;
252 }
253
254 // Otherwise, we have to make a token factor node.
255 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
256 PendingLoads.clear();
257 DAG.setRoot(Root);
258 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000259 }
260
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 void visit(Instruction &I) { visit(I.getOpcode(), I); }
262
263 void visit(unsigned Opcode, User &I) {
264 switch (Opcode) {
265 default: assert(0 && "Unknown instruction type encountered!");
266 abort();
267 // Build the switch statement using the Instruction.def file.
268#define HANDLE_INST(NUM, OPCODE, CLASS) \
269 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
270#include "llvm/Instruction.def"
271 }
272 }
273
274 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
275
276
277 SDOperand getIntPtrConstant(uint64_t Val) {
278 return DAG.getConstant(Val, TLI.getPointerTy());
279 }
280
281 SDOperand getValue(const Value *V) {
282 SDOperand &N = NodeMap[V];
283 if (N.Val) return N;
284
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000285 const Type *VTy = V->getType();
286 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000287 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
288 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
289 visit(CE->getOpcode(), *CE);
290 assert(N.Val && "visit didn't populate the ValueMap!");
291 return N;
292 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
293 return N = DAG.getGlobalAddress(GV, VT);
294 } else if (isa<ConstantPointerNull>(C)) {
295 return N = DAG.getConstant(0, TLI.getPointerTy());
296 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000297 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000298 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
299 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000300 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
301 unsigned NumElements = PTy->getNumElements();
302 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
303 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
304
305 // Now that we know the number and type of the elements, push a
306 // Constant or ConstantFP node onto the ops list for each element of
307 // the packed constant.
308 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000309 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
310 if (MVT::isFloatingPoint(PVT)) {
311 for (unsigned i = 0; i != NumElements; ++i) {
312 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
313 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
314 }
315 } else {
316 for (unsigned i = 0; i != NumElements; ++i) {
317 const ConstantIntegral *El =
318 cast<ConstantIntegral>(CP->getOperand(i));
319 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
320 }
321 }
322 } else {
323 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
324 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000325 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000326 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000327 else
Chris Lattner803a5752005-12-21 02:43:26 +0000328 Op = DAG.getConstant(0, PVT);
329 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000330 }
Chris Lattner803a5752005-12-21 02:43:26 +0000331
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000332 // Handle the case where we have a 1-element vector, in which
333 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000334 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000335 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000336 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
337 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
338 } else {
339 // If the packed type isn't legal, then create a ConstantVec node with
340 // generic Vector type instead.
341 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
342 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000343 } else {
344 // Canonicalize all constant ints to be unsigned.
345 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
346 }
347
348 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
349 std::map<const AllocaInst*, int>::iterator SI =
350 FuncInfo.StaticAllocaMap.find(AI);
351 if (SI != FuncInfo.StaticAllocaMap.end())
352 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
353 }
354
355 std::map<const Value*, unsigned>::const_iterator VMI =
356 FuncInfo.ValueMap.find(V);
357 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000358
Chris Lattner33182322005-08-16 21:55:35 +0000359 unsigned InReg = VMI->second;
360
361 // If this type is not legal, make it so now.
362 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
363
364 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
365 if (DestVT < VT) {
366 // Source must be expanded. This input value is actually coming from the
367 // register pair VMI->second and VMI->second+1.
368 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
369 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
370 } else {
371 if (DestVT > VT) { // Promotion case
372 if (MVT::isFloatingPoint(VT))
373 N = DAG.getNode(ISD::FP_ROUND, VT, N);
374 else
375 N = DAG.getNode(ISD::TRUNCATE, VT, N);
376 }
377 }
378
379 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000380 }
381
382 const SDOperand &setValue(const Value *V, SDOperand NewN) {
383 SDOperand &N = NodeMap[V];
384 assert(N.Val == 0 && "Already set a value for this node!");
385 return N = NewN;
386 }
387
388 // Terminator instructions.
389 void visitRet(ReturnInst &I);
390 void visitBr(BranchInst &I);
391 void visitUnreachable(UnreachableInst &I) { /* noop */ }
392
393 // These all get lowered before this pass.
394 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
395 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
396 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
397
398 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000399 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000400 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000401 void visitAdd(User &I) {
402 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000403 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000404 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000405 void visitMul(User &I) {
406 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000407 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000408 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000409 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000410 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000411 }
412 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000413 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000414 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000415 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000416 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
417 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
418 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000419 void visitShl(User &I) { visitShift(I, ISD::SHL); }
420 void visitShr(User &I) {
421 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000422 }
423
424 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
425 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
426 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
427 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
428 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
429 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
430 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
431
432 void visitGetElementPtr(User &I);
433 void visitCast(User &I);
434 void visitSelect(User &I);
435 //
436
437 void visitMalloc(MallocInst &I);
438 void visitFree(FreeInst &I);
439 void visitAlloca(AllocaInst &I);
440 void visitLoad(LoadInst &I);
441 void visitStore(StoreInst &I);
442 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
443 void visitCall(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000444 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000445
Chris Lattner7a60d912005-01-07 07:47:53 +0000446 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000447 void visitVAArg(VAArgInst &I);
448 void visitVAEnd(CallInst &I);
449 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000450 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000451
Chris Lattner875def92005-01-11 05:56:49 +0000452 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000453
454 void visitUserOp1(Instruction &I) {
455 assert(0 && "UserOp1 should not exist at instruction selection time!");
456 abort();
457 }
458 void visitUserOp2(Instruction &I) {
459 assert(0 && "UserOp2 should not exist at instruction selection time!");
460 abort();
461 }
462};
463} // end namespace llvm
464
465void SelectionDAGLowering::visitRet(ReturnInst &I) {
466 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000467 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000468 return;
469 }
470
471 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000472 MVT::ValueType TmpVT;
473
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 switch (Op1.getValueType()) {
475 default: assert(0 && "Unknown value type!");
476 case MVT::i1:
477 case MVT::i8:
478 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000479 case MVT::i32:
480 // If this is a machine where 32-bits is legal or expanded, promote to
481 // 32-bits, otherwise, promote to 64-bits.
482 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
483 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000485 TmpVT = MVT::i32;
486
487 // Extend integer types to result type.
488 if (I.getOperand(0)->getType()->isSigned())
489 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
490 else
491 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 break;
493 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000494 case MVT::i64:
495 case MVT::f64:
496 break; // No extension needed!
497 }
Nate Begeman78afac22005-10-18 23:23:37 +0000498 // Allow targets to lower this further to meet ABI requirements
499 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000500}
501
502void SelectionDAGLowering::visitBr(BranchInst &I) {
503 // Update machine-CFG edges.
504 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000505
506 // Figure out which block is immediately after the current one.
507 MachineBasicBlock *NextBlock = 0;
508 MachineFunction::iterator BBI = CurMBB;
509 if (++BBI != CurMBB->getParent()->end())
510 NextBlock = BBI;
511
512 if (I.isUnconditional()) {
513 // If this is not a fall-through branch, emit the branch.
514 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000515 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000516 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000517 } else {
518 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000519
520 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000521 if (Succ1MBB == NextBlock) {
522 // If the condition is false, fall through. This means we should branch
523 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000524 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000525 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000526 } else if (Succ0MBB == NextBlock) {
527 // If the condition is true, fall through. This means we should branch if
528 // the condition is false to Succ #1. Invert the condition first.
529 SDOperand True = DAG.getConstant(1, Cond.getValueType());
530 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000531 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000532 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000533 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000534 std::vector<SDOperand> Ops;
535 Ops.push_back(getRoot());
536 Ops.push_back(Cond);
537 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
538 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
539 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000540 }
541 }
542}
543
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000544void SelectionDAGLowering::visitSub(User &I) {
545 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000546 if (I.getType()->isFloatingPoint()) {
547 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
548 if (CFP->isExactlyValue(-0.0)) {
549 SDOperand Op2 = getValue(I.getOperand(1));
550 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
551 return;
552 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000553 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000554 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000555}
556
Nate Begemanb2e089c2005-11-19 00:36:38 +0000557void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
558 unsigned VecOp) {
559 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000560 SDOperand Op1 = getValue(I.getOperand(0));
561 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000562
Chris Lattner19baba62005-11-19 18:40:42 +0000563 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000564 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
565 } else if (Ty->isFloatingPoint()) {
566 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
567 } else {
568 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000569 unsigned NumElements = PTy->getNumElements();
570 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000571 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000572
573 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000574 // the Legalize pass does not have to deal with them. Similarly, if the
575 // abstract vector is going to turn into one that the target natively
576 // supports, generate that type now so that Legalize doesn't have to deal
577 // with that either. These steps ensure that Legalize only has to handle
578 // vector types in its Expand case.
579 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000580 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000581 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000582 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
583 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000584 } else {
585 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
586 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000587 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000588 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000589 }
Nate Begeman127321b2005-11-18 07:42:56 +0000590}
Chris Lattner96c26752005-01-19 22:31:21 +0000591
Nate Begeman127321b2005-11-18 07:42:56 +0000592void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
593 SDOperand Op1 = getValue(I.getOperand(0));
594 SDOperand Op2 = getValue(I.getOperand(1));
595
596 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
597
Chris Lattner7a60d912005-01-07 07:47:53 +0000598 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
599}
600
601void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
602 ISD::CondCode UnsignedOpcode) {
603 SDOperand Op1 = getValue(I.getOperand(0));
604 SDOperand Op2 = getValue(I.getOperand(1));
605 ISD::CondCode Opcode = SignedOpcode;
606 if (I.getOperand(0)->getType()->isUnsigned())
607 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000608 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000609}
610
611void SelectionDAGLowering::visitSelect(User &I) {
612 SDOperand Cond = getValue(I.getOperand(0));
613 SDOperand TrueVal = getValue(I.getOperand(1));
614 SDOperand FalseVal = getValue(I.getOperand(2));
615 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
616 TrueVal, FalseVal));
617}
618
619void SelectionDAGLowering::visitCast(User &I) {
620 SDOperand N = getValue(I.getOperand(0));
621 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
622 MVT::ValueType DestTy = TLI.getValueType(I.getType());
623
624 if (N.getValueType() == DestTy) {
625 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000626 } else if (DestTy == MVT::i1) {
627 // Cast to bool is a comparison against zero, not truncation to zero.
628 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
629 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000630 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000631 } else if (isInteger(SrcTy)) {
632 if (isInteger(DestTy)) { // Int -> Int cast
633 if (DestTy < SrcTy) // Truncating cast?
634 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
635 else if (I.getOperand(0)->getType()->isSigned())
636 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
637 else
638 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
639 } else { // Int -> FP cast
640 if (I.getOperand(0)->getType()->isSigned())
641 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
642 else
643 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
644 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000645 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000646 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
647 if (isFloatingPoint(DestTy)) { // FP -> FP cast
648 if (DestTy < SrcTy) // Rounding cast?
649 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
650 else
651 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
652 } else { // FP -> Int cast.
653 if (I.getType()->isSigned())
654 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
655 else
656 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
657 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000658 }
659}
660
661void SelectionDAGLowering::visitGetElementPtr(User &I) {
662 SDOperand N = getValue(I.getOperand(0));
663 const Type *Ty = I.getOperand(0)->getType();
664 const Type *UIntPtrTy = TD.getIntPtrType();
665
666 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
667 OI != E; ++OI) {
668 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000669 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000670 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
671 if (Field) {
672 // N = N + Offset
673 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
674 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000675 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000676 }
677 Ty = StTy->getElementType(Field);
678 } else {
679 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000680
Chris Lattner43535a12005-11-09 04:45:33 +0000681 // If this is a constant subscript, handle it quickly.
682 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
683 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000684
Chris Lattner43535a12005-11-09 04:45:33 +0000685 uint64_t Offs;
686 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
687 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
688 else
689 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
690 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
691 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000692 }
Chris Lattner43535a12005-11-09 04:45:33 +0000693
694 // N = N + Idx * ElementSize;
695 uint64_t ElementSize = TD.getTypeSize(Ty);
696 SDOperand IdxN = getValue(Idx);
697
698 // If the index is smaller or larger than intptr_t, truncate or extend
699 // it.
700 if (IdxN.getValueType() < N.getValueType()) {
701 if (Idx->getType()->isSigned())
702 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
703 else
704 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
705 } else if (IdxN.getValueType() > N.getValueType())
706 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
707
708 // If this is a multiply by a power of two, turn it into a shl
709 // immediately. This is a very common case.
710 if (isPowerOf2_64(ElementSize)) {
711 unsigned Amt = Log2_64(ElementSize);
712 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000713 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000714 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
715 continue;
716 }
717
718 SDOperand Scale = getIntPtrConstant(ElementSize);
719 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
720 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000721 }
722 }
723 setValue(&I, N);
724}
725
726void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
727 // If this is a fixed sized alloca in the entry block of the function,
728 // allocate it statically on the stack.
729 if (FuncInfo.StaticAllocaMap.count(&I))
730 return; // getValue will auto-populate this.
731
732 const Type *Ty = I.getAllocatedType();
733 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000734 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
735 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000736
737 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000738 MVT::ValueType IntPtr = TLI.getPointerTy();
739 if (IntPtr < AllocSize.getValueType())
740 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
741 else if (IntPtr > AllocSize.getValueType())
742 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000743
Chris Lattnereccb73d2005-01-22 23:04:37 +0000744 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000745 getIntPtrConstant(TySize));
746
747 // Handle alignment. If the requested alignment is less than or equal to the
748 // stack alignment, ignore it and round the size of the allocation up to the
749 // stack alignment size. If the size is greater than the stack alignment, we
750 // note this in the DYNAMIC_STACKALLOC node.
751 unsigned StackAlign =
752 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
753 if (Align <= StackAlign) {
754 Align = 0;
755 // Add SA-1 to the size.
756 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
757 getIntPtrConstant(StackAlign-1));
758 // Mask out the low bits for alignment purposes.
759 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
760 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
761 }
762
Chris Lattner96c262e2005-05-14 07:29:57 +0000763 std::vector<MVT::ValueType> VTs;
764 VTs.push_back(AllocSize.getValueType());
765 VTs.push_back(MVT::Other);
766 std::vector<SDOperand> Ops;
767 Ops.push_back(getRoot());
768 Ops.push_back(AllocSize);
769 Ops.push_back(getIntPtrConstant(Align));
770 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000771 DAG.setRoot(setValue(&I, DSA).getValue(1));
772
773 // Inform the Frame Information that we have just allocated a variable-sized
774 // object.
775 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
776}
777
Chris Lattner435b4022005-11-29 06:21:05 +0000778/// getStringValue - Turn an LLVM constant pointer that eventually points to a
779/// global into a string value. Return an empty string if we can't do it.
780///
781static std::string getStringValue(Value *V, unsigned Offset = 0) {
782 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
783 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
784 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
785 if (Init->isString()) {
786 std::string Result = Init->getAsString();
787 if (Offset < Result.size()) {
788 // If we are pointing INTO The string, erase the beginning...
789 Result.erase(Result.begin(), Result.begin()+Offset);
790
791 // Take off the null terminator, and any string fragments after it.
792 std::string::size_type NullPos = Result.find_first_of((char)0);
793 if (NullPos != std::string::npos)
794 Result.erase(Result.begin()+NullPos, Result.end());
795 return Result;
796 }
797 }
798 }
799 } else if (Constant *C = dyn_cast<Constant>(V)) {
800 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
801 return getStringValue(GV, Offset);
802 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
803 if (CE->getOpcode() == Instruction::GetElementPtr) {
804 // Turn a gep into the specified offset.
805 if (CE->getNumOperands() == 3 &&
806 cast<Constant>(CE->getOperand(1))->isNullValue() &&
807 isa<ConstantInt>(CE->getOperand(2))) {
808 return getStringValue(CE->getOperand(0),
809 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
810 }
811 }
812 }
813 }
814 return "";
815}
Chris Lattner7a60d912005-01-07 07:47:53 +0000816
817void SelectionDAGLowering::visitLoad(LoadInst &I) {
818 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000819
Chris Lattner4d9651c2005-01-17 22:19:26 +0000820 SDOperand Root;
821 if (I.isVolatile())
822 Root = getRoot();
823 else {
824 // Do not serialize non-volatile loads against each other.
825 Root = DAG.getRoot();
826 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000827
828 const Type *Ty = I.getType();
829 SDOperand L;
830
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000831 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000832 unsigned NumElements = PTy->getNumElements();
833 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000834 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000835
836 // Immediately scalarize packed types containing only one element, so that
837 // the Legalize pass does not have to deal with them.
838 if (NumElements == 1) {
839 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000840 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
841 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000842 } else {
843 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
844 DAG.getSrcValue(I.getOperand(0)));
845 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000846 } else {
847 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
848 DAG.getSrcValue(I.getOperand(0)));
849 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000850 setValue(&I, L);
851
852 if (I.isVolatile())
853 DAG.setRoot(L.getValue(1));
854 else
855 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000856}
857
858
859void SelectionDAGLowering::visitStore(StoreInst &I) {
860 Value *SrcV = I.getOperand(0);
861 SDOperand Src = getValue(SrcV);
862 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000863 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000864 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000865}
866
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000867/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
868/// we want to emit this as a call to a named external function, return the name
869/// otherwise lower it and return null.
870const char *
871SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
872 switch (Intrinsic) {
873 case Intrinsic::vastart: visitVAStart(I); return 0;
874 case Intrinsic::vaend: visitVAEnd(I); return 0;
875 case Intrinsic::vacopy: visitVACopy(I); return 0;
876 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
877 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
878 case Intrinsic::setjmp:
879 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
880 break;
881 case Intrinsic::longjmp:
882 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
883 break;
884 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
885 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
886 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
887
888 case Intrinsic::readport:
889 case Intrinsic::readio: {
890 std::vector<MVT::ValueType> VTs;
891 VTs.push_back(TLI.getValueType(I.getType()));
892 VTs.push_back(MVT::Other);
893 std::vector<SDOperand> Ops;
894 Ops.push_back(getRoot());
895 Ops.push_back(getValue(I.getOperand(1)));
896 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
897 ISD::READPORT : ISD::READIO, VTs, Ops);
898
899 setValue(&I, Tmp);
900 DAG.setRoot(Tmp.getValue(1));
901 return 0;
902 }
903 case Intrinsic::writeport:
904 case Intrinsic::writeio:
905 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
906 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
907 getRoot(), getValue(I.getOperand(1)),
908 getValue(I.getOperand(2))));
909 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000910
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000911 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000912 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
913 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000914
915 std::string fname = "<unknown>";
916 std::vector<SDOperand> Ops;
917
Chris Lattner435b4022005-11-29 06:21:05 +0000918 // Input Chain
919 Ops.push_back(getRoot());
920
921 // line number
922 Ops.push_back(getValue(I.getOperand(2)));
923
924 // column
925 Ops.push_back(getValue(I.getOperand(3)));
926
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000927 // filename/working dir
928 // Pull the filename out of the the compilation unit.
929 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
930 if (cunit && cunit->hasInitializer()) {
931 if (ConstantStruct *CS =
932 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
933 if (CS->getNumOperands() > 0) {
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000934 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskey7c462762005-12-16 22:45:29 +0000935 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000936 }
937 }
938 }
939
940 if (Ops.size() == 5) // Found filename/workingdir.
941 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner8782b782005-12-03 18:50:48 +0000942 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000943 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000944 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000945 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000946 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
947 return "llvm_dbg_region_start";
948 if (I.getType() != Type::VoidTy)
949 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
950 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000951 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000952 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
953 return "llvm_dbg_region_end";
954 if (I.getType() != Type::VoidTy)
955 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
956 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000957 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000958 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
959 return "llvm_dbg_subprogram";
960 if (I.getType() != Type::VoidTy)
961 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
962 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000963 case Intrinsic::dbg_declare:
964 if (I.getType() != Type::VoidTy)
965 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
966 return 0;
967
968 case Intrinsic::isunordered:
969 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
970 getValue(I.getOperand(2)), ISD::SETUO));
971 return 0;
972
973 case Intrinsic::sqrt:
974 setValue(&I, DAG.getNode(ISD::FSQRT,
975 getValue(I.getOperand(1)).getValueType(),
976 getValue(I.getOperand(1))));
977 return 0;
978 case Intrinsic::pcmarker: {
979 SDOperand Tmp = getValue(I.getOperand(1));
980 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
981 return 0;
982 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000983 case Intrinsic::readcyclecounter: {
984 std::vector<MVT::ValueType> VTs;
985 VTs.push_back(MVT::i64);
986 VTs.push_back(MVT::Other);
987 std::vector<SDOperand> Ops;
988 Ops.push_back(getRoot());
989 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
990 setValue(&I, Tmp);
991 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000992 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000993 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000994 case Intrinsic::cttz:
995 setValue(&I, DAG.getNode(ISD::CTTZ,
996 getValue(I.getOperand(1)).getValueType(),
997 getValue(I.getOperand(1))));
998 return 0;
999 case Intrinsic::ctlz:
1000 setValue(&I, DAG.getNode(ISD::CTLZ,
1001 getValue(I.getOperand(1)).getValueType(),
1002 getValue(I.getOperand(1))));
1003 return 0;
1004 case Intrinsic::ctpop:
1005 setValue(&I, DAG.getNode(ISD::CTPOP,
1006 getValue(I.getOperand(1)).getValueType(),
1007 getValue(I.getOperand(1))));
1008 return 0;
Chris Lattner9e8b6332005-12-12 22:51:16 +00001009 case Intrinsic::prefetch:
1010 // FIXME: Currently discarding prefetches.
1011 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001012 default:
1013 std::cerr << I;
1014 assert(0 && "This intrinsic is not implemented yet!");
1015 return 0;
1016 }
1017}
1018
1019
Chris Lattner7a60d912005-01-07 07:47:53 +00001020void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001021 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001022 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001023 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001024 if (unsigned IID = F->getIntrinsicID()) {
1025 RenameFn = visitIntrinsicCall(I, IID);
1026 if (!RenameFn)
1027 return;
1028 } else { // Not an LLVM intrinsic.
1029 const std::string &Name = F->getName();
1030 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001031 if (I.getNumOperands() == 2 && // Basic sanity checks.
1032 I.getOperand(1)->getType()->isFloatingPoint() &&
1033 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001034 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001035 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1036 return;
1037 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001038 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001039 if (I.getNumOperands() == 2 && // Basic sanity checks.
1040 I.getOperand(1)->getType()->isFloatingPoint() &&
1041 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001042 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001043 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1044 return;
1045 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001046 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001047 if (I.getNumOperands() == 2 && // Basic sanity checks.
1048 I.getOperand(1)->getType()->isFloatingPoint() &&
1049 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001050 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001051 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1052 return;
1053 }
1054 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001055 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001056 }
Misha Brukman835702a2005-04-21 22:36:52 +00001057
Chris Lattner18d2b342005-01-08 22:48:57 +00001058 SDOperand Callee;
1059 if (!RenameFn)
1060 Callee = getValue(I.getOperand(0));
1061 else
1062 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001063 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001064 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001065 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1066 Value *Arg = I.getOperand(i);
1067 SDOperand ArgNode = getValue(Arg);
1068 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1069 }
Misha Brukman835702a2005-04-21 22:36:52 +00001070
Nate Begemanf6565252005-03-26 01:29:23 +00001071 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1072 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001073
Chris Lattner1f45cd72005-01-08 19:26:18 +00001074 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001075 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001076 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001077 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001078 setValue(&I, Result.first);
1079 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001080}
1081
1082void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1083 SDOperand Src = getValue(I.getOperand(0));
1084
1085 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001086
1087 if (IntPtr < Src.getValueType())
1088 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1089 else if (IntPtr > Src.getValueType())
1090 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001091
1092 // Scale the source by the type size.
1093 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1094 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1095 Src, getIntPtrConstant(ElementSize));
1096
1097 std::vector<std::pair<SDOperand, const Type*> > Args;
1098 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001099
1100 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001101 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001102 DAG.getExternalSymbol("malloc", IntPtr),
1103 Args, DAG);
1104 setValue(&I, Result.first); // Pointers always fit in registers
1105 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001106}
1107
1108void SelectionDAGLowering::visitFree(FreeInst &I) {
1109 std::vector<std::pair<SDOperand, const Type*> > Args;
1110 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1111 TLI.getTargetData().getIntPtrType()));
1112 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001113 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001114 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001115 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1116 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001117}
1118
Chris Lattner13d7c252005-08-26 20:54:47 +00001119// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1120// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1121// instructions are special in various ways, which require special support to
1122// insert. The specified MachineInstr is created but not inserted into any
1123// basic blocks, and the scheduler passes ownership of it to this method.
1124MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1125 MachineBasicBlock *MBB) {
1126 std::cerr << "If a target marks an instruction with "
1127 "'usesCustomDAGSchedInserter', it must implement "
1128 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1129 abort();
1130 return 0;
1131}
1132
Nate Begeman78afac22005-10-18 23:23:37 +00001133SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1134 SelectionDAG &DAG) {
1135 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1136}
1137
Chris Lattnerf5473e42005-07-05 19:57:53 +00001138SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1139 SDOperand VAListP, Value *VAListV,
1140 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001141 // We have no sane default behavior, just emit a useful error message and bail
1142 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001143 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001144 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001145 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001146}
1147
Chris Lattnerf5473e42005-07-05 19:57:53 +00001148SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001149 SelectionDAG &DAG) {
1150 // Default to a noop.
1151 return Chain;
1152}
1153
Chris Lattnerf5473e42005-07-05 19:57:53 +00001154SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1155 SDOperand SrcP, Value *SrcV,
1156 SDOperand DestP, Value *DestV,
1157 SelectionDAG &DAG) {
1158 // Default to copying the input list.
1159 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1160 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001161 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001162 Val, DestP, DAG.getSrcValue(DestV));
1163 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001164}
1165
1166std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001167TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1168 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001169 // We have no sane default behavior, just emit a useful error message and bail
1170 // out.
1171 std::cerr << "Variable arguments handling not implemented on this target!\n";
1172 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001173 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001174}
1175
1176
1177void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001178 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1179 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001180}
1181
1182void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1183 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001184 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001185 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001186 setValue(&I, Result.first);
1187 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001188}
1189
1190void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001191 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001192 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001193}
1194
1195void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001196 SDOperand Result =
1197 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1198 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1199 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001200}
1201
Chris Lattner58cfd792005-01-09 00:00:49 +00001202
1203// It is always conservatively correct for llvm.returnaddress and
1204// llvm.frameaddress to return 0.
1205std::pair<SDOperand, SDOperand>
1206TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1207 unsigned Depth, SelectionDAG &DAG) {
1208 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001209}
1210
Chris Lattner29dcc712005-05-14 05:50:48 +00001211SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001212 assert(0 && "LowerOperation not implemented for this target!");
1213 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001214 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001215}
1216
Chris Lattner58cfd792005-01-09 00:00:49 +00001217void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1218 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1219 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001220 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001221 setValue(&I, Result.first);
1222 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001223}
1224
Chris Lattner875def92005-01-11 05:56:49 +00001225void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer3fd1b4c2005-11-30 05:21:10 +00001226#if 0
1227 // If the size of the cpy/move/set is constant (known)
1228 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1229 uint64_t size = op3->getValue();
1230 switch (Op) {
1231 case ISD::MEMSET:
1232 if (size <= TLI.getMaxStoresPerMemSet()) {
1233 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1234 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1235 uint64_t align = op4.getValue();
1236 while (size > align) {
1237 size -=align;
1238 }
1239 Value *SrcV = I.getOperand(0);
1240 SDOperand Src = getValue(SrcV);
1241 SDOperand Ptr = getValue(I.getOperand(1));
1242 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1243 DAG.getSrcValue(I.getOperand(1))));
1244 }
1245 break;
1246 }
1247 break; // don't do this optimization, use a normal memset
1248 case ISD::MEMMOVE:
1249 case ISD::MEMCPY:
1250 break; // FIXME: not implemented yet
1251 }
1252 }
1253#endif
1254
1255 // Non-optimized version
Chris Lattner875def92005-01-11 05:56:49 +00001256 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001257 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001258 Ops.push_back(getValue(I.getOperand(1)));
1259 Ops.push_back(getValue(I.getOperand(2)));
1260 Ops.push_back(getValue(I.getOperand(3)));
1261 Ops.push_back(getValue(I.getOperand(4)));
1262 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001263}
1264
Chris Lattner875def92005-01-11 05:56:49 +00001265//===----------------------------------------------------------------------===//
1266// SelectionDAGISel code
1267//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001268
1269unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1270 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1271}
1272
Chris Lattnerc9950c12005-08-17 06:37:43 +00001273void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001274 // FIXME: we only modify the CFG to split critical edges. This
1275 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001276}
Chris Lattner7a60d912005-01-07 07:47:53 +00001277
Chris Lattner35397782005-12-05 07:10:48 +00001278
1279/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1280/// casting to the type of GEPI.
1281static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1282 Value *Ptr, Value *PtrOffset) {
1283 if (V) return V; // Already computed.
1284
1285 BasicBlock::iterator InsertPt;
1286 if (BB == GEPI->getParent()) {
1287 // If insert into the GEP's block, insert right after the GEP.
1288 InsertPt = GEPI;
1289 ++InsertPt;
1290 } else {
1291 // Otherwise, insert at the top of BB, after any PHI nodes
1292 InsertPt = BB->begin();
1293 while (isa<PHINode>(InsertPt)) ++InsertPt;
1294 }
1295
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001296 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1297 // BB so that there is only one value live across basic blocks (the cast
1298 // operand).
1299 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1300 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1301 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1302
Chris Lattner35397782005-12-05 07:10:48 +00001303 // Add the offset, cast it to the right type.
1304 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1305 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1306 return V = Ptr;
1307}
1308
1309
1310/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1311/// selection, we want to be a bit careful about some things. In particular, if
1312/// we have a GEP instruction that is used in a different block than it is
1313/// defined, the addressing expression of the GEP cannot be folded into loads or
1314/// stores that use it. In this case, decompose the GEP and move constant
1315/// indices into blocks that use it.
1316static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1317 const TargetData &TD) {
1318 if (!GEPISelTest) return;
1319
1320 // If this GEP is only used inside the block it is defined in, there is no
1321 // need to rewrite it.
1322 bool isUsedOutsideDefBB = false;
1323 BasicBlock *DefBB = GEPI->getParent();
1324 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1325 UI != E; ++UI) {
1326 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1327 isUsedOutsideDefBB = true;
1328 break;
1329 }
1330 }
1331 if (!isUsedOutsideDefBB) return;
1332
1333 // If this GEP has no non-zero constant indices, there is nothing we can do,
1334 // ignore it.
1335 bool hasConstantIndex = false;
1336 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1337 E = GEPI->op_end(); OI != E; ++OI) {
1338 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1339 if (CI->getRawValue()) {
1340 hasConstantIndex = true;
1341 break;
1342 }
1343 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00001344 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1345 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00001346
1347 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1348 // constant offset (which we now know is non-zero) and deal with it later.
1349 uint64_t ConstantOffset = 0;
1350 const Type *UIntPtrTy = TD.getIntPtrType();
1351 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1352 const Type *Ty = GEPI->getOperand(0)->getType();
1353
1354 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1355 E = GEPI->op_end(); OI != E; ++OI) {
1356 Value *Idx = *OI;
1357 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1358 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1359 if (Field)
1360 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1361 Ty = StTy->getElementType(Field);
1362 } else {
1363 Ty = cast<SequentialType>(Ty)->getElementType();
1364
1365 // Handle constant subscripts.
1366 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1367 if (CI->getRawValue() == 0) continue;
1368
1369 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1370 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1371 else
1372 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1373 continue;
1374 }
1375
1376 // Ptr = Ptr + Idx * ElementSize;
1377
1378 // Cast Idx to UIntPtrTy if needed.
1379 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1380
1381 uint64_t ElementSize = TD.getTypeSize(Ty);
1382 // Mask off bits that should not be set.
1383 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1384 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1385
1386 // Multiply by the element size and add to the base.
1387 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1388 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1389 }
1390 }
1391
1392 // Make sure that the offset fits in uintptr_t.
1393 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1394 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1395
1396 // Okay, we have now emitted all of the variable index parts to the BB that
1397 // the GEP is defined in. Loop over all of the using instructions, inserting
1398 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001399 // instruction to use the newly computed value, making GEPI dead. When the
1400 // user is a load or store instruction address, we emit the add into the user
1401 // block, otherwise we use a canonical version right next to the gep (these
1402 // won't be foldable as addresses, so we might as well share the computation).
1403
Chris Lattner35397782005-12-05 07:10:48 +00001404 std::map<BasicBlock*,Value*> InsertedExprs;
1405 while (!GEPI->use_empty()) {
1406 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001407
1408 // If this use is not foldable into the addressing mode, use a version
1409 // emitted in the GEP block.
1410 Value *NewVal;
1411 if (!isa<LoadInst>(User) &&
1412 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1413 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1414 Ptr, PtrOffset);
1415 } else {
1416 // Otherwise, insert the code in the User's block so it can be folded into
1417 // any users in that block.
1418 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00001419 User->getParent(), GEPI,
1420 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00001421 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001422 User->replaceUsesOfWith(GEPI, NewVal);
1423 }
Chris Lattner35397782005-12-05 07:10:48 +00001424
1425 // Finally, the GEP is dead, remove it.
1426 GEPI->eraseFromParent();
1427}
1428
Chris Lattner7a60d912005-01-07 07:47:53 +00001429bool SelectionDAGISel::runOnFunction(Function &Fn) {
1430 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1431 RegMap = MF.getSSARegMap();
1432 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1433
Chris Lattner35397782005-12-05 07:10:48 +00001434 // First, split all critical edges for PHI nodes with incoming values that are
1435 // constants, this way the load of the constant into a vreg will not be placed
1436 // into MBBs that are used some other way.
1437 //
1438 // In this pass we also look for GEP instructions that are used across basic
1439 // blocks and rewrites them to improve basic-block-at-a-time selection.
1440 //
Chris Lattner1a908c82005-08-18 17:35:14 +00001441 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1442 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00001443 BasicBlock::iterator BBI;
1444 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00001445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1446 if (isa<Constant>(PN->getIncomingValue(i)))
1447 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00001448
1449 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1450 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1451 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00001452 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001453
Chris Lattner7a60d912005-01-07 07:47:53 +00001454 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1455
1456 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1457 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001458
Chris Lattner7a60d912005-01-07 07:47:53 +00001459 return true;
1460}
1461
1462
Chris Lattner718b5c22005-01-13 17:59:43 +00001463SDOperand SelectionDAGISel::
1464CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001465 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001466 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001467 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001468 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001469
1470 // If this type is not legal, we must make sure to not create an invalid
1471 // register use.
1472 MVT::ValueType SrcVT = Op.getValueType();
1473 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1474 SelectionDAG &DAG = SDL.DAG;
1475 if (SrcVT == DestVT) {
1476 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1477 } else if (SrcVT < DestVT) {
1478 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001479 if (MVT::isFloatingPoint(SrcVT))
1480 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1481 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001482 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001483 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1484 } else {
1485 // The src value is expanded into multiple registers.
1486 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1487 Op, DAG.getConstant(0, MVT::i32));
1488 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1489 Op, DAG.getConstant(1, MVT::i32));
1490 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1491 return DAG.getCopyToReg(Op, Reg+1, Hi);
1492 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001493}
1494
Chris Lattner16f64df2005-01-17 17:15:02 +00001495void SelectionDAGISel::
1496LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1497 std::vector<SDOperand> &UnorderedChains) {
1498 // If this is the entry block, emit arguments.
1499 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001500 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001501 SDOperand OldRoot = SDL.DAG.getRoot();
1502 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001503
Chris Lattner6871b232005-10-30 19:42:35 +00001504 unsigned a = 0;
1505 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1506 AI != E; ++AI, ++a)
1507 if (!AI->use_empty()) {
1508 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001509
Chris Lattner6871b232005-10-30 19:42:35 +00001510 // If this argument is live outside of the entry block, insert a copy from
1511 // whereever we got it to the vreg that other BB's will reference it as.
1512 if (FuncInfo.ValueMap.count(AI)) {
1513 SDOperand Copy =
1514 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1515 UnorderedChains.push_back(Copy);
1516 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001517 }
Chris Lattner6871b232005-10-30 19:42:35 +00001518
1519 // Next, if the function has live ins that need to be copied into vregs,
1520 // emit the copies now, into the top of the block.
1521 MachineFunction &MF = SDL.DAG.getMachineFunction();
1522 if (MF.livein_begin() != MF.livein_end()) {
1523 SSARegMap *RegMap = MF.getSSARegMap();
1524 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1525 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1526 E = MF.livein_end(); LI != E; ++LI)
1527 if (LI->second)
1528 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1529 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001530 }
Chris Lattner6871b232005-10-30 19:42:35 +00001531
1532 // Finally, if the target has anything special to do, allow it to do so.
1533 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001534}
1535
1536
Chris Lattner7a60d912005-01-07 07:47:53 +00001537void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1538 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1539 FunctionLoweringInfo &FuncInfo) {
1540 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001541
1542 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001543
Chris Lattner6871b232005-10-30 19:42:35 +00001544 // Lower any arguments needed in this block if this is the entry block.
1545 if (LLVMBB == &LLVMBB->getParent()->front())
1546 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001547
1548 BB = FuncInfo.MBBMap[LLVMBB];
1549 SDL.setCurrentBasicBlock(BB);
1550
1551 // Lower all of the non-terminator instructions.
1552 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1553 I != E; ++I)
1554 SDL.visit(*I);
1555
1556 // Ensure that all instructions which are used outside of their defining
1557 // blocks are available as virtual registers.
1558 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001559 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001560 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001561 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001562 UnorderedChains.push_back(
1563 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001564 }
1565
1566 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1567 // ensure constants are generated when needed. Remember the virtual registers
1568 // that need to be added to the Machine PHI nodes as input. We cannot just
1569 // directly add them, because expansion might result in multiple MBB's for one
1570 // BB. As such, the start of the BB might correspond to a different MBB than
1571 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001572 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001573
1574 // Emit constants only once even if used by multiple PHI nodes.
1575 std::map<Constant*, unsigned> ConstantsOut;
1576
1577 // Check successor nodes PHI nodes that expect a constant to be available from
1578 // this block.
1579 TerminatorInst *TI = LLVMBB->getTerminator();
1580 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1581 BasicBlock *SuccBB = TI->getSuccessor(succ);
1582 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1583 PHINode *PN;
1584
1585 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1586 // nodes and Machine PHI nodes, but the incoming operands have not been
1587 // emitted yet.
1588 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001589 (PN = dyn_cast<PHINode>(I)); ++I)
1590 if (!PN->use_empty()) {
1591 unsigned Reg;
1592 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1593 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1594 unsigned &RegOut = ConstantsOut[C];
1595 if (RegOut == 0) {
1596 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001597 UnorderedChains.push_back(
1598 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001599 }
1600 Reg = RegOut;
1601 } else {
1602 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001603 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001604 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001605 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1606 "Didn't codegen value into a register!??");
1607 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001608 UnorderedChains.push_back(
1609 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001610 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001611 }
Misha Brukman835702a2005-04-21 22:36:52 +00001612
Chris Lattner8ea875f2005-01-07 21:34:19 +00001613 // Remember that this register needs to added to the machine PHI node as
1614 // the input for this MBB.
1615 unsigned NumElements =
1616 TLI.getNumElements(TLI.getValueType(PN->getType()));
1617 for (unsigned i = 0, e = NumElements; i != e; ++i)
1618 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001619 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001620 }
1621 ConstantsOut.clear();
1622
Chris Lattner718b5c22005-01-13 17:59:43 +00001623 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001624 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001625 SDOperand Root = SDL.getRoot();
1626 if (Root.getOpcode() != ISD::EntryToken) {
1627 unsigned i = 0, e = UnorderedChains.size();
1628 for (; i != e; ++i) {
1629 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1630 if (UnorderedChains[i].Val->getOperand(0) == Root)
1631 break; // Don't add the root if we already indirectly depend on it.
1632 }
1633
1634 if (i == e)
1635 UnorderedChains.push_back(Root);
1636 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001637 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1638 }
1639
Chris Lattner7a60d912005-01-07 07:47:53 +00001640 // Lower the terminator after the copies are emitted.
1641 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001642
1643 // Make sure the root of the DAG is up-to-date.
1644 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001645}
1646
1647void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1648 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001649 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001650 CurDAG = &DAG;
1651 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1652
1653 // First step, lower LLVM code to some DAG. This DAG may use operations and
1654 // types that are not supported by the target.
1655 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1656
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001657 // Run the DAG combiner in pre-legalize mode.
1658 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001659
Chris Lattner7a60d912005-01-07 07:47:53 +00001660 DEBUG(std::cerr << "Lowered selection DAG:\n");
1661 DEBUG(DAG.dump());
1662
1663 // Second step, hack on the DAG until it only uses operations and types that
1664 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001665 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001666
1667 DEBUG(std::cerr << "Legalized selection DAG:\n");
1668 DEBUG(DAG.dump());
1669
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001670 // Run the DAG combiner in post-legalize mode.
1671 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001672
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001673 if (ViewDAGs) DAG.viewGraph();
1674
Chris Lattner5ca31d92005-03-30 01:10:47 +00001675 // Third, instruction select all of the operations to machine code, adding the
1676 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001677 InstructionSelectBasicBlock(DAG);
1678
Chris Lattner7a60d912005-01-07 07:47:53 +00001679 DEBUG(std::cerr << "Selected machine code:\n");
1680 DEBUG(BB->dump());
1681
Chris Lattner5ca31d92005-03-30 01:10:47 +00001682 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001683 // PHI nodes in successors.
1684 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1685 MachineInstr *PHI = PHINodesToUpdate[i].first;
1686 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1687 "This is not a machine PHI node that we are updating!");
1688 PHI->addRegOperand(PHINodesToUpdate[i].second);
1689 PHI->addMachineBasicBlockOperand(BB);
1690 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001691
1692 // Finally, add the CFG edges from the last selected MBB to the successor
1693 // MBBs.
1694 TerminatorInst *TI = LLVMBB->getTerminator();
1695 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1696 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1697 BB->addSuccessor(Succ0MBB);
1698 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001699}