blob: 72ee7501082c499999cbb69b4772556fb82faf51 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
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"
Chris Lattnerd4382f02005-09-13 19:30:54 +000027#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetFrameInfo.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetLowering.h"
32#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000034#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/Support/Debug.h"
36#include <map>
37#include <iostream>
38using namespace llvm;
39
Chris Lattner975f5c92005-09-01 18:44:10 +000040#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000041static cl::opt<bool>
42ViewDAGs("view-isel-dags", cl::Hidden,
43 cl::desc("Pop up a window to show isel dags as they are selected"));
44#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000045static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000046#endif
47
Nate Begeman007c6502005-09-07 00:15:36 +000048
Chris Lattner7a60d912005-01-07 07:47:53 +000049namespace llvm {
50 //===--------------------------------------------------------------------===//
51 /// FunctionLoweringInfo - This contains information that is global to a
52 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000053 class FunctionLoweringInfo {
54 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000055 TargetLowering &TLI;
56 Function &Fn;
57 MachineFunction &MF;
58 SSARegMap *RegMap;
59
60 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
61
62 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
64
65 /// ValueMap - Since we emit code for the function a basic block at a time,
66 /// we must remember which virtual registers hold the values for
67 /// cross-basic-block values.
68 std::map<const Value*, unsigned> ValueMap;
69
70 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71 /// the entry block. This allows the allocas to be efficiently referenced
72 /// anywhere in the function.
73 std::map<const AllocaInst*, int> StaticAllocaMap;
74
Chris Lattnere3c2cf42005-01-17 17:55:19 +000075 /// BlockLocalArguments - If any arguments are only used in a single basic
76 /// block, and if the target can access the arguments without side-effects,
77 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
78 /// track of which arguments are local to each BB.
79 std::multimap<BasicBlock*, std::pair<Argument*,
80 unsigned> > BlockLocalArguments;
81
82
Chris Lattner7a60d912005-01-07 07:47:53 +000083 unsigned MakeReg(MVT::ValueType VT) {
84 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
85 }
Misha Brukman835702a2005-04-21 22:36:52 +000086
Chris Lattner7a60d912005-01-07 07:47:53 +000087 unsigned CreateRegForValue(const Value *V) {
88 MVT::ValueType VT = TLI.getValueType(V->getType());
89 // The common case is that we will only create one register for this
90 // value. If we have that case, create and return the virtual register.
91 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000092 if (NV == 1) {
93 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000094 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000095 }
Misha Brukman835702a2005-04-21 22:36:52 +000096
Chris Lattner7a60d912005-01-07 07:47:53 +000097 // If this value is represented with multiple target registers, make sure
98 // to create enough consequtive registers of the right (smaller) type.
99 unsigned NT = VT-1; // Find the type to use.
100 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
101 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000102
Chris Lattner7a60d912005-01-07 07:47:53 +0000103 unsigned R = MakeReg((MVT::ValueType)NT);
104 for (unsigned i = 1; i != NV; ++i)
105 MakeReg((MVT::ValueType)NT);
106 return R;
107 }
Misha Brukman835702a2005-04-21 22:36:52 +0000108
Chris Lattner7a60d912005-01-07 07:47:53 +0000109 unsigned InitializeRegForValue(const Value *V) {
110 unsigned &R = ValueMap[V];
111 assert(R == 0 && "Already initialized this value register!");
112 return R = CreateRegForValue(V);
113 }
114 };
115}
116
117/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118/// PHI nodes or outside of the basic block that defines it.
119static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120 if (isa<PHINode>(I)) return true;
121 BasicBlock *BB = I->getParent();
122 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
124 return true;
125 return false;
126}
127
128FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000129 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000130 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
131
132 // Initialize the mapping of values to registers. This is only set up for
133 // instruction values that are used outside of the block that defines
134 // them.
Chris Lattner490769c2005-05-11 18:57:06 +0000135 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
136 AI != E; ++AI)
Chris Lattner7a60d912005-01-07 07:47:53 +0000137 InitializeRegForValue(AI);
138
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000139 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000140 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
141 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
143 const Type *Ty = AI->getAllocatedType();
144 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
145 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
Chris Lattnercbefe722005-05-13 23:14:17 +0000146
147 // If the alignment of the value is smaller than the size of the value,
148 // and if the size of the value is particularly small (<= 8 bytes),
149 // round up to the size of the value for potentially better performance.
150 //
151 // FIXME: This could be made better with a preferred alignment hook in
152 // TargetData. It serves primarily to 8-byte align doubles for X86.
153 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000154 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000155 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000156 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000157 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000158 }
159
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000160 for (; BB != EB; ++BB)
161 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
163 if (!isa<AllocaInst>(I) ||
164 !StaticAllocaMap.count(cast<AllocaInst>(I)))
165 InitializeRegForValue(I);
166
167 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
168 // also creates the initial PHI MachineInstrs, though none of the input
169 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000170 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000171 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
172 MBBMap[BB] = MBB;
173 MF.getBasicBlockList().push_back(MBB);
174
175 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
176 // appropriate.
177 PHINode *PN;
178 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000179 (PN = dyn_cast<PHINode>(I)); ++I)
180 if (!PN->use_empty()) {
181 unsigned NumElements =
182 TLI.getNumElements(TLI.getValueType(PN->getType()));
183 unsigned PHIReg = ValueMap[PN];
184 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
185 for (unsigned i = 0; i != NumElements; ++i)
186 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
187 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000188 }
189}
190
191
192
193//===----------------------------------------------------------------------===//
194/// SelectionDAGLowering - This is the common target-independent lowering
195/// implementation that is parameterized by a TargetLowering object.
196/// Also, targets can overload any lowering method.
197///
198namespace llvm {
199class SelectionDAGLowering {
200 MachineBasicBlock *CurMBB;
201
202 std::map<const Value*, SDOperand> NodeMap;
203
Chris Lattner4d9651c2005-01-17 22:19:26 +0000204 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
205 /// them up and then emit token factor nodes when possible. This allows us to
206 /// get simple disambiguation between loads without worrying about alias
207 /// analysis.
208 std::vector<SDOperand> PendingLoads;
209
Chris Lattner7a60d912005-01-07 07:47:53 +0000210public:
211 // TLI - This is information that describes the available target features we
212 // need for lowering. This indicates when operations are unavailable,
213 // implemented with a libcall, etc.
214 TargetLowering &TLI;
215 SelectionDAG &DAG;
216 const TargetData &TD;
217
218 /// FuncInfo - Information about the function as a whole.
219 ///
220 FunctionLoweringInfo &FuncInfo;
221
222 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000223 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
225 FuncInfo(funcinfo) {
226 }
227
Chris Lattner4108bb02005-01-17 19:43:36 +0000228 /// getRoot - Return the current virtual root of the Selection DAG.
229 ///
230 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000231 if (PendingLoads.empty())
232 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000233
Chris Lattner4d9651c2005-01-17 22:19:26 +0000234 if (PendingLoads.size() == 1) {
235 SDOperand Root = PendingLoads[0];
236 DAG.setRoot(Root);
237 PendingLoads.clear();
238 return Root;
239 }
240
241 // Otherwise, we have to make a token factor node.
242 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
243 PendingLoads.clear();
244 DAG.setRoot(Root);
245 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000246 }
247
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 void visit(Instruction &I) { visit(I.getOpcode(), I); }
249
250 void visit(unsigned Opcode, User &I) {
251 switch (Opcode) {
252 default: assert(0 && "Unknown instruction type encountered!");
253 abort();
254 // Build the switch statement using the Instruction.def file.
255#define HANDLE_INST(NUM, OPCODE, CLASS) \
256 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
257#include "llvm/Instruction.def"
258 }
259 }
260
261 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
262
263
264 SDOperand getIntPtrConstant(uint64_t Val) {
265 return DAG.getConstant(Val, TLI.getPointerTy());
266 }
267
268 SDOperand getValue(const Value *V) {
269 SDOperand &N = NodeMap[V];
270 if (N.Val) return N;
271
272 MVT::ValueType VT = TLI.getValueType(V->getType());
273 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
275 visit(CE->getOpcode(), *CE);
276 assert(N.Val && "visit didn't populate the ValueMap!");
277 return N;
278 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
279 return N = DAG.getGlobalAddress(GV, VT);
280 } else if (isa<ConstantPointerNull>(C)) {
281 return N = DAG.getConstant(0, TLI.getPointerTy());
282 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000283 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000284 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
285 return N = DAG.getConstantFP(CFP->getValue(), VT);
286 } else {
287 // Canonicalize all constant ints to be unsigned.
288 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
289 }
290
291 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
292 std::map<const AllocaInst*, int>::iterator SI =
293 FuncInfo.StaticAllocaMap.find(AI);
294 if (SI != FuncInfo.StaticAllocaMap.end())
295 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
296 }
297
298 std::map<const Value*, unsigned>::const_iterator VMI =
299 FuncInfo.ValueMap.find(V);
300 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000301
Chris Lattner33182322005-08-16 21:55:35 +0000302 unsigned InReg = VMI->second;
303
304 // If this type is not legal, make it so now.
305 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
306
307 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
308 if (DestVT < VT) {
309 // Source must be expanded. This input value is actually coming from the
310 // register pair VMI->second and VMI->second+1.
311 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
312 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
313 } else {
314 if (DestVT > VT) { // Promotion case
315 if (MVT::isFloatingPoint(VT))
316 N = DAG.getNode(ISD::FP_ROUND, VT, N);
317 else
318 N = DAG.getNode(ISD::TRUNCATE, VT, N);
319 }
320 }
321
322 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000323 }
324
325 const SDOperand &setValue(const Value *V, SDOperand NewN) {
326 SDOperand &N = NodeMap[V];
327 assert(N.Val == 0 && "Already set a value for this node!");
328 return N = NewN;
329 }
330
331 // Terminator instructions.
332 void visitRet(ReturnInst &I);
333 void visitBr(BranchInst &I);
334 void visitUnreachable(UnreachableInst &I) { /* noop */ }
335
336 // These all get lowered before this pass.
337 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
338 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
339 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
340
341 //
Chris Lattner7f9e0782005-08-22 17:28:31 +0000342 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000343 void visitAdd(User &I) {
344 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
345 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000346 void visitSub(User &I);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000347 void visitMul(User &I) {
348 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
349 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000350 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000351 unsigned Opc;
352 const Type *Ty = I.getType();
353 if (Ty->isFloatingPoint())
354 Opc = ISD::FDIV;
355 else if (Ty->isUnsigned())
356 Opc = ISD::UDIV;
357 else
358 Opc = ISD::SDIV;
359 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000360 }
361 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000362 unsigned Opc;
363 const Type *Ty = I.getType();
364 if (Ty->isFloatingPoint())
365 Opc = ISD::FREM;
366 else if (Ty->isUnsigned())
367 Opc = ISD::UREM;
368 else
369 Opc = ISD::SREM;
370 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000371 }
372 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
373 void visitOr (User &I) { visitBinary(I, ISD::OR); }
374 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner7f9e0782005-08-22 17:28:31 +0000375 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000376 void visitShr(User &I) {
Chris Lattner7f9e0782005-08-22 17:28:31 +0000377 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner7a60d912005-01-07 07:47:53 +0000378 }
379
380 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
381 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
382 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
383 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
384 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
385 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
386 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
387
388 void visitGetElementPtr(User &I);
389 void visitCast(User &I);
390 void visitSelect(User &I);
391 //
392
393 void visitMalloc(MallocInst &I);
394 void visitFree(FreeInst &I);
395 void visitAlloca(AllocaInst &I);
396 void visitLoad(LoadInst &I);
397 void visitStore(StoreInst &I);
398 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
399 void visitCall(CallInst &I);
400
Chris Lattner7a60d912005-01-07 07:47:53 +0000401 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000402 void visitVAArg(VAArgInst &I);
403 void visitVAEnd(CallInst &I);
404 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000405 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000406
Chris Lattner875def92005-01-11 05:56:49 +0000407 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000408
409 void visitUserOp1(Instruction &I) {
410 assert(0 && "UserOp1 should not exist at instruction selection time!");
411 abort();
412 }
413 void visitUserOp2(Instruction &I) {
414 assert(0 && "UserOp2 should not exist at instruction selection time!");
415 abort();
416 }
417};
418} // end namespace llvm
419
420void SelectionDAGLowering::visitRet(ReturnInst &I) {
421 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000422 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000423 return;
424 }
425
426 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000427 MVT::ValueType TmpVT;
428
Chris Lattner7a60d912005-01-07 07:47:53 +0000429 switch (Op1.getValueType()) {
430 default: assert(0 && "Unknown value type!");
431 case MVT::i1:
432 case MVT::i8:
433 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000434 case MVT::i32:
435 // If this is a machine where 32-bits is legal or expanded, promote to
436 // 32-bits, otherwise, promote to 64-bits.
437 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
438 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000439 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000440 TmpVT = MVT::i32;
441
442 // Extend integer types to result type.
443 if (I.getOperand(0)->getType()->isSigned())
444 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
445 else
446 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000447 break;
448 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000449 case MVT::i64:
450 case MVT::f64:
451 break; // No extension needed!
452 }
453
Chris Lattner4108bb02005-01-17 19:43:36 +0000454 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000455}
456
457void SelectionDAGLowering::visitBr(BranchInst &I) {
458 // Update machine-CFG edges.
459 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000460
461 // Figure out which block is immediately after the current one.
462 MachineBasicBlock *NextBlock = 0;
463 MachineFunction::iterator BBI = CurMBB;
464 if (++BBI != CurMBB->getParent()->end())
465 NextBlock = BBI;
466
467 if (I.isUnconditional()) {
468 // If this is not a fall-through branch, emit the branch.
469 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000470 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000471 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000472 } else {
473 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000474
475 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000476 if (Succ1MBB == NextBlock) {
477 // If the condition is false, fall through. This means we should branch
478 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000479 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000480 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000481 } else if (Succ0MBB == NextBlock) {
482 // If the condition is true, fall through. This means we should branch if
483 // the condition is false to Succ #1. Invert the condition first.
484 SDOperand True = DAG.getConstant(1, Cond.getValueType());
485 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000486 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000487 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000489 std::vector<SDOperand> Ops;
490 Ops.push_back(getRoot());
491 Ops.push_back(Cond);
492 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
493 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
494 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 }
496 }
497}
498
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000499void SelectionDAGLowering::visitSub(User &I) {
500 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000501 if (I.getType()->isFloatingPoint()) {
502 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
503 if (CFP->isExactlyValue(-0.0)) {
504 SDOperand Op2 = getValue(I.getOperand(1));
505 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
506 return;
507 }
508 visitBinary(I, ISD::FSUB);
509 } else {
510 visitBinary(I, ISD::SUB);
511 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000512}
513
Chris Lattner7f9e0782005-08-22 17:28:31 +0000514void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000515 SDOperand Op1 = getValue(I.getOperand(0));
516 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000517
Chris Lattner7f9e0782005-08-22 17:28:31 +0000518 if (isShift)
Chris Lattnera66403d2005-09-02 00:19:37 +0000519 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner96c26752005-01-19 22:31:21 +0000520
Chris Lattner7a60d912005-01-07 07:47:53 +0000521 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
522}
523
524void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
525 ISD::CondCode UnsignedOpcode) {
526 SDOperand Op1 = getValue(I.getOperand(0));
527 SDOperand Op2 = getValue(I.getOperand(1));
528 ISD::CondCode Opcode = SignedOpcode;
529 if (I.getOperand(0)->getType()->isUnsigned())
530 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000531 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000532}
533
534void SelectionDAGLowering::visitSelect(User &I) {
535 SDOperand Cond = getValue(I.getOperand(0));
536 SDOperand TrueVal = getValue(I.getOperand(1));
537 SDOperand FalseVal = getValue(I.getOperand(2));
538 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
539 TrueVal, FalseVal));
540}
541
542void SelectionDAGLowering::visitCast(User &I) {
543 SDOperand N = getValue(I.getOperand(0));
544 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
545 MVT::ValueType DestTy = TLI.getValueType(I.getType());
546
547 if (N.getValueType() == DestTy) {
548 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000549 } else if (DestTy == MVT::i1) {
550 // Cast to bool is a comparison against zero, not truncation to zero.
551 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
552 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000553 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000554 } else if (isInteger(SrcTy)) {
555 if (isInteger(DestTy)) { // Int -> Int cast
556 if (DestTy < SrcTy) // Truncating cast?
557 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
558 else if (I.getOperand(0)->getType()->isSigned())
559 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
560 else
561 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
562 } else { // Int -> FP cast
563 if (I.getOperand(0)->getType()->isSigned())
564 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
565 else
566 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
567 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000568 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000569 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
570 if (isFloatingPoint(DestTy)) { // FP -> FP cast
571 if (DestTy < SrcTy) // Rounding cast?
572 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
573 else
574 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
575 } else { // FP -> Int cast.
576 if (I.getType()->isSigned())
577 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
578 else
579 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
580 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000581 }
582}
583
584void SelectionDAGLowering::visitGetElementPtr(User &I) {
585 SDOperand N = getValue(I.getOperand(0));
586 const Type *Ty = I.getOperand(0)->getType();
587 const Type *UIntPtrTy = TD.getIntPtrType();
588
589 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
590 OI != E; ++OI) {
591 Value *Idx = *OI;
592 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
593 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
594 if (Field) {
595 // N = N + Offset
596 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
597 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000598 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000599 }
600 Ty = StTy->getElementType(Field);
601 } else {
602 Ty = cast<SequentialType>(Ty)->getElementType();
603 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
604 // N = N + Idx * ElementSize;
605 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000606 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
607
608 // If the index is smaller or larger than intptr_t, truncate or extend
609 // it.
610 if (IdxN.getValueType() < Scale.getValueType()) {
611 if (Idx->getType()->isSigned())
612 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
613 else
614 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
615 } else if (IdxN.getValueType() > Scale.getValueType())
616 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
617
618 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner7a60d912005-01-07 07:47:53 +0000619 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
620 }
621 }
622 }
623 setValue(&I, N);
624}
625
626void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
627 // If this is a fixed sized alloca in the entry block of the function,
628 // allocate it statically on the stack.
629 if (FuncInfo.StaticAllocaMap.count(&I))
630 return; // getValue will auto-populate this.
631
632 const Type *Ty = I.getAllocatedType();
633 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
634 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
635
636 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000637 MVT::ValueType IntPtr = TLI.getPointerTy();
638 if (IntPtr < AllocSize.getValueType())
639 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
640 else if (IntPtr > AllocSize.getValueType())
641 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000642
Chris Lattnereccb73d2005-01-22 23:04:37 +0000643 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000644 getIntPtrConstant(TySize));
645
646 // Handle alignment. If the requested alignment is less than or equal to the
647 // stack alignment, ignore it and round the size of the allocation up to the
648 // stack alignment size. If the size is greater than the stack alignment, we
649 // note this in the DYNAMIC_STACKALLOC node.
650 unsigned StackAlign =
651 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
652 if (Align <= StackAlign) {
653 Align = 0;
654 // Add SA-1 to the size.
655 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
656 getIntPtrConstant(StackAlign-1));
657 // Mask out the low bits for alignment purposes.
658 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
659 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
660 }
661
Chris Lattner96c262e2005-05-14 07:29:57 +0000662 std::vector<MVT::ValueType> VTs;
663 VTs.push_back(AllocSize.getValueType());
664 VTs.push_back(MVT::Other);
665 std::vector<SDOperand> Ops;
666 Ops.push_back(getRoot());
667 Ops.push_back(AllocSize);
668 Ops.push_back(getIntPtrConstant(Align));
669 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000670 DAG.setRoot(setValue(&I, DSA).getValue(1));
671
672 // Inform the Frame Information that we have just allocated a variable-sized
673 // object.
674 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
675}
676
677
678void SelectionDAGLowering::visitLoad(LoadInst &I) {
679 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000680
Chris Lattner4d9651c2005-01-17 22:19:26 +0000681 SDOperand Root;
682 if (I.isVolatile())
683 Root = getRoot();
684 else {
685 // Do not serialize non-volatile loads against each other.
686 Root = DAG.getRoot();
687 }
688
Chris Lattnerf5675a02005-05-09 04:08:33 +0000689 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000690 DAG.getSrcValue(I.getOperand(0)));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000691 setValue(&I, L);
692
693 if (I.isVolatile())
694 DAG.setRoot(L.getValue(1));
695 else
696 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000697}
698
699
700void SelectionDAGLowering::visitStore(StoreInst &I) {
701 Value *SrcV = I.getOperand(0);
702 SDOperand Src = getValue(SrcV);
703 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000704 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000705 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000706}
707
708void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000709 const char *RenameFn = 0;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000710 SDOperand Tmp;
Chris Lattner7a60d912005-01-07 07:47:53 +0000711 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000712 if (F->isExternal())
713 switch (F->getIntrinsicID()) {
714 case 0: // Not an LLVM intrinsic.
715 if (F->getName() == "fabs" || F->getName() == "fabsf") {
716 if (I.getNumOperands() == 2 && // Basic sanity checks.
717 I.getOperand(1)->getType()->isFloatingPoint() &&
718 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000719 Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000720 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
721 return;
722 }
723 }
Chris Lattner80026402005-04-30 04:43:14 +0000724 else if (F->getName() == "sin" || F->getName() == "sinf") {
725 if (I.getNumOperands() == 2 && // Basic sanity checks.
726 I.getOperand(1)->getType()->isFloatingPoint() &&
727 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000728 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000729 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
730 return;
731 }
732 }
733 else if (F->getName() == "cos" || F->getName() == "cosf") {
734 if (I.getNumOperands() == 2 && // Basic sanity checks.
735 I.getOperand(1)->getType()->isFloatingPoint() &&
736 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000737 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000738 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
739 return;
740 }
741 }
Chris Lattner0c140002005-04-02 05:26:53 +0000742 break;
743 case Intrinsic::vastart: visitVAStart(I); return;
744 case Intrinsic::vaend: visitVAEnd(I); return;
745 case Intrinsic::vacopy: visitVACopy(I); return;
746 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
747 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000748
Chris Lattner0fd8f9f2005-09-27 22:15:53 +0000749 case Intrinsic::setjmp:
750 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
751 break;
752 case Intrinsic::longjmp:
753 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
754 break;
Chris Lattner0c140002005-04-02 05:26:53 +0000755 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
756 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
757 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukman835702a2005-04-21 22:36:52 +0000758
Chris Lattner20eaeae2005-05-09 20:22:36 +0000759 case Intrinsic::readport:
Chris Lattnere4f71d02005-05-14 13:56:55 +0000760 case Intrinsic::readio: {
761 std::vector<MVT::ValueType> VTs;
762 VTs.push_back(TLI.getValueType(I.getType()));
763 VTs.push_back(MVT::Other);
764 std::vector<SDOperand> Ops;
765 Ops.push_back(getRoot());
766 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattner20eaeae2005-05-09 20:22:36 +0000767 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattnere4f71d02005-05-14 13:56:55 +0000768 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000769
Chris Lattner20eaeae2005-05-09 20:22:36 +0000770 setValue(&I, Tmp);
771 DAG.setRoot(Tmp.getValue(1));
772 return;
Chris Lattnere4f71d02005-05-14 13:56:55 +0000773 }
Chris Lattner20eaeae2005-05-09 20:22:36 +0000774 case Intrinsic::writeport:
775 case Intrinsic::writeio:
776 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
777 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
778 getRoot(), getValue(I.getOperand(1)),
779 getValue(I.getOperand(2))));
780 return;
Chris Lattner78761562005-05-05 17:55:17 +0000781 case Intrinsic::dbg_stoppoint:
782 case Intrinsic::dbg_region_start:
783 case Intrinsic::dbg_region_end:
784 case Intrinsic::dbg_func_start:
785 case Intrinsic::dbg_declare:
786 if (I.getType() != Type::VoidTy)
787 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
788 return;
789
Chris Lattner0c140002005-04-02 05:26:53 +0000790 case Intrinsic::isunordered:
Chris Lattnerd47675e2005-08-09 20:20:18 +0000791 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
792 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattner0c140002005-04-02 05:26:53 +0000793 return;
Chris Lattner80026402005-04-30 04:43:14 +0000794
795 case Intrinsic::sqrt:
796 setValue(&I, DAG.getNode(ISD::FSQRT,
797 getValue(I.getOperand(1)).getValueType(),
798 getValue(I.getOperand(1))));
799 return;
800
Chris Lattner20eaeae2005-05-09 20:22:36 +0000801 case Intrinsic::pcmarker:
802 Tmp = getValue(I.getOperand(1));
803 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattner0c140002005-04-02 05:26:53 +0000804 return;
Andrew Lenharth5e177822005-05-03 17:19:30 +0000805 case Intrinsic::cttz:
806 setValue(&I, DAG.getNode(ISD::CTTZ,
807 getValue(I.getOperand(1)).getValueType(),
808 getValue(I.getOperand(1))));
809 return;
810 case Intrinsic::ctlz:
811 setValue(&I, DAG.getNode(ISD::CTLZ,
812 getValue(I.getOperand(1)).getValueType(),
813 getValue(I.getOperand(1))));
814 return;
815 case Intrinsic::ctpop:
816 setValue(&I, DAG.getNode(ISD::CTPOP,
817 getValue(I.getOperand(1)).getValueType(),
818 getValue(I.getOperand(1))));
819 return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000820 default:
821 std::cerr << I;
822 assert(0 && "This intrinsic is not implemented yet!");
823 return;
Chris Lattner0c140002005-04-02 05:26:53 +0000824 }
Misha Brukman835702a2005-04-21 22:36:52 +0000825
Chris Lattner18d2b342005-01-08 22:48:57 +0000826 SDOperand Callee;
827 if (!RenameFn)
828 Callee = getValue(I.getOperand(0));
829 else
830 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000831 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukman835702a2005-04-21 22:36:52 +0000832
Chris Lattner7a60d912005-01-07 07:47:53 +0000833 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
834 Value *Arg = I.getOperand(i);
835 SDOperand ArgNode = getValue(Arg);
836 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
837 }
Misha Brukman835702a2005-04-21 22:36:52 +0000838
Nate Begemanf6565252005-03-26 01:29:23 +0000839 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
840 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000841
Chris Lattner1f45cd72005-01-08 19:26:18 +0000842 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000843 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000844 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000845 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000846 setValue(&I, Result.first);
847 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000848}
849
850void SelectionDAGLowering::visitMalloc(MallocInst &I) {
851 SDOperand Src = getValue(I.getOperand(0));
852
853 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000854
855 if (IntPtr < Src.getValueType())
856 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
857 else if (IntPtr > Src.getValueType())
858 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000859
860 // Scale the source by the type size.
861 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
862 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
863 Src, getIntPtrConstant(ElementSize));
864
865 std::vector<std::pair<SDOperand, const Type*> > Args;
866 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000867
868 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000869 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000870 DAG.getExternalSymbol("malloc", IntPtr),
871 Args, DAG);
872 setValue(&I, Result.first); // Pointers always fit in registers
873 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000874}
875
876void SelectionDAGLowering::visitFree(FreeInst &I) {
877 std::vector<std::pair<SDOperand, const Type*> > Args;
878 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
879 TLI.getTargetData().getIntPtrType()));
880 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000881 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000882 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000883 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
884 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000885}
886
Chris Lattner13d7c252005-08-26 20:54:47 +0000887// InsertAtEndOfBasicBlock - This method should be implemented by targets that
888// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
889// instructions are special in various ways, which require special support to
890// insert. The specified MachineInstr is created but not inserted into any
891// basic blocks, and the scheduler passes ownership of it to this method.
892MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
893 MachineBasicBlock *MBB) {
894 std::cerr << "If a target marks an instruction with "
895 "'usesCustomDAGSchedInserter', it must implement "
896 "TargetLowering::InsertAtEndOfBasicBlock!\n";
897 abort();
898 return 0;
899}
900
Chris Lattnerf5473e42005-07-05 19:57:53 +0000901SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
902 SDOperand VAListP, Value *VAListV,
903 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000904 // We have no sane default behavior, just emit a useful error message and bail
905 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000906 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000907 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +0000908 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +0000909}
910
Chris Lattnerf5473e42005-07-05 19:57:53 +0000911SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +0000912 SelectionDAG &DAG) {
913 // Default to a noop.
914 return Chain;
915}
916
Chris Lattnerf5473e42005-07-05 19:57:53 +0000917SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
918 SDOperand SrcP, Value *SrcV,
919 SDOperand DestP, Value *DestV,
920 SelectionDAG &DAG) {
921 // Default to copying the input list.
922 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
923 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +0000924 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000925 Val, DestP, DAG.getSrcValue(DestV));
926 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +0000927}
928
929std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +0000930TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
931 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000932 // We have no sane default behavior, just emit a useful error message and bail
933 // out.
934 std::cerr << "Variable arguments handling not implemented on this target!\n";
935 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000936 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000937}
938
939
940void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000941 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
942 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +0000943}
944
945void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
946 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +0000947 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000948 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000949 setValue(&I, Result.first);
950 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000951}
952
953void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000954 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000955 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000956}
957
958void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000959 SDOperand Result =
960 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
961 getValue(I.getOperand(1)), I.getOperand(1), DAG);
962 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +0000963}
964
Chris Lattner58cfd792005-01-09 00:00:49 +0000965
966// It is always conservatively correct for llvm.returnaddress and
967// llvm.frameaddress to return 0.
968std::pair<SDOperand, SDOperand>
969TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
970 unsigned Depth, SelectionDAG &DAG) {
971 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000972}
973
Chris Lattner29dcc712005-05-14 05:50:48 +0000974SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +0000975 assert(0 && "LowerOperation not implemented for this target!");
976 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000977 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000978}
979
Chris Lattner58cfd792005-01-09 00:00:49 +0000980void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
981 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
982 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000983 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000984 setValue(&I, Result.first);
985 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000986}
987
Chris Lattner875def92005-01-11 05:56:49 +0000988void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
989 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000990 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000991 Ops.push_back(getValue(I.getOperand(1)));
992 Ops.push_back(getValue(I.getOperand(2)));
993 Ops.push_back(getValue(I.getOperand(3)));
994 Ops.push_back(getValue(I.getOperand(4)));
995 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000996}
997
Chris Lattner875def92005-01-11 05:56:49 +0000998//===----------------------------------------------------------------------===//
999// SelectionDAGISel code
1000//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001001
1002unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1003 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1004}
1005
Chris Lattnerc9950c12005-08-17 06:37:43 +00001006void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001007 // FIXME: we only modify the CFG to split critical edges. This
1008 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001009}
Chris Lattner7a60d912005-01-07 07:47:53 +00001010
1011
1012bool SelectionDAGISel::runOnFunction(Function &Fn) {
1013 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1014 RegMap = MF.getSSARegMap();
1015 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1016
Chris Lattnerc9950c12005-08-17 06:37:43 +00001017 // First pass, split all critical edges for PHI nodes with incoming values
1018 // that are constants, this way the load of the constant into a vreg will not
1019 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001020 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1021 PHINode *PN;
1022 for (BasicBlock::iterator BBI = BB->begin();
1023 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1024 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1025 if (isa<Constant>(PN->getIncomingValue(i)))
1026 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1027 }
Chris Lattnerc9950c12005-08-17 06:37:43 +00001028
Chris Lattner7a60d912005-01-07 07:47:53 +00001029 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1030
1031 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1032 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001033
Chris Lattner7a60d912005-01-07 07:47:53 +00001034 return true;
1035}
1036
1037
Chris Lattner718b5c22005-01-13 17:59:43 +00001038SDOperand SelectionDAGISel::
1039CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001040 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001041 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001042 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001043 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001044
1045 // If this type is not legal, we must make sure to not create an invalid
1046 // register use.
1047 MVT::ValueType SrcVT = Op.getValueType();
1048 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1049 SelectionDAG &DAG = SDL.DAG;
1050 if (SrcVT == DestVT) {
1051 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1052 } else if (SrcVT < DestVT) {
1053 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001054 if (MVT::isFloatingPoint(SrcVT))
1055 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1056 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001057 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001058 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1059 } else {
1060 // The src value is expanded into multiple registers.
1061 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1062 Op, DAG.getConstant(0, MVT::i32));
1063 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1064 Op, DAG.getConstant(1, MVT::i32));
1065 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1066 return DAG.getCopyToReg(Op, Reg+1, Hi);
1067 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001068}
1069
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001070/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1071/// single basic block, return that block. Otherwise, return a null pointer.
1072static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1073 if (A->use_empty()) return 0;
1074 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1075 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1076 ++UI)
1077 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1078 return 0; // Disagreement among the users?
Chris Lattner0c56a542005-02-17 19:40:32 +00001079
1080 // Okay, there is a single BB user. Only permit this optimization if this is
1081 // the entry block, otherwise, we might sink argument loads into loops and
1082 // stuff. Later, when we have global instruction selection, this won't be an
1083 // issue clearly.
1084 if (BB == BB->getParent()->begin())
1085 return BB;
1086 return 0;
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001087}
1088
Chris Lattner16f64df2005-01-17 17:15:02 +00001089void SelectionDAGISel::
1090LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1091 std::vector<SDOperand> &UnorderedChains) {
1092 // If this is the entry block, emit arguments.
1093 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001094 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +00001095
1096 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001097 SDOperand OldRoot = SDL.DAG.getRoot();
1098
Chris Lattner16f64df2005-01-17 17:15:02 +00001099 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1100
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001101 // If there were side effects accessing the argument list, do not do
1102 // anything special.
1103 if (OldRoot != SDL.DAG.getRoot()) {
1104 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +00001105 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1106 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001107 if (!AI->use_empty()) {
1108 SDL.setValue(AI, Args[a]);
Chris Lattnere7a29982005-08-26 22:49:59 +00001109
Chris Lattnera66403d2005-09-02 00:19:37 +00001110 SDOperand Copy =
1111 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1112 UnorderedChains.push_back(Copy);
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001113 }
1114 } else {
1115 // Otherwise, if any argument is only accessed in a single basic block,
1116 // emit that argument only to that basic block.
1117 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +00001118 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1119 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001120 if (!AI->use_empty()) {
1121 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1122 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1123 std::make_pair(AI, a)));
1124 } else {
1125 SDL.setValue(AI, Args[a]);
Misha Brukman835702a2005-04-21 22:36:52 +00001126 SDOperand Copy =
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001127 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1128 UnorderedChains.push_back(Copy);
1129 }
1130 }
1131 }
Chris Lattnerd0b0ecc2005-05-13 07:33:32 +00001132
Chris Lattnerd4382f02005-09-13 19:30:54 +00001133 // Next, if the function has live ins that need to be copied into vregs,
1134 // emit the copies now, into the top of the block.
1135 MachineFunction &MF = SDL.DAG.getMachineFunction();
1136 if (MF.livein_begin() != MF.livein_end()) {
1137 SSARegMap *RegMap = MF.getSSARegMap();
1138 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1139 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1140 E = MF.livein_end(); LI != E; ++LI)
1141 if (LI->second)
1142 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1143 LI->first, RegMap->getRegClass(LI->second));
1144 }
1145
1146 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattnerd0b0ecc2005-05-13 07:33:32 +00001147 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001148 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001149
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001150 // See if there are any block-local arguments that need to be emitted in this
1151 // block.
1152
1153 if (!FuncInfo.BlockLocalArguments.empty()) {
1154 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1155 FuncInfo.BlockLocalArguments.lower_bound(BB);
1156 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1157 // Lower the arguments into this block.
1158 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukman835702a2005-04-21 22:36:52 +00001159
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001160 // Set up the value mapping for the local arguments.
1161 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1162 ++BLAI)
1163 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukman835702a2005-04-21 22:36:52 +00001164
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001165 // Any dead arguments will just be ignored here.
1166 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001167 }
1168}
1169
1170
Chris Lattner7a60d912005-01-07 07:47:53 +00001171void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1172 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1173 FunctionLoweringInfo &FuncInfo) {
1174 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001175
1176 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001177
Chris Lattner16f64df2005-01-17 17:15:02 +00001178 // Lower any arguments needed in this block.
1179 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001180
1181 BB = FuncInfo.MBBMap[LLVMBB];
1182 SDL.setCurrentBasicBlock(BB);
1183
1184 // Lower all of the non-terminator instructions.
1185 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1186 I != E; ++I)
1187 SDL.visit(*I);
1188
1189 // Ensure that all instructions which are used outside of their defining
1190 // blocks are available as virtual registers.
1191 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001192 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001193 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001194 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001195 UnorderedChains.push_back(
1196 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001197 }
1198
1199 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1200 // ensure constants are generated when needed. Remember the virtual registers
1201 // that need to be added to the Machine PHI nodes as input. We cannot just
1202 // directly add them, because expansion might result in multiple MBB's for one
1203 // BB. As such, the start of the BB might correspond to a different MBB than
1204 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001205 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001206
1207 // Emit constants only once even if used by multiple PHI nodes.
1208 std::map<Constant*, unsigned> ConstantsOut;
1209
1210 // Check successor nodes PHI nodes that expect a constant to be available from
1211 // this block.
1212 TerminatorInst *TI = LLVMBB->getTerminator();
1213 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1214 BasicBlock *SuccBB = TI->getSuccessor(succ);
1215 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1216 PHINode *PN;
1217
1218 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1219 // nodes and Machine PHI nodes, but the incoming operands have not been
1220 // emitted yet.
1221 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001222 (PN = dyn_cast<PHINode>(I)); ++I)
1223 if (!PN->use_empty()) {
1224 unsigned Reg;
1225 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1226 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1227 unsigned &RegOut = ConstantsOut[C];
1228 if (RegOut == 0) {
1229 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001230 UnorderedChains.push_back(
1231 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001232 }
1233 Reg = RegOut;
1234 } else {
1235 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001236 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001237 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001238 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1239 "Didn't codegen value into a register!??");
1240 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001241 UnorderedChains.push_back(
1242 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001243 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001244 }
Misha Brukman835702a2005-04-21 22:36:52 +00001245
Chris Lattner8ea875f2005-01-07 21:34:19 +00001246 // Remember that this register needs to added to the machine PHI node as
1247 // the input for this MBB.
1248 unsigned NumElements =
1249 TLI.getNumElements(TLI.getValueType(PN->getType()));
1250 for (unsigned i = 0, e = NumElements; i != e; ++i)
1251 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001252 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001253 }
1254 ConstantsOut.clear();
1255
Chris Lattner718b5c22005-01-13 17:59:43 +00001256 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001257 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001258 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001259 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1260 }
1261
Chris Lattner7a60d912005-01-07 07:47:53 +00001262 // Lower the terminator after the copies are emitted.
1263 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001264
1265 // Make sure the root of the DAG is up-to-date.
1266 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001267}
1268
1269void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1270 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001271 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001272 CurDAG = &DAG;
1273 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1274
1275 // First step, lower LLVM code to some DAG. This DAG may use operations and
1276 // types that are not supported by the target.
1277 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1278
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001279 // Run the DAG combiner in pre-legalize mode.
1280 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001281
Chris Lattner7a60d912005-01-07 07:47:53 +00001282 DEBUG(std::cerr << "Lowered selection DAG:\n");
1283 DEBUG(DAG.dump());
1284
1285 // Second step, hack on the DAG until it only uses operations and types that
1286 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001287 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001288
1289 DEBUG(std::cerr << "Legalized selection DAG:\n");
1290 DEBUG(DAG.dump());
1291
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001292 // Run the DAG combiner in post-legalize mode.
1293 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001294
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001295 if (ViewDAGs) DAG.viewGraph();
1296
Chris Lattner5ca31d92005-03-30 01:10:47 +00001297 // Third, instruction select all of the operations to machine code, adding the
1298 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001299 InstructionSelectBasicBlock(DAG);
1300
Chris Lattner7a60d912005-01-07 07:47:53 +00001301 DEBUG(std::cerr << "Selected machine code:\n");
1302 DEBUG(BB->dump());
1303
Chris Lattner5ca31d92005-03-30 01:10:47 +00001304 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001305 // PHI nodes in successors.
1306 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1307 MachineInstr *PHI = PHINodesToUpdate[i].first;
1308 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1309 "This is not a machine PHI node that we are updating!");
1310 PHI->addRegOperand(PHINodesToUpdate[i].second);
1311 PHI->addMachineBasicBlockOperand(BB);
1312 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001313
1314 // Finally, add the CFG edges from the last selected MBB to the successor
1315 // MBBs.
1316 TerminatorInst *TI = LLVMBB->getTerminator();
1317 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1318 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1319 BB->addSuccessor(Succ0MBB);
1320 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001321}