blob: ecf9797b4846389cd50afec27bc6c3078b4d5fc6 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/SelectionDAG.h"
26#include "llvm/CodeGen/SSARegMap.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetFrameInfo.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetLowering.h"
31#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000033#include "llvm/Support/CommandLine.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/Support/Debug.h"
35#include <map>
36#include <iostream>
37using namespace llvm;
38
Chris Lattnerda8abb02005-09-01 18:44:10 +000039#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000040static cl::opt<bool>
41ViewDAGs("view-isel-dags", cl::Hidden,
42 cl::desc("Pop up a window to show isel dags as they are selected"));
43#else
Chris Lattnera639a432005-09-02 07:09:28 +000044static const bool ViewDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000045#endif
46
Chris Lattner1c08c712005-01-07 07:47:53 +000047namespace llvm {
48 //===--------------------------------------------------------------------===//
49 /// FunctionLoweringInfo - This contains information that is global to a
50 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000051 class FunctionLoweringInfo {
52 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000053 TargetLowering &TLI;
54 Function &Fn;
55 MachineFunction &MF;
56 SSARegMap *RegMap;
57
58 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
59
60 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
61 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
62
63 /// ValueMap - Since we emit code for the function a basic block at a time,
64 /// we must remember which virtual registers hold the values for
65 /// cross-basic-block values.
66 std::map<const Value*, unsigned> ValueMap;
67
68 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
69 /// the entry block. This allows the allocas to be efficiently referenced
70 /// anywhere in the function.
71 std::map<const AllocaInst*, int> StaticAllocaMap;
72
Chris Lattner0afa8e32005-01-17 17:55:19 +000073 /// BlockLocalArguments - If any arguments are only used in a single basic
74 /// block, and if the target can access the arguments without side-effects,
75 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
76 /// track of which arguments are local to each BB.
77 std::multimap<BasicBlock*, std::pair<Argument*,
78 unsigned> > BlockLocalArguments;
79
80
Chris Lattner1c08c712005-01-07 07:47:53 +000081 unsigned MakeReg(MVT::ValueType VT) {
82 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
83 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000084
Chris Lattner1c08c712005-01-07 07:47:53 +000085 unsigned CreateRegForValue(const Value *V) {
86 MVT::ValueType VT = TLI.getValueType(V->getType());
87 // The common case is that we will only create one register for this
88 // value. If we have that case, create and return the virtual register.
89 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +000090 if (NV == 1) {
91 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000092 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000093 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000094
Chris Lattner1c08c712005-01-07 07:47:53 +000095 // If this value is represented with multiple target registers, make sure
96 // to create enough consequtive registers of the right (smaller) type.
97 unsigned NT = VT-1; // Find the type to use.
98 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
99 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000100
Chris Lattner1c08c712005-01-07 07:47:53 +0000101 unsigned R = MakeReg((MVT::ValueType)NT);
102 for (unsigned i = 1; i != NV; ++i)
103 MakeReg((MVT::ValueType)NT);
104 return R;
105 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000106
Chris Lattner1c08c712005-01-07 07:47:53 +0000107 unsigned InitializeRegForValue(const Value *V) {
108 unsigned &R = ValueMap[V];
109 assert(R == 0 && "Already initialized this value register!");
110 return R = CreateRegForValue(V);
111 }
112 };
113}
114
115/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
116/// PHI nodes or outside of the basic block that defines it.
117static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
118 if (isa<PHINode>(I)) return true;
119 BasicBlock *BB = I->getParent();
120 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
121 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
122 return true;
123 return false;
124}
125
126FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000127 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000128 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
129
130 // Initialize the mapping of values to registers. This is only set up for
131 // instruction values that are used outside of the block that defines
132 // them.
Chris Lattner16ce0df2005-05-11 18:57:06 +0000133 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
134 AI != E; ++AI)
Chris Lattner1c08c712005-01-07 07:47:53 +0000135 InitializeRegForValue(AI);
136
137 Function::iterator BB = Fn.begin(), E = Fn.end();
138 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
139 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
140 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
141 const Type *Ty = AI->getAllocatedType();
142 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
143 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
Chris Lattnera8217e32005-05-13 23:14:17 +0000144
145 // If the alignment of the value is smaller than the size of the value,
146 // and if the size of the value is particularly small (<= 8 bytes),
147 // round up to the size of the value for potentially better performance.
148 //
149 // FIXME: This could be made better with a preferred alignment hook in
150 // TargetData. It serves primarily to 8-byte align doubles for X86.
151 if (Align < TySize && TySize <= 8) Align = TySize;
152
Chris Lattnerfd88f642005-09-02 18:41:28 +0000153 if (CUI->getValue()) // Don't produce zero sized stack objects
154 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner1c08c712005-01-07 07:47:53 +0000155 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000156 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000157 }
158
159 for (; BB != E; ++BB)
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000160 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
162 if (!isa<AllocaInst>(I) ||
163 !StaticAllocaMap.count(cast<AllocaInst>(I)))
164 InitializeRegForValue(I);
165
166 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
167 // also creates the initial PHI MachineInstrs, though none of the input
168 // operands are populated.
169 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
170 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
171 MBBMap[BB] = MBB;
172 MF.getBasicBlockList().push_back(MBB);
173
174 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
175 // appropriate.
176 PHINode *PN;
177 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000178 (PN = dyn_cast<PHINode>(I)); ++I)
179 if (!PN->use_empty()) {
180 unsigned NumElements =
181 TLI.getNumElements(TLI.getValueType(PN->getType()));
182 unsigned PHIReg = ValueMap[PN];
183 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
184 for (unsigned i = 0; i != NumElements; ++i)
185 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
186 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000187 }
188}
189
190
191
192//===----------------------------------------------------------------------===//
193/// SelectionDAGLowering - This is the common target-independent lowering
194/// implementation that is parameterized by a TargetLowering object.
195/// Also, targets can overload any lowering method.
196///
197namespace llvm {
198class SelectionDAGLowering {
199 MachineBasicBlock *CurMBB;
200
201 std::map<const Value*, SDOperand> NodeMap;
202
Chris Lattnerd3948112005-01-17 22:19:26 +0000203 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
204 /// them up and then emit token factor nodes when possible. This allows us to
205 /// get simple disambiguation between loads without worrying about alias
206 /// analysis.
207 std::vector<SDOperand> PendingLoads;
208
Chris Lattner1c08c712005-01-07 07:47:53 +0000209public:
210 // TLI - This is information that describes the available target features we
211 // need for lowering. This indicates when operations are unavailable,
212 // implemented with a libcall, etc.
213 TargetLowering &TLI;
214 SelectionDAG &DAG;
215 const TargetData &TD;
216
217 /// FuncInfo - Information about the function as a whole.
218 ///
219 FunctionLoweringInfo &FuncInfo;
220
221 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000222 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000223 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
224 FuncInfo(funcinfo) {
225 }
226
Chris Lattnera651cf62005-01-17 19:43:36 +0000227 /// getRoot - Return the current virtual root of the Selection DAG.
228 ///
229 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000230 if (PendingLoads.empty())
231 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000232
Chris Lattnerd3948112005-01-17 22:19:26 +0000233 if (PendingLoads.size() == 1) {
234 SDOperand Root = PendingLoads[0];
235 DAG.setRoot(Root);
236 PendingLoads.clear();
237 return Root;
238 }
239
240 // Otherwise, we have to make a token factor node.
241 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
242 PendingLoads.clear();
243 DAG.setRoot(Root);
244 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000245 }
246
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 void visit(Instruction &I) { visit(I.getOpcode(), I); }
248
249 void visit(unsigned Opcode, User &I) {
250 switch (Opcode) {
251 default: assert(0 && "Unknown instruction type encountered!");
252 abort();
253 // Build the switch statement using the Instruction.def file.
254#define HANDLE_INST(NUM, OPCODE, CLASS) \
255 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
256#include "llvm/Instruction.def"
257 }
258 }
259
260 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
261
262
263 SDOperand getIntPtrConstant(uint64_t Val) {
264 return DAG.getConstant(Val, TLI.getPointerTy());
265 }
266
267 SDOperand getValue(const Value *V) {
268 SDOperand &N = NodeMap[V];
269 if (N.Val) return N;
270
271 MVT::ValueType VT = TLI.getValueType(V->getType());
272 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
273 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
274 visit(CE->getOpcode(), *CE);
275 assert(N.Val && "visit didn't populate the ValueMap!");
276 return N;
277 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
278 return N = DAG.getGlobalAddress(GV, VT);
279 } else if (isa<ConstantPointerNull>(C)) {
280 return N = DAG.getConstant(0, TLI.getPointerTy());
281 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000282 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000283 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
284 return N = DAG.getConstantFP(CFP->getValue(), VT);
285 } else {
286 // Canonicalize all constant ints to be unsigned.
287 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
288 }
289
290 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
291 std::map<const AllocaInst*, int>::iterator SI =
292 FuncInfo.StaticAllocaMap.find(AI);
293 if (SI != FuncInfo.StaticAllocaMap.end())
294 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
295 }
296
297 std::map<const Value*, unsigned>::const_iterator VMI =
298 FuncInfo.ValueMap.find(V);
299 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000300
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000301 unsigned InReg = VMI->second;
302
303 // If this type is not legal, make it so now.
304 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
305
306 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
307 if (DestVT < VT) {
308 // Source must be expanded. This input value is actually coming from the
309 // register pair VMI->second and VMI->second+1.
310 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
311 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
312 } else {
313 if (DestVT > VT) { // Promotion case
314 if (MVT::isFloatingPoint(VT))
315 N = DAG.getNode(ISD::FP_ROUND, VT, N);
316 else
317 N = DAG.getNode(ISD::TRUNCATE, VT, N);
318 }
319 }
320
321 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 }
323
324 const SDOperand &setValue(const Value *V, SDOperand NewN) {
325 SDOperand &N = NodeMap[V];
326 assert(N.Val == 0 && "Already set a value for this node!");
327 return N = NewN;
328 }
329
330 // Terminator instructions.
331 void visitRet(ReturnInst &I);
332 void visitBr(BranchInst &I);
333 void visitUnreachable(UnreachableInst &I) { /* noop */ }
334
335 // These all get lowered before this pass.
336 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
337 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
338 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
339
340 //
Chris Lattner8f034052005-08-22 17:28:31 +0000341 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner1c08c712005-01-07 07:47:53 +0000342 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000343 void visitSub(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000344 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
345 void visitDiv(User &I) {
346 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
347 }
348 void visitRem(User &I) {
349 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
350 }
351 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
352 void visitOr (User &I) { visitBinary(I, ISD::OR); }
353 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner8f034052005-08-22 17:28:31 +0000354 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000355 void visitShr(User &I) {
Chris Lattner8f034052005-08-22 17:28:31 +0000356 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner1c08c712005-01-07 07:47:53 +0000357 }
358
359 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
360 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
361 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
362 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
363 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
364 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
365 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
366
367 void visitGetElementPtr(User &I);
368 void visitCast(User &I);
369 void visitSelect(User &I);
370 //
371
372 void visitMalloc(MallocInst &I);
373 void visitFree(FreeInst &I);
374 void visitAlloca(AllocaInst &I);
375 void visitLoad(LoadInst &I);
376 void visitStore(StoreInst &I);
377 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
378 void visitCall(CallInst &I);
379
Chris Lattner1c08c712005-01-07 07:47:53 +0000380 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000381 void visitVAArg(VAArgInst &I);
382 void visitVAEnd(CallInst &I);
383 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000384 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000385
Chris Lattner7041ee32005-01-11 05:56:49 +0000386 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000387
388 void visitUserOp1(Instruction &I) {
389 assert(0 && "UserOp1 should not exist at instruction selection time!");
390 abort();
391 }
392 void visitUserOp2(Instruction &I) {
393 assert(0 && "UserOp2 should not exist at instruction selection time!");
394 abort();
395 }
396};
397} // end namespace llvm
398
399void SelectionDAGLowering::visitRet(ReturnInst &I) {
400 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000401 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000402 return;
403 }
404
405 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000406 MVT::ValueType TmpVT;
407
Chris Lattner1c08c712005-01-07 07:47:53 +0000408 switch (Op1.getValueType()) {
409 default: assert(0 && "Unknown value type!");
410 case MVT::i1:
411 case MVT::i8:
412 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000413 case MVT::i32:
414 // If this is a machine where 32-bits is legal or expanded, promote to
415 // 32-bits, otherwise, promote to 64-bits.
416 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
417 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000419 TmpVT = MVT::i32;
420
421 // Extend integer types to result type.
422 if (I.getOperand(0)->getType()->isSigned())
423 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
424 else
425 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 break;
427 case MVT::f32:
Chris Lattner1c08c712005-01-07 07:47:53 +0000428 case MVT::i64:
429 case MVT::f64:
430 break; // No extension needed!
431 }
432
Chris Lattnera651cf62005-01-17 19:43:36 +0000433 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000434}
435
436void SelectionDAGLowering::visitBr(BranchInst &I) {
437 // Update machine-CFG edges.
438 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000439
440 // Figure out which block is immediately after the current one.
441 MachineBasicBlock *NextBlock = 0;
442 MachineFunction::iterator BBI = CurMBB;
443 if (++BBI != CurMBB->getParent()->end())
444 NextBlock = BBI;
445
446 if (I.isUnconditional()) {
447 // If this is not a fall-through branch, emit the branch.
448 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000449 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000450 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 } else {
452 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000453
454 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000455 if (Succ1MBB == NextBlock) {
456 // If the condition is false, fall through. This means we should branch
457 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000458 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000459 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000460 } else if (Succ0MBB == NextBlock) {
461 // If the condition is true, fall through. This means we should branch if
462 // the condition is false to Succ #1. Invert the condition first.
463 SDOperand True = DAG.getConstant(1, Cond.getValueType());
464 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000465 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000466 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000467 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000468 std::vector<SDOperand> Ops;
469 Ops.push_back(getRoot());
470 Ops.push_back(Cond);
471 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
472 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
473 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 }
475 }
476}
477
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000478void SelectionDAGLowering::visitSub(User &I) {
479 // -0.0 - X --> fneg
480 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
481 if (CFP->isExactlyValue(-0.0)) {
482 SDOperand Op2 = getValue(I.getOperand(1));
483 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
484 return;
485 }
486
487 visitBinary(I, ISD::SUB);
488}
489
Chris Lattner8f034052005-08-22 17:28:31 +0000490void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000491 SDOperand Op1 = getValue(I.getOperand(0));
492 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000493
Chris Lattner8f034052005-08-22 17:28:31 +0000494 if (isShift)
Chris Lattnerfab08872005-09-02 00:19:37 +0000495 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner2c49f272005-01-19 22:31:21 +0000496
Chris Lattner1c08c712005-01-07 07:47:53 +0000497 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
498}
499
500void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
501 ISD::CondCode UnsignedOpcode) {
502 SDOperand Op1 = getValue(I.getOperand(0));
503 SDOperand Op2 = getValue(I.getOperand(1));
504 ISD::CondCode Opcode = SignedOpcode;
505 if (I.getOperand(0)->getType()->isUnsigned())
506 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000507 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000508}
509
510void SelectionDAGLowering::visitSelect(User &I) {
511 SDOperand Cond = getValue(I.getOperand(0));
512 SDOperand TrueVal = getValue(I.getOperand(1));
513 SDOperand FalseVal = getValue(I.getOperand(2));
514 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
515 TrueVal, FalseVal));
516}
517
518void SelectionDAGLowering::visitCast(User &I) {
519 SDOperand N = getValue(I.getOperand(0));
520 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
521 MVT::ValueType DestTy = TLI.getValueType(I.getType());
522
523 if (N.getValueType() == DestTy) {
524 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000525 } else if (DestTy == MVT::i1) {
526 // Cast to bool is a comparison against zero, not truncation to zero.
527 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
528 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000529 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000530 } else if (isInteger(SrcTy)) {
531 if (isInteger(DestTy)) { // Int -> Int cast
532 if (DestTy < SrcTy) // Truncating cast?
533 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
534 else if (I.getOperand(0)->getType()->isSigned())
535 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
536 else
537 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
538 } else { // Int -> FP cast
539 if (I.getOperand(0)->getType()->isSigned())
540 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
541 else
542 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
543 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000544 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000545 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
546 if (isFloatingPoint(DestTy)) { // FP -> FP cast
547 if (DestTy < SrcTy) // Rounding cast?
548 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
549 else
550 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
551 } else { // FP -> Int cast.
552 if (I.getType()->isSigned())
553 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
554 else
555 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
556 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 }
558}
559
560void SelectionDAGLowering::visitGetElementPtr(User &I) {
561 SDOperand N = getValue(I.getOperand(0));
562 const Type *Ty = I.getOperand(0)->getType();
563 const Type *UIntPtrTy = TD.getIntPtrType();
564
565 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
566 OI != E; ++OI) {
567 Value *Idx = *OI;
568 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
569 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
570 if (Field) {
571 // N = N + Offset
572 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
573 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000574 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000575 }
576 Ty = StTy->getElementType(Field);
577 } else {
578 Ty = cast<SequentialType>(Ty)->getElementType();
579 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
580 // N = N + Idx * ElementSize;
581 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner7cc47772005-01-07 21:56:57 +0000582 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
583
584 // If the index is smaller or larger than intptr_t, truncate or extend
585 // it.
586 if (IdxN.getValueType() < Scale.getValueType()) {
587 if (Idx->getType()->isSigned())
588 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
589 else
590 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
591 } else if (IdxN.getValueType() > Scale.getValueType())
592 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
593
594 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner1c08c712005-01-07 07:47:53 +0000595 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
596 }
597 }
598 }
599 setValue(&I, N);
600}
601
602void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
603 // If this is a fixed sized alloca in the entry block of the function,
604 // allocate it statically on the stack.
605 if (FuncInfo.StaticAllocaMap.count(&I))
606 return; // getValue will auto-populate this.
607
608 const Type *Ty = I.getAllocatedType();
609 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
610 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
611
612 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000613 MVT::ValueType IntPtr = TLI.getPointerTy();
614 if (IntPtr < AllocSize.getValueType())
615 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
616 else if (IntPtr > AllocSize.getValueType())
617 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000618
Chris Lattner68cd65e2005-01-22 23:04:37 +0000619 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000620 getIntPtrConstant(TySize));
621
622 // Handle alignment. If the requested alignment is less than or equal to the
623 // stack alignment, ignore it and round the size of the allocation up to the
624 // stack alignment size. If the size is greater than the stack alignment, we
625 // note this in the DYNAMIC_STACKALLOC node.
626 unsigned StackAlign =
627 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
628 if (Align <= StackAlign) {
629 Align = 0;
630 // Add SA-1 to the size.
631 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
632 getIntPtrConstant(StackAlign-1));
633 // Mask out the low bits for alignment purposes.
634 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
635 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
636 }
637
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000638 std::vector<MVT::ValueType> VTs;
639 VTs.push_back(AllocSize.getValueType());
640 VTs.push_back(MVT::Other);
641 std::vector<SDOperand> Ops;
642 Ops.push_back(getRoot());
643 Ops.push_back(AllocSize);
644 Ops.push_back(getIntPtrConstant(Align));
645 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000646 DAG.setRoot(setValue(&I, DSA).getValue(1));
647
648 // Inform the Frame Information that we have just allocated a variable-sized
649 // object.
650 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
651}
652
653
654void SelectionDAGLowering::visitLoad(LoadInst &I) {
655 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000656
Chris Lattnerd3948112005-01-17 22:19:26 +0000657 SDOperand Root;
658 if (I.isVolatile())
659 Root = getRoot();
660 else {
661 // Do not serialize non-volatile loads against each other.
662 Root = DAG.getRoot();
663 }
664
Chris Lattner369e6db2005-05-09 04:08:33 +0000665 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000666 DAG.getSrcValue(I.getOperand(0)));
Chris Lattnerd3948112005-01-17 22:19:26 +0000667 setValue(&I, L);
668
669 if (I.isVolatile())
670 DAG.setRoot(L.getValue(1));
671 else
672 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000673}
674
675
676void SelectionDAGLowering::visitStore(StoreInst &I) {
677 Value *SrcV = I.getOperand(0);
678 SDOperand Src = getValue(SrcV);
679 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000680 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000681 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000682}
683
684void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +0000685 const char *RenameFn = 0;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000686 SDOperand Tmp;
Chris Lattner1c08c712005-01-07 07:47:53 +0000687 if (Function *F = I.getCalledFunction())
Chris Lattnerc0f18152005-04-02 05:26:53 +0000688 if (F->isExternal())
689 switch (F->getIntrinsicID()) {
690 case 0: // Not an LLVM intrinsic.
691 if (F->getName() == "fabs" || F->getName() == "fabsf") {
692 if (I.getNumOperands() == 2 && // Basic sanity checks.
693 I.getOperand(1)->getType()->isFloatingPoint() &&
694 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000695 Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000696 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
697 return;
698 }
699 }
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000700 else if (F->getName() == "sin" || F->getName() == "sinf") {
701 if (I.getNumOperands() == 2 && // Basic sanity checks.
702 I.getOperand(1)->getType()->isFloatingPoint() &&
703 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000704 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000705 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
706 return;
707 }
708 }
709 else if (F->getName() == "cos" || F->getName() == "cosf") {
710 if (I.getNumOperands() == 2 && // Basic sanity checks.
711 I.getOperand(1)->getType()->isFloatingPoint() &&
712 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000713 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000714 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
715 return;
716 }
717 }
Chris Lattnerc0f18152005-04-02 05:26:53 +0000718 break;
719 case Intrinsic::vastart: visitVAStart(I); return;
720 case Intrinsic::vaend: visitVAEnd(I); return;
721 case Intrinsic::vacopy: visitVACopy(I); return;
722 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
723 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000724
Chris Lattnerc0f18152005-04-02 05:26:53 +0000725 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
726 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
727 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
728 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
729 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000730
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000731 case Intrinsic::readport:
Chris Lattner1ca85d52005-05-14 13:56:55 +0000732 case Intrinsic::readio: {
733 std::vector<MVT::ValueType> VTs;
734 VTs.push_back(TLI.getValueType(I.getType()));
735 VTs.push_back(MVT::Other);
736 std::vector<SDOperand> Ops;
737 Ops.push_back(getRoot());
738 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000739 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattner1ca85d52005-05-14 13:56:55 +0000740 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen00b168892005-07-27 06:12:32 +0000741
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000742 setValue(&I, Tmp);
743 DAG.setRoot(Tmp.getValue(1));
744 return;
Chris Lattner1ca85d52005-05-14 13:56:55 +0000745 }
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000746 case Intrinsic::writeport:
747 case Intrinsic::writeio:
748 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
749 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
750 getRoot(), getValue(I.getOperand(1)),
751 getValue(I.getOperand(2))));
752 return;
Chris Lattner7ea0ade2005-05-05 17:55:17 +0000753 case Intrinsic::dbg_stoppoint:
754 case Intrinsic::dbg_region_start:
755 case Intrinsic::dbg_region_end:
756 case Intrinsic::dbg_func_start:
757 case Intrinsic::dbg_declare:
758 if (I.getType() != Type::VoidTy)
759 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
760 return;
761
Chris Lattnerc0f18152005-04-02 05:26:53 +0000762 case Intrinsic::isunordered:
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000763 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
764 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000765 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000766
767 case Intrinsic::sqrt:
768 setValue(&I, DAG.getNode(ISD::FSQRT,
769 getValue(I.getOperand(1)).getValueType(),
770 getValue(I.getOperand(1))));
771 return;
772
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000773 case Intrinsic::pcmarker:
774 Tmp = getValue(I.getOperand(1));
775 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000776 return;
Andrew Lenharth691ef2b2005-05-03 17:19:30 +0000777 case Intrinsic::cttz:
778 setValue(&I, DAG.getNode(ISD::CTTZ,
779 getValue(I.getOperand(1)).getValueType(),
780 getValue(I.getOperand(1))));
781 return;
782 case Intrinsic::ctlz:
783 setValue(&I, DAG.getNode(ISD::CTLZ,
784 getValue(I.getOperand(1)).getValueType(),
785 getValue(I.getOperand(1))));
786 return;
787 case Intrinsic::ctpop:
788 setValue(&I, DAG.getNode(ISD::CTPOP,
789 getValue(I.getOperand(1)).getValueType(),
790 getValue(I.getOperand(1))));
791 return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000792 default:
793 std::cerr << I;
794 assert(0 && "This intrinsic is not implemented yet!");
795 return;
Chris Lattnerc0f18152005-04-02 05:26:53 +0000796 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000797
Chris Lattner64e14b12005-01-08 22:48:57 +0000798 SDOperand Callee;
799 if (!RenameFn)
800 Callee = getValue(I.getOperand(0));
801 else
802 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +0000803 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000804
Chris Lattner1c08c712005-01-07 07:47:53 +0000805 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
806 Value *Arg = I.getOperand(i);
807 SDOperand ArgNode = getValue(Arg);
808 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
809 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000810
Nate Begeman8e21e712005-03-26 01:29:23 +0000811 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
812 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000813
Chris Lattnercf5734d2005-01-08 19:26:18 +0000814 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +0000815 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +0000816 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +0000817 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +0000818 setValue(&I, Result.first);
819 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000820}
821
822void SelectionDAGLowering::visitMalloc(MallocInst &I) {
823 SDOperand Src = getValue(I.getOperand(0));
824
825 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +0000826
827 if (IntPtr < Src.getValueType())
828 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
829 else if (IntPtr > Src.getValueType())
830 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +0000831
832 // Scale the source by the type size.
833 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
834 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
835 Src, getIntPtrConstant(ElementSize));
836
837 std::vector<std::pair<SDOperand, const Type*> > Args;
838 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +0000839
840 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000841 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000842 DAG.getExternalSymbol("malloc", IntPtr),
843 Args, DAG);
844 setValue(&I, Result.first); // Pointers always fit in registers
845 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000846}
847
848void SelectionDAGLowering::visitFree(FreeInst &I) {
849 std::vector<std::pair<SDOperand, const Type*> > Args;
850 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
851 TLI.getTargetData().getIntPtrType()));
852 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +0000853 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000854 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000855 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
856 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000857}
858
Chris Lattner025c39b2005-08-26 20:54:47 +0000859// InsertAtEndOfBasicBlock - This method should be implemented by targets that
860// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
861// instructions are special in various ways, which require special support to
862// insert. The specified MachineInstr is created but not inserted into any
863// basic blocks, and the scheduler passes ownership of it to this method.
864MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
865 MachineBasicBlock *MBB) {
866 std::cerr << "If a target marks an instruction with "
867 "'usesCustomDAGSchedInserter', it must implement "
868 "TargetLowering::InsertAtEndOfBasicBlock!\n";
869 abort();
870 return 0;
871}
872
Chris Lattnere64e72b2005-07-05 19:57:53 +0000873SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
874 SDOperand VAListP, Value *VAListV,
875 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000876 // We have no sane default behavior, just emit a useful error message and bail
877 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +0000878 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000879 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +0000880 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +0000881}
882
Chris Lattnere64e72b2005-07-05 19:57:53 +0000883SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +0000884 SelectionDAG &DAG) {
885 // Default to a noop.
886 return Chain;
887}
888
Chris Lattnere64e72b2005-07-05 19:57:53 +0000889SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
890 SDOperand SrcP, Value *SrcV,
891 SDOperand DestP, Value *DestV,
892 SelectionDAG &DAG) {
893 // Default to copying the input list.
894 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
895 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +0000896 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +0000897 Val, DestP, DAG.getSrcValue(DestV));
898 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +0000899}
900
901std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +0000902TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
903 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000904 // We have no sane default behavior, just emit a useful error message and bail
905 // out.
906 std::cerr << "Variable arguments handling not implemented on this target!\n";
907 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000908 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +0000909}
910
911
912void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +0000913 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
914 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +0000915}
916
917void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
918 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +0000919 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +0000920 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000921 setValue(&I, Result.first);
922 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000923}
924
925void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000926 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +0000927 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000928}
929
930void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +0000931 SDOperand Result =
932 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
933 getValue(I.getOperand(1)), I.getOperand(1), DAG);
934 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +0000935}
936
Chris Lattner39ae3622005-01-09 00:00:49 +0000937
938// It is always conservatively correct for llvm.returnaddress and
939// llvm.frameaddress to return 0.
940std::pair<SDOperand, SDOperand>
941TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
942 unsigned Depth, SelectionDAG &DAG) {
943 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +0000944}
945
Chris Lattner50381b62005-05-14 05:50:48 +0000946SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +0000947 assert(0 && "LowerOperation not implemented for this target!");
948 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000949 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +0000950}
951
Chris Lattner39ae3622005-01-09 00:00:49 +0000952void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
953 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
954 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000955 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000956 setValue(&I, Result.first);
957 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000958}
959
Chris Lattner7041ee32005-01-11 05:56:49 +0000960void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
961 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +0000962 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +0000963 Ops.push_back(getValue(I.getOperand(1)));
964 Ops.push_back(getValue(I.getOperand(2)));
965 Ops.push_back(getValue(I.getOperand(3)));
966 Ops.push_back(getValue(I.getOperand(4)));
967 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000968}
969
Chris Lattner7041ee32005-01-11 05:56:49 +0000970//===----------------------------------------------------------------------===//
971// SelectionDAGISel code
972//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000973
974unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
975 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
976}
977
Chris Lattner495a0b52005-08-17 06:37:43 +0000978void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +0000979 // FIXME: we only modify the CFG to split critical edges. This
980 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +0000981}
Chris Lattner1c08c712005-01-07 07:47:53 +0000982
983
984bool SelectionDAGISel::runOnFunction(Function &Fn) {
985 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
986 RegMap = MF.getSSARegMap();
987 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
988
Chris Lattner495a0b52005-08-17 06:37:43 +0000989 // First pass, split all critical edges for PHI nodes with incoming values
990 // that are constants, this way the load of the constant into a vreg will not
991 // be placed into MBBs that are used some other way.
Chris Lattner36b708f2005-08-18 17:35:14 +0000992 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
993 PHINode *PN;
994 for (BasicBlock::iterator BBI = BB->begin();
995 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
996 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
997 if (isa<Constant>(PN->getIncomingValue(i)))
998 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
999 }
Chris Lattner495a0b52005-08-17 06:37:43 +00001000
Chris Lattner1c08c712005-01-07 07:47:53 +00001001 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1002
1003 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1004 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001005
Chris Lattner1c08c712005-01-07 07:47:53 +00001006 return true;
1007}
1008
1009
Chris Lattnerddb870b2005-01-13 17:59:43 +00001010SDOperand SelectionDAGISel::
1011CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001012 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001013 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001014 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001015 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001016
1017 // If this type is not legal, we must make sure to not create an invalid
1018 // register use.
1019 MVT::ValueType SrcVT = Op.getValueType();
1020 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1021 SelectionDAG &DAG = SDL.DAG;
1022 if (SrcVT == DestVT) {
1023 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1024 } else if (SrcVT < DestVT) {
1025 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001026 if (MVT::isFloatingPoint(SrcVT))
1027 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1028 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001029 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001030 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1031 } else {
1032 // The src value is expanded into multiple registers.
1033 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1034 Op, DAG.getConstant(0, MVT::i32));
1035 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1036 Op, DAG.getConstant(1, MVT::i32));
1037 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1038 return DAG.getCopyToReg(Op, Reg+1, Hi);
1039 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001040}
1041
Chris Lattner0afa8e32005-01-17 17:55:19 +00001042/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1043/// single basic block, return that block. Otherwise, return a null pointer.
1044static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1045 if (A->use_empty()) return 0;
1046 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1047 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1048 ++UI)
1049 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1050 return 0; // Disagreement among the users?
Chris Lattneraa781b32005-02-17 19:40:32 +00001051
1052 // Okay, there is a single BB user. Only permit this optimization if this is
1053 // the entry block, otherwise, we might sink argument loads into loops and
1054 // stuff. Later, when we have global instruction selection, this won't be an
1055 // issue clearly.
1056 if (BB == BB->getParent()->begin())
1057 return BB;
1058 return 0;
Chris Lattner0afa8e32005-01-17 17:55:19 +00001059}
1060
Chris Lattner068a81e2005-01-17 17:15:02 +00001061void SelectionDAGISel::
1062LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1063 std::vector<SDOperand> &UnorderedChains) {
1064 // If this is the entry block, emit arguments.
1065 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001066 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner068a81e2005-01-17 17:15:02 +00001067
1068 if (BB == &F.front()) {
Chris Lattner0afa8e32005-01-17 17:55:19 +00001069 SDOperand OldRoot = SDL.DAG.getRoot();
1070
Chris Lattner068a81e2005-01-17 17:15:02 +00001071 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1072
Chris Lattner0afa8e32005-01-17 17:55:19 +00001073 // If there were side effects accessing the argument list, do not do
1074 // anything special.
1075 if (OldRoot != SDL.DAG.getRoot()) {
1076 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001077 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1078 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001079 if (!AI->use_empty()) {
1080 SDL.setValue(AI, Args[a]);
Chris Lattner9d3a4832005-08-26 22:49:59 +00001081
Chris Lattnerfab08872005-09-02 00:19:37 +00001082 SDOperand Copy =
1083 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1084 UnorderedChains.push_back(Copy);
Chris Lattner0afa8e32005-01-17 17:55:19 +00001085 }
1086 } else {
1087 // Otherwise, if any argument is only accessed in a single basic block,
1088 // emit that argument only to that basic block.
1089 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1091 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001092 if (!AI->use_empty()) {
1093 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1094 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1095 std::make_pair(AI, a)));
1096 } else {
1097 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001098 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +00001099 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1100 UnorderedChains.push_back(Copy);
1101 }
1102 }
1103 }
Chris Lattner405ef9e2005-05-13 07:33:32 +00001104
1105 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner0afa8e32005-01-17 17:55:19 +00001106 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001107
Chris Lattner0afa8e32005-01-17 17:55:19 +00001108 // See if there are any block-local arguments that need to be emitted in this
1109 // block.
1110
1111 if (!FuncInfo.BlockLocalArguments.empty()) {
1112 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1113 FuncInfo.BlockLocalArguments.lower_bound(BB);
1114 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1115 // Lower the arguments into this block.
1116 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001117
Chris Lattner0afa8e32005-01-17 17:55:19 +00001118 // Set up the value mapping for the local arguments.
1119 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1120 ++BLAI)
1121 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001122
Chris Lattner0afa8e32005-01-17 17:55:19 +00001123 // Any dead arguments will just be ignored here.
1124 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001125 }
1126}
1127
1128
Chris Lattner1c08c712005-01-07 07:47:53 +00001129void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1130 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1131 FunctionLoweringInfo &FuncInfo) {
1132 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001133
1134 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001135
Chris Lattner068a81e2005-01-17 17:15:02 +00001136 // Lower any arguments needed in this block.
1137 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001138
1139 BB = FuncInfo.MBBMap[LLVMBB];
1140 SDL.setCurrentBasicBlock(BB);
1141
1142 // Lower all of the non-terminator instructions.
1143 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1144 I != E; ++I)
1145 SDL.visit(*I);
1146
1147 // Ensure that all instructions which are used outside of their defining
1148 // blocks are available as virtual registers.
1149 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001150 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001151 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001152 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001153 UnorderedChains.push_back(
1154 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001155 }
1156
1157 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1158 // ensure constants are generated when needed. Remember the virtual registers
1159 // that need to be added to the Machine PHI nodes as input. We cannot just
1160 // directly add them, because expansion might result in multiple MBB's for one
1161 // BB. As such, the start of the BB might correspond to a different MBB than
1162 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001163 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001164
1165 // Emit constants only once even if used by multiple PHI nodes.
1166 std::map<Constant*, unsigned> ConstantsOut;
1167
1168 // Check successor nodes PHI nodes that expect a constant to be available from
1169 // this block.
1170 TerminatorInst *TI = LLVMBB->getTerminator();
1171 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1172 BasicBlock *SuccBB = TI->getSuccessor(succ);
1173 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1174 PHINode *PN;
1175
1176 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1177 // nodes and Machine PHI nodes, but the incoming operands have not been
1178 // emitted yet.
1179 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001180 (PN = dyn_cast<PHINode>(I)); ++I)
1181 if (!PN->use_empty()) {
1182 unsigned Reg;
1183 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1184 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1185 unsigned &RegOut = ConstantsOut[C];
1186 if (RegOut == 0) {
1187 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001188 UnorderedChains.push_back(
1189 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001190 }
1191 Reg = RegOut;
1192 } else {
1193 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001194 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001195 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001196 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1197 "Didn't codegen value into a register!??");
1198 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001199 UnorderedChains.push_back(
1200 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001201 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001202 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001203
Chris Lattnerf44fd882005-01-07 21:34:19 +00001204 // Remember that this register needs to added to the machine PHI node as
1205 // the input for this MBB.
1206 unsigned NumElements =
1207 TLI.getNumElements(TLI.getValueType(PN->getType()));
1208 for (unsigned i = 0, e = NumElements; i != e; ++i)
1209 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001210 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001211 }
1212 ConstantsOut.clear();
1213
Chris Lattnerddb870b2005-01-13 17:59:43 +00001214 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001215 if (!UnorderedChains.empty()) {
Chris Lattnerd3948112005-01-17 22:19:26 +00001216 UnorderedChains.push_back(SDL.getRoot());
Chris Lattnerddb870b2005-01-13 17:59:43 +00001217 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1218 }
1219
Chris Lattner1c08c712005-01-07 07:47:53 +00001220 // Lower the terminator after the copies are emitted.
1221 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001222
1223 // Make sure the root of the DAG is up-to-date.
1224 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001225}
1226
1227void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1228 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001229 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001230 CurDAG = &DAG;
1231 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1232
1233 // First step, lower LLVM code to some DAG. This DAG may use operations and
1234 // types that are not supported by the target.
1235 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1236
1237 DEBUG(std::cerr << "Lowered selection DAG:\n");
1238 DEBUG(DAG.dump());
1239
1240 // Second step, hack on the DAG until it only uses operations and types that
1241 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001242 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001243
1244 DEBUG(std::cerr << "Legalized selection DAG:\n");
1245 DEBUG(DAG.dump());
1246
Chris Lattner82cfa5d2005-08-24 00:34:29 +00001247 if (ViewDAGs) DAG.viewGraph();
1248
Chris Lattnera33ef482005-03-30 01:10:47 +00001249 // Third, instruction select all of the operations to machine code, adding the
1250 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001251 InstructionSelectBasicBlock(DAG);
1252
Chris Lattner1c08c712005-01-07 07:47:53 +00001253 DEBUG(std::cerr << "Selected machine code:\n");
1254 DEBUG(BB->dump());
1255
Chris Lattnera33ef482005-03-30 01:10:47 +00001256 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001257 // PHI nodes in successors.
1258 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1259 MachineInstr *PHI = PHINodesToUpdate[i].first;
1260 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1261 "This is not a machine PHI node that we are updating!");
1262 PHI->addRegOperand(PHINodesToUpdate[i].second);
1263 PHI->addMachineBasicBlockOperand(BB);
1264 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001265
1266 // Finally, add the CFG edges from the last selected MBB to the successor
1267 // MBBs.
1268 TerminatorInst *TI = LLVMBB->getTerminator();
1269 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1270 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1271 BB->addSuccessor(Succ0MBB);
1272 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001273}