blob: 64256c963ebc8963146915d86a2c5e0c3ee81244 [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
75 unsigned MakeReg(MVT::ValueType VT) {
76 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
77 }
Misha Brukman835702a2005-04-21 22:36:52 +000078
Chris Lattner7a60d912005-01-07 07:47:53 +000079 unsigned CreateRegForValue(const Value *V) {
80 MVT::ValueType VT = TLI.getValueType(V->getType());
81 // The common case is that we will only create one register for this
82 // value. If we have that case, create and return the virtual register.
83 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000084 if (NV == 1) {
85 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000086 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000087 }
Misha Brukman835702a2005-04-21 22:36:52 +000088
Chris Lattner7a60d912005-01-07 07:47:53 +000089 // If this value is represented with multiple target registers, make sure
90 // to create enough consequtive registers of the right (smaller) type.
91 unsigned NT = VT-1; // Find the type to use.
92 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
93 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000094
Chris Lattner7a60d912005-01-07 07:47:53 +000095 unsigned R = MakeReg((MVT::ValueType)NT);
96 for (unsigned i = 1; i != NV; ++i)
97 MakeReg((MVT::ValueType)NT);
98 return R;
99 }
Misha Brukman835702a2005-04-21 22:36:52 +0000100
Chris Lattner7a60d912005-01-07 07:47:53 +0000101 unsigned InitializeRegForValue(const Value *V) {
102 unsigned &R = ValueMap[V];
103 assert(R == 0 && "Already initialized this value register!");
104 return R = CreateRegForValue(V);
105 }
106 };
107}
108
109/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
110/// PHI nodes or outside of the basic block that defines it.
111static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
112 if (isa<PHINode>(I)) return true;
113 BasicBlock *BB = I->getParent();
114 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
115 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
116 return true;
117 return false;
118}
119
Chris Lattner6871b232005-10-30 19:42:35 +0000120/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
121/// entry block, return true.
122static bool isOnlyUsedInEntryBlock(Argument *A) {
123 BasicBlock *Entry = A->getParent()->begin();
124 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
125 if (cast<Instruction>(*UI)->getParent() != Entry)
126 return false; // Use not in entry block.
127 return true;
128}
129
Chris Lattner7a60d912005-01-07 07:47:53 +0000130FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000131 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000132 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
133
Chris Lattner6871b232005-10-30 19:42:35 +0000134 // Create a vreg for each argument register that is not dead and is used
135 // outside of the entry block for the function.
136 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137 AI != E; ++AI)
138 if (!isOnlyUsedInEntryBlock(AI))
139 InitializeRegForValue(AI);
140
Chris Lattner7a60d912005-01-07 07:47:53 +0000141 // Initialize the mapping of values to registers. This is only set up for
142 // instruction values that are used outside of the block that defines
143 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000144 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000145 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
146 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
147 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
148 const Type *Ty = AI->getAllocatedType();
149 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000150 unsigned Align =
151 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
152 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000153
154 // If the alignment of the value is smaller than the size of the value,
155 // and if the size of the value is particularly small (<= 8 bytes),
156 // round up to the size of the value for potentially better performance.
157 //
158 // FIXME: This could be made better with a preferred alignment hook in
159 // TargetData. It serves primarily to 8-byte align doubles for X86.
160 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000161 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000162 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000163 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000164 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000165 }
166
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000167 for (; BB != EB; ++BB)
168 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000169 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
170 if (!isa<AllocaInst>(I) ||
171 !StaticAllocaMap.count(cast<AllocaInst>(I)))
172 InitializeRegForValue(I);
173
174 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
175 // also creates the initial PHI MachineInstrs, though none of the input
176 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000177 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000178 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
179 MBBMap[BB] = MBB;
180 MF.getBasicBlockList().push_back(MBB);
181
182 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
183 // appropriate.
184 PHINode *PN;
185 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000186 (PN = dyn_cast<PHINode>(I)); ++I)
187 if (!PN->use_empty()) {
188 unsigned NumElements =
189 TLI.getNumElements(TLI.getValueType(PN->getType()));
190 unsigned PHIReg = ValueMap[PN];
191 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
192 for (unsigned i = 0; i != NumElements; ++i)
193 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
194 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000195 }
196}
197
198
199
200//===----------------------------------------------------------------------===//
201/// SelectionDAGLowering - This is the common target-independent lowering
202/// implementation that is parameterized by a TargetLowering object.
203/// Also, targets can overload any lowering method.
204///
205namespace llvm {
206class SelectionDAGLowering {
207 MachineBasicBlock *CurMBB;
208
209 std::map<const Value*, SDOperand> NodeMap;
210
Chris Lattner4d9651c2005-01-17 22:19:26 +0000211 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
212 /// them up and then emit token factor nodes when possible. This allows us to
213 /// get simple disambiguation between loads without worrying about alias
214 /// analysis.
215 std::vector<SDOperand> PendingLoads;
216
Chris Lattner7a60d912005-01-07 07:47:53 +0000217public:
218 // TLI - This is information that describes the available target features we
219 // need for lowering. This indicates when operations are unavailable,
220 // implemented with a libcall, etc.
221 TargetLowering &TLI;
222 SelectionDAG &DAG;
223 const TargetData &TD;
224
225 /// FuncInfo - Information about the function as a whole.
226 ///
227 FunctionLoweringInfo &FuncInfo;
228
229 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000230 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000231 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
232 FuncInfo(funcinfo) {
233 }
234
Chris Lattner4108bb02005-01-17 19:43:36 +0000235 /// getRoot - Return the current virtual root of the Selection DAG.
236 ///
237 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000238 if (PendingLoads.empty())
239 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000240
Chris Lattner4d9651c2005-01-17 22:19:26 +0000241 if (PendingLoads.size() == 1) {
242 SDOperand Root = PendingLoads[0];
243 DAG.setRoot(Root);
244 PendingLoads.clear();
245 return Root;
246 }
247
248 // Otherwise, we have to make a token factor node.
249 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
250 PendingLoads.clear();
251 DAG.setRoot(Root);
252 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000253 }
254
Chris Lattner7a60d912005-01-07 07:47:53 +0000255 void visit(Instruction &I) { visit(I.getOpcode(), I); }
256
257 void visit(unsigned Opcode, User &I) {
258 switch (Opcode) {
259 default: assert(0 && "Unknown instruction type encountered!");
260 abort();
261 // Build the switch statement using the Instruction.def file.
262#define HANDLE_INST(NUM, OPCODE, CLASS) \
263 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
264#include "llvm/Instruction.def"
265 }
266 }
267
268 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
269
270
271 SDOperand getIntPtrConstant(uint64_t Val) {
272 return DAG.getConstant(Val, TLI.getPointerTy());
273 }
274
275 SDOperand getValue(const Value *V) {
276 SDOperand &N = NodeMap[V];
277 if (N.Val) return N;
278
279 MVT::ValueType VT = TLI.getValueType(V->getType());
280 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
282 visit(CE->getOpcode(), *CE);
283 assert(N.Val && "visit didn't populate the ValueMap!");
284 return N;
285 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
286 return N = DAG.getGlobalAddress(GV, VT);
287 } else if (isa<ConstantPointerNull>(C)) {
288 return N = DAG.getConstant(0, TLI.getPointerTy());
289 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000290 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000291 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
292 return N = DAG.getConstantFP(CFP->getValue(), VT);
293 } else {
294 // Canonicalize all constant ints to be unsigned.
295 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
296 }
297
298 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
299 std::map<const AllocaInst*, int>::iterator SI =
300 FuncInfo.StaticAllocaMap.find(AI);
301 if (SI != FuncInfo.StaticAllocaMap.end())
302 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
303 }
304
305 std::map<const Value*, unsigned>::const_iterator VMI =
306 FuncInfo.ValueMap.find(V);
307 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000308
Chris Lattner33182322005-08-16 21:55:35 +0000309 unsigned InReg = VMI->second;
310
311 // If this type is not legal, make it so now.
312 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
313
314 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
315 if (DestVT < VT) {
316 // Source must be expanded. This input value is actually coming from the
317 // register pair VMI->second and VMI->second+1.
318 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
319 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
320 } else {
321 if (DestVT > VT) { // Promotion case
322 if (MVT::isFloatingPoint(VT))
323 N = DAG.getNode(ISD::FP_ROUND, VT, N);
324 else
325 N = DAG.getNode(ISD::TRUNCATE, VT, N);
326 }
327 }
328
329 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000330 }
331
332 const SDOperand &setValue(const Value *V, SDOperand NewN) {
333 SDOperand &N = NodeMap[V];
334 assert(N.Val == 0 && "Already set a value for this node!");
335 return N = NewN;
336 }
337
338 // Terminator instructions.
339 void visitRet(ReturnInst &I);
340 void visitBr(BranchInst &I);
341 void visitUnreachable(UnreachableInst &I) { /* noop */ }
342
343 // These all get lowered before this pass.
344 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
345 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
346 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
347
348 //
Chris Lattner7f9e0782005-08-22 17:28:31 +0000349 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000350 void visitAdd(User &I) {
351 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
352 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000353 void visitSub(User &I);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000354 void visitMul(User &I) {
355 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
356 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000357 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000358 unsigned Opc;
359 const Type *Ty = I.getType();
360 if (Ty->isFloatingPoint())
361 Opc = ISD::FDIV;
362 else if (Ty->isUnsigned())
363 Opc = ISD::UDIV;
364 else
365 Opc = ISD::SDIV;
366 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000367 }
368 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000369 unsigned Opc;
370 const Type *Ty = I.getType();
371 if (Ty->isFloatingPoint())
372 Opc = ISD::FREM;
373 else if (Ty->isUnsigned())
374 Opc = ISD::UREM;
375 else
376 Opc = ISD::SREM;
377 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000378 }
379 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
380 void visitOr (User &I) { visitBinary(I, ISD::OR); }
381 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner7f9e0782005-08-22 17:28:31 +0000382 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 void visitShr(User &I) {
Chris Lattner7f9e0782005-08-22 17:28:31 +0000384 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner7a60d912005-01-07 07:47:53 +0000385 }
386
387 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
388 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
389 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
390 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
391 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
392 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
393 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
394
395 void visitGetElementPtr(User &I);
396 void visitCast(User &I);
397 void visitSelect(User &I);
398 //
399
400 void visitMalloc(MallocInst &I);
401 void visitFree(FreeInst &I);
402 void visitAlloca(AllocaInst &I);
403 void visitLoad(LoadInst &I);
404 void visitStore(StoreInst &I);
405 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
406 void visitCall(CallInst &I);
407
Chris Lattner7a60d912005-01-07 07:47:53 +0000408 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000409 void visitVAArg(VAArgInst &I);
410 void visitVAEnd(CallInst &I);
411 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000412 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000413
Chris Lattner875def92005-01-11 05:56:49 +0000414 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000415
416 void visitUserOp1(Instruction &I) {
417 assert(0 && "UserOp1 should not exist at instruction selection time!");
418 abort();
419 }
420 void visitUserOp2(Instruction &I) {
421 assert(0 && "UserOp2 should not exist at instruction selection time!");
422 abort();
423 }
424};
425} // end namespace llvm
426
427void SelectionDAGLowering::visitRet(ReturnInst &I) {
428 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000429 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 return;
431 }
432
433 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000434 MVT::ValueType TmpVT;
435
Chris Lattner7a60d912005-01-07 07:47:53 +0000436 switch (Op1.getValueType()) {
437 default: assert(0 && "Unknown value type!");
438 case MVT::i1:
439 case MVT::i8:
440 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000441 case MVT::i32:
442 // If this is a machine where 32-bits is legal or expanded, promote to
443 // 32-bits, otherwise, promote to 64-bits.
444 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
445 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000446 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000447 TmpVT = MVT::i32;
448
449 // Extend integer types to result type.
450 if (I.getOperand(0)->getType()->isSigned())
451 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
452 else
453 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000454 break;
455 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 case MVT::i64:
457 case MVT::f64:
458 break; // No extension needed!
459 }
Nate Begeman78afac22005-10-18 23:23:37 +0000460 // Allow targets to lower this further to meet ABI requirements
461 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000462}
463
464void SelectionDAGLowering::visitBr(BranchInst &I) {
465 // Update machine-CFG edges.
466 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000467
468 // Figure out which block is immediately after the current one.
469 MachineBasicBlock *NextBlock = 0;
470 MachineFunction::iterator BBI = CurMBB;
471 if (++BBI != CurMBB->getParent()->end())
472 NextBlock = BBI;
473
474 if (I.isUnconditional()) {
475 // If this is not a fall-through branch, emit the branch.
476 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000477 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000478 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 } else {
480 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000481
482 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000483 if (Succ1MBB == NextBlock) {
484 // If the condition is false, fall through. This means we should branch
485 // if the condition is true to Succ #0.
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(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 } else if (Succ0MBB == NextBlock) {
489 // If the condition is true, fall through. This means we should branch if
490 // the condition is false to Succ #1. Invert the condition first.
491 SDOperand True = DAG.getConstant(1, Cond.getValueType());
492 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000493 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000494 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000496 std::vector<SDOperand> Ops;
497 Ops.push_back(getRoot());
498 Ops.push_back(Cond);
499 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
500 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
501 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000502 }
503 }
504}
505
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000506void SelectionDAGLowering::visitSub(User &I) {
507 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000508 if (I.getType()->isFloatingPoint()) {
509 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
510 if (CFP->isExactlyValue(-0.0)) {
511 SDOperand Op2 = getValue(I.getOperand(1));
512 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
513 return;
514 }
515 visitBinary(I, ISD::FSUB);
516 } else {
517 visitBinary(I, ISD::SUB);
518 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000519}
520
Chris Lattner7f9e0782005-08-22 17:28:31 +0000521void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000522 SDOperand Op1 = getValue(I.getOperand(0));
523 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000524
Chris Lattner7f9e0782005-08-22 17:28:31 +0000525 if (isShift)
Chris Lattnera66403d2005-09-02 00:19:37 +0000526 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner96c26752005-01-19 22:31:21 +0000527
Chris Lattner7a60d912005-01-07 07:47:53 +0000528 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
529}
530
531void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
532 ISD::CondCode UnsignedOpcode) {
533 SDOperand Op1 = getValue(I.getOperand(0));
534 SDOperand Op2 = getValue(I.getOperand(1));
535 ISD::CondCode Opcode = SignedOpcode;
536 if (I.getOperand(0)->getType()->isUnsigned())
537 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000538 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000539}
540
541void SelectionDAGLowering::visitSelect(User &I) {
542 SDOperand Cond = getValue(I.getOperand(0));
543 SDOperand TrueVal = getValue(I.getOperand(1));
544 SDOperand FalseVal = getValue(I.getOperand(2));
545 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
546 TrueVal, FalseVal));
547}
548
549void SelectionDAGLowering::visitCast(User &I) {
550 SDOperand N = getValue(I.getOperand(0));
551 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
552 MVT::ValueType DestTy = TLI.getValueType(I.getType());
553
554 if (N.getValueType() == DestTy) {
555 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000556 } else if (DestTy == MVT::i1) {
557 // Cast to bool is a comparison against zero, not truncation to zero.
558 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
559 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000560 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000561 } else if (isInteger(SrcTy)) {
562 if (isInteger(DestTy)) { // Int -> Int cast
563 if (DestTy < SrcTy) // Truncating cast?
564 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
565 else if (I.getOperand(0)->getType()->isSigned())
566 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
567 else
568 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
569 } else { // Int -> FP cast
570 if (I.getOperand(0)->getType()->isSigned())
571 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
572 else
573 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
574 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000575 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000576 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
577 if (isFloatingPoint(DestTy)) { // FP -> FP cast
578 if (DestTy < SrcTy) // Rounding cast?
579 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
580 else
581 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
582 } else { // FP -> Int cast.
583 if (I.getType()->isSigned())
584 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
585 else
586 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
587 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000588 }
589}
590
591void SelectionDAGLowering::visitGetElementPtr(User &I) {
592 SDOperand N = getValue(I.getOperand(0));
593 const Type *Ty = I.getOperand(0)->getType();
594 const Type *UIntPtrTy = TD.getIntPtrType();
595
596 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
597 OI != E; ++OI) {
598 Value *Idx = *OI;
599 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
600 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
601 if (Field) {
602 // N = N + Offset
603 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
604 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000605 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000606 }
607 Ty = StTy->getElementType(Field);
608 } else {
609 Ty = cast<SequentialType>(Ty)->getElementType();
610 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
611 // N = N + Idx * ElementSize;
612 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000613 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
614
615 // If the index is smaller or larger than intptr_t, truncate or extend
616 // it.
617 if (IdxN.getValueType() < Scale.getValueType()) {
618 if (Idx->getType()->isSigned())
619 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
620 else
621 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
622 } else if (IdxN.getValueType() > Scale.getValueType())
623 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
624
625 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner7a60d912005-01-07 07:47:53 +0000626 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
627 }
628 }
629 }
630 setValue(&I, N);
631}
632
633void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
634 // If this is a fixed sized alloca in the entry block of the function,
635 // allocate it statically on the stack.
636 if (FuncInfo.StaticAllocaMap.count(&I))
637 return; // getValue will auto-populate this.
638
639 const Type *Ty = I.getAllocatedType();
640 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000641 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
642 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000643
644 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000645 MVT::ValueType IntPtr = TLI.getPointerTy();
646 if (IntPtr < AllocSize.getValueType())
647 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
648 else if (IntPtr > AllocSize.getValueType())
649 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000650
Chris Lattnereccb73d2005-01-22 23:04:37 +0000651 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000652 getIntPtrConstant(TySize));
653
654 // Handle alignment. If the requested alignment is less than or equal to the
655 // stack alignment, ignore it and round the size of the allocation up to the
656 // stack alignment size. If the size is greater than the stack alignment, we
657 // note this in the DYNAMIC_STACKALLOC node.
658 unsigned StackAlign =
659 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
660 if (Align <= StackAlign) {
661 Align = 0;
662 // Add SA-1 to the size.
663 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
664 getIntPtrConstant(StackAlign-1));
665 // Mask out the low bits for alignment purposes.
666 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
667 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
668 }
669
Chris Lattner96c262e2005-05-14 07:29:57 +0000670 std::vector<MVT::ValueType> VTs;
671 VTs.push_back(AllocSize.getValueType());
672 VTs.push_back(MVT::Other);
673 std::vector<SDOperand> Ops;
674 Ops.push_back(getRoot());
675 Ops.push_back(AllocSize);
676 Ops.push_back(getIntPtrConstant(Align));
677 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000678 DAG.setRoot(setValue(&I, DSA).getValue(1));
679
680 // Inform the Frame Information that we have just allocated a variable-sized
681 // object.
682 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
683}
684
685
686void SelectionDAGLowering::visitLoad(LoadInst &I) {
687 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000688
Chris Lattner4d9651c2005-01-17 22:19:26 +0000689 SDOperand Root;
690 if (I.isVolatile())
691 Root = getRoot();
692 else {
693 // Do not serialize non-volatile loads against each other.
694 Root = DAG.getRoot();
695 }
696
Chris Lattnerf5675a02005-05-09 04:08:33 +0000697 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000698 DAG.getSrcValue(I.getOperand(0)));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000699 setValue(&I, L);
700
701 if (I.isVolatile())
702 DAG.setRoot(L.getValue(1));
703 else
704 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000705}
706
707
708void SelectionDAGLowering::visitStore(StoreInst &I) {
709 Value *SrcV = I.getOperand(0);
710 SDOperand Src = getValue(SrcV);
711 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000712 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000713 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000714}
715
716void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000717 const char *RenameFn = 0;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000718 SDOperand Tmp;
Chris Lattner7a60d912005-01-07 07:47:53 +0000719 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000720 if (F->isExternal())
721 switch (F->getIntrinsicID()) {
722 case 0: // Not an LLVM intrinsic.
723 if (F->getName() == "fabs" || F->getName() == "fabsf") {
724 if (I.getNumOperands() == 2 && // Basic sanity checks.
725 I.getOperand(1)->getType()->isFloatingPoint() &&
726 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000727 Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000728 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
729 return;
730 }
731 }
Chris Lattner80026402005-04-30 04:43:14 +0000732 else if (F->getName() == "sin" || F->getName() == "sinf") {
733 if (I.getNumOperands() == 2 && // Basic sanity checks.
734 I.getOperand(1)->getType()->isFloatingPoint() &&
735 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000736 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000737 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
738 return;
739 }
740 }
741 else if (F->getName() == "cos" || F->getName() == "cosf") {
742 if (I.getNumOperands() == 2 && // Basic sanity checks.
743 I.getOperand(1)->getType()->isFloatingPoint() &&
744 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000745 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000746 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
747 return;
748 }
749 }
Chris Lattner0c140002005-04-02 05:26:53 +0000750 break;
751 case Intrinsic::vastart: visitVAStart(I); return;
752 case Intrinsic::vaend: visitVAEnd(I); return;
753 case Intrinsic::vacopy: visitVACopy(I); return;
754 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
755 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000756
Chris Lattner0fd8f9f2005-09-27 22:15:53 +0000757 case Intrinsic::setjmp:
758 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
759 break;
760 case Intrinsic::longjmp:
761 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
762 break;
Chris Lattner0c140002005-04-02 05:26:53 +0000763 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
764 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
765 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukman835702a2005-04-21 22:36:52 +0000766
Chris Lattner20eaeae2005-05-09 20:22:36 +0000767 case Intrinsic::readport:
Chris Lattnere4f71d02005-05-14 13:56:55 +0000768 case Intrinsic::readio: {
769 std::vector<MVT::ValueType> VTs;
770 VTs.push_back(TLI.getValueType(I.getType()));
771 VTs.push_back(MVT::Other);
772 std::vector<SDOperand> Ops;
773 Ops.push_back(getRoot());
774 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattner20eaeae2005-05-09 20:22:36 +0000775 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattnere4f71d02005-05-14 13:56:55 +0000776 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000777
Chris Lattner20eaeae2005-05-09 20:22:36 +0000778 setValue(&I, Tmp);
779 DAG.setRoot(Tmp.getValue(1));
780 return;
Chris Lattnere4f71d02005-05-14 13:56:55 +0000781 }
Chris Lattner20eaeae2005-05-09 20:22:36 +0000782 case Intrinsic::writeport:
783 case Intrinsic::writeio:
784 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
785 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
786 getRoot(), getValue(I.getOperand(1)),
787 getValue(I.getOperand(2))));
788 return;
Chris Lattner78761562005-05-05 17:55:17 +0000789 case Intrinsic::dbg_stoppoint:
790 case Intrinsic::dbg_region_start:
791 case Intrinsic::dbg_region_end:
792 case Intrinsic::dbg_func_start:
793 case Intrinsic::dbg_declare:
794 if (I.getType() != Type::VoidTy)
795 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
796 return;
797
Chris Lattner0c140002005-04-02 05:26:53 +0000798 case Intrinsic::isunordered:
Chris Lattnerd47675e2005-08-09 20:20:18 +0000799 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
800 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattner0c140002005-04-02 05:26:53 +0000801 return;
Chris Lattner80026402005-04-30 04:43:14 +0000802
803 case Intrinsic::sqrt:
804 setValue(&I, DAG.getNode(ISD::FSQRT,
805 getValue(I.getOperand(1)).getValueType(),
806 getValue(I.getOperand(1))));
807 return;
808
Chris Lattner20eaeae2005-05-09 20:22:36 +0000809 case Intrinsic::pcmarker:
810 Tmp = getValue(I.getOperand(1));
811 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattner0c140002005-04-02 05:26:53 +0000812 return;
Andrew Lenharth5e177822005-05-03 17:19:30 +0000813 case Intrinsic::cttz:
814 setValue(&I, DAG.getNode(ISD::CTTZ,
815 getValue(I.getOperand(1)).getValueType(),
816 getValue(I.getOperand(1))));
817 return;
818 case Intrinsic::ctlz:
819 setValue(&I, DAG.getNode(ISD::CTLZ,
820 getValue(I.getOperand(1)).getValueType(),
821 getValue(I.getOperand(1))));
822 return;
823 case Intrinsic::ctpop:
824 setValue(&I, DAG.getNode(ISD::CTPOP,
825 getValue(I.getOperand(1)).getValueType(),
826 getValue(I.getOperand(1))));
827 return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000828 default:
829 std::cerr << I;
830 assert(0 && "This intrinsic is not implemented yet!");
831 return;
Chris Lattner0c140002005-04-02 05:26:53 +0000832 }
Misha Brukman835702a2005-04-21 22:36:52 +0000833
Chris Lattner18d2b342005-01-08 22:48:57 +0000834 SDOperand Callee;
835 if (!RenameFn)
836 Callee = getValue(I.getOperand(0));
837 else
838 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000839 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukman835702a2005-04-21 22:36:52 +0000840
Chris Lattner7a60d912005-01-07 07:47:53 +0000841 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
842 Value *Arg = I.getOperand(i);
843 SDOperand ArgNode = getValue(Arg);
844 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
845 }
Misha Brukman835702a2005-04-21 22:36:52 +0000846
Nate Begemanf6565252005-03-26 01:29:23 +0000847 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
848 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000849
Chris Lattner1f45cd72005-01-08 19:26:18 +0000850 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000851 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000852 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000853 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000854 setValue(&I, Result.first);
855 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000856}
857
858void SelectionDAGLowering::visitMalloc(MallocInst &I) {
859 SDOperand Src = getValue(I.getOperand(0));
860
861 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000862
863 if (IntPtr < Src.getValueType())
864 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
865 else if (IntPtr > Src.getValueType())
866 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000867
868 // Scale the source by the type size.
869 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
870 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
871 Src, getIntPtrConstant(ElementSize));
872
873 std::vector<std::pair<SDOperand, const Type*> > Args;
874 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000875
876 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000877 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000878 DAG.getExternalSymbol("malloc", IntPtr),
879 Args, DAG);
880 setValue(&I, Result.first); // Pointers always fit in registers
881 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000882}
883
884void SelectionDAGLowering::visitFree(FreeInst &I) {
885 std::vector<std::pair<SDOperand, const Type*> > Args;
886 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
887 TLI.getTargetData().getIntPtrType()));
888 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000889 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000890 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000891 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
892 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000893}
894
Chris Lattner13d7c252005-08-26 20:54:47 +0000895// InsertAtEndOfBasicBlock - This method should be implemented by targets that
896// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
897// instructions are special in various ways, which require special support to
898// insert. The specified MachineInstr is created but not inserted into any
899// basic blocks, and the scheduler passes ownership of it to this method.
900MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
901 MachineBasicBlock *MBB) {
902 std::cerr << "If a target marks an instruction with "
903 "'usesCustomDAGSchedInserter', it must implement "
904 "TargetLowering::InsertAtEndOfBasicBlock!\n";
905 abort();
906 return 0;
907}
908
Nate Begeman78afac22005-10-18 23:23:37 +0000909SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
910 SelectionDAG &DAG) {
911 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
912}
913
Chris Lattnerf5473e42005-07-05 19:57:53 +0000914SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
915 SDOperand VAListP, Value *VAListV,
916 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000917 // We have no sane default behavior, just emit a useful error message and bail
918 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000919 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000920 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +0000921 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +0000922}
923
Chris Lattnerf5473e42005-07-05 19:57:53 +0000924SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +0000925 SelectionDAG &DAG) {
926 // Default to a noop.
927 return Chain;
928}
929
Chris Lattnerf5473e42005-07-05 19:57:53 +0000930SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
931 SDOperand SrcP, Value *SrcV,
932 SDOperand DestP, Value *DestV,
933 SelectionDAG &DAG) {
934 // Default to copying the input list.
935 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
936 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +0000937 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000938 Val, DestP, DAG.getSrcValue(DestV));
939 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +0000940}
941
942std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +0000943TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
944 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000945 // We have no sane default behavior, just emit a useful error message and bail
946 // out.
947 std::cerr << "Variable arguments handling not implemented on this target!\n";
948 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000949 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000950}
951
952
953void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000954 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
955 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +0000956}
957
958void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
959 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +0000960 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000961 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000962 setValue(&I, Result.first);
963 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000964}
965
966void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000967 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000968 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000969}
970
971void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000972 SDOperand Result =
973 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
974 getValue(I.getOperand(1)), I.getOperand(1), DAG);
975 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +0000976}
977
Chris Lattner58cfd792005-01-09 00:00:49 +0000978
979// It is always conservatively correct for llvm.returnaddress and
980// llvm.frameaddress to return 0.
981std::pair<SDOperand, SDOperand>
982TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
983 unsigned Depth, SelectionDAG &DAG) {
984 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000985}
986
Chris Lattner29dcc712005-05-14 05:50:48 +0000987SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +0000988 assert(0 && "LowerOperation not implemented for this target!");
989 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000990 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000991}
992
Chris Lattner58cfd792005-01-09 00:00:49 +0000993void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
994 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
995 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000996 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000997 setValue(&I, Result.first);
998 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000999}
1000
Chris Lattner875def92005-01-11 05:56:49 +00001001void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1002 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001003 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001004 Ops.push_back(getValue(I.getOperand(1)));
1005 Ops.push_back(getValue(I.getOperand(2)));
1006 Ops.push_back(getValue(I.getOperand(3)));
1007 Ops.push_back(getValue(I.getOperand(4)));
1008 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001009}
1010
Chris Lattner875def92005-01-11 05:56:49 +00001011//===----------------------------------------------------------------------===//
1012// SelectionDAGISel code
1013//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001014
1015unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1016 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1017}
1018
Chris Lattnerc9950c12005-08-17 06:37:43 +00001019void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001020 // FIXME: we only modify the CFG to split critical edges. This
1021 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001022}
Chris Lattner7a60d912005-01-07 07:47:53 +00001023
1024
1025bool SelectionDAGISel::runOnFunction(Function &Fn) {
1026 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1027 RegMap = MF.getSSARegMap();
1028 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1029
Chris Lattnerc9950c12005-08-17 06:37:43 +00001030 // First pass, split all critical edges for PHI nodes with incoming values
1031 // that are constants, this way the load of the constant into a vreg will not
1032 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001033 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1034 PHINode *PN;
1035 for (BasicBlock::iterator BBI = BB->begin();
1036 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1037 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1038 if (isa<Constant>(PN->getIncomingValue(i)))
1039 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1040 }
Chris Lattnerc9950c12005-08-17 06:37:43 +00001041
Chris Lattner7a60d912005-01-07 07:47:53 +00001042 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1043
1044 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1045 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001046
Chris Lattner7a60d912005-01-07 07:47:53 +00001047 return true;
1048}
1049
1050
Chris Lattner718b5c22005-01-13 17:59:43 +00001051SDOperand SelectionDAGISel::
1052CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001053 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001054 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001055 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001056 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001057
1058 // If this type is not legal, we must make sure to not create an invalid
1059 // register use.
1060 MVT::ValueType SrcVT = Op.getValueType();
1061 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1062 SelectionDAG &DAG = SDL.DAG;
1063 if (SrcVT == DestVT) {
1064 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1065 } else if (SrcVT < DestVT) {
1066 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001067 if (MVT::isFloatingPoint(SrcVT))
1068 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1069 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001070 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001071 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1072 } else {
1073 // The src value is expanded into multiple registers.
1074 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1075 Op, DAG.getConstant(0, MVT::i32));
1076 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1077 Op, DAG.getConstant(1, MVT::i32));
1078 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1079 return DAG.getCopyToReg(Op, Reg+1, Hi);
1080 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001081}
1082
Chris Lattner16f64df2005-01-17 17:15:02 +00001083void SelectionDAGISel::
1084LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1085 std::vector<SDOperand> &UnorderedChains) {
1086 // If this is the entry block, emit arguments.
1087 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001088 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001089 SDOperand OldRoot = SDL.DAG.getRoot();
1090 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001091
Chris Lattner6871b232005-10-30 19:42:35 +00001092 unsigned a = 0;
1093 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1094 AI != E; ++AI, ++a)
1095 if (!AI->use_empty()) {
1096 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001097
Chris Lattner6871b232005-10-30 19:42:35 +00001098 // If this argument is live outside of the entry block, insert a copy from
1099 // whereever we got it to the vreg that other BB's will reference it as.
1100 if (FuncInfo.ValueMap.count(AI)) {
1101 SDOperand Copy =
1102 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1103 UnorderedChains.push_back(Copy);
1104 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001105 }
Chris Lattner6871b232005-10-30 19:42:35 +00001106
1107 // Next, if the function has live ins that need to be copied into vregs,
1108 // emit the copies now, into the top of the block.
1109 MachineFunction &MF = SDL.DAG.getMachineFunction();
1110 if (MF.livein_begin() != MF.livein_end()) {
1111 SSARegMap *RegMap = MF.getSSARegMap();
1112 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1113 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1114 E = MF.livein_end(); LI != E; ++LI)
1115 if (LI->second)
1116 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1117 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001118 }
Chris Lattner6871b232005-10-30 19:42:35 +00001119
1120 // Finally, if the target has anything special to do, allow it to do so.
1121 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001122}
1123
1124
Chris Lattner7a60d912005-01-07 07:47:53 +00001125void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1126 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1127 FunctionLoweringInfo &FuncInfo) {
1128 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001129
1130 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001131
Chris Lattner6871b232005-10-30 19:42:35 +00001132 // Lower any arguments needed in this block if this is the entry block.
1133 if (LLVMBB == &LLVMBB->getParent()->front())
1134 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001135
1136 BB = FuncInfo.MBBMap[LLVMBB];
1137 SDL.setCurrentBasicBlock(BB);
1138
1139 // Lower all of the non-terminator instructions.
1140 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1141 I != E; ++I)
1142 SDL.visit(*I);
1143
1144 // Ensure that all instructions which are used outside of their defining
1145 // blocks are available as virtual registers.
1146 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001147 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001148 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001149 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001150 UnorderedChains.push_back(
1151 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001152 }
1153
1154 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1155 // ensure constants are generated when needed. Remember the virtual registers
1156 // that need to be added to the Machine PHI nodes as input. We cannot just
1157 // directly add them, because expansion might result in multiple MBB's for one
1158 // BB. As such, the start of the BB might correspond to a different MBB than
1159 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001160 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001161
1162 // Emit constants only once even if used by multiple PHI nodes.
1163 std::map<Constant*, unsigned> ConstantsOut;
1164
1165 // Check successor nodes PHI nodes that expect a constant to be available from
1166 // this block.
1167 TerminatorInst *TI = LLVMBB->getTerminator();
1168 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1169 BasicBlock *SuccBB = TI->getSuccessor(succ);
1170 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1171 PHINode *PN;
1172
1173 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1174 // nodes and Machine PHI nodes, but the incoming operands have not been
1175 // emitted yet.
1176 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001177 (PN = dyn_cast<PHINode>(I)); ++I)
1178 if (!PN->use_empty()) {
1179 unsigned Reg;
1180 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1181 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1182 unsigned &RegOut = ConstantsOut[C];
1183 if (RegOut == 0) {
1184 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001185 UnorderedChains.push_back(
1186 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001187 }
1188 Reg = RegOut;
1189 } else {
1190 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001191 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001192 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001193 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1194 "Didn't codegen value into a register!??");
1195 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001196 UnorderedChains.push_back(
1197 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001198 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001199 }
Misha Brukman835702a2005-04-21 22:36:52 +00001200
Chris Lattner8ea875f2005-01-07 21:34:19 +00001201 // Remember that this register needs to added to the machine PHI node as
1202 // the input for this MBB.
1203 unsigned NumElements =
1204 TLI.getNumElements(TLI.getValueType(PN->getType()));
1205 for (unsigned i = 0, e = NumElements; i != e; ++i)
1206 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001207 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001208 }
1209 ConstantsOut.clear();
1210
Chris Lattner718b5c22005-01-13 17:59:43 +00001211 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001212 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001213 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001214 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1215 }
1216
Chris Lattner7a60d912005-01-07 07:47:53 +00001217 // Lower the terminator after the copies are emitted.
1218 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001219
1220 // Make sure the root of the DAG is up-to-date.
1221 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001222}
1223
1224void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1225 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001226 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001227 CurDAG = &DAG;
1228 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1229
1230 // First step, lower LLVM code to some DAG. This DAG may use operations and
1231 // types that are not supported by the target.
1232 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1233
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001234 // Run the DAG combiner in pre-legalize mode.
1235 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001236
Chris Lattner7a60d912005-01-07 07:47:53 +00001237 DEBUG(std::cerr << "Lowered selection DAG:\n");
1238 DEBUG(DAG.dump());
1239
1240 // Second step, hack on the DAG until it only uses operations and types that
1241 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001242 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001243
1244 DEBUG(std::cerr << "Legalized selection DAG:\n");
1245 DEBUG(DAG.dump());
1246
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001247 // Run the DAG combiner in post-legalize mode.
1248 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001249
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001250 if (ViewDAGs) DAG.viewGraph();
1251
Chris Lattner5ca31d92005-03-30 01:10:47 +00001252 // Third, instruction select all of the operations to machine code, adding the
1253 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001254 InstructionSelectBasicBlock(DAG);
1255
Chris Lattner7a60d912005-01-07 07:47:53 +00001256 DEBUG(std::cerr << "Selected machine code:\n");
1257 DEBUG(BB->dump());
1258
Chris Lattner5ca31d92005-03-30 01:10:47 +00001259 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001260 // PHI nodes in successors.
1261 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1262 MachineInstr *PHI = PHINodesToUpdate[i].first;
1263 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1264 "This is not a machine PHI node that we are updating!");
1265 PHI->addRegOperand(PHINodesToUpdate[i].second);
1266 PHI->addMachineBasicBlockOperand(BB);
1267 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001268
1269 // Finally, add the CFG edges from the last selected MBB to the successor
1270 // MBBs.
1271 TerminatorInst *TI = LLVMBB->getTerminator();
1272 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1273 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1274 BB->addSuccessor(Succ0MBB);
1275 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001276}