blob: 881168137420b8302d366865727bb9726c176bd0 [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"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000022#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/SelectionDAG.h"
27#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000028#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetFrameInfo.h"
31#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
33#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000035#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000036#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Support/Debug.h"
38#include <map>
39#include <iostream>
40using namespace llvm;
41
Chris Lattner975f5c92005-09-01 18:44:10 +000042#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000043static cl::opt<bool>
44ViewDAGs("view-isel-dags", cl::Hidden,
45 cl::desc("Pop up a window to show isel dags as they are selected"));
46#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000047static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000048#endif
49
Chris Lattner7a60d912005-01-07 07:47:53 +000050namespace llvm {
51 //===--------------------------------------------------------------------===//
52 /// FunctionLoweringInfo - This contains information that is global to a
53 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000054 class FunctionLoweringInfo {
55 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000056 TargetLowering &TLI;
57 Function &Fn;
58 MachineFunction &MF;
59 SSARegMap *RegMap;
60
61 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
62
63 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
64 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
65
66 /// ValueMap - Since we emit code for the function a basic block at a time,
67 /// we must remember which virtual registers hold the values for
68 /// cross-basic-block values.
69 std::map<const Value*, unsigned> ValueMap;
70
71 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
72 /// the entry block. This allows the allocas to be efficiently referenced
73 /// anywhere in the function.
74 std::map<const AllocaInst*, int> StaticAllocaMap;
75
76 unsigned MakeReg(MVT::ValueType VT) {
77 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
78 }
Misha Brukman835702a2005-04-21 22:36:52 +000079
Chris Lattner7a60d912005-01-07 07:47:53 +000080 unsigned CreateRegForValue(const Value *V) {
81 MVT::ValueType VT = TLI.getValueType(V->getType());
82 // The common case is that we will only create one register for this
83 // value. If we have that case, create and return the virtual register.
84 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000085 if (NV == 1) {
86 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000087 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000088 }
Misha Brukman835702a2005-04-21 22:36:52 +000089
Chris Lattner7a60d912005-01-07 07:47:53 +000090 // If this value is represented with multiple target registers, make sure
91 // to create enough consequtive registers of the right (smaller) type.
92 unsigned NT = VT-1; // Find the type to use.
93 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
94 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000095
Chris Lattner7a60d912005-01-07 07:47:53 +000096 unsigned R = MakeReg((MVT::ValueType)NT);
97 for (unsigned i = 1; i != NV; ++i)
98 MakeReg((MVT::ValueType)NT);
99 return R;
100 }
Misha Brukman835702a2005-04-21 22:36:52 +0000101
Chris Lattner7a60d912005-01-07 07:47:53 +0000102 unsigned InitializeRegForValue(const Value *V) {
103 unsigned &R = ValueMap[V];
104 assert(R == 0 && "Already initialized this value register!");
105 return R = CreateRegForValue(V);
106 }
107 };
108}
109
110/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
111/// PHI nodes or outside of the basic block that defines it.
112static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
113 if (isa<PHINode>(I)) return true;
114 BasicBlock *BB = I->getParent();
115 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
116 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
117 return true;
118 return false;
119}
120
Chris Lattner6871b232005-10-30 19:42:35 +0000121/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
122/// entry block, return true.
123static bool isOnlyUsedInEntryBlock(Argument *A) {
124 BasicBlock *Entry = A->getParent()->begin();
125 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
126 if (cast<Instruction>(*UI)->getParent() != Entry)
127 return false; // Use not in entry block.
128 return true;
129}
130
Chris Lattner7a60d912005-01-07 07:47:53 +0000131FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000132 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000133 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
134
Chris Lattner6871b232005-10-30 19:42:35 +0000135 // Create a vreg for each argument register that is not dead and is used
136 // outside of the entry block for the function.
137 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
138 AI != E; ++AI)
139 if (!isOnlyUsedInEntryBlock(AI))
140 InitializeRegForValue(AI);
141
Chris Lattner7a60d912005-01-07 07:47:53 +0000142 // Initialize the mapping of values to registers. This is only set up for
143 // instruction values that are used outside of the block that defines
144 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000145 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000146 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
147 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
148 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
149 const Type *Ty = AI->getAllocatedType();
150 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000151 unsigned Align =
152 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
153 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000154
155 // If the alignment of the value is smaller than the size of the value,
156 // and if the size of the value is particularly small (<= 8 bytes),
157 // round up to the size of the value for potentially better performance.
158 //
159 // FIXME: This could be made better with a preferred alignment hook in
160 // TargetData. It serves primarily to 8-byte align doubles for X86.
161 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000162 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000163 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000165 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000166 }
167
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000168 for (; BB != EB; ++BB)
169 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000170 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
171 if (!isa<AllocaInst>(I) ||
172 !StaticAllocaMap.count(cast<AllocaInst>(I)))
173 InitializeRegForValue(I);
174
175 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
176 // also creates the initial PHI MachineInstrs, though none of the input
177 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000178 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000179 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
180 MBBMap[BB] = MBB;
181 MF.getBasicBlockList().push_back(MBB);
182
183 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
184 // appropriate.
185 PHINode *PN;
186 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000187 (PN = dyn_cast<PHINode>(I)); ++I)
188 if (!PN->use_empty()) {
189 unsigned NumElements =
190 TLI.getNumElements(TLI.getValueType(PN->getType()));
191 unsigned PHIReg = ValueMap[PN];
192 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
193 for (unsigned i = 0; i != NumElements; ++i)
194 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
195 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 }
197}
198
199
200
201//===----------------------------------------------------------------------===//
202/// SelectionDAGLowering - This is the common target-independent lowering
203/// implementation that is parameterized by a TargetLowering object.
204/// Also, targets can overload any lowering method.
205///
206namespace llvm {
207class SelectionDAGLowering {
208 MachineBasicBlock *CurMBB;
209
210 std::map<const Value*, SDOperand> NodeMap;
211
Chris Lattner4d9651c2005-01-17 22:19:26 +0000212 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
213 /// them up and then emit token factor nodes when possible. This allows us to
214 /// get simple disambiguation between loads without worrying about alias
215 /// analysis.
216 std::vector<SDOperand> PendingLoads;
217
Chris Lattner7a60d912005-01-07 07:47:53 +0000218public:
219 // TLI - This is information that describes the available target features we
220 // need for lowering. This indicates when operations are unavailable,
221 // implemented with a libcall, etc.
222 TargetLowering &TLI;
223 SelectionDAG &DAG;
224 const TargetData &TD;
225
226 /// FuncInfo - Information about the function as a whole.
227 ///
228 FunctionLoweringInfo &FuncInfo;
229
230 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000231 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000232 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
233 FuncInfo(funcinfo) {
234 }
235
Chris Lattner4108bb02005-01-17 19:43:36 +0000236 /// getRoot - Return the current virtual root of the Selection DAG.
237 ///
238 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000239 if (PendingLoads.empty())
240 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000241
Chris Lattner4d9651c2005-01-17 22:19:26 +0000242 if (PendingLoads.size() == 1) {
243 SDOperand Root = PendingLoads[0];
244 DAG.setRoot(Root);
245 PendingLoads.clear();
246 return Root;
247 }
248
249 // Otherwise, we have to make a token factor node.
250 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
251 PendingLoads.clear();
252 DAG.setRoot(Root);
253 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000254 }
255
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 void visit(Instruction &I) { visit(I.getOpcode(), I); }
257
258 void visit(unsigned Opcode, User &I) {
259 switch (Opcode) {
260 default: assert(0 && "Unknown instruction type encountered!");
261 abort();
262 // Build the switch statement using the Instruction.def file.
263#define HANDLE_INST(NUM, OPCODE, CLASS) \
264 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
265#include "llvm/Instruction.def"
266 }
267 }
268
269 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
270
271
272 SDOperand getIntPtrConstant(uint64_t Val) {
273 return DAG.getConstant(Val, TLI.getPointerTy());
274 }
275
276 SDOperand getValue(const Value *V) {
277 SDOperand &N = NodeMap[V];
278 if (N.Val) return N;
279
280 MVT::ValueType VT = TLI.getValueType(V->getType());
281 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
282 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
283 visit(CE->getOpcode(), *CE);
284 assert(N.Val && "visit didn't populate the ValueMap!");
285 return N;
286 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
287 return N = DAG.getGlobalAddress(GV, VT);
288 } else if (isa<ConstantPointerNull>(C)) {
289 return N = DAG.getConstant(0, TLI.getPointerTy());
290 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000291 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000292 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
293 return N = DAG.getConstantFP(CFP->getValue(), VT);
294 } else {
295 // Canonicalize all constant ints to be unsigned.
296 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
297 }
298
299 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
300 std::map<const AllocaInst*, int>::iterator SI =
301 FuncInfo.StaticAllocaMap.find(AI);
302 if (SI != FuncInfo.StaticAllocaMap.end())
303 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
304 }
305
306 std::map<const Value*, unsigned>::const_iterator VMI =
307 FuncInfo.ValueMap.find(V);
308 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000309
Chris Lattner33182322005-08-16 21:55:35 +0000310 unsigned InReg = VMI->second;
311
312 // If this type is not legal, make it so now.
313 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
314
315 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
316 if (DestVT < VT) {
317 // Source must be expanded. This input value is actually coming from the
318 // register pair VMI->second and VMI->second+1.
319 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
320 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
321 } else {
322 if (DestVT > VT) { // Promotion case
323 if (MVT::isFloatingPoint(VT))
324 N = DAG.getNode(ISD::FP_ROUND, VT, N);
325 else
326 N = DAG.getNode(ISD::TRUNCATE, VT, N);
327 }
328 }
329
330 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000331 }
332
333 const SDOperand &setValue(const Value *V, SDOperand NewN) {
334 SDOperand &N = NodeMap[V];
335 assert(N.Val == 0 && "Already set a value for this node!");
336 return N = NewN;
337 }
338
339 // Terminator instructions.
340 void visitRet(ReturnInst &I);
341 void visitBr(BranchInst &I);
342 void visitUnreachable(UnreachableInst &I) { /* noop */ }
343
344 // These all get lowered before this pass.
345 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
346 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
347 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
348
349 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000350 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000351 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000352 void visitAdd(User &I) {
353 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000354 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000355 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000356 void visitMul(User &I) {
357 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000358 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000359 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000360 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000361 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000362 }
363 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000364 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000365 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000366 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000367 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
368 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
369 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000370 void visitShl(User &I) { visitShift(I, ISD::SHL); }
371 void visitShr(User &I) {
372 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000373 }
374
375 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
376 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
377 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
378 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
379 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
380 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
381 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
382
383 void visitGetElementPtr(User &I);
384 void visitCast(User &I);
385 void visitSelect(User &I);
386 //
387
388 void visitMalloc(MallocInst &I);
389 void visitFree(FreeInst &I);
390 void visitAlloca(AllocaInst &I);
391 void visitLoad(LoadInst &I);
392 void visitStore(StoreInst &I);
393 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
394 void visitCall(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000395 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000396
Chris Lattner7a60d912005-01-07 07:47:53 +0000397 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000398 void visitVAArg(VAArgInst &I);
399 void visitVAEnd(CallInst &I);
400 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000401 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000402
Chris Lattner875def92005-01-11 05:56:49 +0000403 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
405 void visitUserOp1(Instruction &I) {
406 assert(0 && "UserOp1 should not exist at instruction selection time!");
407 abort();
408 }
409 void visitUserOp2(Instruction &I) {
410 assert(0 && "UserOp2 should not exist at instruction selection time!");
411 abort();
412 }
413};
414} // end namespace llvm
415
416void SelectionDAGLowering::visitRet(ReturnInst &I) {
417 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000418 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000419 return;
420 }
421
422 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000423 MVT::ValueType TmpVT;
424
Chris Lattner7a60d912005-01-07 07:47:53 +0000425 switch (Op1.getValueType()) {
426 default: assert(0 && "Unknown value type!");
427 case MVT::i1:
428 case MVT::i8:
429 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000430 case MVT::i32:
431 // If this is a machine where 32-bits is legal or expanded, promote to
432 // 32-bits, otherwise, promote to 64-bits.
433 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
434 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000435 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000436 TmpVT = MVT::i32;
437
438 // Extend integer types to result type.
439 if (I.getOperand(0)->getType()->isSigned())
440 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
441 else
442 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 break;
444 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 case MVT::i64:
446 case MVT::f64:
447 break; // No extension needed!
448 }
Nate Begeman78afac22005-10-18 23:23:37 +0000449 // Allow targets to lower this further to meet ABI requirements
450 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000451}
452
453void SelectionDAGLowering::visitBr(BranchInst &I) {
454 // Update machine-CFG edges.
455 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000456
457 // Figure out which block is immediately after the current one.
458 MachineBasicBlock *NextBlock = 0;
459 MachineFunction::iterator BBI = CurMBB;
460 if (++BBI != CurMBB->getParent()->end())
461 NextBlock = BBI;
462
463 if (I.isUnconditional()) {
464 // If this is not a fall-through branch, emit the branch.
465 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000466 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000467 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000468 } else {
469 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000470
471 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000472 if (Succ1MBB == NextBlock) {
473 // If the condition is false, fall through. This means we should branch
474 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000475 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000476 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000477 } else if (Succ0MBB == NextBlock) {
478 // If the condition is true, fall through. This means we should branch if
479 // the condition is false to Succ #1. Invert the condition first.
480 SDOperand True = DAG.getConstant(1, Cond.getValueType());
481 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000482 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000483 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000485 std::vector<SDOperand> Ops;
486 Ops.push_back(getRoot());
487 Ops.push_back(Cond);
488 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
489 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
490 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 }
492 }
493}
494
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000495void SelectionDAGLowering::visitSub(User &I) {
496 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000497 if (I.getType()->isFloatingPoint()) {
498 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
499 if (CFP->isExactlyValue(-0.0)) {
500 SDOperand Op2 = getValue(I.getOperand(1));
501 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
502 return;
503 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000504 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000505 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000506}
507
Nate Begemanb2e089c2005-11-19 00:36:38 +0000508void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
509 unsigned VecOp) {
510 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 SDOperand Op1 = getValue(I.getOperand(0));
512 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000513
Chris Lattner19baba62005-11-19 18:40:42 +0000514 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000515 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
516 } else if (Ty->isFloatingPoint()) {
517 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
518 } else {
519 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000520 unsigned NumElements = PTy->getNumElements();
521 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
522
523 // Immediately scalarize packed types containing only one element, so that
524 // the Legalize pass does not have to deal with them.
525 if (NumElements == 1) {
526 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
527 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
528 } else {
529 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
530 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000531 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000532 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000533 }
Nate Begeman127321b2005-11-18 07:42:56 +0000534}
Chris Lattner96c26752005-01-19 22:31:21 +0000535
Nate Begeman127321b2005-11-18 07:42:56 +0000536void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
537 SDOperand Op1 = getValue(I.getOperand(0));
538 SDOperand Op2 = getValue(I.getOperand(1));
539
540 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
541
Chris Lattner7a60d912005-01-07 07:47:53 +0000542 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
543}
544
545void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
546 ISD::CondCode UnsignedOpcode) {
547 SDOperand Op1 = getValue(I.getOperand(0));
548 SDOperand Op2 = getValue(I.getOperand(1));
549 ISD::CondCode Opcode = SignedOpcode;
550 if (I.getOperand(0)->getType()->isUnsigned())
551 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000552 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000553}
554
555void SelectionDAGLowering::visitSelect(User &I) {
556 SDOperand Cond = getValue(I.getOperand(0));
557 SDOperand TrueVal = getValue(I.getOperand(1));
558 SDOperand FalseVal = getValue(I.getOperand(2));
559 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
560 TrueVal, FalseVal));
561}
562
563void SelectionDAGLowering::visitCast(User &I) {
564 SDOperand N = getValue(I.getOperand(0));
565 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
566 MVT::ValueType DestTy = TLI.getValueType(I.getType());
567
568 if (N.getValueType() == DestTy) {
569 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000570 } else if (DestTy == MVT::i1) {
571 // Cast to bool is a comparison against zero, not truncation to zero.
572 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
573 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000574 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000575 } else if (isInteger(SrcTy)) {
576 if (isInteger(DestTy)) { // Int -> Int cast
577 if (DestTy < SrcTy) // Truncating cast?
578 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
579 else if (I.getOperand(0)->getType()->isSigned())
580 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
581 else
582 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
583 } else { // Int -> FP cast
584 if (I.getOperand(0)->getType()->isSigned())
585 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
586 else
587 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
588 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000589 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000590 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
591 if (isFloatingPoint(DestTy)) { // FP -> FP cast
592 if (DestTy < SrcTy) // Rounding cast?
593 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
594 else
595 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
596 } else { // FP -> Int cast.
597 if (I.getType()->isSigned())
598 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
599 else
600 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
601 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000602 }
603}
604
605void SelectionDAGLowering::visitGetElementPtr(User &I) {
606 SDOperand N = getValue(I.getOperand(0));
607 const Type *Ty = I.getOperand(0)->getType();
608 const Type *UIntPtrTy = TD.getIntPtrType();
609
610 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
611 OI != E; ++OI) {
612 Value *Idx = *OI;
613 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
614 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
615 if (Field) {
616 // N = N + Offset
617 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
618 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000619 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000620 }
621 Ty = StTy->getElementType(Field);
622 } else {
623 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000624
Chris Lattner43535a12005-11-09 04:45:33 +0000625 // If this is a constant subscript, handle it quickly.
626 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
627 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000628
Chris Lattner43535a12005-11-09 04:45:33 +0000629 uint64_t Offs;
630 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
631 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
632 else
633 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
634 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
635 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000636 }
Chris Lattner43535a12005-11-09 04:45:33 +0000637
638 // N = N + Idx * ElementSize;
639 uint64_t ElementSize = TD.getTypeSize(Ty);
640 SDOperand IdxN = getValue(Idx);
641
642 // If the index is smaller or larger than intptr_t, truncate or extend
643 // it.
644 if (IdxN.getValueType() < N.getValueType()) {
645 if (Idx->getType()->isSigned())
646 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
647 else
648 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
649 } else if (IdxN.getValueType() > N.getValueType())
650 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
651
652 // If this is a multiply by a power of two, turn it into a shl
653 // immediately. This is a very common case.
654 if (isPowerOf2_64(ElementSize)) {
655 unsigned Amt = Log2_64(ElementSize);
656 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000657 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000658 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
659 continue;
660 }
661
662 SDOperand Scale = getIntPtrConstant(ElementSize);
663 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
664 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000665 }
666 }
667 setValue(&I, N);
668}
669
670void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
671 // If this is a fixed sized alloca in the entry block of the function,
672 // allocate it statically on the stack.
673 if (FuncInfo.StaticAllocaMap.count(&I))
674 return; // getValue will auto-populate this.
675
676 const Type *Ty = I.getAllocatedType();
677 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000678 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
679 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000680
681 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000682 MVT::ValueType IntPtr = TLI.getPointerTy();
683 if (IntPtr < AllocSize.getValueType())
684 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
685 else if (IntPtr > AllocSize.getValueType())
686 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000687
Chris Lattnereccb73d2005-01-22 23:04:37 +0000688 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000689 getIntPtrConstant(TySize));
690
691 // Handle alignment. If the requested alignment is less than or equal to the
692 // stack alignment, ignore it and round the size of the allocation up to the
693 // stack alignment size. If the size is greater than the stack alignment, we
694 // note this in the DYNAMIC_STACKALLOC node.
695 unsigned StackAlign =
696 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
697 if (Align <= StackAlign) {
698 Align = 0;
699 // Add SA-1 to the size.
700 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
701 getIntPtrConstant(StackAlign-1));
702 // Mask out the low bits for alignment purposes.
703 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
704 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
705 }
706
Chris Lattner96c262e2005-05-14 07:29:57 +0000707 std::vector<MVT::ValueType> VTs;
708 VTs.push_back(AllocSize.getValueType());
709 VTs.push_back(MVT::Other);
710 std::vector<SDOperand> Ops;
711 Ops.push_back(getRoot());
712 Ops.push_back(AllocSize);
713 Ops.push_back(getIntPtrConstant(Align));
714 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000715 DAG.setRoot(setValue(&I, DSA).getValue(1));
716
717 // Inform the Frame Information that we have just allocated a variable-sized
718 // object.
719 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
720}
721
722
723void SelectionDAGLowering::visitLoad(LoadInst &I) {
724 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000725
Chris Lattner4d9651c2005-01-17 22:19:26 +0000726 SDOperand Root;
727 if (I.isVolatile())
728 Root = getRoot();
729 else {
730 // Do not serialize non-volatile loads against each other.
731 Root = DAG.getRoot();
732 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000733
734 const Type *Ty = I.getType();
735 SDOperand L;
736
737 if (Type::PackedTyID == Ty->getTypeID()) {
738 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000739 unsigned NumElements = PTy->getNumElements();
740 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
741
742 // Immediately scalarize packed types containing only one element, so that
743 // the Legalize pass does not have to deal with them.
744 if (NumElements == 1) {
745 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
746 } else {
747 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
748 DAG.getSrcValue(I.getOperand(0)));
749 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000750 } else {
751 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
752 DAG.getSrcValue(I.getOperand(0)));
753 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000754 setValue(&I, L);
755
756 if (I.isVolatile())
757 DAG.setRoot(L.getValue(1));
758 else
759 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000760}
761
762
763void SelectionDAGLowering::visitStore(StoreInst &I) {
764 Value *SrcV = I.getOperand(0);
765 SDOperand Src = getValue(SrcV);
766 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000767 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000768 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000769}
770
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000771/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
772/// we want to emit this as a call to a named external function, return the name
773/// otherwise lower it and return null.
774const char *
775SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
776 switch (Intrinsic) {
777 case Intrinsic::vastart: visitVAStart(I); return 0;
778 case Intrinsic::vaend: visitVAEnd(I); return 0;
779 case Intrinsic::vacopy: visitVACopy(I); return 0;
780 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
781 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
782 case Intrinsic::setjmp:
783 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
784 break;
785 case Intrinsic::longjmp:
786 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
787 break;
788 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
789 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
790 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
791
792 case Intrinsic::readport:
793 case Intrinsic::readio: {
794 std::vector<MVT::ValueType> VTs;
795 VTs.push_back(TLI.getValueType(I.getType()));
796 VTs.push_back(MVT::Other);
797 std::vector<SDOperand> Ops;
798 Ops.push_back(getRoot());
799 Ops.push_back(getValue(I.getOperand(1)));
800 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
801 ISD::READPORT : ISD::READIO, VTs, Ops);
802
803 setValue(&I, Tmp);
804 DAG.setRoot(Tmp.getValue(1));
805 return 0;
806 }
807 case Intrinsic::writeport:
808 case Intrinsic::writeio:
809 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
810 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
811 getRoot(), getValue(I.getOperand(1)),
812 getValue(I.getOperand(2))));
813 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000814
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000815 case Intrinsic::dbg_stoppoint:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000816 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
817 return "llvm_debugger_stop";
818 if (I.getType() != Type::VoidTy)
819 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
820 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000821 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000822 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
823 return "llvm_dbg_region_start";
824 if (I.getType() != Type::VoidTy)
825 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
826 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000827 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000828 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
829 return "llvm_dbg_region_end";
830 if (I.getType() != Type::VoidTy)
831 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
832 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000833 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000834 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
835 return "llvm_dbg_subprogram";
836 if (I.getType() != Type::VoidTy)
837 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
838 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000839 case Intrinsic::dbg_declare:
840 if (I.getType() != Type::VoidTy)
841 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
842 return 0;
843
844 case Intrinsic::isunordered:
845 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
846 getValue(I.getOperand(2)), ISD::SETUO));
847 return 0;
848
849 case Intrinsic::sqrt:
850 setValue(&I, DAG.getNode(ISD::FSQRT,
851 getValue(I.getOperand(1)).getValueType(),
852 getValue(I.getOperand(1))));
853 return 0;
854 case Intrinsic::pcmarker: {
855 SDOperand Tmp = getValue(I.getOperand(1));
856 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
857 return 0;
858 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000859 case Intrinsic::readcyclecounter: {
860 std::vector<MVT::ValueType> VTs;
861 VTs.push_back(MVT::i64);
862 VTs.push_back(MVT::Other);
863 std::vector<SDOperand> Ops;
864 Ops.push_back(getRoot());
865 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
866 setValue(&I, Tmp);
867 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000868 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000869 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000870 case Intrinsic::cttz:
871 setValue(&I, DAG.getNode(ISD::CTTZ,
872 getValue(I.getOperand(1)).getValueType(),
873 getValue(I.getOperand(1))));
874 return 0;
875 case Intrinsic::ctlz:
876 setValue(&I, DAG.getNode(ISD::CTLZ,
877 getValue(I.getOperand(1)).getValueType(),
878 getValue(I.getOperand(1))));
879 return 0;
880 case Intrinsic::ctpop:
881 setValue(&I, DAG.getNode(ISD::CTPOP,
882 getValue(I.getOperand(1)).getValueType(),
883 getValue(I.getOperand(1))));
884 return 0;
885 default:
886 std::cerr << I;
887 assert(0 && "This intrinsic is not implemented yet!");
888 return 0;
889 }
890}
891
892
Chris Lattner7a60d912005-01-07 07:47:53 +0000893void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000894 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000895 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +0000896 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000897 if (unsigned IID = F->getIntrinsicID()) {
898 RenameFn = visitIntrinsicCall(I, IID);
899 if (!RenameFn)
900 return;
901 } else { // Not an LLVM intrinsic.
902 const std::string &Name = F->getName();
903 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +0000904 if (I.getNumOperands() == 2 && // Basic sanity checks.
905 I.getOperand(1)->getType()->isFloatingPoint() &&
906 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000907 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000908 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
909 return;
910 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000911 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000912 if (I.getNumOperands() == 2 && // Basic sanity checks.
913 I.getOperand(1)->getType()->isFloatingPoint() &&
914 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000915 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000916 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
917 return;
918 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000919 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000920 if (I.getNumOperands() == 2 && // Basic sanity checks.
921 I.getOperand(1)->getType()->isFloatingPoint() &&
922 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000923 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000924 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
925 return;
926 }
927 }
Chris Lattnere4f71d02005-05-14 13:56:55 +0000928 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000929 }
Misha Brukman835702a2005-04-21 22:36:52 +0000930
Chris Lattner18d2b342005-01-08 22:48:57 +0000931 SDOperand Callee;
932 if (!RenameFn)
933 Callee = getValue(I.getOperand(0));
934 else
935 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000936 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000937 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +0000938 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
939 Value *Arg = I.getOperand(i);
940 SDOperand ArgNode = getValue(Arg);
941 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
942 }
Misha Brukman835702a2005-04-21 22:36:52 +0000943
Nate Begemanf6565252005-03-26 01:29:23 +0000944 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
945 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000946
Chris Lattner1f45cd72005-01-08 19:26:18 +0000947 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000948 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000949 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000950 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000951 setValue(&I, Result.first);
952 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000953}
954
955void SelectionDAGLowering::visitMalloc(MallocInst &I) {
956 SDOperand Src = getValue(I.getOperand(0));
957
958 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000959
960 if (IntPtr < Src.getValueType())
961 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
962 else if (IntPtr > Src.getValueType())
963 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000964
965 // Scale the source by the type size.
966 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
967 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
968 Src, getIntPtrConstant(ElementSize));
969
970 std::vector<std::pair<SDOperand, const Type*> > Args;
971 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000972
973 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000974 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000975 DAG.getExternalSymbol("malloc", IntPtr),
976 Args, DAG);
977 setValue(&I, Result.first); // Pointers always fit in registers
978 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000979}
980
981void SelectionDAGLowering::visitFree(FreeInst &I) {
982 std::vector<std::pair<SDOperand, const Type*> > Args;
983 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
984 TLI.getTargetData().getIntPtrType()));
985 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000986 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000987 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000988 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
989 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000990}
991
Chris Lattner13d7c252005-08-26 20:54:47 +0000992// InsertAtEndOfBasicBlock - This method should be implemented by targets that
993// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
994// instructions are special in various ways, which require special support to
995// insert. The specified MachineInstr is created but not inserted into any
996// basic blocks, and the scheduler passes ownership of it to this method.
997MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
998 MachineBasicBlock *MBB) {
999 std::cerr << "If a target marks an instruction with "
1000 "'usesCustomDAGSchedInserter', it must implement "
1001 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1002 abort();
1003 return 0;
1004}
1005
Nate Begeman78afac22005-10-18 23:23:37 +00001006SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1007 SelectionDAG &DAG) {
1008 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1009}
1010
Chris Lattnerf5473e42005-07-05 19:57:53 +00001011SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1012 SDOperand VAListP, Value *VAListV,
1013 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001014 // We have no sane default behavior, just emit a useful error message and bail
1015 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001016 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001017 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001018 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001019}
1020
Chris Lattnerf5473e42005-07-05 19:57:53 +00001021SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001022 SelectionDAG &DAG) {
1023 // Default to a noop.
1024 return Chain;
1025}
1026
Chris Lattnerf5473e42005-07-05 19:57:53 +00001027SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1028 SDOperand SrcP, Value *SrcV,
1029 SDOperand DestP, Value *DestV,
1030 SelectionDAG &DAG) {
1031 // Default to copying the input list.
1032 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1033 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001034 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001035 Val, DestP, DAG.getSrcValue(DestV));
1036 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001037}
1038
1039std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001040TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1041 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001042 // We have no sane default behavior, just emit a useful error message and bail
1043 // out.
1044 std::cerr << "Variable arguments handling not implemented on this target!\n";
1045 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001046 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001047}
1048
1049
1050void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001051 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1052 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001053}
1054
1055void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1056 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001057 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001058 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001059 setValue(&I, Result.first);
1060 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001061}
1062
1063void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001064 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001065 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001066}
1067
1068void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001069 SDOperand Result =
1070 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1071 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1072 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001073}
1074
Chris Lattner58cfd792005-01-09 00:00:49 +00001075
1076// It is always conservatively correct for llvm.returnaddress and
1077// llvm.frameaddress to return 0.
1078std::pair<SDOperand, SDOperand>
1079TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1080 unsigned Depth, SelectionDAG &DAG) {
1081 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001082}
1083
Chris Lattner29dcc712005-05-14 05:50:48 +00001084SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001085 assert(0 && "LowerOperation not implemented for this target!");
1086 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001087 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001088}
1089
Chris Lattner58cfd792005-01-09 00:00:49 +00001090void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1091 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1092 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001093 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001094 setValue(&I, Result.first);
1095 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001096}
1097
Chris Lattner875def92005-01-11 05:56:49 +00001098void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1099 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001100 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001101 Ops.push_back(getValue(I.getOperand(1)));
1102 Ops.push_back(getValue(I.getOperand(2)));
1103 Ops.push_back(getValue(I.getOperand(3)));
1104 Ops.push_back(getValue(I.getOperand(4)));
1105 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001106}
1107
Chris Lattner875def92005-01-11 05:56:49 +00001108//===----------------------------------------------------------------------===//
1109// SelectionDAGISel code
1110//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001111
1112unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1113 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1114}
1115
Chris Lattnerc9950c12005-08-17 06:37:43 +00001116void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001117 // FIXME: we only modify the CFG to split critical edges. This
1118 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001119}
Chris Lattner7a60d912005-01-07 07:47:53 +00001120
Chris Lattner7a60d912005-01-07 07:47:53 +00001121bool SelectionDAGISel::runOnFunction(Function &Fn) {
1122 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1123 RegMap = MF.getSSARegMap();
1124 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1125
Chris Lattnerc9950c12005-08-17 06:37:43 +00001126 // First pass, split all critical edges for PHI nodes with incoming values
1127 // that are constants, this way the load of the constant into a vreg will not
1128 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001129 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1130 PHINode *PN;
1131 for (BasicBlock::iterator BBI = BB->begin();
1132 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1133 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1134 if (isa<Constant>(PN->getIncomingValue(i)))
1135 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1136 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001137
Chris Lattner7a60d912005-01-07 07:47:53 +00001138 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1139
1140 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1141 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001142
Chris Lattner7a60d912005-01-07 07:47:53 +00001143 return true;
1144}
1145
1146
Chris Lattner718b5c22005-01-13 17:59:43 +00001147SDOperand SelectionDAGISel::
1148CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001149 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001150 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001151 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001152 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001153
1154 // If this type is not legal, we must make sure to not create an invalid
1155 // register use.
1156 MVT::ValueType SrcVT = Op.getValueType();
1157 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1158 SelectionDAG &DAG = SDL.DAG;
1159 if (SrcVT == DestVT) {
1160 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1161 } else if (SrcVT < DestVT) {
1162 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001163 if (MVT::isFloatingPoint(SrcVT))
1164 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1165 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001166 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001167 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1168 } else {
1169 // The src value is expanded into multiple registers.
1170 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1171 Op, DAG.getConstant(0, MVT::i32));
1172 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1173 Op, DAG.getConstant(1, MVT::i32));
1174 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1175 return DAG.getCopyToReg(Op, Reg+1, Hi);
1176 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001177}
1178
Chris Lattner16f64df2005-01-17 17:15:02 +00001179void SelectionDAGISel::
1180LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1181 std::vector<SDOperand> &UnorderedChains) {
1182 // If this is the entry block, emit arguments.
1183 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001184 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001185 SDOperand OldRoot = SDL.DAG.getRoot();
1186 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001187
Chris Lattner6871b232005-10-30 19:42:35 +00001188 unsigned a = 0;
1189 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1190 AI != E; ++AI, ++a)
1191 if (!AI->use_empty()) {
1192 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001193
Chris Lattner6871b232005-10-30 19:42:35 +00001194 // If this argument is live outside of the entry block, insert a copy from
1195 // whereever we got it to the vreg that other BB's will reference it as.
1196 if (FuncInfo.ValueMap.count(AI)) {
1197 SDOperand Copy =
1198 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1199 UnorderedChains.push_back(Copy);
1200 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001201 }
Chris Lattner6871b232005-10-30 19:42:35 +00001202
1203 // Next, if the function has live ins that need to be copied into vregs,
1204 // emit the copies now, into the top of the block.
1205 MachineFunction &MF = SDL.DAG.getMachineFunction();
1206 if (MF.livein_begin() != MF.livein_end()) {
1207 SSARegMap *RegMap = MF.getSSARegMap();
1208 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1209 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1210 E = MF.livein_end(); LI != E; ++LI)
1211 if (LI->second)
1212 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1213 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001214 }
Chris Lattner6871b232005-10-30 19:42:35 +00001215
1216 // Finally, if the target has anything special to do, allow it to do so.
1217 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001218}
1219
1220
Chris Lattner7a60d912005-01-07 07:47:53 +00001221void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1222 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1223 FunctionLoweringInfo &FuncInfo) {
1224 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001225
1226 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001227
Chris Lattner6871b232005-10-30 19:42:35 +00001228 // Lower any arguments needed in this block if this is the entry block.
1229 if (LLVMBB == &LLVMBB->getParent()->front())
1230 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001231
1232 BB = FuncInfo.MBBMap[LLVMBB];
1233 SDL.setCurrentBasicBlock(BB);
1234
1235 // Lower all of the non-terminator instructions.
1236 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1237 I != E; ++I)
1238 SDL.visit(*I);
1239
1240 // Ensure that all instructions which are used outside of their defining
1241 // blocks are available as virtual registers.
1242 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001243 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001244 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001245 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001246 UnorderedChains.push_back(
1247 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001248 }
1249
1250 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1251 // ensure constants are generated when needed. Remember the virtual registers
1252 // that need to be added to the Machine PHI nodes as input. We cannot just
1253 // directly add them, because expansion might result in multiple MBB's for one
1254 // BB. As such, the start of the BB might correspond to a different MBB than
1255 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001256 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001257
1258 // Emit constants only once even if used by multiple PHI nodes.
1259 std::map<Constant*, unsigned> ConstantsOut;
1260
1261 // Check successor nodes PHI nodes that expect a constant to be available from
1262 // this block.
1263 TerminatorInst *TI = LLVMBB->getTerminator();
1264 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1265 BasicBlock *SuccBB = TI->getSuccessor(succ);
1266 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1267 PHINode *PN;
1268
1269 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1270 // nodes and Machine PHI nodes, but the incoming operands have not been
1271 // emitted yet.
1272 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001273 (PN = dyn_cast<PHINode>(I)); ++I)
1274 if (!PN->use_empty()) {
1275 unsigned Reg;
1276 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1277 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1278 unsigned &RegOut = ConstantsOut[C];
1279 if (RegOut == 0) {
1280 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001281 UnorderedChains.push_back(
1282 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001283 }
1284 Reg = RegOut;
1285 } else {
1286 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001287 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001288 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001289 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1290 "Didn't codegen value into a register!??");
1291 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001292 UnorderedChains.push_back(
1293 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001294 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001295 }
Misha Brukman835702a2005-04-21 22:36:52 +00001296
Chris Lattner8ea875f2005-01-07 21:34:19 +00001297 // Remember that this register needs to added to the machine PHI node as
1298 // the input for this MBB.
1299 unsigned NumElements =
1300 TLI.getNumElements(TLI.getValueType(PN->getType()));
1301 for (unsigned i = 0, e = NumElements; i != e; ++i)
1302 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001303 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001304 }
1305 ConstantsOut.clear();
1306
Chris Lattner718b5c22005-01-13 17:59:43 +00001307 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001308 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001309 SDOperand Root = SDL.getRoot();
1310 if (Root.getOpcode() != ISD::EntryToken) {
1311 unsigned i = 0, e = UnorderedChains.size();
1312 for (; i != e; ++i) {
1313 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1314 if (UnorderedChains[i].Val->getOperand(0) == Root)
1315 break; // Don't add the root if we already indirectly depend on it.
1316 }
1317
1318 if (i == e)
1319 UnorderedChains.push_back(Root);
1320 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001321 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1322 }
1323
Chris Lattner7a60d912005-01-07 07:47:53 +00001324 // Lower the terminator after the copies are emitted.
1325 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001326
1327 // Make sure the root of the DAG is up-to-date.
1328 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001329}
1330
1331void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1332 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001333 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001334 CurDAG = &DAG;
1335 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1336
1337 // First step, lower LLVM code to some DAG. This DAG may use operations and
1338 // types that are not supported by the target.
1339 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1340
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001341 // Run the DAG combiner in pre-legalize mode.
1342 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001343
Chris Lattner7a60d912005-01-07 07:47:53 +00001344 DEBUG(std::cerr << "Lowered selection DAG:\n");
1345 DEBUG(DAG.dump());
1346
1347 // Second step, hack on the DAG until it only uses operations and types that
1348 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001349 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001350
1351 DEBUG(std::cerr << "Legalized selection DAG:\n");
1352 DEBUG(DAG.dump());
1353
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001354 // Run the DAG combiner in post-legalize mode.
1355 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001356
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001357 if (ViewDAGs) DAG.viewGraph();
1358
Chris Lattner5ca31d92005-03-30 01:10:47 +00001359 // Third, instruction select all of the operations to machine code, adding the
1360 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001361 InstructionSelectBasicBlock(DAG);
1362
Chris Lattner7a60d912005-01-07 07:47:53 +00001363 DEBUG(std::cerr << "Selected machine code:\n");
1364 DEBUG(BB->dump());
1365
Chris Lattner5ca31d92005-03-30 01:10:47 +00001366 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001367 // PHI nodes in successors.
1368 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1369 MachineInstr *PHI = PHINodesToUpdate[i].first;
1370 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1371 "This is not a machine PHI node that we are updating!");
1372 PHI->addRegOperand(PHINodesToUpdate[i].second);
1373 PHI->addMachineBasicBlockOperand(BB);
1374 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001375
1376 // Finally, add the CFG edges from the last selected MBB to the successor
1377 // MBBs.
1378 TerminatorInst *TI = LLVMBB->getTerminator();
1379 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1380 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1381 BB->addSuccessor(Succ0MBB);
1382 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001383}