blob: 6cc4d436e903877777f92198f11a3757c2baf6db [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"),
62 cl::init(noScheduling),
63 cl::values(
64 clEnumValN(noScheduling, "none",
65 "No scheduling: breath first sequencing"),
66 clEnumValN(simpleScheduling, "simple",
67 "Simple two pass scheduling: minimize critical path "
68 "and maximize processor utilization"),
69 clEnumValN(simpleNoItinScheduling, "simple-noitin",
70 "Simple two pass scheduling: Same as simple "
71 "except using generic latency"),
Evan Chengf0f9c902006-01-23 08:26:10 +000072 clEnumValN(listSchedulingBURR, "list-BURR",
73 "Bottom up register reduction list scheduling"),
Evan Cheng4ef10862006-01-23 07:01:07 +000074 clEnumValEnd));
75} // namespace
76
77
Chris Lattner1c08c712005-01-07 07:47:53 +000078namespace llvm {
79 //===--------------------------------------------------------------------===//
80 /// FunctionLoweringInfo - This contains information that is global to a
81 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000082 class FunctionLoweringInfo {
83 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000084 TargetLowering &TLI;
85 Function &Fn;
86 MachineFunction &MF;
87 SSARegMap *RegMap;
88
89 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
90
91 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
92 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
93
94 /// ValueMap - Since we emit code for the function a basic block at a time,
95 /// we must remember which virtual registers hold the values for
96 /// cross-basic-block values.
97 std::map<const Value*, unsigned> ValueMap;
98
99 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
100 /// the entry block. This allows the allocas to be efficiently referenced
101 /// anywhere in the function.
102 std::map<const AllocaInst*, int> StaticAllocaMap;
103
104 unsigned MakeReg(MVT::ValueType VT) {
105 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
106 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000107
Chris Lattner1c08c712005-01-07 07:47:53 +0000108 unsigned CreateRegForValue(const Value *V) {
109 MVT::ValueType VT = TLI.getValueType(V->getType());
110 // The common case is that we will only create one register for this
111 // value. If we have that case, create and return the virtual register.
112 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000113 if (NV == 1) {
114 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000115 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000116 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000117
Chris Lattner1c08c712005-01-07 07:47:53 +0000118 // If this value is represented with multiple target registers, make sure
119 // to create enough consequtive registers of the right (smaller) type.
120 unsigned NT = VT-1; // Find the type to use.
121 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
122 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000123
Chris Lattner1c08c712005-01-07 07:47:53 +0000124 unsigned R = MakeReg((MVT::ValueType)NT);
125 for (unsigned i = 1; i != NV; ++i)
126 MakeReg((MVT::ValueType)NT);
127 return R;
128 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000129
Chris Lattner1c08c712005-01-07 07:47:53 +0000130 unsigned InitializeRegForValue(const Value *V) {
131 unsigned &R = ValueMap[V];
132 assert(R == 0 && "Already initialized this value register!");
133 return R = CreateRegForValue(V);
134 }
135 };
136}
137
138/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
139/// PHI nodes or outside of the basic block that defines it.
140static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
141 if (isa<PHINode>(I)) return true;
142 BasicBlock *BB = I->getParent();
143 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
144 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
145 return true;
146 return false;
147}
148
Chris Lattnerbf209482005-10-30 19:42:35 +0000149/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
150/// entry block, return true.
151static bool isOnlyUsedInEntryBlock(Argument *A) {
152 BasicBlock *Entry = A->getParent()->begin();
153 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
154 if (cast<Instruction>(*UI)->getParent() != Entry)
155 return false; // Use not in entry block.
156 return true;
157}
158
Chris Lattner1c08c712005-01-07 07:47:53 +0000159FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000160 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
162
Chris Lattnerbf209482005-10-30 19:42:35 +0000163 // Create a vreg for each argument register that is not dead and is used
164 // outside of the entry block for the function.
165 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
166 AI != E; ++AI)
167 if (!isOnlyUsedInEntryBlock(AI))
168 InitializeRegForValue(AI);
169
Chris Lattner1c08c712005-01-07 07:47:53 +0000170 // Initialize the mapping of values to registers. This is only set up for
171 // instruction values that are used outside of the block that defines
172 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000173 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
175 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
176 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
177 const Type *Ty = AI->getAllocatedType();
178 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000179 unsigned Align =
180 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
181 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000182
183 // If the alignment of the value is smaller than the size of the value,
184 // and if the size of the value is particularly small (<= 8 bytes),
185 // round up to the size of the value for potentially better performance.
186 //
187 // FIXME: This could be made better with a preferred alignment hook in
188 // TargetData. It serves primarily to 8-byte align doubles for X86.
189 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000190 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000191 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000192 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000193 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 }
195
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000196 for (; BB != EB; ++BB)
197 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000198 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
199 if (!isa<AllocaInst>(I) ||
200 !StaticAllocaMap.count(cast<AllocaInst>(I)))
201 InitializeRegForValue(I);
202
203 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
204 // also creates the initial PHI MachineInstrs, though none of the input
205 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000206 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000207 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
208 MBBMap[BB] = MBB;
209 MF.getBasicBlockList().push_back(MBB);
210
211 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
212 // appropriate.
213 PHINode *PN;
214 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000215 (PN = dyn_cast<PHINode>(I)); ++I)
216 if (!PN->use_empty()) {
217 unsigned NumElements =
218 TLI.getNumElements(TLI.getValueType(PN->getType()));
219 unsigned PHIReg = ValueMap[PN];
220 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
221 for (unsigned i = 0; i != NumElements; ++i)
222 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
223 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000224 }
225}
226
227
228
229//===----------------------------------------------------------------------===//
230/// SelectionDAGLowering - This is the common target-independent lowering
231/// implementation that is parameterized by a TargetLowering object.
232/// Also, targets can overload any lowering method.
233///
234namespace llvm {
235class SelectionDAGLowering {
236 MachineBasicBlock *CurMBB;
237
238 std::map<const Value*, SDOperand> NodeMap;
239
Chris Lattnerd3948112005-01-17 22:19:26 +0000240 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
241 /// them up and then emit token factor nodes when possible. This allows us to
242 /// get simple disambiguation between loads without worrying about alias
243 /// analysis.
244 std::vector<SDOperand> PendingLoads;
245
Chris Lattner1c08c712005-01-07 07:47:53 +0000246public:
247 // TLI - This is information that describes the available target features we
248 // need for lowering. This indicates when operations are unavailable,
249 // implemented with a libcall, etc.
250 TargetLowering &TLI;
251 SelectionDAG &DAG;
252 const TargetData &TD;
253
254 /// FuncInfo - Information about the function as a whole.
255 ///
256 FunctionLoweringInfo &FuncInfo;
257
258 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000259 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
261 FuncInfo(funcinfo) {
262 }
263
Chris Lattnera651cf62005-01-17 19:43:36 +0000264 /// getRoot - Return the current virtual root of the Selection DAG.
265 ///
266 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000267 if (PendingLoads.empty())
268 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000269
Chris Lattnerd3948112005-01-17 22:19:26 +0000270 if (PendingLoads.size() == 1) {
271 SDOperand Root = PendingLoads[0];
272 DAG.setRoot(Root);
273 PendingLoads.clear();
274 return Root;
275 }
276
277 // Otherwise, we have to make a token factor node.
278 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
279 PendingLoads.clear();
280 DAG.setRoot(Root);
281 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000282 }
283
Chris Lattner1c08c712005-01-07 07:47:53 +0000284 void visit(Instruction &I) { visit(I.getOpcode(), I); }
285
286 void visit(unsigned Opcode, User &I) {
287 switch (Opcode) {
288 default: assert(0 && "Unknown instruction type encountered!");
289 abort();
290 // Build the switch statement using the Instruction.def file.
291#define HANDLE_INST(NUM, OPCODE, CLASS) \
292 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
293#include "llvm/Instruction.def"
294 }
295 }
296
297 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
298
299
300 SDOperand getIntPtrConstant(uint64_t Val) {
301 return DAG.getConstant(Val, TLI.getPointerTy());
302 }
303
304 SDOperand getValue(const Value *V) {
305 SDOperand &N = NodeMap[V];
306 if (N.Val) return N;
307
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000308 const Type *VTy = V->getType();
309 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000310 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
311 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
312 visit(CE->getOpcode(), *CE);
313 assert(N.Val && "visit didn't populate the ValueMap!");
314 return N;
315 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
316 return N = DAG.getGlobalAddress(GV, VT);
317 } else if (isa<ConstantPointerNull>(C)) {
318 return N = DAG.getConstant(0, TLI.getPointerTy());
319 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000320 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000321 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
322 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000323 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
324 unsigned NumElements = PTy->getNumElements();
325 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
326 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
327
328 // Now that we know the number and type of the elements, push a
329 // Constant or ConstantFP node onto the ops list for each element of
330 // the packed constant.
331 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000332 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
333 if (MVT::isFloatingPoint(PVT)) {
334 for (unsigned i = 0; i != NumElements; ++i) {
335 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
336 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
337 }
338 } else {
339 for (unsigned i = 0; i != NumElements; ++i) {
340 const ConstantIntegral *El =
341 cast<ConstantIntegral>(CP->getOperand(i));
342 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
343 }
344 }
345 } else {
346 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
347 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000348 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000349 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000350 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000351 Op = DAG.getConstant(0, PVT);
352 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000353 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000354
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000355 // Handle the case where we have a 1-element vector, in which
356 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000357 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000358 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000359 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
360 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
361 } else {
362 // If the packed type isn't legal, then create a ConstantVec node with
363 // generic Vector type instead.
364 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
365 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000366 } else {
367 // Canonicalize all constant ints to be unsigned.
368 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
369 }
370
371 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
372 std::map<const AllocaInst*, int>::iterator SI =
373 FuncInfo.StaticAllocaMap.find(AI);
374 if (SI != FuncInfo.StaticAllocaMap.end())
375 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
376 }
377
378 std::map<const Value*, unsigned>::const_iterator VMI =
379 FuncInfo.ValueMap.find(V);
380 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000381
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000382 unsigned InReg = VMI->second;
383
384 // If this type is not legal, make it so now.
385 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
386
387 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
388 if (DestVT < VT) {
389 // Source must be expanded. This input value is actually coming from the
390 // register pair VMI->second and VMI->second+1.
391 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
392 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
393 } else {
394 if (DestVT > VT) { // Promotion case
395 if (MVT::isFloatingPoint(VT))
396 N = DAG.getNode(ISD::FP_ROUND, VT, N);
397 else
398 N = DAG.getNode(ISD::TRUNCATE, VT, N);
399 }
400 }
401
402 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000403 }
404
405 const SDOperand &setValue(const Value *V, SDOperand NewN) {
406 SDOperand &N = NodeMap[V];
407 assert(N.Val == 0 && "Already set a value for this node!");
408 return N = NewN;
409 }
410
411 // Terminator instructions.
412 void visitRet(ReturnInst &I);
413 void visitBr(BranchInst &I);
414 void visitUnreachable(UnreachableInst &I) { /* noop */ }
415
416 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000417 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000418 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000419 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
420 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
421 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
422
423 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000424 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000425 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000426 void visitAdd(User &I) {
427 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000428 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000429 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000430 void visitMul(User &I) {
431 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000432 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000434 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000435 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000436 }
437 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000438 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000439 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000440 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000441 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
442 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
443 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000444 void visitShl(User &I) { visitShift(I, ISD::SHL); }
445 void visitShr(User &I) {
446 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000447 }
448
449 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
450 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
451 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
452 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
453 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
454 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
455 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
456
457 void visitGetElementPtr(User &I);
458 void visitCast(User &I);
459 void visitSelect(User &I);
460 //
461
462 void visitMalloc(MallocInst &I);
463 void visitFree(FreeInst &I);
464 void visitAlloca(AllocaInst &I);
465 void visitLoad(LoadInst &I);
466 void visitStore(StoreInst &I);
467 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
468 void visitCall(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000469 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000470
Chris Lattner1c08c712005-01-07 07:47:53 +0000471 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000472 void visitVAArg(VAArgInst &I);
473 void visitVAEnd(CallInst &I);
474 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000475 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000476
Chris Lattner7041ee32005-01-11 05:56:49 +0000477 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000478
479 void visitUserOp1(Instruction &I) {
480 assert(0 && "UserOp1 should not exist at instruction selection time!");
481 abort();
482 }
483 void visitUserOp2(Instruction &I) {
484 assert(0 && "UserOp2 should not exist at instruction selection time!");
485 abort();
486 }
487};
488} // end namespace llvm
489
490void SelectionDAGLowering::visitRet(ReturnInst &I) {
491 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000492 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000493 return;
494 }
495
496 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000497 MVT::ValueType TmpVT;
498
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 switch (Op1.getValueType()) {
500 default: assert(0 && "Unknown value type!");
501 case MVT::i1:
502 case MVT::i8:
503 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000504 case MVT::i32:
505 // If this is a machine where 32-bits is legal or expanded, promote to
506 // 32-bits, otherwise, promote to 64-bits.
507 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
508 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000509 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000510 TmpVT = MVT::i32;
511
512 // Extend integer types to result type.
513 if (I.getOperand(0)->getType()->isSigned())
514 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
515 else
516 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000517 break;
518 case MVT::f32:
Chris Lattner4eebb602006-01-20 18:38:32 +0000519 // If this is a machine where f32 is promoted to f64, do so now.
520 if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
521 Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
522 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000523 case MVT::i64:
524 case MVT::f64:
525 break; // No extension needed!
526 }
Nate Begeman4a959452005-10-18 23:23:37 +0000527 // Allow targets to lower this further to meet ABI requirements
528 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000529}
530
531void SelectionDAGLowering::visitBr(BranchInst &I) {
532 // Update machine-CFG edges.
533 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000534
535 // Figure out which block is immediately after the current one.
536 MachineBasicBlock *NextBlock = 0;
537 MachineFunction::iterator BBI = CurMBB;
538 if (++BBI != CurMBB->getParent()->end())
539 NextBlock = BBI;
540
541 if (I.isUnconditional()) {
542 // If this is not a fall-through branch, emit the branch.
543 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000544 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000545 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000546 } else {
547 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000548
549 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000550 if (Succ1MBB == NextBlock) {
551 // If the condition is false, fall through. This means we should branch
552 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000553 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000554 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000555 } else if (Succ0MBB == NextBlock) {
556 // If the condition is true, fall through. This means we should branch if
557 // the condition is false to Succ #1. Invert the condition first.
558 SDOperand True = DAG.getConstant(1, Cond.getValueType());
559 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000560 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000561 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000562 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000563 std::vector<SDOperand> Ops;
564 Ops.push_back(getRoot());
565 Ops.push_back(Cond);
566 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
567 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
568 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000569 }
570 }
571}
572
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000573void SelectionDAGLowering::visitSub(User &I) {
574 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000575 if (I.getType()->isFloatingPoint()) {
576 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
577 if (CFP->isExactlyValue(-0.0)) {
578 SDOperand Op2 = getValue(I.getOperand(1));
579 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
580 return;
581 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000582 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000583 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000584}
585
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000586void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
587 unsigned VecOp) {
588 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000589 SDOperand Op1 = getValue(I.getOperand(0));
590 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000591
Chris Lattnerb67eb912005-11-19 18:40:42 +0000592 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000593 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
594 } else if (Ty->isFloatingPoint()) {
595 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
596 } else {
597 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000598 unsigned NumElements = PTy->getNumElements();
599 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000600 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000601
602 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000603 // the Legalize pass does not have to deal with them. Similarly, if the
604 // abstract vector is going to turn into one that the target natively
605 // supports, generate that type now so that Legalize doesn't have to deal
606 // with that either. These steps ensure that Legalize only has to handle
607 // vector types in its Expand case.
608 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000609 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000610 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000611 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
612 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000613 } else {
614 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
615 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000616 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000617 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000618 }
Nate Begemane21ea612005-11-18 07:42:56 +0000619}
Chris Lattner2c49f272005-01-19 22:31:21 +0000620
Nate Begemane21ea612005-11-18 07:42:56 +0000621void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
622 SDOperand Op1 = getValue(I.getOperand(0));
623 SDOperand Op2 = getValue(I.getOperand(1));
624
625 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
626
Chris Lattner1c08c712005-01-07 07:47:53 +0000627 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
628}
629
630void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
631 ISD::CondCode UnsignedOpcode) {
632 SDOperand Op1 = getValue(I.getOperand(0));
633 SDOperand Op2 = getValue(I.getOperand(1));
634 ISD::CondCode Opcode = SignedOpcode;
635 if (I.getOperand(0)->getType()->isUnsigned())
636 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000637 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000638}
639
640void SelectionDAGLowering::visitSelect(User &I) {
641 SDOperand Cond = getValue(I.getOperand(0));
642 SDOperand TrueVal = getValue(I.getOperand(1));
643 SDOperand FalseVal = getValue(I.getOperand(2));
644 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
645 TrueVal, FalseVal));
646}
647
648void SelectionDAGLowering::visitCast(User &I) {
649 SDOperand N = getValue(I.getOperand(0));
650 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
651 MVT::ValueType DestTy = TLI.getValueType(I.getType());
652
653 if (N.getValueType() == DestTy) {
654 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000655 } else if (DestTy == MVT::i1) {
656 // Cast to bool is a comparison against zero, not truncation to zero.
657 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
658 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000659 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000660 } else if (isInteger(SrcTy)) {
661 if (isInteger(DestTy)) { // Int -> Int cast
662 if (DestTy < SrcTy) // Truncating cast?
663 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
664 else if (I.getOperand(0)->getType()->isSigned())
665 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
666 else
667 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
668 } else { // Int -> FP cast
669 if (I.getOperand(0)->getType()->isSigned())
670 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
671 else
672 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
673 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000674 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000675 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
676 if (isFloatingPoint(DestTy)) { // FP -> FP cast
677 if (DestTy < SrcTy) // Rounding cast?
678 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
679 else
680 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
681 } else { // FP -> Int cast.
682 if (I.getType()->isSigned())
683 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
684 else
685 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
686 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000687 }
688}
689
690void SelectionDAGLowering::visitGetElementPtr(User &I) {
691 SDOperand N = getValue(I.getOperand(0));
692 const Type *Ty = I.getOperand(0)->getType();
693 const Type *UIntPtrTy = TD.getIntPtrType();
694
695 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
696 OI != E; ++OI) {
697 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000698 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000699 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
700 if (Field) {
701 // N = N + Offset
702 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
703 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000704 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000705 }
706 Ty = StTy->getElementType(Field);
707 } else {
708 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000709
Chris Lattner7c0104b2005-11-09 04:45:33 +0000710 // If this is a constant subscript, handle it quickly.
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
712 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000713
Chris Lattner7c0104b2005-11-09 04:45:33 +0000714 uint64_t Offs;
715 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
716 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
717 else
718 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
719 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
720 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000722
723 // N = N + Idx * ElementSize;
724 uint64_t ElementSize = TD.getTypeSize(Ty);
725 SDOperand IdxN = getValue(Idx);
726
727 // If the index is smaller or larger than intptr_t, truncate or extend
728 // it.
729 if (IdxN.getValueType() < N.getValueType()) {
730 if (Idx->getType()->isSigned())
731 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
732 else
733 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
734 } else if (IdxN.getValueType() > N.getValueType())
735 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
736
737 // If this is a multiply by a power of two, turn it into a shl
738 // immediately. This is a very common case.
739 if (isPowerOf2_64(ElementSize)) {
740 unsigned Amt = Log2_64(ElementSize);
741 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000742 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000743 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
744 continue;
745 }
746
747 SDOperand Scale = getIntPtrConstant(ElementSize);
748 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
749 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000750 }
751 }
752 setValue(&I, N);
753}
754
755void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
756 // If this is a fixed sized alloca in the entry block of the function,
757 // allocate it statically on the stack.
758 if (FuncInfo.StaticAllocaMap.count(&I))
759 return; // getValue will auto-populate this.
760
761 const Type *Ty = I.getAllocatedType();
762 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000763 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
764 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000765
766 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000767 MVT::ValueType IntPtr = TLI.getPointerTy();
768 if (IntPtr < AllocSize.getValueType())
769 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
770 else if (IntPtr > AllocSize.getValueType())
771 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000772
Chris Lattner68cd65e2005-01-22 23:04:37 +0000773 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000774 getIntPtrConstant(TySize));
775
776 // Handle alignment. If the requested alignment is less than or equal to the
777 // stack alignment, ignore it and round the size of the allocation up to the
778 // stack alignment size. If the size is greater than the stack alignment, we
779 // note this in the DYNAMIC_STACKALLOC node.
780 unsigned StackAlign =
781 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
782 if (Align <= StackAlign) {
783 Align = 0;
784 // Add SA-1 to the size.
785 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
786 getIntPtrConstant(StackAlign-1));
787 // Mask out the low bits for alignment purposes.
788 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
789 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
790 }
791
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000792 std::vector<MVT::ValueType> VTs;
793 VTs.push_back(AllocSize.getValueType());
794 VTs.push_back(MVT::Other);
795 std::vector<SDOperand> Ops;
796 Ops.push_back(getRoot());
797 Ops.push_back(AllocSize);
798 Ops.push_back(getIntPtrConstant(Align));
799 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000800 DAG.setRoot(setValue(&I, DSA).getValue(1));
801
802 // Inform the Frame Information that we have just allocated a variable-sized
803 // object.
804 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
805}
806
Chris Lattner36ce6912005-11-29 06:21:05 +0000807/// getStringValue - Turn an LLVM constant pointer that eventually points to a
808/// global into a string value. Return an empty string if we can't do it.
809///
810static std::string getStringValue(Value *V, unsigned Offset = 0) {
811 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
812 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
813 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
814 if (Init->isString()) {
815 std::string Result = Init->getAsString();
816 if (Offset < Result.size()) {
817 // If we are pointing INTO The string, erase the beginning...
818 Result.erase(Result.begin(), Result.begin()+Offset);
819
820 // Take off the null terminator, and any string fragments after it.
821 std::string::size_type NullPos = Result.find_first_of((char)0);
822 if (NullPos != std::string::npos)
823 Result.erase(Result.begin()+NullPos, Result.end());
824 return Result;
825 }
826 }
827 }
828 } else if (Constant *C = dyn_cast<Constant>(V)) {
829 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
830 return getStringValue(GV, Offset);
831 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
832 if (CE->getOpcode() == Instruction::GetElementPtr) {
833 // Turn a gep into the specified offset.
834 if (CE->getNumOperands() == 3 &&
835 cast<Constant>(CE->getOperand(1))->isNullValue() &&
836 isa<ConstantInt>(CE->getOperand(2))) {
837 return getStringValue(CE->getOperand(0),
838 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
839 }
840 }
841 }
842 }
843 return "";
844}
Chris Lattner1c08c712005-01-07 07:47:53 +0000845
846void SelectionDAGLowering::visitLoad(LoadInst &I) {
847 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000848
Chris Lattnerd3948112005-01-17 22:19:26 +0000849 SDOperand Root;
850 if (I.isVolatile())
851 Root = getRoot();
852 else {
853 // Do not serialize non-volatile loads against each other.
854 Root = DAG.getRoot();
855 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000856
857 const Type *Ty = I.getType();
858 SDOperand L;
859
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000860 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000861 unsigned NumElements = PTy->getNumElements();
862 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000863 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000864
865 // Immediately scalarize packed types containing only one element, so that
866 // the Legalize pass does not have to deal with them.
867 if (NumElements == 1) {
868 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000869 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
870 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000871 } else {
872 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
873 DAG.getSrcValue(I.getOperand(0)));
874 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000875 } else {
876 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
877 DAG.getSrcValue(I.getOperand(0)));
878 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000879 setValue(&I, L);
880
881 if (I.isVolatile())
882 DAG.setRoot(L.getValue(1));
883 else
884 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000885}
886
887
888void SelectionDAGLowering::visitStore(StoreInst &I) {
889 Value *SrcV = I.getOperand(0);
890 SDOperand Src = getValue(SrcV);
891 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000892 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000893 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000894}
895
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000896/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
897/// we want to emit this as a call to a named external function, return the name
898/// otherwise lower it and return null.
899const char *
900SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
901 switch (Intrinsic) {
902 case Intrinsic::vastart: visitVAStart(I); return 0;
903 case Intrinsic::vaend: visitVAEnd(I); return 0;
904 case Intrinsic::vacopy: visitVACopy(I); return 0;
905 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
906 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
907 case Intrinsic::setjmp:
908 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
909 break;
910 case Intrinsic::longjmp:
911 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
912 break;
913 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
914 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
915 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
916
917 case Intrinsic::readport:
918 case Intrinsic::readio: {
919 std::vector<MVT::ValueType> VTs;
920 VTs.push_back(TLI.getValueType(I.getType()));
921 VTs.push_back(MVT::Other);
922 std::vector<SDOperand> Ops;
923 Ops.push_back(getRoot());
924 Ops.push_back(getValue(I.getOperand(1)));
925 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
926 ISD::READPORT : ISD::READIO, VTs, Ops);
927
928 setValue(&I, Tmp);
929 DAG.setRoot(Tmp.getValue(1));
930 return 0;
931 }
932 case Intrinsic::writeport:
933 case Intrinsic::writeio:
934 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
935 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
936 getRoot(), getValue(I.getOperand(1)),
937 getValue(I.getOperand(2))));
938 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000939
Chris Lattner86cb6432005-12-13 17:40:33 +0000940 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000941 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
942 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000943
944 std::string fname = "<unknown>";
945 std::vector<SDOperand> Ops;
946
Chris Lattner36ce6912005-11-29 06:21:05 +0000947 // Input Chain
948 Ops.push_back(getRoot());
949
950 // line number
951 Ops.push_back(getValue(I.getOperand(2)));
952
953 // column
954 Ops.push_back(getValue(I.getOperand(3)));
955
Chris Lattner86cb6432005-12-13 17:40:33 +0000956 // filename/working dir
957 // Pull the filename out of the the compilation unit.
958 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
959 if (cunit && cunit->hasInitializer()) {
960 if (ConstantStruct *CS =
961 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
962 if (CS->getNumOperands() > 0) {
Chris Lattner86cb6432005-12-13 17:40:33 +0000963 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskeyf5395ce2005-12-16 22:45:29 +0000964 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner86cb6432005-12-13 17:40:33 +0000965 }
966 }
967 }
968
969 if (Ops.size() == 5) // Found filename/workingdir.
970 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000971 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000972 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000973 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000974 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000975 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
976 return "llvm_dbg_region_start";
977 if (I.getType() != Type::VoidTy)
978 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
979 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000980 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000981 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
982 return "llvm_dbg_region_end";
983 if (I.getType() != Type::VoidTy)
984 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
985 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000986 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000987 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
988 return "llvm_dbg_subprogram";
989 if (I.getType() != Type::VoidTy)
990 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
991 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000992 case Intrinsic::dbg_declare:
993 if (I.getType() != Type::VoidTy)
994 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
995 return 0;
996
Reid Spencer0b118202006-01-16 21:12:35 +0000997 case Intrinsic::isunordered_f32:
998 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000999 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1000 getValue(I.getOperand(2)), ISD::SETUO));
1001 return 0;
1002
Reid Spencer0b118202006-01-16 21:12:35 +00001003 case Intrinsic::sqrt_f32:
1004 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001005 setValue(&I, DAG.getNode(ISD::FSQRT,
1006 getValue(I.getOperand(1)).getValueType(),
1007 getValue(I.getOperand(1))));
1008 return 0;
1009 case Intrinsic::pcmarker: {
1010 SDOperand Tmp = getValue(I.getOperand(1));
1011 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1012 return 0;
1013 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001014 case Intrinsic::readcyclecounter: {
1015 std::vector<MVT::ValueType> VTs;
1016 VTs.push_back(MVT::i64);
1017 VTs.push_back(MVT::Other);
1018 std::vector<SDOperand> Ops;
1019 Ops.push_back(getRoot());
1020 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1021 setValue(&I, Tmp);
1022 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001023 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001024 }
Nate Begemand88fc032006-01-14 03:14:10 +00001025 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001026 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001027 case Intrinsic::bswap_i64:
1028 setValue(&I, DAG.getNode(ISD::BSWAP,
1029 getValue(I.getOperand(1)).getValueType(),
1030 getValue(I.getOperand(1))));
1031 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001032 case Intrinsic::cttz_i8:
1033 case Intrinsic::cttz_i16:
1034 case Intrinsic::cttz_i32:
1035 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001036 setValue(&I, DAG.getNode(ISD::CTTZ,
1037 getValue(I.getOperand(1)).getValueType(),
1038 getValue(I.getOperand(1))));
1039 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001040 case Intrinsic::ctlz_i8:
1041 case Intrinsic::ctlz_i16:
1042 case Intrinsic::ctlz_i32:
1043 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001044 setValue(&I, DAG.getNode(ISD::CTLZ,
1045 getValue(I.getOperand(1)).getValueType(),
1046 getValue(I.getOperand(1))));
1047 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001048 case Intrinsic::ctpop_i8:
1049 case Intrinsic::ctpop_i16:
1050 case Intrinsic::ctpop_i32:
1051 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001052 setValue(&I, DAG.getNode(ISD::CTPOP,
1053 getValue(I.getOperand(1)).getValueType(),
1054 getValue(I.getOperand(1))));
1055 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001056 case Intrinsic::stacksave: {
1057 std::vector<MVT::ValueType> VTs;
1058 VTs.push_back(TLI.getPointerTy());
1059 VTs.push_back(MVT::Other);
1060 std::vector<SDOperand> Ops;
1061 Ops.push_back(getRoot());
1062 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1063 setValue(&I, Tmp);
1064 DAG.setRoot(Tmp.getValue(1));
1065 return 0;
1066 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001067 case Intrinsic::stackrestore: {
1068 SDOperand Tmp = getValue(I.getOperand(1));
1069 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001070 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001071 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001072 case Intrinsic::prefetch:
1073 // FIXME: Currently discarding prefetches.
1074 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001075 default:
1076 std::cerr << I;
1077 assert(0 && "This intrinsic is not implemented yet!");
1078 return 0;
1079 }
1080}
1081
1082
Chris Lattner1c08c712005-01-07 07:47:53 +00001083void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001084 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001085 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001086 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001087 if (unsigned IID = F->getIntrinsicID()) {
1088 RenameFn = visitIntrinsicCall(I, IID);
1089 if (!RenameFn)
1090 return;
1091 } else { // Not an LLVM intrinsic.
1092 const std::string &Name = F->getName();
1093 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001094 if (I.getNumOperands() == 2 && // Basic sanity checks.
1095 I.getOperand(1)->getType()->isFloatingPoint() &&
1096 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001097 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001098 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1099 return;
1100 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001101 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001102 if (I.getNumOperands() == 2 && // Basic sanity checks.
1103 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001104 I.getType() == I.getOperand(1)->getType() &&
1105 TLI.isOperationLegal(ISD::FSIN,
1106 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001107 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001108 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1109 return;
1110 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001111 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001112 if (I.getNumOperands() == 2 && // Basic sanity checks.
1113 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001114 I.getType() == I.getOperand(1)->getType() &&
1115 TLI.isOperationLegal(ISD::FCOS,
1116 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001117 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001118 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1119 return;
1120 }
1121 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001122 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001123 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001124
Chris Lattner64e14b12005-01-08 22:48:57 +00001125 SDOperand Callee;
1126 if (!RenameFn)
1127 Callee = getValue(I.getOperand(0));
1128 else
1129 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001130 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001131 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001132 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1133 Value *Arg = I.getOperand(i);
1134 SDOperand ArgNode = getValue(Arg);
1135 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1136 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001137
Nate Begeman8e21e712005-03-26 01:29:23 +00001138 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1139 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001140
Chris Lattnercf5734d2005-01-08 19:26:18 +00001141 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001142 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001143 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001144 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001145 setValue(&I, Result.first);
1146 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001147}
1148
1149void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1150 SDOperand Src = getValue(I.getOperand(0));
1151
1152 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001153
1154 if (IntPtr < Src.getValueType())
1155 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1156 else if (IntPtr > Src.getValueType())
1157 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001158
1159 // Scale the source by the type size.
1160 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1161 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1162 Src, getIntPtrConstant(ElementSize));
1163
1164 std::vector<std::pair<SDOperand, const Type*> > Args;
1165 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001166
1167 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001168 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001169 DAG.getExternalSymbol("malloc", IntPtr),
1170 Args, DAG);
1171 setValue(&I, Result.first); // Pointers always fit in registers
1172 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001173}
1174
1175void SelectionDAGLowering::visitFree(FreeInst &I) {
1176 std::vector<std::pair<SDOperand, const Type*> > Args;
1177 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1178 TLI.getTargetData().getIntPtrType()));
1179 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001180 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001181 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001182 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1183 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001184}
1185
Chris Lattner025c39b2005-08-26 20:54:47 +00001186// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1187// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1188// instructions are special in various ways, which require special support to
1189// insert. The specified MachineInstr is created but not inserted into any
1190// basic blocks, and the scheduler passes ownership of it to this method.
1191MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1192 MachineBasicBlock *MBB) {
1193 std::cerr << "If a target marks an instruction with "
1194 "'usesCustomDAGSchedInserter', it must implement "
1195 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1196 abort();
1197 return 0;
1198}
1199
Nate Begeman4a959452005-10-18 23:23:37 +00001200SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1201 SelectionDAG &DAG) {
1202 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1203}
1204
Chris Lattnere64e72b2005-07-05 19:57:53 +00001205SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1206 SDOperand VAListP, Value *VAListV,
1207 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001208 // We have no sane default behavior, just emit a useful error message and bail
1209 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +00001210 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00001211 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +00001212 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +00001213}
1214
Chris Lattnere64e72b2005-07-05 19:57:53 +00001215SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +00001216 SelectionDAG &DAG) {
1217 // Default to a noop.
1218 return Chain;
1219}
1220
Chris Lattnere64e72b2005-07-05 19:57:53 +00001221SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1222 SDOperand SrcP, Value *SrcV,
1223 SDOperand DestP, Value *DestV,
1224 SelectionDAG &DAG) {
1225 // Default to copying the input list.
1226 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1227 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001228 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001229 Val, DestP, DAG.getSrcValue(DestV));
1230 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +00001231}
1232
1233std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +00001234TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1235 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +00001236 // We have no sane default behavior, just emit a useful error message and bail
1237 // out.
1238 std::cerr << "Variable arguments handling not implemented on this target!\n";
1239 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001240 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +00001241}
1242
1243
1244void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001245 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1246 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +00001247}
1248
1249void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1250 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +00001251 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +00001252 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001253 setValue(&I, Result.first);
1254 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001255}
1256
1257void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001258 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001259 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +00001260}
1261
1262void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001263 SDOperand Result =
1264 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1265 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1266 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +00001267}
1268
Chris Lattner39ae3622005-01-09 00:00:49 +00001269
1270// It is always conservatively correct for llvm.returnaddress and
1271// llvm.frameaddress to return 0.
1272std::pair<SDOperand, SDOperand>
1273TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1274 unsigned Depth, SelectionDAG &DAG) {
1275 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001276}
1277
Chris Lattner50381b62005-05-14 05:50:48 +00001278SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001279 assert(0 && "LowerOperation not implemented for this target!");
1280 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001281 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001282}
1283
Chris Lattner39ae3622005-01-09 00:00:49 +00001284void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1285 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1286 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001287 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001288 setValue(&I, Result.first);
1289 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001290}
1291
Chris Lattner7041ee32005-01-11 05:56:49 +00001292void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer6ff72402005-11-30 05:21:10 +00001293#if 0
1294 // If the size of the cpy/move/set is constant (known)
1295 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1296 uint64_t size = op3->getValue();
1297 switch (Op) {
1298 case ISD::MEMSET:
1299 if (size <= TLI.getMaxStoresPerMemSet()) {
1300 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1301 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1302 uint64_t align = op4.getValue();
1303 while (size > align) {
1304 size -=align;
1305 }
1306 Value *SrcV = I.getOperand(0);
1307 SDOperand Src = getValue(SrcV);
1308 SDOperand Ptr = getValue(I.getOperand(1));
1309 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1310 DAG.getSrcValue(I.getOperand(1))));
1311 }
1312 break;
1313 }
1314 break; // don't do this optimization, use a normal memset
1315 case ISD::MEMMOVE:
1316 case ISD::MEMCPY:
1317 break; // FIXME: not implemented yet
1318 }
1319 }
1320#endif
1321
1322 // Non-optimized version
Chris Lattner7041ee32005-01-11 05:56:49 +00001323 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001324 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +00001325 Ops.push_back(getValue(I.getOperand(1)));
1326 Ops.push_back(getValue(I.getOperand(2)));
1327 Ops.push_back(getValue(I.getOperand(3)));
1328 Ops.push_back(getValue(I.getOperand(4)));
1329 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001330}
1331
Chris Lattner7041ee32005-01-11 05:56:49 +00001332//===----------------------------------------------------------------------===//
1333// SelectionDAGISel code
1334//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001335
1336unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1337 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1338}
1339
Chris Lattner495a0b52005-08-17 06:37:43 +00001340void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001341 // FIXME: we only modify the CFG to split critical edges. This
1342 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001343}
Chris Lattner1c08c712005-01-07 07:47:53 +00001344
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001345
1346/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1347/// casting to the type of GEPI.
1348static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1349 Value *Ptr, Value *PtrOffset) {
1350 if (V) return V; // Already computed.
1351
1352 BasicBlock::iterator InsertPt;
1353 if (BB == GEPI->getParent()) {
1354 // If insert into the GEP's block, insert right after the GEP.
1355 InsertPt = GEPI;
1356 ++InsertPt;
1357 } else {
1358 // Otherwise, insert at the top of BB, after any PHI nodes
1359 InsertPt = BB->begin();
1360 while (isa<PHINode>(InsertPt)) ++InsertPt;
1361 }
1362
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001363 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1364 // BB so that there is only one value live across basic blocks (the cast
1365 // operand).
1366 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1367 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1368 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1369
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001370 // Add the offset, cast it to the right type.
1371 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1372 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1373 return V = Ptr;
1374}
1375
1376
1377/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1378/// selection, we want to be a bit careful about some things. In particular, if
1379/// we have a GEP instruction that is used in a different block than it is
1380/// defined, the addressing expression of the GEP cannot be folded into loads or
1381/// stores that use it. In this case, decompose the GEP and move constant
1382/// indices into blocks that use it.
1383static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1384 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001385 // If this GEP is only used inside the block it is defined in, there is no
1386 // need to rewrite it.
1387 bool isUsedOutsideDefBB = false;
1388 BasicBlock *DefBB = GEPI->getParent();
1389 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1390 UI != E; ++UI) {
1391 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1392 isUsedOutsideDefBB = true;
1393 break;
1394 }
1395 }
1396 if (!isUsedOutsideDefBB) return;
1397
1398 // If this GEP has no non-zero constant indices, there is nothing we can do,
1399 // ignore it.
1400 bool hasConstantIndex = false;
1401 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1402 E = GEPI->op_end(); OI != E; ++OI) {
1403 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1404 if (CI->getRawValue()) {
1405 hasConstantIndex = true;
1406 break;
1407 }
1408 }
Chris Lattner3802c252005-12-11 09:05:13 +00001409 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1410 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001411
1412 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1413 // constant offset (which we now know is non-zero) and deal with it later.
1414 uint64_t ConstantOffset = 0;
1415 const Type *UIntPtrTy = TD.getIntPtrType();
1416 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1417 const Type *Ty = GEPI->getOperand(0)->getType();
1418
1419 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1420 E = GEPI->op_end(); OI != E; ++OI) {
1421 Value *Idx = *OI;
1422 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1423 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1424 if (Field)
1425 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1426 Ty = StTy->getElementType(Field);
1427 } else {
1428 Ty = cast<SequentialType>(Ty)->getElementType();
1429
1430 // Handle constant subscripts.
1431 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1432 if (CI->getRawValue() == 0) continue;
1433
1434 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1435 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1436 else
1437 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1438 continue;
1439 }
1440
1441 // Ptr = Ptr + Idx * ElementSize;
1442
1443 // Cast Idx to UIntPtrTy if needed.
1444 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1445
1446 uint64_t ElementSize = TD.getTypeSize(Ty);
1447 // Mask off bits that should not be set.
1448 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1449 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1450
1451 // Multiply by the element size and add to the base.
1452 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1453 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1454 }
1455 }
1456
1457 // Make sure that the offset fits in uintptr_t.
1458 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1459 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1460
1461 // Okay, we have now emitted all of the variable index parts to the BB that
1462 // the GEP is defined in. Loop over all of the using instructions, inserting
1463 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001464 // instruction to use the newly computed value, making GEPI dead. When the
1465 // user is a load or store instruction address, we emit the add into the user
1466 // block, otherwise we use a canonical version right next to the gep (these
1467 // won't be foldable as addresses, so we might as well share the computation).
1468
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001469 std::map<BasicBlock*,Value*> InsertedExprs;
1470 while (!GEPI->use_empty()) {
1471 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001472
1473 // If this use is not foldable into the addressing mode, use a version
1474 // emitted in the GEP block.
1475 Value *NewVal;
1476 if (!isa<LoadInst>(User) &&
1477 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1478 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1479 Ptr, PtrOffset);
1480 } else {
1481 // Otherwise, insert the code in the User's block so it can be folded into
1482 // any users in that block.
1483 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001484 User->getParent(), GEPI,
1485 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001486 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001487 User->replaceUsesOfWith(GEPI, NewVal);
1488 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001489
1490 // Finally, the GEP is dead, remove it.
1491 GEPI->eraseFromParent();
1492}
1493
Chris Lattner1c08c712005-01-07 07:47:53 +00001494bool SelectionDAGISel::runOnFunction(Function &Fn) {
1495 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1496 RegMap = MF.getSSARegMap();
1497 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1498
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001499 // First, split all critical edges for PHI nodes with incoming values that are
1500 // constants, this way the load of the constant into a vreg will not be placed
1501 // into MBBs that are used some other way.
1502 //
1503 // In this pass we also look for GEP instructions that are used across basic
1504 // blocks and rewrites them to improve basic-block-at-a-time selection.
1505 //
Chris Lattner36b708f2005-08-18 17:35:14 +00001506 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1507 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001508 BasicBlock::iterator BBI;
1509 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00001510 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1511 if (isa<Constant>(PN->getIncomingValue(i)))
1512 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001513
1514 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1515 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1516 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00001517 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001518
Chris Lattner1c08c712005-01-07 07:47:53 +00001519 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1520
1521 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1522 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001523
Chris Lattner1c08c712005-01-07 07:47:53 +00001524 return true;
1525}
1526
1527
Chris Lattnerddb870b2005-01-13 17:59:43 +00001528SDOperand SelectionDAGISel::
1529CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001530 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001531 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001532 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001533 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001534
1535 // If this type is not legal, we must make sure to not create an invalid
1536 // register use.
1537 MVT::ValueType SrcVT = Op.getValueType();
1538 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1539 SelectionDAG &DAG = SDL.DAG;
1540 if (SrcVT == DestVT) {
1541 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1542 } else if (SrcVT < DestVT) {
1543 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001544 if (MVT::isFloatingPoint(SrcVT))
1545 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1546 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001547 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001548 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1549 } else {
1550 // The src value is expanded into multiple registers.
1551 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1552 Op, DAG.getConstant(0, MVT::i32));
1553 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1554 Op, DAG.getConstant(1, MVT::i32));
1555 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1556 return DAG.getCopyToReg(Op, Reg+1, Hi);
1557 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001558}
1559
Chris Lattner068a81e2005-01-17 17:15:02 +00001560void SelectionDAGISel::
1561LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1562 std::vector<SDOperand> &UnorderedChains) {
1563 // If this is the entry block, emit arguments.
1564 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001565 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00001566 SDOperand OldRoot = SDL.DAG.getRoot();
1567 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00001568
Chris Lattnerbf209482005-10-30 19:42:35 +00001569 unsigned a = 0;
1570 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1571 AI != E; ++AI, ++a)
1572 if (!AI->use_empty()) {
1573 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00001574
Chris Lattnerbf209482005-10-30 19:42:35 +00001575 // If this argument is live outside of the entry block, insert a copy from
1576 // whereever we got it to the vreg that other BB's will reference it as.
1577 if (FuncInfo.ValueMap.count(AI)) {
1578 SDOperand Copy =
1579 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1580 UnorderedChains.push_back(Copy);
1581 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00001582 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001583
1584 // Next, if the function has live ins that need to be copied into vregs,
1585 // emit the copies now, into the top of the block.
1586 MachineFunction &MF = SDL.DAG.getMachineFunction();
1587 if (MF.livein_begin() != MF.livein_end()) {
1588 SSARegMap *RegMap = MF.getSSARegMap();
1589 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1590 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1591 E = MF.livein_end(); LI != E; ++LI)
1592 if (LI->second)
1593 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1594 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00001595 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001596
1597 // Finally, if the target has anything special to do, allow it to do so.
1598 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00001599}
1600
1601
Chris Lattner1c08c712005-01-07 07:47:53 +00001602void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1603 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1604 FunctionLoweringInfo &FuncInfo) {
1605 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001606
1607 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001608
Chris Lattnerbf209482005-10-30 19:42:35 +00001609 // Lower any arguments needed in this block if this is the entry block.
1610 if (LLVMBB == &LLVMBB->getParent()->front())
1611 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001612
1613 BB = FuncInfo.MBBMap[LLVMBB];
1614 SDL.setCurrentBasicBlock(BB);
1615
1616 // Lower all of the non-terminator instructions.
1617 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1618 I != E; ++I)
1619 SDL.visit(*I);
1620
1621 // Ensure that all instructions which are used outside of their defining
1622 // blocks are available as virtual registers.
1623 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001624 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001625 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001626 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001627 UnorderedChains.push_back(
1628 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001629 }
1630
1631 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1632 // ensure constants are generated when needed. Remember the virtual registers
1633 // that need to be added to the Machine PHI nodes as input. We cannot just
1634 // directly add them, because expansion might result in multiple MBB's for one
1635 // BB. As such, the start of the BB might correspond to a different MBB than
1636 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001637 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001638
1639 // Emit constants only once even if used by multiple PHI nodes.
1640 std::map<Constant*, unsigned> ConstantsOut;
1641
1642 // Check successor nodes PHI nodes that expect a constant to be available from
1643 // this block.
1644 TerminatorInst *TI = LLVMBB->getTerminator();
1645 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1646 BasicBlock *SuccBB = TI->getSuccessor(succ);
1647 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1648 PHINode *PN;
1649
1650 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1651 // nodes and Machine PHI nodes, but the incoming operands have not been
1652 // emitted yet.
1653 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001654 (PN = dyn_cast<PHINode>(I)); ++I)
1655 if (!PN->use_empty()) {
1656 unsigned Reg;
1657 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1658 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1659 unsigned &RegOut = ConstantsOut[C];
1660 if (RegOut == 0) {
1661 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001662 UnorderedChains.push_back(
1663 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001664 }
1665 Reg = RegOut;
1666 } else {
1667 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001668 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001669 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001670 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1671 "Didn't codegen value into a register!??");
1672 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001673 UnorderedChains.push_back(
1674 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001675 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001676 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001677
Chris Lattnerf44fd882005-01-07 21:34:19 +00001678 // Remember that this register needs to added to the machine PHI node as
1679 // the input for this MBB.
1680 unsigned NumElements =
1681 TLI.getNumElements(TLI.getValueType(PN->getType()));
1682 for (unsigned i = 0, e = NumElements; i != e; ++i)
1683 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001684 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001685 }
1686 ConstantsOut.clear();
1687
Chris Lattnerddb870b2005-01-13 17:59:43 +00001688 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001689 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00001690 SDOperand Root = SDL.getRoot();
1691 if (Root.getOpcode() != ISD::EntryToken) {
1692 unsigned i = 0, e = UnorderedChains.size();
1693 for (; i != e; ++i) {
1694 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1695 if (UnorderedChains[i].Val->getOperand(0) == Root)
1696 break; // Don't add the root if we already indirectly depend on it.
1697 }
1698
1699 if (i == e)
1700 UnorderedChains.push_back(Root);
1701 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00001702 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1703 }
1704
Chris Lattner1c08c712005-01-07 07:47:53 +00001705 // Lower the terminator after the copies are emitted.
1706 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001707
1708 // Make sure the root of the DAG is up-to-date.
1709 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001710}
1711
1712void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1713 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00001714 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00001715 CurDAG = &DAG;
1716 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1717
1718 // First step, lower LLVM code to some DAG. This DAG may use operations and
1719 // types that are not supported by the target.
1720 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1721
Chris Lattneraf21d552005-10-10 16:47:10 +00001722 // Run the DAG combiner in pre-legalize mode.
1723 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00001724
Chris Lattner1c08c712005-01-07 07:47:53 +00001725 DEBUG(std::cerr << "Lowered selection DAG:\n");
1726 DEBUG(DAG.dump());
1727
1728 // Second step, hack on the DAG until it only uses operations and types that
1729 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001730 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001731
1732 DEBUG(std::cerr << "Legalized selection DAG:\n");
1733 DEBUG(DAG.dump());
1734
Chris Lattneraf21d552005-10-10 16:47:10 +00001735 // Run the DAG combiner in post-legalize mode.
1736 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00001737
Evan Chenga9c20912006-01-21 02:32:06 +00001738 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00001739
Chris Lattnera33ef482005-03-30 01:10:47 +00001740 // Third, instruction select all of the operations to machine code, adding the
1741 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001742 InstructionSelectBasicBlock(DAG);
1743
Chris Lattner1c08c712005-01-07 07:47:53 +00001744 DEBUG(std::cerr << "Selected machine code:\n");
1745 DEBUG(BB->dump());
1746
Chris Lattnera33ef482005-03-30 01:10:47 +00001747 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001748 // PHI nodes in successors.
1749 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1750 MachineInstr *PHI = PHINodesToUpdate[i].first;
1751 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1752 "This is not a machine PHI node that we are updating!");
1753 PHI->addRegOperand(PHINodesToUpdate[i].second);
1754 PHI->addMachineBasicBlockOperand(BB);
1755 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001756
1757 // Finally, add the CFG edges from the last selected MBB to the successor
1758 // MBBs.
1759 TerminatorInst *TI = LLVMBB->getTerminator();
1760 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1761 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1762 BB->addSuccessor(Succ0MBB);
1763 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001764}
Evan Chenga9c20912006-01-21 02:32:06 +00001765
1766//===----------------------------------------------------------------------===//
1767/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1768/// target node in the graph.
1769void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1770 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00001771 ScheduleDAG *SL = NULL;
1772
1773 switch (ISHeuristic) {
1774 default: assert(0 && "Unrecognized scheduling heuristic");
1775 case noScheduling:
1776 case simpleScheduling:
1777 case simpleNoItinScheduling:
1778 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
1779 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00001780 case listSchedulingBURR:
1781 SL = createBURRListDAGScheduler(DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00001782 }
Chris Lattnera3818e62006-01-21 19:12:11 +00001783 BB = SL->Run();
Evan Chenga9c20912006-01-21 02:32:06 +00001784}