blob: f747b35cf8d40d5c68d677806cdd7e0f6042de00 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3// 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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/SelectionDAG.h"
25#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetFrameInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetMachine.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/Support/Debug.h"
33#include <map>
34#include <iostream>
35using namespace llvm;
36
Chris Lattnere05a4612005-01-12 03:41:21 +000037#ifndef _NDEBUG
38static cl::opt<bool>
39ViewDAGs("view-isel-dags", cl::Hidden,
40 cl::desc("Pop up a window to show isel dags as they are selected"));
41#else
42static const bool ViewDAGS = 0;
43#endif
44
Chris Lattner7a60d912005-01-07 07:47:53 +000045namespace llvm {
46 //===--------------------------------------------------------------------===//
47 /// FunctionLoweringInfo - This contains information that is global to a
48 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000049 class FunctionLoweringInfo {
50 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000051 TargetLowering &TLI;
52 Function &Fn;
53 MachineFunction &MF;
54 SSARegMap *RegMap;
55
56 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
57
58 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
59 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
60
61 /// ValueMap - Since we emit code for the function a basic block at a time,
62 /// we must remember which virtual registers hold the values for
63 /// cross-basic-block values.
64 std::map<const Value*, unsigned> ValueMap;
65
66 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
67 /// the entry block. This allows the allocas to be efficiently referenced
68 /// anywhere in the function.
69 std::map<const AllocaInst*, int> StaticAllocaMap;
70
71 unsigned MakeReg(MVT::ValueType VT) {
72 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
73 }
74
75 unsigned CreateRegForValue(const Value *V) {
76 MVT::ValueType VT = TLI.getValueType(V->getType());
77 // The common case is that we will only create one register for this
78 // value. If we have that case, create and return the virtual register.
79 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000080 if (NV == 1) {
81 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000082 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000083 }
Chris Lattner7a60d912005-01-07 07:47:53 +000084
85 // If this value is represented with multiple target registers, make sure
86 // to create enough consequtive registers of the right (smaller) type.
87 unsigned NT = VT-1; // Find the type to use.
88 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
89 --NT;
90
91 unsigned R = MakeReg((MVT::ValueType)NT);
92 for (unsigned i = 1; i != NV; ++i)
93 MakeReg((MVT::ValueType)NT);
94 return R;
95 }
96
97 unsigned InitializeRegForValue(const Value *V) {
98 unsigned &R = ValueMap[V];
99 assert(R == 0 && "Already initialized this value register!");
100 return R = CreateRegForValue(V);
101 }
102 };
103}
104
105/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
106/// PHI nodes or outside of the basic block that defines it.
107static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
108 if (isa<PHINode>(I)) return true;
109 BasicBlock *BB = I->getParent();
110 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
111 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
112 return true;
113 return false;
114}
115
116FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
117 Function &fn, MachineFunction &mf)
118 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
119
120 // Initialize the mapping of values to registers. This is only set up for
121 // instruction values that are used outside of the block that defines
122 // them.
123 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
124 InitializeRegForValue(AI);
125
126 Function::iterator BB = Fn.begin(), E = Fn.end();
127 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
128 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
129 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
130 const Type *Ty = AI->getAllocatedType();
131 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
132 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
133 TySize *= CUI->getValue(); // Get total allocated size.
134 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000135 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000136 }
137
138 for (; BB != E; ++BB)
Chris Lattnerd0061952005-01-08 19:52:31 +0000139 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000140 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
141 if (!isa<AllocaInst>(I) ||
142 !StaticAllocaMap.count(cast<AllocaInst>(I)))
143 InitializeRegForValue(I);
144
145 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
146 // also creates the initial PHI MachineInstrs, though none of the input
147 // operands are populated.
148 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
149 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
150 MBBMap[BB] = MBB;
151 MF.getBasicBlockList().push_back(MBB);
152
153 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
154 // appropriate.
155 PHINode *PN;
156 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000157 (PN = dyn_cast<PHINode>(I)); ++I)
158 if (!PN->use_empty()) {
159 unsigned NumElements =
160 TLI.getNumElements(TLI.getValueType(PN->getType()));
161 unsigned PHIReg = ValueMap[PN];
162 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
163 for (unsigned i = 0; i != NumElements; ++i)
164 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
165 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000166 }
167}
168
169
170
171//===----------------------------------------------------------------------===//
172/// SelectionDAGLowering - This is the common target-independent lowering
173/// implementation that is parameterized by a TargetLowering object.
174/// Also, targets can overload any lowering method.
175///
176namespace llvm {
177class SelectionDAGLowering {
178 MachineBasicBlock *CurMBB;
179
180 std::map<const Value*, SDOperand> NodeMap;
181
182public:
183 // TLI - This is information that describes the available target features we
184 // need for lowering. This indicates when operations are unavailable,
185 // implemented with a libcall, etc.
186 TargetLowering &TLI;
187 SelectionDAG &DAG;
188 const TargetData &TD;
189
190 /// FuncInfo - Information about the function as a whole.
191 ///
192 FunctionLoweringInfo &FuncInfo;
193
194 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
195 FunctionLoweringInfo &funcinfo)
196 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
197 FuncInfo(funcinfo) {
198 }
199
200 void visit(Instruction &I) { visit(I.getOpcode(), I); }
201
202 void visit(unsigned Opcode, User &I) {
203 switch (Opcode) {
204 default: assert(0 && "Unknown instruction type encountered!");
205 abort();
206 // Build the switch statement using the Instruction.def file.
207#define HANDLE_INST(NUM, OPCODE, CLASS) \
208 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
209#include "llvm/Instruction.def"
210 }
211 }
212
213 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
214
215
216 SDOperand getIntPtrConstant(uint64_t Val) {
217 return DAG.getConstant(Val, TLI.getPointerTy());
218 }
219
220 SDOperand getValue(const Value *V) {
221 SDOperand &N = NodeMap[V];
222 if (N.Val) return N;
223
224 MVT::ValueType VT = TLI.getValueType(V->getType());
225 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
226 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
227 visit(CE->getOpcode(), *CE);
228 assert(N.Val && "visit didn't populate the ValueMap!");
229 return N;
230 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
231 return N = DAG.getGlobalAddress(GV, VT);
232 } else if (isa<ConstantPointerNull>(C)) {
233 return N = DAG.getConstant(0, TLI.getPointerTy());
234 } else if (isa<UndefValue>(C)) {
235 /// FIXME: Implement UNDEFVALUE better.
236 if (MVT::isInteger(VT))
237 return N = DAG.getConstant(0, VT);
238 else if (MVT::isFloatingPoint(VT))
239 return N = DAG.getConstantFP(0, VT);
240 else
241 assert(0 && "Unknown value type!");
242
243 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
244 return N = DAG.getConstantFP(CFP->getValue(), VT);
245 } else {
246 // Canonicalize all constant ints to be unsigned.
247 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
248 }
249
250 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
251 std::map<const AllocaInst*, int>::iterator SI =
252 FuncInfo.StaticAllocaMap.find(AI);
253 if (SI != FuncInfo.StaticAllocaMap.end())
254 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
255 }
256
257 std::map<const Value*, unsigned>::const_iterator VMI =
258 FuncInfo.ValueMap.find(V);
259 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000260
261 MVT::ValueType RegVT = VT;
262 if (TLI.getTypeAction(VT) == 1) // Must promote this value?
263 RegVT = TLI.getTypeToTransformTo(VT);
264
265 N = DAG.getCopyFromReg(VMI->second, RegVT, DAG.getEntryNode());
266
267 if (RegVT != VT)
268 if (MVT::isFloatingPoint(VT))
269 N = DAG.getNode(ISD::FP_ROUND, VT, N);
270 else
271 N = DAG.getNode(ISD::TRUNCATE, VT, N);
272
273 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000274 }
275
276 const SDOperand &setValue(const Value *V, SDOperand NewN) {
277 SDOperand &N = NodeMap[V];
278 assert(N.Val == 0 && "Already set a value for this node!");
279 return N = NewN;
280 }
281
282 // Terminator instructions.
283 void visitRet(ReturnInst &I);
284 void visitBr(BranchInst &I);
285 void visitUnreachable(UnreachableInst &I) { /* noop */ }
286
287 // These all get lowered before this pass.
288 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
289 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
290 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
291
292 //
293 void visitBinary(User &I, unsigned Opcode);
294 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
295 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
296 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
297 void visitDiv(User &I) {
298 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
299 }
300 void visitRem(User &I) {
301 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
302 }
303 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
304 void visitOr (User &I) { visitBinary(I, ISD::OR); }
305 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
306 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
307 void visitShr(User &I) {
308 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
309 }
310
311 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
312 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
313 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
314 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
315 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
316 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
317 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
318
319 void visitGetElementPtr(User &I);
320 void visitCast(User &I);
321 void visitSelect(User &I);
322 //
323
324 void visitMalloc(MallocInst &I);
325 void visitFree(FreeInst &I);
326 void visitAlloca(AllocaInst &I);
327 void visitLoad(LoadInst &I);
328 void visitStore(StoreInst &I);
329 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
330 void visitCall(CallInst &I);
331
Chris Lattner7a60d912005-01-07 07:47:53 +0000332 void visitVAStart(CallInst &I);
333 void visitVANext(VANextInst &I);
334 void visitVAArg(VAArgInst &I);
335 void visitVAEnd(CallInst &I);
336 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000337 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000338
Chris Lattner875def92005-01-11 05:56:49 +0000339 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000340
341 void visitUserOp1(Instruction &I) {
342 assert(0 && "UserOp1 should not exist at instruction selection time!");
343 abort();
344 }
345 void visitUserOp2(Instruction &I) {
346 assert(0 && "UserOp2 should not exist at instruction selection time!");
347 abort();
348 }
349};
350} // end namespace llvm
351
352void SelectionDAGLowering::visitRet(ReturnInst &I) {
353 if (I.getNumOperands() == 0) {
354 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, DAG.getRoot()));
355 return;
356 }
357
358 SDOperand Op1 = getValue(I.getOperand(0));
359 switch (Op1.getValueType()) {
360 default: assert(0 && "Unknown value type!");
361 case MVT::i1:
362 case MVT::i8:
363 case MVT::i16:
364 // Extend integer types to 32-bits.
365 if (I.getOperand(0)->getType()->isSigned())
366 Op1 = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Op1);
367 else
368 Op1 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op1);
369 break;
370 case MVT::f32:
371 // Extend float to double.
372 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
373 break;
374 case MVT::i32:
375 case MVT::i64:
376 case MVT::f64:
377 break; // No extension needed!
378 }
379
380 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, DAG.getRoot(), Op1));
381}
382
383void SelectionDAGLowering::visitBr(BranchInst &I) {
384 // Update machine-CFG edges.
385 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
386 CurMBB->addSuccessor(Succ0MBB);
387
388 // Figure out which block is immediately after the current one.
389 MachineBasicBlock *NextBlock = 0;
390 MachineFunction::iterator BBI = CurMBB;
391 if (++BBI != CurMBB->getParent()->end())
392 NextBlock = BBI;
393
394 if (I.isUnconditional()) {
395 // If this is not a fall-through branch, emit the branch.
396 if (Succ0MBB != NextBlock)
397 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, DAG.getRoot(),
398 DAG.getBasicBlock(Succ0MBB)));
399 } else {
400 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
401 CurMBB->addSuccessor(Succ1MBB);
402
403 SDOperand Cond = getValue(I.getCondition());
404
405 if (Succ1MBB == NextBlock) {
406 // If the condition is false, fall through. This means we should branch
407 // if the condition is true to Succ #0.
408 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
409 Cond, DAG.getBasicBlock(Succ0MBB)));
410 } else if (Succ0MBB == NextBlock) {
411 // If the condition is true, fall through. This means we should branch if
412 // the condition is false to Succ #1. Invert the condition first.
413 SDOperand True = DAG.getConstant(1, Cond.getValueType());
414 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
415 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
416 Cond, DAG.getBasicBlock(Succ1MBB)));
417 } else {
418 // Neither edge is a fall through. If the comparison is true, jump to
419 // Succ#0, otherwise branch unconditionally to succ #1.
420 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
421 Cond, DAG.getBasicBlock(Succ0MBB)));
422 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, DAG.getRoot(),
423 DAG.getBasicBlock(Succ1MBB)));
424 }
425 }
426}
427
428void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
429 SDOperand Op1 = getValue(I.getOperand(0));
430 SDOperand Op2 = getValue(I.getOperand(1));
431 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
432}
433
434void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
435 ISD::CondCode UnsignedOpcode) {
436 SDOperand Op1 = getValue(I.getOperand(0));
437 SDOperand Op2 = getValue(I.getOperand(1));
438 ISD::CondCode Opcode = SignedOpcode;
439 if (I.getOperand(0)->getType()->isUnsigned())
440 Opcode = UnsignedOpcode;
441 setValue(&I, DAG.getSetCC(Opcode, Op1, Op2));
442}
443
444void SelectionDAGLowering::visitSelect(User &I) {
445 SDOperand Cond = getValue(I.getOperand(0));
446 SDOperand TrueVal = getValue(I.getOperand(1));
447 SDOperand FalseVal = getValue(I.getOperand(2));
448 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
449 TrueVal, FalseVal));
450}
451
452void SelectionDAGLowering::visitCast(User &I) {
453 SDOperand N = getValue(I.getOperand(0));
454 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
455 MVT::ValueType DestTy = TLI.getValueType(I.getType());
456
457 if (N.getValueType() == DestTy) {
458 setValue(&I, N); // noop cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000459 } else if (isInteger(SrcTy)) {
460 if (isInteger(DestTy)) { // Int -> Int cast
461 if (DestTy < SrcTy) // Truncating cast?
462 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
463 else if (I.getOperand(0)->getType()->isSigned())
464 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
465 else
466 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
467 } else { // Int -> FP cast
468 if (I.getOperand(0)->getType()->isSigned())
469 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
470 else
471 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
472 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000474 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
475 if (isFloatingPoint(DestTy)) { // FP -> FP cast
476 if (DestTy < SrcTy) // Rounding cast?
477 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
478 else
479 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
480 } else { // FP -> Int cast.
481 if (I.getType()->isSigned())
482 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
483 else
484 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
485 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000486 }
487}
488
489void SelectionDAGLowering::visitGetElementPtr(User &I) {
490 SDOperand N = getValue(I.getOperand(0));
491 const Type *Ty = I.getOperand(0)->getType();
492 const Type *UIntPtrTy = TD.getIntPtrType();
493
494 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
495 OI != E; ++OI) {
496 Value *Idx = *OI;
497 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
498 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
499 if (Field) {
500 // N = N + Offset
501 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
502 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
503 getIntPtrConstant(Offset));
504 }
505 Ty = StTy->getElementType(Field);
506 } else {
507 Ty = cast<SequentialType>(Ty)->getElementType();
508 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
509 // N = N + Idx * ElementSize;
510 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000511 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
512
513 // If the index is smaller or larger than intptr_t, truncate or extend
514 // it.
515 if (IdxN.getValueType() < Scale.getValueType()) {
516 if (Idx->getType()->isSigned())
517 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
518 else
519 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
520 } else if (IdxN.getValueType() > Scale.getValueType())
521 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
522
523 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
524
Chris Lattner7a60d912005-01-07 07:47:53 +0000525 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
526 }
527 }
528 }
529 setValue(&I, N);
530}
531
532void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
533 // If this is a fixed sized alloca in the entry block of the function,
534 // allocate it statically on the stack.
535 if (FuncInfo.StaticAllocaMap.count(&I))
536 return; // getValue will auto-populate this.
537
538 const Type *Ty = I.getAllocatedType();
539 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
540 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
541
542 SDOperand AllocSize = getValue(I.getArraySize());
543
544 assert(AllocSize.getValueType() == TLI.getPointerTy() &&
545 "FIXME: should extend or truncate to pointer size!");
546
547 AllocSize = DAG.getNode(ISD::MUL, TLI.getPointerTy(), AllocSize,
548 getIntPtrConstant(TySize));
549
550 // Handle alignment. If the requested alignment is less than or equal to the
551 // stack alignment, ignore it and round the size of the allocation up to the
552 // stack alignment size. If the size is greater than the stack alignment, we
553 // note this in the DYNAMIC_STACKALLOC node.
554 unsigned StackAlign =
555 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
556 if (Align <= StackAlign) {
557 Align = 0;
558 // Add SA-1 to the size.
559 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
560 getIntPtrConstant(StackAlign-1));
561 // Mask out the low bits for alignment purposes.
562 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
563 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
564 }
565
566 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
567 DAG.getRoot(), AllocSize,
568 getIntPtrConstant(Align));
569 DAG.setRoot(setValue(&I, DSA).getValue(1));
570
571 // Inform the Frame Information that we have just allocated a variable-sized
572 // object.
573 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
574}
575
576
577void SelectionDAGLowering::visitLoad(LoadInst &I) {
578 SDOperand Ptr = getValue(I.getOperand(0));
579 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), DAG.getRoot(), Ptr);
580 DAG.setRoot(setValue(&I, L).getValue(1));
581}
582
583
584void SelectionDAGLowering::visitStore(StoreInst &I) {
585 Value *SrcV = I.getOperand(0);
586 SDOperand Src = getValue(SrcV);
587 SDOperand Ptr = getValue(I.getOperand(1));
588 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, DAG.getRoot(), Src, Ptr));
Chris Lattner7a60d912005-01-07 07:47:53 +0000589}
590
591void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000592 const char *RenameFn = 0;
Chris Lattner7a60d912005-01-07 07:47:53 +0000593 if (Function *F = I.getCalledFunction())
594 switch (F->getIntrinsicID()) {
595 case 0: break; // Not an intrinsic.
596 case Intrinsic::vastart: visitVAStart(I); return;
597 case Intrinsic::vaend: visitVAEnd(I); return;
598 case Intrinsic::vacopy: visitVACopy(I); return;
Chris Lattner58cfd792005-01-09 00:00:49 +0000599 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
600 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 default:
602 // FIXME: IMPLEMENT THESE.
603 // readport, writeport, readio, writeio
604 assert(0 && "This intrinsic is not implemented yet!");
605 return;
Chris Lattner18d2b342005-01-08 22:48:57 +0000606 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
607 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
Chris Lattner875def92005-01-11 05:56:49 +0000608 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
609 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
610 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000611
612 case Intrinsic::isunordered:
613 setValue(&I, DAG.getSetCC(ISD::SETUO, getValue(I.getOperand(1)),
614 getValue(I.getOperand(2))));
615 return;
616 }
617
Chris Lattner18d2b342005-01-08 22:48:57 +0000618 SDOperand Callee;
619 if (!RenameFn)
620 Callee = getValue(I.getOperand(0));
621 else
622 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000623 std::vector<std::pair<SDOperand, const Type*> > Args;
624
625 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
626 Value *Arg = I.getOperand(i);
627 SDOperand ArgNode = getValue(Arg);
628 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
629 }
630
Chris Lattner1f45cd72005-01-08 19:26:18 +0000631 std::pair<SDOperand,SDOperand> Result =
632 TLI.LowerCallTo(DAG.getRoot(), I.getType(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000633 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000634 setValue(&I, Result.first);
635 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000636}
637
638void SelectionDAGLowering::visitMalloc(MallocInst &I) {
639 SDOperand Src = getValue(I.getOperand(0));
640
641 MVT::ValueType IntPtr = TLI.getPointerTy();
642 // FIXME: Extend or truncate to the intptr size.
643 assert(Src.getValueType() == IntPtr && "Need to adjust the amount!");
644
645 // Scale the source by the type size.
646 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
647 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
648 Src, getIntPtrConstant(ElementSize));
649
650 std::vector<std::pair<SDOperand, const Type*> > Args;
651 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000652
653 std::pair<SDOperand,SDOperand> Result =
654 TLI.LowerCallTo(DAG.getRoot(), I.getType(),
655 DAG.getExternalSymbol("malloc", IntPtr),
656 Args, DAG);
657 setValue(&I, Result.first); // Pointers always fit in registers
658 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000659}
660
661void SelectionDAGLowering::visitFree(FreeInst &I) {
662 std::vector<std::pair<SDOperand, const Type*> > Args;
663 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
664 TLI.getTargetData().getIntPtrType()));
665 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000666 std::pair<SDOperand,SDOperand> Result =
667 TLI.LowerCallTo(DAG.getRoot(), Type::VoidTy,
668 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
669 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000670}
671
Chris Lattner58cfd792005-01-09 00:00:49 +0000672std::pair<SDOperand, SDOperand>
673TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000674 // We have no sane default behavior, just emit a useful error message and bail
675 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000676 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000677 abort();
678}
679
Chris Lattner58cfd792005-01-09 00:00:49 +0000680SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
681 SelectionDAG &DAG) {
682 // Default to a noop.
683 return Chain;
684}
685
686std::pair<SDOperand,SDOperand>
687TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
688 // Default to returning the input list.
689 return std::make_pair(L, Chain);
690}
691
692std::pair<SDOperand,SDOperand>
693TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
694 const Type *ArgTy, SelectionDAG &DAG) {
695 // We have no sane default behavior, just emit a useful error message and bail
696 // out.
697 std::cerr << "Variable arguments handling not implemented on this target!\n";
698 abort();
699}
700
701
702void SelectionDAGLowering::visitVAStart(CallInst &I) {
703 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(DAG.getRoot(), DAG);
704 setValue(&I, Result.first);
705 DAG.setRoot(Result.second);
706}
707
708void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
709 std::pair<SDOperand,SDOperand> Result =
710 TLI.LowerVAArgNext(false, DAG.getRoot(), getValue(I.getOperand(0)),
711 I.getType(), DAG);
712 setValue(&I, Result.first);
713 DAG.setRoot(Result.second);
714}
715
Chris Lattner7a60d912005-01-07 07:47:53 +0000716void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000717 std::pair<SDOperand,SDOperand> Result =
718 TLI.LowerVAArgNext(true, DAG.getRoot(), getValue(I.getOperand(0)),
719 I.getArgType(), DAG);
720 setValue(&I, Result.first);
721 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000722}
723
724void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000725 DAG.setRoot(TLI.LowerVAEnd(DAG.getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000726}
727
728void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000729 std::pair<SDOperand,SDOperand> Result =
730 TLI.LowerVACopy(DAG.getRoot(), getValue(I.getOperand(1)), DAG);
731 setValue(&I, Result.first);
732 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000733}
734
Chris Lattner58cfd792005-01-09 00:00:49 +0000735
736// It is always conservatively correct for llvm.returnaddress and
737// llvm.frameaddress to return 0.
738std::pair<SDOperand, SDOperand>
739TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
740 unsigned Depth, SelectionDAG &DAG) {
741 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000742}
743
Chris Lattner897cd7d2005-01-16 07:28:41 +0000744SDOperand TargetLowering::LowerOperation(SDOperand Op) {
745 assert(0 && "LowerOperation not implemented for this target!");
746 abort();
747}
748
Chris Lattner58cfd792005-01-09 00:00:49 +0000749void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
750 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
751 std::pair<SDOperand,SDOperand> Result =
752 TLI.LowerFrameReturnAddress(isFrame, DAG.getRoot(), Depth, DAG);
753 setValue(&I, Result.first);
754 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000755}
756
Chris Lattner875def92005-01-11 05:56:49 +0000757void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
758 std::vector<SDOperand> Ops;
759 Ops.push_back(DAG.getRoot());
760 Ops.push_back(getValue(I.getOperand(1)));
761 Ops.push_back(getValue(I.getOperand(2)));
762 Ops.push_back(getValue(I.getOperand(3)));
763 Ops.push_back(getValue(I.getOperand(4)));
764 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000765}
766
Chris Lattner875def92005-01-11 05:56:49 +0000767//===----------------------------------------------------------------------===//
768// SelectionDAGISel code
769//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000770
771unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
772 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
773}
774
775
776
777bool SelectionDAGISel::runOnFunction(Function &Fn) {
778 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
779 RegMap = MF.getSSARegMap();
780 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
781
782 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
783
784 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
785 SelectBasicBlock(I, MF, FuncInfo);
786
787 return true;
788}
789
790
Chris Lattner718b5c22005-01-13 17:59:43 +0000791SDOperand SelectionDAGISel::
792CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000793 SelectionDAG &DAG = SDL.DAG;
Chris Lattner613f79f2005-01-11 22:03:46 +0000794 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +0000795 assert((Op.getOpcode() != ISD::CopyFromReg ||
796 cast<RegSDNode>(Op)->getReg() != Reg) &&
797 "Copy from a reg to the same reg!");
Chris Lattner209f5852005-01-16 02:23:07 +0000798 MVT::ValueType VT = Op.getValueType();
799 if (TLI.getTypeAction(VT) == 1) { // Must promote this value?
800 if (MVT::isFloatingPoint(VT))
801 Op = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(VT), Op);
802 else
803 Op = DAG.getNode(ISD::ZERO_EXTEND, TLI.getTypeToTransformTo(VT), Op);
804 }
805
Chris Lattner718b5c22005-01-13 17:59:43 +0000806 return DAG.getCopyToReg(DAG.getRoot(), Op, Reg);
Chris Lattner7a60d912005-01-07 07:47:53 +0000807}
808
809void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
810 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
811 FunctionLoweringInfo &FuncInfo) {
812 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +0000813
814 std::vector<SDOperand> UnorderedChains;
Chris Lattner7a60d912005-01-07 07:47:53 +0000815
816 // If this is the entry block, emit arguments.
817 Function *F = LLVMBB->getParent();
818 if (LLVMBB == &F->front()) {
819 // FIXME: If an argument is only used in one basic block, we could directly
820 // emit it (ONLY) into that block, not emitting the COPY_TO_VREG node. This
821 // would improve codegen in several cases on X86 by allowing the loads to be
822 // folded into the user operation.
823 std::vector<SDOperand> Args = TLI.LowerArguments(*LLVMBB->getParent(), DAG);
824
825 unsigned a = 0;
826 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI,++a)
827 if (!AI->use_empty()) {
828 SDL.setValue(AI, Args[a]);
Chris Lattner718b5c22005-01-13 17:59:43 +0000829 UnorderedChains.push_back(
830 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]));
Chris Lattner7a60d912005-01-07 07:47:53 +0000831 }
832 }
833
834 BB = FuncInfo.MBBMap[LLVMBB];
835 SDL.setCurrentBasicBlock(BB);
836
837 // Lower all of the non-terminator instructions.
838 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
839 I != E; ++I)
840 SDL.visit(*I);
841
842 // Ensure that all instructions which are used outside of their defining
843 // blocks are available as virtual registers.
844 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +0000845 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +0000846 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000847 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +0000848 UnorderedChains.push_back(
849 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +0000850 }
851
852 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
853 // ensure constants are generated when needed. Remember the virtual registers
854 // that need to be added to the Machine PHI nodes as input. We cannot just
855 // directly add them, because expansion might result in multiple MBB's for one
856 // BB. As such, the start of the BB might correspond to a different MBB than
857 // the end.
858 //
859
860 // Emit constants only once even if used by multiple PHI nodes.
861 std::map<Constant*, unsigned> ConstantsOut;
862
863 // Check successor nodes PHI nodes that expect a constant to be available from
864 // this block.
865 TerminatorInst *TI = LLVMBB->getTerminator();
866 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
867 BasicBlock *SuccBB = TI->getSuccessor(succ);
868 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
869 PHINode *PN;
870
871 // At this point we know that there is a 1-1 correspondence between LLVM PHI
872 // nodes and Machine PHI nodes, but the incoming operands have not been
873 // emitted yet.
874 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000875 (PN = dyn_cast<PHINode>(I)); ++I)
876 if (!PN->use_empty()) {
877 unsigned Reg;
878 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
879 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
880 unsigned &RegOut = ConstantsOut[C];
881 if (RegOut == 0) {
882 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +0000883 UnorderedChains.push_back(
884 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +0000885 }
886 Reg = RegOut;
887 } else {
888 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +0000889 if (Reg == 0) {
890 assert(isa<AllocaInst>(PHIOp) &&
891 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
892 "Didn't codegen value into a register!??");
893 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +0000894 UnorderedChains.push_back(
895 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +0000896 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000897 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000898
899 // Remember that this register needs to added to the machine PHI node as
900 // the input for this MBB.
901 unsigned NumElements =
902 TLI.getNumElements(TLI.getValueType(PN->getType()));
903 for (unsigned i = 0, e = NumElements; i != e; ++i)
904 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +0000905 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000906 }
907 ConstantsOut.clear();
908
Chris Lattner718b5c22005-01-13 17:59:43 +0000909 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +0000910 if (!UnorderedChains.empty()) {
911 UnorderedChains.push_back(DAG.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +0000912 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
913 }
914
Chris Lattner7a60d912005-01-07 07:47:53 +0000915 // Lower the terminator after the copies are emitted.
916 SDL.visit(*LLVMBB->getTerminator());
917}
918
919void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
920 FunctionLoweringInfo &FuncInfo) {
921 SelectionDAG DAG(TLI.getTargetMachine(), MF);
922 CurDAG = &DAG;
923 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
924
925 // First step, lower LLVM code to some DAG. This DAG may use operations and
926 // types that are not supported by the target.
927 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
928
929 DEBUG(std::cerr << "Lowered selection DAG:\n");
930 DEBUG(DAG.dump());
931
932 // Second step, hack on the DAG until it only uses operations and types that
933 // the target supports.
934 DAG.Legalize(TLI);
935
936 DEBUG(std::cerr << "Legalized selection DAG:\n");
937 DEBUG(DAG.dump());
938
939 // Finally, instruction select all of the operations to machine code, adding
940 // the code to the MachineBasicBlock.
941 InstructionSelectBasicBlock(DAG);
942
Chris Lattnere05a4612005-01-12 03:41:21 +0000943 if (ViewDAGs) DAG.viewGraph();
944
Chris Lattner7a60d912005-01-07 07:47:53 +0000945 DEBUG(std::cerr << "Selected machine code:\n");
946 DEBUG(BB->dump());
947
948 // Finally, now that we know what the last MBB the LLVM BB expanded is, update
949 // PHI nodes in successors.
950 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
951 MachineInstr *PHI = PHINodesToUpdate[i].first;
952 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
953 "This is not a machine PHI node that we are updating!");
954 PHI->addRegOperand(PHINodesToUpdate[i].second);
955 PHI->addMachineBasicBlockOperand(BB);
956 }
957}