blob: 06a3b016de26303c21e76e1f77740567535dd96f [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000022#include "llvm/Instructions.h"
23#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000024#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000025#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
29#include "llvm/CodeGen/SelectionDAG.h"
30#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000031#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/Target/TargetData.h"
33#include "llvm/Target/TargetFrameInfo.h"
34#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000038#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000039#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000040#include "llvm/Support/Debug.h"
41#include <map>
42#include <iostream>
43using namespace llvm;
44
Chris Lattnerda8abb02005-09-01 18:44:10 +000045#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000046static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000047ViewISelDAGs("view-isel-dags", cl::Hidden,
48 cl::desc("Pop up a window to show isel dags as they are selected"));
49static cl::opt<bool>
50ViewSchedDAGs("view-sched-dags", cl::Hidden,
51 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000052#else
Evan Chenga9c20912006-01-21 02:32:06 +000053static const bool ViewISelDAGs = 0;
54static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000055#endif
56
Evan Cheng4ef10862006-01-23 07:01:07 +000057namespace {
58 cl::opt<SchedHeuristics>
59 ISHeuristic(
60 "sched",
61 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000062 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000063 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000064 clEnumValN(defaultScheduling, "default",
65 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000066 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000067 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000068 clEnumValN(simpleScheduling, "simple",
69 "Simple two pass scheduling: minimize critical path "
70 "and maximize processor utilization"),
71 clEnumValN(simpleNoItinScheduling, "simple-noitin",
72 "Simple two pass scheduling: Same as simple "
73 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000074 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000075 "Bottom up register reduction list scheduling"),
Evan Cheng4ef10862006-01-23 07:01:07 +000076 clEnumValEnd));
77} // namespace
78
79
Chris Lattner1c08c712005-01-07 07:47:53 +000080namespace llvm {
81 //===--------------------------------------------------------------------===//
82 /// FunctionLoweringInfo - This contains information that is global to a
83 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000084 class FunctionLoweringInfo {
85 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000086 TargetLowering &TLI;
87 Function &Fn;
88 MachineFunction &MF;
89 SSARegMap *RegMap;
90
91 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
92
93 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
94 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
95
96 /// ValueMap - Since we emit code for the function a basic block at a time,
97 /// we must remember which virtual registers hold the values for
98 /// cross-basic-block values.
99 std::map<const Value*, unsigned> ValueMap;
100
101 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
102 /// the entry block. This allows the allocas to be efficiently referenced
103 /// anywhere in the function.
104 std::map<const AllocaInst*, int> StaticAllocaMap;
105
106 unsigned MakeReg(MVT::ValueType VT) {
107 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
108 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000109
Chris Lattner1c08c712005-01-07 07:47:53 +0000110 unsigned CreateRegForValue(const Value *V) {
111 MVT::ValueType VT = TLI.getValueType(V->getType());
112 // The common case is that we will only create one register for this
113 // value. If we have that case, create and return the virtual register.
114 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000115 if (NV == 1) {
116 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000117 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000118 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000119
Chris Lattner1c08c712005-01-07 07:47:53 +0000120 // If this value is represented with multiple target registers, make sure
121 // to create enough consequtive registers of the right (smaller) type.
122 unsigned NT = VT-1; // Find the type to use.
123 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
124 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000125
Chris Lattner1c08c712005-01-07 07:47:53 +0000126 unsigned R = MakeReg((MVT::ValueType)NT);
127 for (unsigned i = 1; i != NV; ++i)
128 MakeReg((MVT::ValueType)NT);
129 return R;
130 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000131
Chris Lattner1c08c712005-01-07 07:47:53 +0000132 unsigned InitializeRegForValue(const Value *V) {
133 unsigned &R = ValueMap[V];
134 assert(R == 0 && "Already initialized this value register!");
135 return R = CreateRegForValue(V);
136 }
137 };
138}
139
140/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
141/// PHI nodes or outside of the basic block that defines it.
142static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
143 if (isa<PHINode>(I)) return true;
144 BasicBlock *BB = I->getParent();
145 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
146 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
147 return true;
148 return false;
149}
150
Chris Lattnerbf209482005-10-30 19:42:35 +0000151/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
152/// entry block, return true.
153static bool isOnlyUsedInEntryBlock(Argument *A) {
154 BasicBlock *Entry = A->getParent()->begin();
155 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
156 if (cast<Instruction>(*UI)->getParent() != Entry)
157 return false; // Use not in entry block.
158 return true;
159}
160
Chris Lattner1c08c712005-01-07 07:47:53 +0000161FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000162 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000163 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
164
Chris Lattnerbf209482005-10-30 19:42:35 +0000165 // Create a vreg for each argument register that is not dead and is used
166 // outside of the entry block for the function.
167 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
168 AI != E; ++AI)
169 if (!isOnlyUsedInEntryBlock(AI))
170 InitializeRegForValue(AI);
171
Chris Lattner1c08c712005-01-07 07:47:53 +0000172 // Initialize the mapping of values to registers. This is only set up for
173 // instruction values that are used outside of the block that defines
174 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000175 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000176 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
177 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
178 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
179 const Type *Ty = AI->getAllocatedType();
180 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000181 unsigned Align =
182 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
183 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000184
185 // If the alignment of the value is smaller than the size of the value,
186 // and if the size of the value is particularly small (<= 8 bytes),
187 // round up to the size of the value for potentially better performance.
188 //
189 // FIXME: This could be made better with a preferred alignment hook in
190 // TargetData. It serves primarily to 8-byte align doubles for X86.
191 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000192 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000193 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000195 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000196 }
197
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000198 for (; BB != EB; ++BB)
199 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000200 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
201 if (!isa<AllocaInst>(I) ||
202 !StaticAllocaMap.count(cast<AllocaInst>(I)))
203 InitializeRegForValue(I);
204
205 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
206 // also creates the initial PHI MachineInstrs, though none of the input
207 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000208 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000209 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
210 MBBMap[BB] = MBB;
211 MF.getBasicBlockList().push_back(MBB);
212
213 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
214 // appropriate.
215 PHINode *PN;
216 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000217 (PN = dyn_cast<PHINode>(I)); ++I)
218 if (!PN->use_empty()) {
219 unsigned NumElements =
220 TLI.getNumElements(TLI.getValueType(PN->getType()));
221 unsigned PHIReg = ValueMap[PN];
222 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
223 for (unsigned i = 0; i != NumElements; ++i)
224 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
225 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000226 }
227}
228
229
230
231//===----------------------------------------------------------------------===//
232/// SelectionDAGLowering - This is the common target-independent lowering
233/// implementation that is parameterized by a TargetLowering object.
234/// Also, targets can overload any lowering method.
235///
236namespace llvm {
237class SelectionDAGLowering {
238 MachineBasicBlock *CurMBB;
239
240 std::map<const Value*, SDOperand> NodeMap;
241
Chris Lattnerd3948112005-01-17 22:19:26 +0000242 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
243 /// them up and then emit token factor nodes when possible. This allows us to
244 /// get simple disambiguation between loads without worrying about alias
245 /// analysis.
246 std::vector<SDOperand> PendingLoads;
247
Chris Lattner1c08c712005-01-07 07:47:53 +0000248public:
249 // TLI - This is information that describes the available target features we
250 // need for lowering. This indicates when operations are unavailable,
251 // implemented with a libcall, etc.
252 TargetLowering &TLI;
253 SelectionDAG &DAG;
254 const TargetData &TD;
255
256 /// FuncInfo - Information about the function as a whole.
257 ///
258 FunctionLoweringInfo &FuncInfo;
259
260 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000261 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
263 FuncInfo(funcinfo) {
264 }
265
Chris Lattnera651cf62005-01-17 19:43:36 +0000266 /// getRoot - Return the current virtual root of the Selection DAG.
267 ///
268 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000269 if (PendingLoads.empty())
270 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000271
Chris Lattnerd3948112005-01-17 22:19:26 +0000272 if (PendingLoads.size() == 1) {
273 SDOperand Root = PendingLoads[0];
274 DAG.setRoot(Root);
275 PendingLoads.clear();
276 return Root;
277 }
278
279 // Otherwise, we have to make a token factor node.
280 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
281 PendingLoads.clear();
282 DAG.setRoot(Root);
283 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000284 }
285
Chris Lattner1c08c712005-01-07 07:47:53 +0000286 void visit(Instruction &I) { visit(I.getOpcode(), I); }
287
288 void visit(unsigned Opcode, User &I) {
289 switch (Opcode) {
290 default: assert(0 && "Unknown instruction type encountered!");
291 abort();
292 // Build the switch statement using the Instruction.def file.
293#define HANDLE_INST(NUM, OPCODE, CLASS) \
294 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
295#include "llvm/Instruction.def"
296 }
297 }
298
299 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
300
301
302 SDOperand getIntPtrConstant(uint64_t Val) {
303 return DAG.getConstant(Val, TLI.getPointerTy());
304 }
305
306 SDOperand getValue(const Value *V) {
307 SDOperand &N = NodeMap[V];
308 if (N.Val) return N;
309
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000310 const Type *VTy = V->getType();
311 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000312 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
314 visit(CE->getOpcode(), *CE);
315 assert(N.Val && "visit didn't populate the ValueMap!");
316 return N;
317 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
318 return N = DAG.getGlobalAddress(GV, VT);
319 } else if (isa<ConstantPointerNull>(C)) {
320 return N = DAG.getConstant(0, TLI.getPointerTy());
321 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000322 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000323 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
324 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000325 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
326 unsigned NumElements = PTy->getNumElements();
327 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
328 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
329
330 // Now that we know the number and type of the elements, push a
331 // Constant or ConstantFP node onto the ops list for each element of
332 // the packed constant.
333 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000334 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
335 if (MVT::isFloatingPoint(PVT)) {
336 for (unsigned i = 0; i != NumElements; ++i) {
337 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
338 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
339 }
340 } else {
341 for (unsigned i = 0; i != NumElements; ++i) {
342 const ConstantIntegral *El =
343 cast<ConstantIntegral>(CP->getOperand(i));
344 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
345 }
346 }
347 } else {
348 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
349 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000350 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000351 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000352 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000353 Op = DAG.getConstant(0, PVT);
354 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000355 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000356
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000357 // Handle the case where we have a 1-element vector, in which
358 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000359 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000360 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000361 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
362 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
363 } else {
364 // If the packed type isn't legal, then create a ConstantVec node with
365 // generic Vector type instead.
366 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
367 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000368 } else {
369 // Canonicalize all constant ints to be unsigned.
370 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
371 }
372
373 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
374 std::map<const AllocaInst*, int>::iterator SI =
375 FuncInfo.StaticAllocaMap.find(AI);
376 if (SI != FuncInfo.StaticAllocaMap.end())
377 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
378 }
379
380 std::map<const Value*, unsigned>::const_iterator VMI =
381 FuncInfo.ValueMap.find(V);
382 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000383
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000384 unsigned InReg = VMI->second;
385
386 // If this type is not legal, make it so now.
387 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
388
389 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
390 if (DestVT < VT) {
391 // Source must be expanded. This input value is actually coming from the
392 // register pair VMI->second and VMI->second+1.
393 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
394 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
395 } else {
396 if (DestVT > VT) { // Promotion case
397 if (MVT::isFloatingPoint(VT))
398 N = DAG.getNode(ISD::FP_ROUND, VT, N);
399 else
400 N = DAG.getNode(ISD::TRUNCATE, VT, N);
401 }
402 }
403
404 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000405 }
406
407 const SDOperand &setValue(const Value *V, SDOperand NewN) {
408 SDOperand &N = NodeMap[V];
409 assert(N.Val == 0 && "Already set a value for this node!");
410 return N = NewN;
411 }
412
413 // Terminator instructions.
414 void visitRet(ReturnInst &I);
415 void visitBr(BranchInst &I);
416 void visitUnreachable(UnreachableInst &I) { /* noop */ }
417
418 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000419 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000420 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000421 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
422 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
423 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
424
425 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000426 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000427 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000428 void visitAdd(User &I) {
429 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000430 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000431 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000432 void visitMul(User &I) {
433 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000434 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000435 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000436 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000437 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000438 }
439 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000440 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000441 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000442 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000443 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
444 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
445 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000446 void visitShl(User &I) { visitShift(I, ISD::SHL); }
447 void visitShr(User &I) {
448 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000449 }
450
451 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
452 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
453 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
454 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
455 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
456 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
457 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
458
459 void visitGetElementPtr(User &I);
460 void visitCast(User &I);
461 void visitSelect(User &I);
462 //
463
464 void visitMalloc(MallocInst &I);
465 void visitFree(FreeInst &I);
466 void visitAlloca(AllocaInst &I);
467 void visitLoad(LoadInst &I);
468 void visitStore(StoreInst &I);
469 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
470 void visitCall(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000471 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000472
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 void visitVAArg(VAArgInst &I);
475 void visitVAEnd(CallInst &I);
476 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000477 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000478
Chris Lattner7041ee32005-01-11 05:56:49 +0000479 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000480
481 void visitUserOp1(Instruction &I) {
482 assert(0 && "UserOp1 should not exist at instruction selection time!");
483 abort();
484 }
485 void visitUserOp2(Instruction &I) {
486 assert(0 && "UserOp2 should not exist at instruction selection time!");
487 abort();
488 }
489};
490} // end namespace llvm
491
492void SelectionDAGLowering::visitRet(ReturnInst &I) {
493 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000494 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000495 return;
496 }
497
498 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000499 MVT::ValueType TmpVT;
500
Chris Lattner1c08c712005-01-07 07:47:53 +0000501 switch (Op1.getValueType()) {
502 default: assert(0 && "Unknown value type!");
503 case MVT::i1:
504 case MVT::i8:
505 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000506 case MVT::i32:
507 // If this is a machine where 32-bits is legal or expanded, promote to
508 // 32-bits, otherwise, promote to 64-bits.
509 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
510 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000511 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000512 TmpVT = MVT::i32;
513
514 // Extend integer types to result type.
515 if (I.getOperand(0)->getType()->isSigned())
516 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
517 else
518 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000519 break;
520 case MVT::f32:
Chris Lattner4eebb602006-01-20 18:38:32 +0000521 // If this is a machine where f32 is promoted to f64, do so now.
522 if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
523 Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
524 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000525 case MVT::i64:
526 case MVT::f64:
527 break; // No extension needed!
528 }
Nate Begeman4a959452005-10-18 23:23:37 +0000529 // Allow targets to lower this further to meet ABI requirements
530 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000531}
532
533void SelectionDAGLowering::visitBr(BranchInst &I) {
534 // Update machine-CFG edges.
535 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000536
537 // Figure out which block is immediately after the current one.
538 MachineBasicBlock *NextBlock = 0;
539 MachineFunction::iterator BBI = CurMBB;
540 if (++BBI != CurMBB->getParent()->end())
541 NextBlock = BBI;
542
543 if (I.isUnconditional()) {
544 // If this is not a fall-through branch, emit the branch.
545 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000546 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000547 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000548 } else {
549 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000550
551 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000552 if (Succ1MBB == NextBlock) {
553 // If the condition is false, fall through. This means we should branch
554 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000555 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000556 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 } else if (Succ0MBB == NextBlock) {
558 // If the condition is true, fall through. This means we should branch if
559 // the condition is false to Succ #1. Invert the condition first.
560 SDOperand True = DAG.getConstant(1, Cond.getValueType());
561 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000562 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000563 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000564 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000565 std::vector<SDOperand> Ops;
566 Ops.push_back(getRoot());
567 Ops.push_back(Cond);
568 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
569 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
570 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000571 }
572 }
573}
574
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000575void SelectionDAGLowering::visitSub(User &I) {
576 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000577 if (I.getType()->isFloatingPoint()) {
578 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
579 if (CFP->isExactlyValue(-0.0)) {
580 SDOperand Op2 = getValue(I.getOperand(1));
581 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
582 return;
583 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000584 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000585 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000586}
587
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000588void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
589 unsigned VecOp) {
590 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000591 SDOperand Op1 = getValue(I.getOperand(0));
592 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000593
Chris Lattnerb67eb912005-11-19 18:40:42 +0000594 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000595 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
596 } else if (Ty->isFloatingPoint()) {
597 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
598 } else {
599 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000600 unsigned NumElements = PTy->getNumElements();
601 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000602 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000603
604 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000605 // the Legalize pass does not have to deal with them. Similarly, if the
606 // abstract vector is going to turn into one that the target natively
607 // supports, generate that type now so that Legalize doesn't have to deal
608 // with that either. These steps ensure that Legalize only has to handle
609 // vector types in its Expand case.
610 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000611 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000612 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000613 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
614 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000615 } else {
616 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
617 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000618 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000619 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000620 }
Nate Begemane21ea612005-11-18 07:42:56 +0000621}
Chris Lattner2c49f272005-01-19 22:31:21 +0000622
Nate Begemane21ea612005-11-18 07:42:56 +0000623void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
624 SDOperand Op1 = getValue(I.getOperand(0));
625 SDOperand Op2 = getValue(I.getOperand(1));
626
627 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
628
Chris Lattner1c08c712005-01-07 07:47:53 +0000629 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
630}
631
632void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
633 ISD::CondCode UnsignedOpcode) {
634 SDOperand Op1 = getValue(I.getOperand(0));
635 SDOperand Op2 = getValue(I.getOperand(1));
636 ISD::CondCode Opcode = SignedOpcode;
637 if (I.getOperand(0)->getType()->isUnsigned())
638 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000639 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000640}
641
642void SelectionDAGLowering::visitSelect(User &I) {
643 SDOperand Cond = getValue(I.getOperand(0));
644 SDOperand TrueVal = getValue(I.getOperand(1));
645 SDOperand FalseVal = getValue(I.getOperand(2));
646 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
647 TrueVal, FalseVal));
648}
649
650void SelectionDAGLowering::visitCast(User &I) {
651 SDOperand N = getValue(I.getOperand(0));
652 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
653 MVT::ValueType DestTy = TLI.getValueType(I.getType());
654
655 if (N.getValueType() == DestTy) {
656 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000657 } else if (DestTy == MVT::i1) {
658 // Cast to bool is a comparison against zero, not truncation to zero.
659 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
660 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000661 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000662 } else if (isInteger(SrcTy)) {
663 if (isInteger(DestTy)) { // Int -> Int cast
664 if (DestTy < SrcTy) // Truncating cast?
665 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
666 else if (I.getOperand(0)->getType()->isSigned())
667 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
668 else
669 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
670 } else { // Int -> FP cast
671 if (I.getOperand(0)->getType()->isSigned())
672 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
673 else
674 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
675 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000676 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000677 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
678 if (isFloatingPoint(DestTy)) { // FP -> FP cast
679 if (DestTy < SrcTy) // Rounding cast?
680 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
681 else
682 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
683 } else { // FP -> Int cast.
684 if (I.getType()->isSigned())
685 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
686 else
687 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
688 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000689 }
690}
691
692void SelectionDAGLowering::visitGetElementPtr(User &I) {
693 SDOperand N = getValue(I.getOperand(0));
694 const Type *Ty = I.getOperand(0)->getType();
695 const Type *UIntPtrTy = TD.getIntPtrType();
696
697 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
698 OI != E; ++OI) {
699 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000700 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000701 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
702 if (Field) {
703 // N = N + Offset
704 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
705 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000706 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 }
708 Ty = StTy->getElementType(Field);
709 } else {
710 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000711
Chris Lattner7c0104b2005-11-09 04:45:33 +0000712 // If this is a constant subscript, handle it quickly.
713 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
714 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000715
Chris Lattner7c0104b2005-11-09 04:45:33 +0000716 uint64_t Offs;
717 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
718 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
719 else
720 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
721 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
722 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000723 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000724
725 // N = N + Idx * ElementSize;
726 uint64_t ElementSize = TD.getTypeSize(Ty);
727 SDOperand IdxN = getValue(Idx);
728
729 // If the index is smaller or larger than intptr_t, truncate or extend
730 // it.
731 if (IdxN.getValueType() < N.getValueType()) {
732 if (Idx->getType()->isSigned())
733 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
734 else
735 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
736 } else if (IdxN.getValueType() > N.getValueType())
737 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
738
739 // If this is a multiply by a power of two, turn it into a shl
740 // immediately. This is a very common case.
741 if (isPowerOf2_64(ElementSize)) {
742 unsigned Amt = Log2_64(ElementSize);
743 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000744 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000745 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
746 continue;
747 }
748
749 SDOperand Scale = getIntPtrConstant(ElementSize);
750 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
751 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000752 }
753 }
754 setValue(&I, N);
755}
756
757void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
758 // If this is a fixed sized alloca in the entry block of the function,
759 // allocate it statically on the stack.
760 if (FuncInfo.StaticAllocaMap.count(&I))
761 return; // getValue will auto-populate this.
762
763 const Type *Ty = I.getAllocatedType();
764 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000765 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
766 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000767
768 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000769 MVT::ValueType IntPtr = TLI.getPointerTy();
770 if (IntPtr < AllocSize.getValueType())
771 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
772 else if (IntPtr > AllocSize.getValueType())
773 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000774
Chris Lattner68cd65e2005-01-22 23:04:37 +0000775 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000776 getIntPtrConstant(TySize));
777
778 // Handle alignment. If the requested alignment is less than or equal to the
779 // stack alignment, ignore it and round the size of the allocation up to the
780 // stack alignment size. If the size is greater than the stack alignment, we
781 // note this in the DYNAMIC_STACKALLOC node.
782 unsigned StackAlign =
783 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
784 if (Align <= StackAlign) {
785 Align = 0;
786 // Add SA-1 to the size.
787 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
788 getIntPtrConstant(StackAlign-1));
789 // Mask out the low bits for alignment purposes.
790 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
791 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
792 }
793
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000794 std::vector<MVT::ValueType> VTs;
795 VTs.push_back(AllocSize.getValueType());
796 VTs.push_back(MVT::Other);
797 std::vector<SDOperand> Ops;
798 Ops.push_back(getRoot());
799 Ops.push_back(AllocSize);
800 Ops.push_back(getIntPtrConstant(Align));
801 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000802 DAG.setRoot(setValue(&I, DSA).getValue(1));
803
804 // Inform the Frame Information that we have just allocated a variable-sized
805 // object.
806 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
807}
808
Chris Lattner36ce6912005-11-29 06:21:05 +0000809/// getStringValue - Turn an LLVM constant pointer that eventually points to a
810/// global into a string value. Return an empty string if we can't do it.
811///
812static std::string getStringValue(Value *V, unsigned Offset = 0) {
813 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
814 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
815 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
816 if (Init->isString()) {
817 std::string Result = Init->getAsString();
818 if (Offset < Result.size()) {
819 // If we are pointing INTO The string, erase the beginning...
820 Result.erase(Result.begin(), Result.begin()+Offset);
821
822 // Take off the null terminator, and any string fragments after it.
823 std::string::size_type NullPos = Result.find_first_of((char)0);
824 if (NullPos != std::string::npos)
825 Result.erase(Result.begin()+NullPos, Result.end());
826 return Result;
827 }
828 }
829 }
830 } else if (Constant *C = dyn_cast<Constant>(V)) {
831 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
832 return getStringValue(GV, Offset);
833 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
834 if (CE->getOpcode() == Instruction::GetElementPtr) {
835 // Turn a gep into the specified offset.
836 if (CE->getNumOperands() == 3 &&
837 cast<Constant>(CE->getOperand(1))->isNullValue() &&
838 isa<ConstantInt>(CE->getOperand(2))) {
839 return getStringValue(CE->getOperand(0),
840 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
841 }
842 }
843 }
844 }
845 return "";
846}
Chris Lattner1c08c712005-01-07 07:47:53 +0000847
848void SelectionDAGLowering::visitLoad(LoadInst &I) {
849 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000850
Chris Lattnerd3948112005-01-17 22:19:26 +0000851 SDOperand Root;
852 if (I.isVolatile())
853 Root = getRoot();
854 else {
855 // Do not serialize non-volatile loads against each other.
856 Root = DAG.getRoot();
857 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000858
859 const Type *Ty = I.getType();
860 SDOperand L;
861
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000862 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000863 unsigned NumElements = PTy->getNumElements();
864 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000865 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000866
867 // Immediately scalarize packed types containing only one element, so that
868 // the Legalize pass does not have to deal with them.
869 if (NumElements == 1) {
870 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000871 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
872 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000873 } else {
874 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
875 DAG.getSrcValue(I.getOperand(0)));
876 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000877 } else {
878 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
879 DAG.getSrcValue(I.getOperand(0)));
880 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000881 setValue(&I, L);
882
883 if (I.isVolatile())
884 DAG.setRoot(L.getValue(1));
885 else
886 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000887}
888
889
890void SelectionDAGLowering::visitStore(StoreInst &I) {
891 Value *SrcV = I.getOperand(0);
892 SDOperand Src = getValue(SrcV);
893 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000894 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000895 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000896}
897
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000898/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
899/// we want to emit this as a call to a named external function, return the name
900/// otherwise lower it and return null.
901const char *
902SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
903 switch (Intrinsic) {
904 case Intrinsic::vastart: visitVAStart(I); return 0;
905 case Intrinsic::vaend: visitVAEnd(I); return 0;
906 case Intrinsic::vacopy: visitVACopy(I); return 0;
907 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
908 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
909 case Intrinsic::setjmp:
910 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
911 break;
912 case Intrinsic::longjmp:
913 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
914 break;
915 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
916 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
917 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
918
919 case Intrinsic::readport:
920 case Intrinsic::readio: {
921 std::vector<MVT::ValueType> VTs;
922 VTs.push_back(TLI.getValueType(I.getType()));
923 VTs.push_back(MVT::Other);
924 std::vector<SDOperand> Ops;
925 Ops.push_back(getRoot());
926 Ops.push_back(getValue(I.getOperand(1)));
927 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
928 ISD::READPORT : ISD::READIO, VTs, Ops);
929
930 setValue(&I, Tmp);
931 DAG.setRoot(Tmp.getValue(1));
932 return 0;
933 }
934 case Intrinsic::writeport:
935 case Intrinsic::writeio:
936 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
937 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
938 getRoot(), getValue(I.getOperand(1)),
939 getValue(I.getOperand(2))));
940 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000941
Chris Lattner86cb6432005-12-13 17:40:33 +0000942 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000943 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
944 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000945
946 std::string fname = "<unknown>";
947 std::vector<SDOperand> Ops;
948
Chris Lattner36ce6912005-11-29 06:21:05 +0000949 // Input Chain
950 Ops.push_back(getRoot());
951
952 // line number
953 Ops.push_back(getValue(I.getOperand(2)));
954
955 // column
956 Ops.push_back(getValue(I.getOperand(3)));
957
Chris Lattner86cb6432005-12-13 17:40:33 +0000958 // filename/working dir
959 // Pull the filename out of the the compilation unit.
960 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
961 if (cunit && cunit->hasInitializer()) {
962 if (ConstantStruct *CS =
963 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
964 if (CS->getNumOperands() > 0) {
Chris Lattner86cb6432005-12-13 17:40:33 +0000965 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskeyf5395ce2005-12-16 22:45:29 +0000966 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner86cb6432005-12-13 17:40:33 +0000967 }
968 }
969 }
970
971 if (Ops.size() == 5) // Found filename/workingdir.
972 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000973 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000974 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000975 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000976 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000977 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
978 return "llvm_dbg_region_start";
979 if (I.getType() != Type::VoidTy)
980 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
981 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000982 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000983 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
984 return "llvm_dbg_region_end";
985 if (I.getType() != Type::VoidTy)
986 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
987 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000988 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000989 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
990 return "llvm_dbg_subprogram";
991 if (I.getType() != Type::VoidTy)
992 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
993 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000994 case Intrinsic::dbg_declare:
995 if (I.getType() != Type::VoidTy)
996 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
997 return 0;
998
Reid Spencer0b118202006-01-16 21:12:35 +0000999 case Intrinsic::isunordered_f32:
1000 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001001 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1002 getValue(I.getOperand(2)), ISD::SETUO));
1003 return 0;
1004
Reid Spencer0b118202006-01-16 21:12:35 +00001005 case Intrinsic::sqrt_f32:
1006 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001007 setValue(&I, DAG.getNode(ISD::FSQRT,
1008 getValue(I.getOperand(1)).getValueType(),
1009 getValue(I.getOperand(1))));
1010 return 0;
1011 case Intrinsic::pcmarker: {
1012 SDOperand Tmp = getValue(I.getOperand(1));
1013 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1014 return 0;
1015 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001016 case Intrinsic::readcyclecounter: {
1017 std::vector<MVT::ValueType> VTs;
1018 VTs.push_back(MVT::i64);
1019 VTs.push_back(MVT::Other);
1020 std::vector<SDOperand> Ops;
1021 Ops.push_back(getRoot());
1022 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1023 setValue(&I, Tmp);
1024 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001025 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001026 }
Nate Begemand88fc032006-01-14 03:14:10 +00001027 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001028 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001029 case Intrinsic::bswap_i64:
1030 setValue(&I, DAG.getNode(ISD::BSWAP,
1031 getValue(I.getOperand(1)).getValueType(),
1032 getValue(I.getOperand(1))));
1033 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001034 case Intrinsic::cttz_i8:
1035 case Intrinsic::cttz_i16:
1036 case Intrinsic::cttz_i32:
1037 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001038 setValue(&I, DAG.getNode(ISD::CTTZ,
1039 getValue(I.getOperand(1)).getValueType(),
1040 getValue(I.getOperand(1))));
1041 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001042 case Intrinsic::ctlz_i8:
1043 case Intrinsic::ctlz_i16:
1044 case Intrinsic::ctlz_i32:
1045 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001046 setValue(&I, DAG.getNode(ISD::CTLZ,
1047 getValue(I.getOperand(1)).getValueType(),
1048 getValue(I.getOperand(1))));
1049 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001050 case Intrinsic::ctpop_i8:
1051 case Intrinsic::ctpop_i16:
1052 case Intrinsic::ctpop_i32:
1053 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001054 setValue(&I, DAG.getNode(ISD::CTPOP,
1055 getValue(I.getOperand(1)).getValueType(),
1056 getValue(I.getOperand(1))));
1057 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001058 case Intrinsic::stacksave: {
1059 std::vector<MVT::ValueType> VTs;
1060 VTs.push_back(TLI.getPointerTy());
1061 VTs.push_back(MVT::Other);
1062 std::vector<SDOperand> Ops;
1063 Ops.push_back(getRoot());
1064 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1065 setValue(&I, Tmp);
1066 DAG.setRoot(Tmp.getValue(1));
1067 return 0;
1068 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001069 case Intrinsic::stackrestore: {
1070 SDOperand Tmp = getValue(I.getOperand(1));
1071 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001072 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001073 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001074 case Intrinsic::prefetch:
1075 // FIXME: Currently discarding prefetches.
1076 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001077 default:
1078 std::cerr << I;
1079 assert(0 && "This intrinsic is not implemented yet!");
1080 return 0;
1081 }
1082}
1083
1084
Chris Lattner1c08c712005-01-07 07:47:53 +00001085void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001086 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001087 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001088 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001089 if (unsigned IID = F->getIntrinsicID()) {
1090 RenameFn = visitIntrinsicCall(I, IID);
1091 if (!RenameFn)
1092 return;
1093 } else { // Not an LLVM intrinsic.
1094 const std::string &Name = F->getName();
1095 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001096 if (I.getNumOperands() == 2 && // Basic sanity checks.
1097 I.getOperand(1)->getType()->isFloatingPoint() &&
1098 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001099 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001100 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1101 return;
1102 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001103 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001104 if (I.getNumOperands() == 2 && // Basic sanity checks.
1105 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001106 I.getType() == I.getOperand(1)->getType() &&
1107 TLI.isOperationLegal(ISD::FSIN,
1108 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001109 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001110 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1111 return;
1112 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001113 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001114 if (I.getNumOperands() == 2 && // Basic sanity checks.
1115 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001116 I.getType() == I.getOperand(1)->getType() &&
1117 TLI.isOperationLegal(ISD::FCOS,
1118 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001119 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001120 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1121 return;
1122 }
1123 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001124 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001125 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001126
Chris Lattner64e14b12005-01-08 22:48:57 +00001127 SDOperand Callee;
1128 if (!RenameFn)
1129 Callee = getValue(I.getOperand(0));
1130 else
1131 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001132 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001133 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001134 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1135 Value *Arg = I.getOperand(i);
1136 SDOperand ArgNode = getValue(Arg);
1137 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1138 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001139
Nate Begeman8e21e712005-03-26 01:29:23 +00001140 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1141 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001142
Chris Lattnercf5734d2005-01-08 19:26:18 +00001143 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001144 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001145 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001146 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001147 setValue(&I, Result.first);
1148 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001149}
1150
1151void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1152 SDOperand Src = getValue(I.getOperand(0));
1153
1154 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001155
1156 if (IntPtr < Src.getValueType())
1157 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1158 else if (IntPtr > Src.getValueType())
1159 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001160
1161 // Scale the source by the type size.
1162 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1163 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1164 Src, getIntPtrConstant(ElementSize));
1165
1166 std::vector<std::pair<SDOperand, const Type*> > Args;
1167 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001168
1169 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001170 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001171 DAG.getExternalSymbol("malloc", IntPtr),
1172 Args, DAG);
1173 setValue(&I, Result.first); // Pointers always fit in registers
1174 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001175}
1176
1177void SelectionDAGLowering::visitFree(FreeInst &I) {
1178 std::vector<std::pair<SDOperand, const Type*> > Args;
1179 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1180 TLI.getTargetData().getIntPtrType()));
1181 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001182 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001183 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001184 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1185 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001186}
1187
Chris Lattner025c39b2005-08-26 20:54:47 +00001188// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1189// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1190// instructions are special in various ways, which require special support to
1191// insert. The specified MachineInstr is created but not inserted into any
1192// basic blocks, and the scheduler passes ownership of it to this method.
1193MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1194 MachineBasicBlock *MBB) {
1195 std::cerr << "If a target marks an instruction with "
1196 "'usesCustomDAGSchedInserter', it must implement "
1197 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1198 abort();
1199 return 0;
1200}
1201
Nate Begeman4a959452005-10-18 23:23:37 +00001202SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1203 SelectionDAG &DAG) {
1204 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1205}
1206
Chris Lattnere64e72b2005-07-05 19:57:53 +00001207SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1208 SDOperand VAListP, Value *VAListV,
1209 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001210 // We have no sane default behavior, just emit a useful error message and bail
1211 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +00001212 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00001213 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +00001214 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +00001215}
1216
Chris Lattnere64e72b2005-07-05 19:57:53 +00001217SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +00001218 SelectionDAG &DAG) {
1219 // Default to a noop.
1220 return Chain;
1221}
1222
Chris Lattnere64e72b2005-07-05 19:57:53 +00001223SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1224 SDOperand SrcP, Value *SrcV,
1225 SDOperand DestP, Value *DestV,
1226 SelectionDAG &DAG) {
1227 // Default to copying the input list.
1228 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1229 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001230 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001231 Val, DestP, DAG.getSrcValue(DestV));
1232 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +00001233}
1234
1235std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +00001236TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1237 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +00001238 // We have no sane default behavior, just emit a useful error message and bail
1239 // out.
1240 std::cerr << "Variable arguments handling not implemented on this target!\n";
1241 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001242 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +00001243}
1244
1245
1246void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001247 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1248 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +00001249}
1250
1251void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1252 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +00001253 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +00001254 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001255 setValue(&I, Result.first);
1256 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001257}
1258
1259void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001260 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001261 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +00001262}
1263
1264void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001265 SDOperand Result =
1266 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1267 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1268 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +00001269}
1270
Chris Lattner39ae3622005-01-09 00:00:49 +00001271
1272// It is always conservatively correct for llvm.returnaddress and
1273// llvm.frameaddress to return 0.
1274std::pair<SDOperand, SDOperand>
1275TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1276 unsigned Depth, SelectionDAG &DAG) {
1277 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001278}
1279
Chris Lattner50381b62005-05-14 05:50:48 +00001280SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001281 assert(0 && "LowerOperation not implemented for this target!");
1282 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001283 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001284}
1285
Chris Lattner39ae3622005-01-09 00:00:49 +00001286void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1287 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1288 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001289 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001290 setValue(&I, Result.first);
1291 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001292}
1293
Chris Lattner7041ee32005-01-11 05:56:49 +00001294void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer6ff72402005-11-30 05:21:10 +00001295#if 0
1296 // If the size of the cpy/move/set is constant (known)
1297 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1298 uint64_t size = op3->getValue();
1299 switch (Op) {
1300 case ISD::MEMSET:
1301 if (size <= TLI.getMaxStoresPerMemSet()) {
1302 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1303 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1304 uint64_t align = op4.getValue();
1305 while (size > align) {
1306 size -=align;
1307 }
1308 Value *SrcV = I.getOperand(0);
1309 SDOperand Src = getValue(SrcV);
1310 SDOperand Ptr = getValue(I.getOperand(1));
1311 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1312 DAG.getSrcValue(I.getOperand(1))));
1313 }
1314 break;
1315 }
1316 break; // don't do this optimization, use a normal memset
1317 case ISD::MEMMOVE:
1318 case ISD::MEMCPY:
1319 break; // FIXME: not implemented yet
1320 }
1321 }
1322#endif
1323
1324 // Non-optimized version
Chris Lattner7041ee32005-01-11 05:56:49 +00001325 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001326 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +00001327 Ops.push_back(getValue(I.getOperand(1)));
1328 Ops.push_back(getValue(I.getOperand(2)));
1329 Ops.push_back(getValue(I.getOperand(3)));
1330 Ops.push_back(getValue(I.getOperand(4)));
1331 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001332}
1333
Chris Lattner7041ee32005-01-11 05:56:49 +00001334//===----------------------------------------------------------------------===//
1335// SelectionDAGISel code
1336//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001337
1338unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1339 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1340}
1341
Chris Lattner495a0b52005-08-17 06:37:43 +00001342void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001343 // FIXME: we only modify the CFG to split critical edges. This
1344 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001345}
Chris Lattner1c08c712005-01-07 07:47:53 +00001346
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001347
1348/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1349/// casting to the type of GEPI.
1350static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1351 Value *Ptr, Value *PtrOffset) {
1352 if (V) return V; // Already computed.
1353
1354 BasicBlock::iterator InsertPt;
1355 if (BB == GEPI->getParent()) {
1356 // If insert into the GEP's block, insert right after the GEP.
1357 InsertPt = GEPI;
1358 ++InsertPt;
1359 } else {
1360 // Otherwise, insert at the top of BB, after any PHI nodes
1361 InsertPt = BB->begin();
1362 while (isa<PHINode>(InsertPt)) ++InsertPt;
1363 }
1364
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001365 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1366 // BB so that there is only one value live across basic blocks (the cast
1367 // operand).
1368 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1369 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1370 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1371
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001372 // Add the offset, cast it to the right type.
1373 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1374 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1375 return V = Ptr;
1376}
1377
1378
1379/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1380/// selection, we want to be a bit careful about some things. In particular, if
1381/// we have a GEP instruction that is used in a different block than it is
1382/// defined, the addressing expression of the GEP cannot be folded into loads or
1383/// stores that use it. In this case, decompose the GEP and move constant
1384/// indices into blocks that use it.
1385static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1386 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001387 // If this GEP is only used inside the block it is defined in, there is no
1388 // need to rewrite it.
1389 bool isUsedOutsideDefBB = false;
1390 BasicBlock *DefBB = GEPI->getParent();
1391 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1392 UI != E; ++UI) {
1393 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1394 isUsedOutsideDefBB = true;
1395 break;
1396 }
1397 }
1398 if (!isUsedOutsideDefBB) return;
1399
1400 // If this GEP has no non-zero constant indices, there is nothing we can do,
1401 // ignore it.
1402 bool hasConstantIndex = false;
1403 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1404 E = GEPI->op_end(); OI != E; ++OI) {
1405 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1406 if (CI->getRawValue()) {
1407 hasConstantIndex = true;
1408 break;
1409 }
1410 }
Chris Lattner3802c252005-12-11 09:05:13 +00001411 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1412 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001413
1414 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1415 // constant offset (which we now know is non-zero) and deal with it later.
1416 uint64_t ConstantOffset = 0;
1417 const Type *UIntPtrTy = TD.getIntPtrType();
1418 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1419 const Type *Ty = GEPI->getOperand(0)->getType();
1420
1421 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1422 E = GEPI->op_end(); OI != E; ++OI) {
1423 Value *Idx = *OI;
1424 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1425 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1426 if (Field)
1427 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1428 Ty = StTy->getElementType(Field);
1429 } else {
1430 Ty = cast<SequentialType>(Ty)->getElementType();
1431
1432 // Handle constant subscripts.
1433 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1434 if (CI->getRawValue() == 0) continue;
1435
1436 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1437 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1438 else
1439 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1440 continue;
1441 }
1442
1443 // Ptr = Ptr + Idx * ElementSize;
1444
1445 // Cast Idx to UIntPtrTy if needed.
1446 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1447
1448 uint64_t ElementSize = TD.getTypeSize(Ty);
1449 // Mask off bits that should not be set.
1450 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1451 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1452
1453 // Multiply by the element size and add to the base.
1454 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1455 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1456 }
1457 }
1458
1459 // Make sure that the offset fits in uintptr_t.
1460 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1461 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1462
1463 // Okay, we have now emitted all of the variable index parts to the BB that
1464 // the GEP is defined in. Loop over all of the using instructions, inserting
1465 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001466 // instruction to use the newly computed value, making GEPI dead. When the
1467 // user is a load or store instruction address, we emit the add into the user
1468 // block, otherwise we use a canonical version right next to the gep (these
1469 // won't be foldable as addresses, so we might as well share the computation).
1470
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001471 std::map<BasicBlock*,Value*> InsertedExprs;
1472 while (!GEPI->use_empty()) {
1473 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001474
1475 // If this use is not foldable into the addressing mode, use a version
1476 // emitted in the GEP block.
1477 Value *NewVal;
1478 if (!isa<LoadInst>(User) &&
1479 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1480 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1481 Ptr, PtrOffset);
1482 } else {
1483 // Otherwise, insert the code in the User's block so it can be folded into
1484 // any users in that block.
1485 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001486 User->getParent(), GEPI,
1487 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001488 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001489 User->replaceUsesOfWith(GEPI, NewVal);
1490 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001491
1492 // Finally, the GEP is dead, remove it.
1493 GEPI->eraseFromParent();
1494}
1495
Chris Lattner1c08c712005-01-07 07:47:53 +00001496bool SelectionDAGISel::runOnFunction(Function &Fn) {
1497 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1498 RegMap = MF.getSSARegMap();
1499 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1500
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001501 // First, split all critical edges for PHI nodes with incoming values that are
1502 // constants, this way the load of the constant into a vreg will not be placed
1503 // into MBBs that are used some other way.
1504 //
1505 // In this pass we also look for GEP instructions that are used across basic
1506 // blocks and rewrites them to improve basic-block-at-a-time selection.
1507 //
Chris Lattner36b708f2005-08-18 17:35:14 +00001508 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1509 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001510 BasicBlock::iterator BBI;
1511 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00001512 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1513 if (isa<Constant>(PN->getIncomingValue(i)))
1514 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001515
1516 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1517 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1518 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00001519 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001520
Chris Lattner1c08c712005-01-07 07:47:53 +00001521 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1522
1523 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1524 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001525
Chris Lattner1c08c712005-01-07 07:47:53 +00001526 return true;
1527}
1528
1529
Chris Lattnerddb870b2005-01-13 17:59:43 +00001530SDOperand SelectionDAGISel::
1531CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001532 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001533 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001534 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001535 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001536
1537 // If this type is not legal, we must make sure to not create an invalid
1538 // register use.
1539 MVT::ValueType SrcVT = Op.getValueType();
1540 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1541 SelectionDAG &DAG = SDL.DAG;
1542 if (SrcVT == DestVT) {
1543 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1544 } else if (SrcVT < DestVT) {
1545 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001546 if (MVT::isFloatingPoint(SrcVT))
1547 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1548 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001549 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001550 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1551 } else {
1552 // The src value is expanded into multiple registers.
1553 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1554 Op, DAG.getConstant(0, MVT::i32));
1555 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1556 Op, DAG.getConstant(1, MVT::i32));
1557 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1558 return DAG.getCopyToReg(Op, Reg+1, Hi);
1559 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001560}
1561
Chris Lattner068a81e2005-01-17 17:15:02 +00001562void SelectionDAGISel::
1563LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1564 std::vector<SDOperand> &UnorderedChains) {
1565 // If this is the entry block, emit arguments.
1566 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001567 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00001568 SDOperand OldRoot = SDL.DAG.getRoot();
1569 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00001570
Chris Lattnerbf209482005-10-30 19:42:35 +00001571 unsigned a = 0;
1572 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1573 AI != E; ++AI, ++a)
1574 if (!AI->use_empty()) {
1575 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00001576
Chris Lattnerbf209482005-10-30 19:42:35 +00001577 // If this argument is live outside of the entry block, insert a copy from
1578 // whereever we got it to the vreg that other BB's will reference it as.
1579 if (FuncInfo.ValueMap.count(AI)) {
1580 SDOperand Copy =
1581 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1582 UnorderedChains.push_back(Copy);
1583 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00001584 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001585
1586 // Next, if the function has live ins that need to be copied into vregs,
1587 // emit the copies now, into the top of the block.
1588 MachineFunction &MF = SDL.DAG.getMachineFunction();
1589 if (MF.livein_begin() != MF.livein_end()) {
1590 SSARegMap *RegMap = MF.getSSARegMap();
1591 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1592 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1593 E = MF.livein_end(); LI != E; ++LI)
1594 if (LI->second)
1595 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1596 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00001597 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001598
1599 // Finally, if the target has anything special to do, allow it to do so.
1600 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00001601}
1602
1603
Chris Lattner1c08c712005-01-07 07:47:53 +00001604void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1605 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1606 FunctionLoweringInfo &FuncInfo) {
1607 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001608
1609 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001610
Chris Lattnerbf209482005-10-30 19:42:35 +00001611 // Lower any arguments needed in this block if this is the entry block.
1612 if (LLVMBB == &LLVMBB->getParent()->front())
1613 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001614
1615 BB = FuncInfo.MBBMap[LLVMBB];
1616 SDL.setCurrentBasicBlock(BB);
1617
1618 // Lower all of the non-terminator instructions.
1619 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1620 I != E; ++I)
1621 SDL.visit(*I);
1622
1623 // Ensure that all instructions which are used outside of their defining
1624 // blocks are available as virtual registers.
1625 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001626 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001627 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001628 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001629 UnorderedChains.push_back(
1630 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001631 }
1632
1633 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1634 // ensure constants are generated when needed. Remember the virtual registers
1635 // that need to be added to the Machine PHI nodes as input. We cannot just
1636 // directly add them, because expansion might result in multiple MBB's for one
1637 // BB. As such, the start of the BB might correspond to a different MBB than
1638 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001639 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001640
1641 // Emit constants only once even if used by multiple PHI nodes.
1642 std::map<Constant*, unsigned> ConstantsOut;
1643
1644 // Check successor nodes PHI nodes that expect a constant to be available from
1645 // this block.
1646 TerminatorInst *TI = LLVMBB->getTerminator();
1647 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1648 BasicBlock *SuccBB = TI->getSuccessor(succ);
1649 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1650 PHINode *PN;
1651
1652 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1653 // nodes and Machine PHI nodes, but the incoming operands have not been
1654 // emitted yet.
1655 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001656 (PN = dyn_cast<PHINode>(I)); ++I)
1657 if (!PN->use_empty()) {
1658 unsigned Reg;
1659 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1660 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1661 unsigned &RegOut = ConstantsOut[C];
1662 if (RegOut == 0) {
1663 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001664 UnorderedChains.push_back(
1665 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001666 }
1667 Reg = RegOut;
1668 } else {
1669 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001670 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001671 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001672 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1673 "Didn't codegen value into a register!??");
1674 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001675 UnorderedChains.push_back(
1676 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001677 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001678 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001679
Chris Lattnerf44fd882005-01-07 21:34:19 +00001680 // Remember that this register needs to added to the machine PHI node as
1681 // the input for this MBB.
1682 unsigned NumElements =
1683 TLI.getNumElements(TLI.getValueType(PN->getType()));
1684 for (unsigned i = 0, e = NumElements; i != e; ++i)
1685 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001686 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001687 }
1688 ConstantsOut.clear();
1689
Chris Lattnerddb870b2005-01-13 17:59:43 +00001690 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001691 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00001692 SDOperand Root = SDL.getRoot();
1693 if (Root.getOpcode() != ISD::EntryToken) {
1694 unsigned i = 0, e = UnorderedChains.size();
1695 for (; i != e; ++i) {
1696 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1697 if (UnorderedChains[i].Val->getOperand(0) == Root)
1698 break; // Don't add the root if we already indirectly depend on it.
1699 }
1700
1701 if (i == e)
1702 UnorderedChains.push_back(Root);
1703 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00001704 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1705 }
1706
Chris Lattner1c08c712005-01-07 07:47:53 +00001707 // Lower the terminator after the copies are emitted.
1708 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001709
1710 // Make sure the root of the DAG is up-to-date.
1711 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001712}
1713
1714void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1715 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00001716 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00001717 CurDAG = &DAG;
1718 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1719
1720 // First step, lower LLVM code to some DAG. This DAG may use operations and
1721 // types that are not supported by the target.
1722 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1723
Chris Lattneraf21d552005-10-10 16:47:10 +00001724 // Run the DAG combiner in pre-legalize mode.
1725 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00001726
Chris Lattner1c08c712005-01-07 07:47:53 +00001727 DEBUG(std::cerr << "Lowered selection DAG:\n");
1728 DEBUG(DAG.dump());
1729
1730 // Second step, hack on the DAG until it only uses operations and types that
1731 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001732 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001733
1734 DEBUG(std::cerr << "Legalized selection DAG:\n");
1735 DEBUG(DAG.dump());
1736
Chris Lattneraf21d552005-10-10 16:47:10 +00001737 // Run the DAG combiner in post-legalize mode.
1738 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00001739
Evan Chenga9c20912006-01-21 02:32:06 +00001740 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00001741
Chris Lattnera33ef482005-03-30 01:10:47 +00001742 // Third, instruction select all of the operations to machine code, adding the
1743 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001744 InstructionSelectBasicBlock(DAG);
1745
Chris Lattner1c08c712005-01-07 07:47:53 +00001746 DEBUG(std::cerr << "Selected machine code:\n");
1747 DEBUG(BB->dump());
1748
Chris Lattnera33ef482005-03-30 01:10:47 +00001749 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001750 // PHI nodes in successors.
1751 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1752 MachineInstr *PHI = PHINodesToUpdate[i].first;
1753 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1754 "This is not a machine PHI node that we are updating!");
1755 PHI->addRegOperand(PHINodesToUpdate[i].second);
1756 PHI->addMachineBasicBlockOperand(BB);
1757 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001758
1759 // Finally, add the CFG edges from the last selected MBB to the successor
1760 // MBBs.
1761 TerminatorInst *TI = LLVMBB->getTerminator();
1762 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1763 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1764 BB->addSuccessor(Succ0MBB);
1765 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001766}
Evan Chenga9c20912006-01-21 02:32:06 +00001767
1768//===----------------------------------------------------------------------===//
1769/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1770/// target node in the graph.
1771void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1772 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00001773 ScheduleDAG *SL = NULL;
1774
1775 switch (ISHeuristic) {
1776 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00001777 case defaultScheduling:
1778 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
1779 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
1780 else /* TargetLowering::SchedulingForRegPressure */
1781 SL = createBURRListDAGScheduler(DAG, BB);
1782 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00001783 case noScheduling:
1784 case simpleScheduling:
1785 case simpleNoItinScheduling:
1786 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
1787 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00001788 case listSchedulingBURR:
1789 SL = createBURRListDAGScheduler(DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00001790 }
Chris Lattnera3818e62006-01-21 19:12:11 +00001791 BB = SL->Run();
Evan Chenga9c20912006-01-21 02:32:06 +00001792}