blob: 30d94337e9151580bae674b044e6482ffcd8097c [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"
Chris Lattner435b4022005-11-29 06:21:05 +000020#include "llvm/GlobalVariable.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/Instructions.h"
22#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000023#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/SelectionDAG.h"
28#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000029#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/Target/TargetData.h"
31#include "llvm/Target/TargetFrameInfo.h"
32#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
34#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000036#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000037#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Support/Debug.h"
39#include <map>
40#include <iostream>
41using namespace llvm;
42
Chris Lattner975f5c92005-09-01 18:44:10 +000043#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000044static cl::opt<bool>
45ViewDAGs("view-isel-dags", cl::Hidden,
46 cl::desc("Pop up a window to show isel dags as they are selected"));
47#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000048static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000049#endif
50
Chris Lattner7a60d912005-01-07 07:47:53 +000051namespace llvm {
52 //===--------------------------------------------------------------------===//
53 /// FunctionLoweringInfo - This contains information that is global to a
54 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000055 class FunctionLoweringInfo {
56 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000057 TargetLowering &TLI;
58 Function &Fn;
59 MachineFunction &MF;
60 SSARegMap *RegMap;
61
62 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
63
64 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
65 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
66
67 /// ValueMap - Since we emit code for the function a basic block at a time,
68 /// we must remember which virtual registers hold the values for
69 /// cross-basic-block values.
70 std::map<const Value*, unsigned> ValueMap;
71
72 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
73 /// the entry block. This allows the allocas to be efficiently referenced
74 /// anywhere in the function.
75 std::map<const AllocaInst*, int> StaticAllocaMap;
76
77 unsigned MakeReg(MVT::ValueType VT) {
78 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
79 }
Misha Brukman835702a2005-04-21 22:36:52 +000080
Chris Lattner7a60d912005-01-07 07:47:53 +000081 unsigned CreateRegForValue(const Value *V) {
82 MVT::ValueType VT = TLI.getValueType(V->getType());
83 // The common case is that we will only create one register for this
84 // value. If we have that case, create and return the virtual register.
85 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000086 if (NV == 1) {
87 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000088 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000089 }
Misha Brukman835702a2005-04-21 22:36:52 +000090
Chris Lattner7a60d912005-01-07 07:47:53 +000091 // If this value is represented with multiple target registers, make sure
92 // to create enough consequtive registers of the right (smaller) type.
93 unsigned NT = VT-1; // Find the type to use.
94 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
95 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000096
Chris Lattner7a60d912005-01-07 07:47:53 +000097 unsigned R = MakeReg((MVT::ValueType)NT);
98 for (unsigned i = 1; i != NV; ++i)
99 MakeReg((MVT::ValueType)NT);
100 return R;
101 }
Misha Brukman835702a2005-04-21 22:36:52 +0000102
Chris Lattner7a60d912005-01-07 07:47:53 +0000103 unsigned InitializeRegForValue(const Value *V) {
104 unsigned &R = ValueMap[V];
105 assert(R == 0 && "Already initialized this value register!");
106 return R = CreateRegForValue(V);
107 }
108 };
109}
110
111/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
112/// PHI nodes or outside of the basic block that defines it.
113static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
114 if (isa<PHINode>(I)) return true;
115 BasicBlock *BB = I->getParent();
116 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
117 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
118 return true;
119 return false;
120}
121
Chris Lattner6871b232005-10-30 19:42:35 +0000122/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
123/// entry block, return true.
124static bool isOnlyUsedInEntryBlock(Argument *A) {
125 BasicBlock *Entry = A->getParent()->begin();
126 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
127 if (cast<Instruction>(*UI)->getParent() != Entry)
128 return false; // Use not in entry block.
129 return true;
130}
131
Chris Lattner7a60d912005-01-07 07:47:53 +0000132FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000133 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000134 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
135
Chris Lattner6871b232005-10-30 19:42:35 +0000136 // Create a vreg for each argument register that is not dead and is used
137 // outside of the entry block for the function.
138 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
139 AI != E; ++AI)
140 if (!isOnlyUsedInEntryBlock(AI))
141 InitializeRegForValue(AI);
142
Chris Lattner7a60d912005-01-07 07:47:53 +0000143 // Initialize the mapping of values to registers. This is only set up for
144 // instruction values that are used outside of the block that defines
145 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000146 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000147 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
148 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
149 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
150 const Type *Ty = AI->getAllocatedType();
151 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000152 unsigned Align =
153 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
154 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000155
156 // If the alignment of the value is smaller than the size of the value,
157 // and if the size of the value is particularly small (<= 8 bytes),
158 // round up to the size of the value for potentially better performance.
159 //
160 // FIXME: This could be made better with a preferred alignment hook in
161 // TargetData. It serves primarily to 8-byte align doubles for X86.
162 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000163 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000164 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000165 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000166 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000167 }
168
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000169 for (; BB != EB; ++BB)
170 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000171 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
172 if (!isa<AllocaInst>(I) ||
173 !StaticAllocaMap.count(cast<AllocaInst>(I)))
174 InitializeRegForValue(I);
175
176 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
177 // also creates the initial PHI MachineInstrs, though none of the input
178 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000179 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000180 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
181 MBBMap[BB] = MBB;
182 MF.getBasicBlockList().push_back(MBB);
183
184 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
185 // appropriate.
186 PHINode *PN;
187 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000188 (PN = dyn_cast<PHINode>(I)); ++I)
189 if (!PN->use_empty()) {
190 unsigned NumElements =
191 TLI.getNumElements(TLI.getValueType(PN->getType()));
192 unsigned PHIReg = ValueMap[PN];
193 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
194 for (unsigned i = 0; i != NumElements; ++i)
195 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
196 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000197 }
198}
199
200
201
202//===----------------------------------------------------------------------===//
203/// SelectionDAGLowering - This is the common target-independent lowering
204/// implementation that is parameterized by a TargetLowering object.
205/// Also, targets can overload any lowering method.
206///
207namespace llvm {
208class SelectionDAGLowering {
209 MachineBasicBlock *CurMBB;
210
211 std::map<const Value*, SDOperand> NodeMap;
212
Chris Lattner4d9651c2005-01-17 22:19:26 +0000213 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
214 /// them up and then emit token factor nodes when possible. This allows us to
215 /// get simple disambiguation between loads without worrying about alias
216 /// analysis.
217 std::vector<SDOperand> PendingLoads;
218
Chris Lattner7a60d912005-01-07 07:47:53 +0000219public:
220 // TLI - This is information that describes the available target features we
221 // need for lowering. This indicates when operations are unavailable,
222 // implemented with a libcall, etc.
223 TargetLowering &TLI;
224 SelectionDAG &DAG;
225 const TargetData &TD;
226
227 /// FuncInfo - Information about the function as a whole.
228 ///
229 FunctionLoweringInfo &FuncInfo;
230
231 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000232 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000233 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
234 FuncInfo(funcinfo) {
235 }
236
Chris Lattner4108bb02005-01-17 19:43:36 +0000237 /// getRoot - Return the current virtual root of the Selection DAG.
238 ///
239 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000240 if (PendingLoads.empty())
241 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000242
Chris Lattner4d9651c2005-01-17 22:19:26 +0000243 if (PendingLoads.size() == 1) {
244 SDOperand Root = PendingLoads[0];
245 DAG.setRoot(Root);
246 PendingLoads.clear();
247 return Root;
248 }
249
250 // Otherwise, we have to make a token factor node.
251 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
252 PendingLoads.clear();
253 DAG.setRoot(Root);
254 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000255 }
256
Chris Lattner7a60d912005-01-07 07:47:53 +0000257 void visit(Instruction &I) { visit(I.getOpcode(), I); }
258
259 void visit(unsigned Opcode, User &I) {
260 switch (Opcode) {
261 default: assert(0 && "Unknown instruction type encountered!");
262 abort();
263 // Build the switch statement using the Instruction.def file.
264#define HANDLE_INST(NUM, OPCODE, CLASS) \
265 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
266#include "llvm/Instruction.def"
267 }
268 }
269
270 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
271
272
273 SDOperand getIntPtrConstant(uint64_t Val) {
274 return DAG.getConstant(Val, TLI.getPointerTy());
275 }
276
277 SDOperand getValue(const Value *V) {
278 SDOperand &N = NodeMap[V];
279 if (N.Val) return N;
280
281 MVT::ValueType VT = TLI.getValueType(V->getType());
282 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
283 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
284 visit(CE->getOpcode(), *CE);
285 assert(N.Val && "visit didn't populate the ValueMap!");
286 return N;
287 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
288 return N = DAG.getGlobalAddress(GV, VT);
289 } else if (isa<ConstantPointerNull>(C)) {
290 return N = DAG.getConstant(0, TLI.getPointerTy());
291 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000292 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
294 return N = DAG.getConstantFP(CFP->getValue(), VT);
295 } else {
296 // Canonicalize all constant ints to be unsigned.
297 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
298 }
299
300 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
301 std::map<const AllocaInst*, int>::iterator SI =
302 FuncInfo.StaticAllocaMap.find(AI);
303 if (SI != FuncInfo.StaticAllocaMap.end())
304 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
305 }
306
307 std::map<const Value*, unsigned>::const_iterator VMI =
308 FuncInfo.ValueMap.find(V);
309 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000310
Chris Lattner33182322005-08-16 21:55:35 +0000311 unsigned InReg = VMI->second;
312
313 // If this type is not legal, make it so now.
314 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
315
316 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
317 if (DestVT < VT) {
318 // Source must be expanded. This input value is actually coming from the
319 // register pair VMI->second and VMI->second+1.
320 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
321 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
322 } else {
323 if (DestVT > VT) { // Promotion case
324 if (MVT::isFloatingPoint(VT))
325 N = DAG.getNode(ISD::FP_ROUND, VT, N);
326 else
327 N = DAG.getNode(ISD::TRUNCATE, VT, N);
328 }
329 }
330
331 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000332 }
333
334 const SDOperand &setValue(const Value *V, SDOperand NewN) {
335 SDOperand &N = NodeMap[V];
336 assert(N.Val == 0 && "Already set a value for this node!");
337 return N = NewN;
338 }
339
340 // Terminator instructions.
341 void visitRet(ReturnInst &I);
342 void visitBr(BranchInst &I);
343 void visitUnreachable(UnreachableInst &I) { /* noop */ }
344
345 // These all get lowered before this pass.
346 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
347 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
348 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
349
350 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000351 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000352 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000353 void visitAdd(User &I) {
354 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000355 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000356 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000357 void visitMul(User &I) {
358 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000359 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000360 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000361 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000362 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000363 }
364 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000365 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000366 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000367 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000368 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
369 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
370 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000371 void visitShl(User &I) { visitShift(I, ISD::SHL); }
372 void visitShr(User &I) {
373 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000374 }
375
376 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
377 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
378 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
379 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
380 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
381 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
382 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
383
384 void visitGetElementPtr(User &I);
385 void visitCast(User &I);
386 void visitSelect(User &I);
387 //
388
389 void visitMalloc(MallocInst &I);
390 void visitFree(FreeInst &I);
391 void visitAlloca(AllocaInst &I);
392 void visitLoad(LoadInst &I);
393 void visitStore(StoreInst &I);
394 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
395 void visitCall(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000396 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000397
Chris Lattner7a60d912005-01-07 07:47:53 +0000398 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000399 void visitVAArg(VAArgInst &I);
400 void visitVAEnd(CallInst &I);
401 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000402 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000403
Chris Lattner875def92005-01-11 05:56:49 +0000404 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000405
406 void visitUserOp1(Instruction &I) {
407 assert(0 && "UserOp1 should not exist at instruction selection time!");
408 abort();
409 }
410 void visitUserOp2(Instruction &I) {
411 assert(0 && "UserOp2 should not exist at instruction selection time!");
412 abort();
413 }
414};
415} // end namespace llvm
416
417void SelectionDAGLowering::visitRet(ReturnInst &I) {
418 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000419 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 return;
421 }
422
423 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000424 MVT::ValueType TmpVT;
425
Chris Lattner7a60d912005-01-07 07:47:53 +0000426 switch (Op1.getValueType()) {
427 default: assert(0 && "Unknown value type!");
428 case MVT::i1:
429 case MVT::i8:
430 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000431 case MVT::i32:
432 // If this is a machine where 32-bits is legal or expanded, promote to
433 // 32-bits, otherwise, promote to 64-bits.
434 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
435 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000436 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000437 TmpVT = MVT::i32;
438
439 // Extend integer types to result type.
440 if (I.getOperand(0)->getType()->isSigned())
441 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
442 else
443 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000444 break;
445 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000446 case MVT::i64:
447 case MVT::f64:
448 break; // No extension needed!
449 }
Nate Begeman78afac22005-10-18 23:23:37 +0000450 // Allow targets to lower this further to meet ABI requirements
451 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000452}
453
454void SelectionDAGLowering::visitBr(BranchInst &I) {
455 // Update machine-CFG edges.
456 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000457
458 // Figure out which block is immediately after the current one.
459 MachineBasicBlock *NextBlock = 0;
460 MachineFunction::iterator BBI = CurMBB;
461 if (++BBI != CurMBB->getParent()->end())
462 NextBlock = BBI;
463
464 if (I.isUnconditional()) {
465 // If this is not a fall-through branch, emit the branch.
466 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000467 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000468 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 } else {
470 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000471
472 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 if (Succ1MBB == NextBlock) {
474 // If the condition is false, fall through. This means we should branch
475 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000476 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000477 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000478 } else if (Succ0MBB == NextBlock) {
479 // If the condition is true, fall through. This means we should branch if
480 // the condition is false to Succ #1. Invert the condition first.
481 SDOperand True = DAG.getConstant(1, Cond.getValueType());
482 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000483 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000484 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000486 std::vector<SDOperand> Ops;
487 Ops.push_back(getRoot());
488 Ops.push_back(Cond);
489 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
490 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
491 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 }
493 }
494}
495
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000496void SelectionDAGLowering::visitSub(User &I) {
497 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000498 if (I.getType()->isFloatingPoint()) {
499 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
500 if (CFP->isExactlyValue(-0.0)) {
501 SDOperand Op2 = getValue(I.getOperand(1));
502 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
503 return;
504 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000505 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000506 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000507}
508
Nate Begemanb2e089c2005-11-19 00:36:38 +0000509void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
510 unsigned VecOp) {
511 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 SDOperand Op1 = getValue(I.getOperand(0));
513 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000514
Chris Lattner19baba62005-11-19 18:40:42 +0000515 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000516 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
517 } else if (Ty->isFloatingPoint()) {
518 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
519 } else {
520 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000521 unsigned NumElements = PTy->getNumElements();
522 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000523 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000524
525 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000526 // the Legalize pass does not have to deal with them. Similarly, if the
527 // abstract vector is going to turn into one that the target natively
528 // supports, generate that type now so that Legalize doesn't have to deal
529 // with that either. These steps ensure that Legalize only has to handle
530 // vector types in its Expand case.
531 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000532 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000533 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000534 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
535 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000536 } else {
537 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
538 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000539 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000540 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000541 }
Nate Begeman127321b2005-11-18 07:42:56 +0000542}
Chris Lattner96c26752005-01-19 22:31:21 +0000543
Nate Begeman127321b2005-11-18 07:42:56 +0000544void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
545 SDOperand Op1 = getValue(I.getOperand(0));
546 SDOperand Op2 = getValue(I.getOperand(1));
547
548 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
549
Chris Lattner7a60d912005-01-07 07:47:53 +0000550 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
551}
552
553void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
554 ISD::CondCode UnsignedOpcode) {
555 SDOperand Op1 = getValue(I.getOperand(0));
556 SDOperand Op2 = getValue(I.getOperand(1));
557 ISD::CondCode Opcode = SignedOpcode;
558 if (I.getOperand(0)->getType()->isUnsigned())
559 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000560 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000561}
562
563void SelectionDAGLowering::visitSelect(User &I) {
564 SDOperand Cond = getValue(I.getOperand(0));
565 SDOperand TrueVal = getValue(I.getOperand(1));
566 SDOperand FalseVal = getValue(I.getOperand(2));
567 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
568 TrueVal, FalseVal));
569}
570
571void SelectionDAGLowering::visitCast(User &I) {
572 SDOperand N = getValue(I.getOperand(0));
573 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
574 MVT::ValueType DestTy = TLI.getValueType(I.getType());
575
576 if (N.getValueType() == DestTy) {
577 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000578 } else if (DestTy == MVT::i1) {
579 // Cast to bool is a comparison against zero, not truncation to zero.
580 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
581 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000582 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000583 } else if (isInteger(SrcTy)) {
584 if (isInteger(DestTy)) { // Int -> Int cast
585 if (DestTy < SrcTy) // Truncating cast?
586 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
587 else if (I.getOperand(0)->getType()->isSigned())
588 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
589 else
590 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
591 } else { // Int -> FP cast
592 if (I.getOperand(0)->getType()->isSigned())
593 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
594 else
595 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
596 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000597 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000598 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
599 if (isFloatingPoint(DestTy)) { // FP -> FP cast
600 if (DestTy < SrcTy) // Rounding cast?
601 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
602 else
603 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
604 } else { // FP -> Int cast.
605 if (I.getType()->isSigned())
606 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
607 else
608 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
609 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000610 }
611}
612
613void SelectionDAGLowering::visitGetElementPtr(User &I) {
614 SDOperand N = getValue(I.getOperand(0));
615 const Type *Ty = I.getOperand(0)->getType();
616 const Type *UIntPtrTy = TD.getIntPtrType();
617
618 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
619 OI != E; ++OI) {
620 Value *Idx = *OI;
621 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
622 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
623 if (Field) {
624 // N = N + Offset
625 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
626 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000627 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000628 }
629 Ty = StTy->getElementType(Field);
630 } else {
631 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000632
Chris Lattner43535a12005-11-09 04:45:33 +0000633 // If this is a constant subscript, handle it quickly.
634 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
635 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000636
Chris Lattner43535a12005-11-09 04:45:33 +0000637 uint64_t Offs;
638 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
639 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
640 else
641 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
642 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
643 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000644 }
Chris Lattner43535a12005-11-09 04:45:33 +0000645
646 // N = N + Idx * ElementSize;
647 uint64_t ElementSize = TD.getTypeSize(Ty);
648 SDOperand IdxN = getValue(Idx);
649
650 // If the index is smaller or larger than intptr_t, truncate or extend
651 // it.
652 if (IdxN.getValueType() < N.getValueType()) {
653 if (Idx->getType()->isSigned())
654 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
655 else
656 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
657 } else if (IdxN.getValueType() > N.getValueType())
658 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
659
660 // If this is a multiply by a power of two, turn it into a shl
661 // immediately. This is a very common case.
662 if (isPowerOf2_64(ElementSize)) {
663 unsigned Amt = Log2_64(ElementSize);
664 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000665 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000666 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
667 continue;
668 }
669
670 SDOperand Scale = getIntPtrConstant(ElementSize);
671 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
672 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000673 }
674 }
675 setValue(&I, N);
676}
677
678void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
679 // If this is a fixed sized alloca in the entry block of the function,
680 // allocate it statically on the stack.
681 if (FuncInfo.StaticAllocaMap.count(&I))
682 return; // getValue will auto-populate this.
683
684 const Type *Ty = I.getAllocatedType();
685 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000686 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
687 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000688
689 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000690 MVT::ValueType IntPtr = TLI.getPointerTy();
691 if (IntPtr < AllocSize.getValueType())
692 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
693 else if (IntPtr > AllocSize.getValueType())
694 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000695
Chris Lattnereccb73d2005-01-22 23:04:37 +0000696 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000697 getIntPtrConstant(TySize));
698
699 // Handle alignment. If the requested alignment is less than or equal to the
700 // stack alignment, ignore it and round the size of the allocation up to the
701 // stack alignment size. If the size is greater than the stack alignment, we
702 // note this in the DYNAMIC_STACKALLOC node.
703 unsigned StackAlign =
704 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
705 if (Align <= StackAlign) {
706 Align = 0;
707 // Add SA-1 to the size.
708 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
709 getIntPtrConstant(StackAlign-1));
710 // Mask out the low bits for alignment purposes.
711 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
712 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
713 }
714
Chris Lattner96c262e2005-05-14 07:29:57 +0000715 std::vector<MVT::ValueType> VTs;
716 VTs.push_back(AllocSize.getValueType());
717 VTs.push_back(MVT::Other);
718 std::vector<SDOperand> Ops;
719 Ops.push_back(getRoot());
720 Ops.push_back(AllocSize);
721 Ops.push_back(getIntPtrConstant(Align));
722 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000723 DAG.setRoot(setValue(&I, DSA).getValue(1));
724
725 // Inform the Frame Information that we have just allocated a variable-sized
726 // object.
727 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
728}
729
Chris Lattner435b4022005-11-29 06:21:05 +0000730/// getStringValue - Turn an LLVM constant pointer that eventually points to a
731/// global into a string value. Return an empty string if we can't do it.
732///
733static std::string getStringValue(Value *V, unsigned Offset = 0) {
734 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
735 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
736 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
737 if (Init->isString()) {
738 std::string Result = Init->getAsString();
739 if (Offset < Result.size()) {
740 // If we are pointing INTO The string, erase the beginning...
741 Result.erase(Result.begin(), Result.begin()+Offset);
742
743 // Take off the null terminator, and any string fragments after it.
744 std::string::size_type NullPos = Result.find_first_of((char)0);
745 if (NullPos != std::string::npos)
746 Result.erase(Result.begin()+NullPos, Result.end());
747 return Result;
748 }
749 }
750 }
751 } else if (Constant *C = dyn_cast<Constant>(V)) {
752 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
753 return getStringValue(GV, Offset);
754 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
755 if (CE->getOpcode() == Instruction::GetElementPtr) {
756 // Turn a gep into the specified offset.
757 if (CE->getNumOperands() == 3 &&
758 cast<Constant>(CE->getOperand(1))->isNullValue() &&
759 isa<ConstantInt>(CE->getOperand(2))) {
760 return getStringValue(CE->getOperand(0),
761 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
762 }
763 }
764 }
765 }
766 return "";
767}
Chris Lattner7a60d912005-01-07 07:47:53 +0000768
769void SelectionDAGLowering::visitLoad(LoadInst &I) {
770 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000771
Chris Lattner4d9651c2005-01-17 22:19:26 +0000772 SDOperand Root;
773 if (I.isVolatile())
774 Root = getRoot();
775 else {
776 // Do not serialize non-volatile loads against each other.
777 Root = DAG.getRoot();
778 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000779
780 const Type *Ty = I.getType();
781 SDOperand L;
782
783 if (Type::PackedTyID == Ty->getTypeID()) {
784 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000785 unsigned NumElements = PTy->getNumElements();
786 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000787 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000788
789 // Immediately scalarize packed types containing only one element, so that
790 // the Legalize pass does not have to deal with them.
791 if (NumElements == 1) {
792 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000793 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
794 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000795 } else {
796 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
797 DAG.getSrcValue(I.getOperand(0)));
798 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000799 } else {
800 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
801 DAG.getSrcValue(I.getOperand(0)));
802 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000803 setValue(&I, L);
804
805 if (I.isVolatile())
806 DAG.setRoot(L.getValue(1));
807 else
808 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000809}
810
811
812void SelectionDAGLowering::visitStore(StoreInst &I) {
813 Value *SrcV = I.getOperand(0);
814 SDOperand Src = getValue(SrcV);
815 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000816 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000817 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000818}
819
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000820/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
821/// we want to emit this as a call to a named external function, return the name
822/// otherwise lower it and return null.
823const char *
824SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
825 switch (Intrinsic) {
826 case Intrinsic::vastart: visitVAStart(I); return 0;
827 case Intrinsic::vaend: visitVAEnd(I); return 0;
828 case Intrinsic::vacopy: visitVACopy(I); return 0;
829 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
830 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
831 case Intrinsic::setjmp:
832 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
833 break;
834 case Intrinsic::longjmp:
835 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
836 break;
837 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
838 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
839 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
840
841 case Intrinsic::readport:
842 case Intrinsic::readio: {
843 std::vector<MVT::ValueType> VTs;
844 VTs.push_back(TLI.getValueType(I.getType()));
845 VTs.push_back(MVT::Other);
846 std::vector<SDOperand> Ops;
847 Ops.push_back(getRoot());
848 Ops.push_back(getValue(I.getOperand(1)));
849 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
850 ISD::READPORT : ISD::READIO, VTs, Ops);
851
852 setValue(&I, Tmp);
853 DAG.setRoot(Tmp.getValue(1));
854 return 0;
855 }
856 case Intrinsic::writeport:
857 case Intrinsic::writeio:
858 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
859 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
860 getRoot(), getValue(I.getOperand(1)),
861 getValue(I.getOperand(2))));
862 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000863
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000864 case Intrinsic::dbg_stoppoint:
Chris Lattner435b4022005-11-29 06:21:05 +0000865 {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000866 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
867 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000868
869 std::string fname = "<unknown>";
870 std::vector<SDOperand> Ops;
871
872 // Pull the filename out of the the compilation unit.
873 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
874 if (cunit && cunit->hasInitializer()) {
875 ConstantStruct *CS = dyn_cast<ConstantStruct>(cunit->getInitializer());
876 if (CS->getNumOperands() > 0) {
877 std::string dirname = getStringValue(CS->getOperand(4));
878 fname = dirname + "/" + getStringValue(CS->getOperand(3));
879 }
880 }
881 // Input Chain
882 Ops.push_back(getRoot());
883
884 // line number
885 Ops.push_back(getValue(I.getOperand(2)));
886
887 // column
888 Ops.push_back(getValue(I.getOperand(3)));
889
890 // filename
891 Ops.push_back(DAG.getString(fname));
892 Ops.push_back(DAG.getString(""));
893 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000894 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000895 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000896 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000897 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
898 return "llvm_dbg_region_start";
899 if (I.getType() != Type::VoidTy)
900 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
901 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000902 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000903 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
904 return "llvm_dbg_region_end";
905 if (I.getType() != Type::VoidTy)
906 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
907 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000908 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000909 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
910 return "llvm_dbg_subprogram";
911 if (I.getType() != Type::VoidTy)
912 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
913 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000914 case Intrinsic::dbg_declare:
915 if (I.getType() != Type::VoidTy)
916 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
917 return 0;
918
919 case Intrinsic::isunordered:
920 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
921 getValue(I.getOperand(2)), ISD::SETUO));
922 return 0;
923
924 case Intrinsic::sqrt:
925 setValue(&I, DAG.getNode(ISD::FSQRT,
926 getValue(I.getOperand(1)).getValueType(),
927 getValue(I.getOperand(1))));
928 return 0;
929 case Intrinsic::pcmarker: {
930 SDOperand Tmp = getValue(I.getOperand(1));
931 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
932 return 0;
933 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000934 case Intrinsic::readcyclecounter: {
935 std::vector<MVT::ValueType> VTs;
936 VTs.push_back(MVT::i64);
937 VTs.push_back(MVT::Other);
938 std::vector<SDOperand> Ops;
939 Ops.push_back(getRoot());
940 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
941 setValue(&I, Tmp);
942 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000943 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000944 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000945 case Intrinsic::cttz:
946 setValue(&I, DAG.getNode(ISD::CTTZ,
947 getValue(I.getOperand(1)).getValueType(),
948 getValue(I.getOperand(1))));
949 return 0;
950 case Intrinsic::ctlz:
951 setValue(&I, DAG.getNode(ISD::CTLZ,
952 getValue(I.getOperand(1)).getValueType(),
953 getValue(I.getOperand(1))));
954 return 0;
955 case Intrinsic::ctpop:
956 setValue(&I, DAG.getNode(ISD::CTPOP,
957 getValue(I.getOperand(1)).getValueType(),
958 getValue(I.getOperand(1))));
959 return 0;
960 default:
961 std::cerr << I;
962 assert(0 && "This intrinsic is not implemented yet!");
963 return 0;
964 }
965}
966
967
Chris Lattner7a60d912005-01-07 07:47:53 +0000968void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000969 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000970 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +0000971 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000972 if (unsigned IID = F->getIntrinsicID()) {
973 RenameFn = visitIntrinsicCall(I, IID);
974 if (!RenameFn)
975 return;
976 } else { // Not an LLVM intrinsic.
977 const std::string &Name = F->getName();
978 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +0000979 if (I.getNumOperands() == 2 && // Basic sanity checks.
980 I.getOperand(1)->getType()->isFloatingPoint() &&
981 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000982 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000983 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
984 return;
985 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000986 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000987 if (I.getNumOperands() == 2 && // Basic sanity checks.
988 I.getOperand(1)->getType()->isFloatingPoint() &&
989 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000990 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000991 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
992 return;
993 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000994 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000995 if (I.getNumOperands() == 2 && // Basic sanity checks.
996 I.getOperand(1)->getType()->isFloatingPoint() &&
997 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000998 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000999 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1000 return;
1001 }
1002 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001003 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001004 }
Misha Brukman835702a2005-04-21 22:36:52 +00001005
Chris Lattner18d2b342005-01-08 22:48:57 +00001006 SDOperand Callee;
1007 if (!RenameFn)
1008 Callee = getValue(I.getOperand(0));
1009 else
1010 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001011 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001012 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001013 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1014 Value *Arg = I.getOperand(i);
1015 SDOperand ArgNode = getValue(Arg);
1016 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1017 }
Misha Brukman835702a2005-04-21 22:36:52 +00001018
Nate Begemanf6565252005-03-26 01:29:23 +00001019 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1020 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001021
Chris Lattner1f45cd72005-01-08 19:26:18 +00001022 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001023 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001024 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001025 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001026 setValue(&I, Result.first);
1027 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001028}
1029
1030void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1031 SDOperand Src = getValue(I.getOperand(0));
1032
1033 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001034
1035 if (IntPtr < Src.getValueType())
1036 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1037 else if (IntPtr > Src.getValueType())
1038 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001039
1040 // Scale the source by the type size.
1041 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1042 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1043 Src, getIntPtrConstant(ElementSize));
1044
1045 std::vector<std::pair<SDOperand, const Type*> > Args;
1046 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001047
1048 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001049 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001050 DAG.getExternalSymbol("malloc", IntPtr),
1051 Args, DAG);
1052 setValue(&I, Result.first); // Pointers always fit in registers
1053 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001054}
1055
1056void SelectionDAGLowering::visitFree(FreeInst &I) {
1057 std::vector<std::pair<SDOperand, const Type*> > Args;
1058 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1059 TLI.getTargetData().getIntPtrType()));
1060 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001061 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001062 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001063 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1064 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001065}
1066
Chris Lattner13d7c252005-08-26 20:54:47 +00001067// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1068// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1069// instructions are special in various ways, which require special support to
1070// insert. The specified MachineInstr is created but not inserted into any
1071// basic blocks, and the scheduler passes ownership of it to this method.
1072MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1073 MachineBasicBlock *MBB) {
1074 std::cerr << "If a target marks an instruction with "
1075 "'usesCustomDAGSchedInserter', it must implement "
1076 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1077 abort();
1078 return 0;
1079}
1080
Nate Begeman78afac22005-10-18 23:23:37 +00001081SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1082 SelectionDAG &DAG) {
1083 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1084}
1085
Chris Lattnerf5473e42005-07-05 19:57:53 +00001086SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1087 SDOperand VAListP, Value *VAListV,
1088 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001089 // We have no sane default behavior, just emit a useful error message and bail
1090 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001091 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001092 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001093 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001094}
1095
Chris Lattnerf5473e42005-07-05 19:57:53 +00001096SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001097 SelectionDAG &DAG) {
1098 // Default to a noop.
1099 return Chain;
1100}
1101
Chris Lattnerf5473e42005-07-05 19:57:53 +00001102SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1103 SDOperand SrcP, Value *SrcV,
1104 SDOperand DestP, Value *DestV,
1105 SelectionDAG &DAG) {
1106 // Default to copying the input list.
1107 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1108 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001109 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001110 Val, DestP, DAG.getSrcValue(DestV));
1111 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001112}
1113
1114std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001115TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1116 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001117 // We have no sane default behavior, just emit a useful error message and bail
1118 // out.
1119 std::cerr << "Variable arguments handling not implemented on this target!\n";
1120 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001121 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001122}
1123
1124
1125void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001126 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1127 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001128}
1129
1130void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1131 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001132 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001133 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001134 setValue(&I, Result.first);
1135 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001136}
1137
1138void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001139 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001140 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001141}
1142
1143void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001144 SDOperand Result =
1145 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1146 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1147 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001148}
1149
Chris Lattner58cfd792005-01-09 00:00:49 +00001150
1151// It is always conservatively correct for llvm.returnaddress and
1152// llvm.frameaddress to return 0.
1153std::pair<SDOperand, SDOperand>
1154TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1155 unsigned Depth, SelectionDAG &DAG) {
1156 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001157}
1158
Chris Lattner29dcc712005-05-14 05:50:48 +00001159SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001160 assert(0 && "LowerOperation not implemented for this target!");
1161 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001162 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001163}
1164
Chris Lattner58cfd792005-01-09 00:00:49 +00001165void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1166 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1167 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001168 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001169 setValue(&I, Result.first);
1170 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001171}
1172
Chris Lattner875def92005-01-11 05:56:49 +00001173void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer3fd1b4c2005-11-30 05:21:10 +00001174#if 0
1175 // If the size of the cpy/move/set is constant (known)
1176 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1177 uint64_t size = op3->getValue();
1178 switch (Op) {
1179 case ISD::MEMSET:
1180 if (size <= TLI.getMaxStoresPerMemSet()) {
1181 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1182 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1183 uint64_t align = op4.getValue();
1184 while (size > align) {
1185 size -=align;
1186 }
1187 Value *SrcV = I.getOperand(0);
1188 SDOperand Src = getValue(SrcV);
1189 SDOperand Ptr = getValue(I.getOperand(1));
1190 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1191 DAG.getSrcValue(I.getOperand(1))));
1192 }
1193 break;
1194 }
1195 break; // don't do this optimization, use a normal memset
1196 case ISD::MEMMOVE:
1197 case ISD::MEMCPY:
1198 break; // FIXME: not implemented yet
1199 }
1200 }
1201#endif
1202
1203 // Non-optimized version
Chris Lattner875def92005-01-11 05:56:49 +00001204 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001205 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001206 Ops.push_back(getValue(I.getOperand(1)));
1207 Ops.push_back(getValue(I.getOperand(2)));
1208 Ops.push_back(getValue(I.getOperand(3)));
1209 Ops.push_back(getValue(I.getOperand(4)));
1210 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001211}
1212
Chris Lattner875def92005-01-11 05:56:49 +00001213//===----------------------------------------------------------------------===//
1214// SelectionDAGISel code
1215//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001216
1217unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1218 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1219}
1220
Chris Lattnerc9950c12005-08-17 06:37:43 +00001221void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001222 // FIXME: we only modify the CFG to split critical edges. This
1223 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001224}
Chris Lattner7a60d912005-01-07 07:47:53 +00001225
Chris Lattner7a60d912005-01-07 07:47:53 +00001226bool SelectionDAGISel::runOnFunction(Function &Fn) {
1227 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1228 RegMap = MF.getSSARegMap();
1229 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1230
Chris Lattnerc9950c12005-08-17 06:37:43 +00001231 // First pass, split all critical edges for PHI nodes with incoming values
1232 // that are constants, this way the load of the constant into a vreg will not
1233 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001234 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1235 PHINode *PN;
1236 for (BasicBlock::iterator BBI = BB->begin();
1237 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1238 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1239 if (isa<Constant>(PN->getIncomingValue(i)))
1240 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1241 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001242
Chris Lattner7a60d912005-01-07 07:47:53 +00001243 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1244
1245 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1246 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001247
Chris Lattner7a60d912005-01-07 07:47:53 +00001248 return true;
1249}
1250
1251
Chris Lattner718b5c22005-01-13 17:59:43 +00001252SDOperand SelectionDAGISel::
1253CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001254 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001255 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001256 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001257 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001258
1259 // If this type is not legal, we must make sure to not create an invalid
1260 // register use.
1261 MVT::ValueType SrcVT = Op.getValueType();
1262 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1263 SelectionDAG &DAG = SDL.DAG;
1264 if (SrcVT == DestVT) {
1265 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1266 } else if (SrcVT < DestVT) {
1267 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001268 if (MVT::isFloatingPoint(SrcVT))
1269 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1270 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001271 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001272 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1273 } else {
1274 // The src value is expanded into multiple registers.
1275 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1276 Op, DAG.getConstant(0, MVT::i32));
1277 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1278 Op, DAG.getConstant(1, MVT::i32));
1279 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1280 return DAG.getCopyToReg(Op, Reg+1, Hi);
1281 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001282}
1283
Chris Lattner16f64df2005-01-17 17:15:02 +00001284void SelectionDAGISel::
1285LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1286 std::vector<SDOperand> &UnorderedChains) {
1287 // If this is the entry block, emit arguments.
1288 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001289 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001290 SDOperand OldRoot = SDL.DAG.getRoot();
1291 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001292
Chris Lattner6871b232005-10-30 19:42:35 +00001293 unsigned a = 0;
1294 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1295 AI != E; ++AI, ++a)
1296 if (!AI->use_empty()) {
1297 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001298
Chris Lattner6871b232005-10-30 19:42:35 +00001299 // If this argument is live outside of the entry block, insert a copy from
1300 // whereever we got it to the vreg that other BB's will reference it as.
1301 if (FuncInfo.ValueMap.count(AI)) {
1302 SDOperand Copy =
1303 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1304 UnorderedChains.push_back(Copy);
1305 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001306 }
Chris Lattner6871b232005-10-30 19:42:35 +00001307
1308 // Next, if the function has live ins that need to be copied into vregs,
1309 // emit the copies now, into the top of the block.
1310 MachineFunction &MF = SDL.DAG.getMachineFunction();
1311 if (MF.livein_begin() != MF.livein_end()) {
1312 SSARegMap *RegMap = MF.getSSARegMap();
1313 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1314 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1315 E = MF.livein_end(); LI != E; ++LI)
1316 if (LI->second)
1317 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1318 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001319 }
Chris Lattner6871b232005-10-30 19:42:35 +00001320
1321 // Finally, if the target has anything special to do, allow it to do so.
1322 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001323}
1324
1325
Chris Lattner7a60d912005-01-07 07:47:53 +00001326void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1327 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1328 FunctionLoweringInfo &FuncInfo) {
1329 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001330
1331 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001332
Chris Lattner6871b232005-10-30 19:42:35 +00001333 // Lower any arguments needed in this block if this is the entry block.
1334 if (LLVMBB == &LLVMBB->getParent()->front())
1335 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001336
1337 BB = FuncInfo.MBBMap[LLVMBB];
1338 SDL.setCurrentBasicBlock(BB);
1339
1340 // Lower all of the non-terminator instructions.
1341 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1342 I != E; ++I)
1343 SDL.visit(*I);
1344
1345 // Ensure that all instructions which are used outside of their defining
1346 // blocks are available as virtual registers.
1347 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001348 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001349 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001350 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001351 UnorderedChains.push_back(
1352 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001353 }
1354
1355 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1356 // ensure constants are generated when needed. Remember the virtual registers
1357 // that need to be added to the Machine PHI nodes as input. We cannot just
1358 // directly add them, because expansion might result in multiple MBB's for one
1359 // BB. As such, the start of the BB might correspond to a different MBB than
1360 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001361 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001362
1363 // Emit constants only once even if used by multiple PHI nodes.
1364 std::map<Constant*, unsigned> ConstantsOut;
1365
1366 // Check successor nodes PHI nodes that expect a constant to be available from
1367 // this block.
1368 TerminatorInst *TI = LLVMBB->getTerminator();
1369 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1370 BasicBlock *SuccBB = TI->getSuccessor(succ);
1371 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1372 PHINode *PN;
1373
1374 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1375 // nodes and Machine PHI nodes, but the incoming operands have not been
1376 // emitted yet.
1377 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001378 (PN = dyn_cast<PHINode>(I)); ++I)
1379 if (!PN->use_empty()) {
1380 unsigned Reg;
1381 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1382 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1383 unsigned &RegOut = ConstantsOut[C];
1384 if (RegOut == 0) {
1385 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001386 UnorderedChains.push_back(
1387 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001388 }
1389 Reg = RegOut;
1390 } else {
1391 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001392 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001393 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001394 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1395 "Didn't codegen value into a register!??");
1396 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001397 UnorderedChains.push_back(
1398 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001399 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001400 }
Misha Brukman835702a2005-04-21 22:36:52 +00001401
Chris Lattner8ea875f2005-01-07 21:34:19 +00001402 // Remember that this register needs to added to the machine PHI node as
1403 // the input for this MBB.
1404 unsigned NumElements =
1405 TLI.getNumElements(TLI.getValueType(PN->getType()));
1406 for (unsigned i = 0, e = NumElements; i != e; ++i)
1407 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001408 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001409 }
1410 ConstantsOut.clear();
1411
Chris Lattner718b5c22005-01-13 17:59:43 +00001412 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001413 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001414 SDOperand Root = SDL.getRoot();
1415 if (Root.getOpcode() != ISD::EntryToken) {
1416 unsigned i = 0, e = UnorderedChains.size();
1417 for (; i != e; ++i) {
1418 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1419 if (UnorderedChains[i].Val->getOperand(0) == Root)
1420 break; // Don't add the root if we already indirectly depend on it.
1421 }
1422
1423 if (i == e)
1424 UnorderedChains.push_back(Root);
1425 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001426 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1427 }
1428
Chris Lattner7a60d912005-01-07 07:47:53 +00001429 // Lower the terminator after the copies are emitted.
1430 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001431
1432 // Make sure the root of the DAG is up-to-date.
1433 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001434}
1435
1436void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1437 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001438 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001439 CurDAG = &DAG;
1440 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1441
1442 // First step, lower LLVM code to some DAG. This DAG may use operations and
1443 // types that are not supported by the target.
1444 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1445
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001446 // Run the DAG combiner in pre-legalize mode.
1447 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001448
Chris Lattner7a60d912005-01-07 07:47:53 +00001449 DEBUG(std::cerr << "Lowered selection DAG:\n");
1450 DEBUG(DAG.dump());
1451
1452 // Second step, hack on the DAG until it only uses operations and types that
1453 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001454 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001455
1456 DEBUG(std::cerr << "Legalized selection DAG:\n");
1457 DEBUG(DAG.dump());
1458
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001459 // Run the DAG combiner in post-legalize mode.
1460 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001461
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001462 if (ViewDAGs) DAG.viewGraph();
1463
Chris Lattner5ca31d92005-03-30 01:10:47 +00001464 // Third, instruction select all of the operations to machine code, adding the
1465 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001466 InstructionSelectBasicBlock(DAG);
1467
Chris Lattner7a60d912005-01-07 07:47:53 +00001468 DEBUG(std::cerr << "Selected machine code:\n");
1469 DEBUG(BB->dump());
1470
Chris Lattner5ca31d92005-03-30 01:10:47 +00001471 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001472 // PHI nodes in successors.
1473 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1474 MachineInstr *PHI = PHINodesToUpdate[i].first;
1475 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1476 "This is not a machine PHI node that we are updating!");
1477 PHI->addRegOperand(PHINodesToUpdate[i].second);
1478 PHI->addMachineBasicBlockOperand(BB);
1479 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001480
1481 // Finally, add the CFG edges from the last selected MBB to the successor
1482 // MBBs.
1483 TerminatorInst *TI = LLVMBB->getTerminator();
1484 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1485 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1486 BB->addSuccessor(Succ0MBB);
1487 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001488}