blob: 00dc56ef9185dfd54f7fe8c8d68674e40e83aae9 [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());
523
524 // Immediately scalarize packed types containing only one element, so that
525 // the Legalize pass does not have to deal with them.
526 if (NumElements == 1) {
527 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
528 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
529 } else {
530 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
531 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000532 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000533 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000534 }
Nate Begeman127321b2005-11-18 07:42:56 +0000535}
Chris Lattner96c26752005-01-19 22:31:21 +0000536
Nate Begeman127321b2005-11-18 07:42:56 +0000537void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
538 SDOperand Op1 = getValue(I.getOperand(0));
539 SDOperand Op2 = getValue(I.getOperand(1));
540
541 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
542
Chris Lattner7a60d912005-01-07 07:47:53 +0000543 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
544}
545
546void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
547 ISD::CondCode UnsignedOpcode) {
548 SDOperand Op1 = getValue(I.getOperand(0));
549 SDOperand Op2 = getValue(I.getOperand(1));
550 ISD::CondCode Opcode = SignedOpcode;
551 if (I.getOperand(0)->getType()->isUnsigned())
552 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000553 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000554}
555
556void SelectionDAGLowering::visitSelect(User &I) {
557 SDOperand Cond = getValue(I.getOperand(0));
558 SDOperand TrueVal = getValue(I.getOperand(1));
559 SDOperand FalseVal = getValue(I.getOperand(2));
560 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
561 TrueVal, FalseVal));
562}
563
564void SelectionDAGLowering::visitCast(User &I) {
565 SDOperand N = getValue(I.getOperand(0));
566 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
567 MVT::ValueType DestTy = TLI.getValueType(I.getType());
568
569 if (N.getValueType() == DestTy) {
570 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000571 } else if (DestTy == MVT::i1) {
572 // Cast to bool is a comparison against zero, not truncation to zero.
573 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
574 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000575 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000576 } else if (isInteger(SrcTy)) {
577 if (isInteger(DestTy)) { // Int -> Int cast
578 if (DestTy < SrcTy) // Truncating cast?
579 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
580 else if (I.getOperand(0)->getType()->isSigned())
581 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
582 else
583 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
584 } else { // Int -> FP cast
585 if (I.getOperand(0)->getType()->isSigned())
586 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
587 else
588 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
589 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000590 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000591 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
592 if (isFloatingPoint(DestTy)) { // FP -> FP cast
593 if (DestTy < SrcTy) // Rounding cast?
594 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
595 else
596 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
597 } else { // FP -> Int cast.
598 if (I.getType()->isSigned())
599 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
600 else
601 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
602 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000603 }
604}
605
606void SelectionDAGLowering::visitGetElementPtr(User &I) {
607 SDOperand N = getValue(I.getOperand(0));
608 const Type *Ty = I.getOperand(0)->getType();
609 const Type *UIntPtrTy = TD.getIntPtrType();
610
611 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
612 OI != E; ++OI) {
613 Value *Idx = *OI;
614 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
615 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
616 if (Field) {
617 // N = N + Offset
618 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
619 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000620 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000621 }
622 Ty = StTy->getElementType(Field);
623 } else {
624 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000625
Chris Lattner43535a12005-11-09 04:45:33 +0000626 // If this is a constant subscript, handle it quickly.
627 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
628 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000629
Chris Lattner43535a12005-11-09 04:45:33 +0000630 uint64_t Offs;
631 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
632 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
633 else
634 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
635 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
636 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000637 }
Chris Lattner43535a12005-11-09 04:45:33 +0000638
639 // N = N + Idx * ElementSize;
640 uint64_t ElementSize = TD.getTypeSize(Ty);
641 SDOperand IdxN = getValue(Idx);
642
643 // If the index is smaller or larger than intptr_t, truncate or extend
644 // it.
645 if (IdxN.getValueType() < N.getValueType()) {
646 if (Idx->getType()->isSigned())
647 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
648 else
649 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
650 } else if (IdxN.getValueType() > N.getValueType())
651 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
652
653 // If this is a multiply by a power of two, turn it into a shl
654 // immediately. This is a very common case.
655 if (isPowerOf2_64(ElementSize)) {
656 unsigned Amt = Log2_64(ElementSize);
657 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000658 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000659 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
660 continue;
661 }
662
663 SDOperand Scale = getIntPtrConstant(ElementSize);
664 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
665 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000666 }
667 }
668 setValue(&I, N);
669}
670
671void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
672 // If this is a fixed sized alloca in the entry block of the function,
673 // allocate it statically on the stack.
674 if (FuncInfo.StaticAllocaMap.count(&I))
675 return; // getValue will auto-populate this.
676
677 const Type *Ty = I.getAllocatedType();
678 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000679 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
680 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000681
682 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000683 MVT::ValueType IntPtr = TLI.getPointerTy();
684 if (IntPtr < AllocSize.getValueType())
685 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
686 else if (IntPtr > AllocSize.getValueType())
687 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000688
Chris Lattnereccb73d2005-01-22 23:04:37 +0000689 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000690 getIntPtrConstant(TySize));
691
692 // Handle alignment. If the requested alignment is less than or equal to the
693 // stack alignment, ignore it and round the size of the allocation up to the
694 // stack alignment size. If the size is greater than the stack alignment, we
695 // note this in the DYNAMIC_STACKALLOC node.
696 unsigned StackAlign =
697 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
698 if (Align <= StackAlign) {
699 Align = 0;
700 // Add SA-1 to the size.
701 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
702 getIntPtrConstant(StackAlign-1));
703 // Mask out the low bits for alignment purposes.
704 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
705 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
706 }
707
Chris Lattner96c262e2005-05-14 07:29:57 +0000708 std::vector<MVT::ValueType> VTs;
709 VTs.push_back(AllocSize.getValueType());
710 VTs.push_back(MVT::Other);
711 std::vector<SDOperand> Ops;
712 Ops.push_back(getRoot());
713 Ops.push_back(AllocSize);
714 Ops.push_back(getIntPtrConstant(Align));
715 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000716 DAG.setRoot(setValue(&I, DSA).getValue(1));
717
718 // Inform the Frame Information that we have just allocated a variable-sized
719 // object.
720 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
721}
722
Chris Lattner435b4022005-11-29 06:21:05 +0000723/// getStringValue - Turn an LLVM constant pointer that eventually points to a
724/// global into a string value. Return an empty string if we can't do it.
725///
726static std::string getStringValue(Value *V, unsigned Offset = 0) {
727 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
728 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
729 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
730 if (Init->isString()) {
731 std::string Result = Init->getAsString();
732 if (Offset < Result.size()) {
733 // If we are pointing INTO The string, erase the beginning...
734 Result.erase(Result.begin(), Result.begin()+Offset);
735
736 // Take off the null terminator, and any string fragments after it.
737 std::string::size_type NullPos = Result.find_first_of((char)0);
738 if (NullPos != std::string::npos)
739 Result.erase(Result.begin()+NullPos, Result.end());
740 return Result;
741 }
742 }
743 }
744 } else if (Constant *C = dyn_cast<Constant>(V)) {
745 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
746 return getStringValue(GV, Offset);
747 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
748 if (CE->getOpcode() == Instruction::GetElementPtr) {
749 // Turn a gep into the specified offset.
750 if (CE->getNumOperands() == 3 &&
751 cast<Constant>(CE->getOperand(1))->isNullValue() &&
752 isa<ConstantInt>(CE->getOperand(2))) {
753 return getStringValue(CE->getOperand(0),
754 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
755 }
756 }
757 }
758 }
759 return "";
760}
Chris Lattner7a60d912005-01-07 07:47:53 +0000761
762void SelectionDAGLowering::visitLoad(LoadInst &I) {
763 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000764
Chris Lattner4d9651c2005-01-17 22:19:26 +0000765 SDOperand Root;
766 if (I.isVolatile())
767 Root = getRoot();
768 else {
769 // Do not serialize non-volatile loads against each other.
770 Root = DAG.getRoot();
771 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000772
773 const Type *Ty = I.getType();
774 SDOperand L;
775
776 if (Type::PackedTyID == Ty->getTypeID()) {
777 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000778 unsigned NumElements = PTy->getNumElements();
779 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
780
781 // Immediately scalarize packed types containing only one element, so that
782 // the Legalize pass does not have to deal with them.
783 if (NumElements == 1) {
784 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
785 } else {
786 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
787 DAG.getSrcValue(I.getOperand(0)));
788 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000789 } else {
790 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
791 DAG.getSrcValue(I.getOperand(0)));
792 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000793 setValue(&I, L);
794
795 if (I.isVolatile())
796 DAG.setRoot(L.getValue(1));
797 else
798 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000799}
800
801
802void SelectionDAGLowering::visitStore(StoreInst &I) {
803 Value *SrcV = I.getOperand(0);
804 SDOperand Src = getValue(SrcV);
805 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000806 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000807 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000808}
809
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000810/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
811/// we want to emit this as a call to a named external function, return the name
812/// otherwise lower it and return null.
813const char *
814SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
815 switch (Intrinsic) {
816 case Intrinsic::vastart: visitVAStart(I); return 0;
817 case Intrinsic::vaend: visitVAEnd(I); return 0;
818 case Intrinsic::vacopy: visitVACopy(I); return 0;
819 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
820 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
821 case Intrinsic::setjmp:
822 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
823 break;
824 case Intrinsic::longjmp:
825 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
826 break;
827 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
828 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
829 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
830
831 case Intrinsic::readport:
832 case Intrinsic::readio: {
833 std::vector<MVT::ValueType> VTs;
834 VTs.push_back(TLI.getValueType(I.getType()));
835 VTs.push_back(MVT::Other);
836 std::vector<SDOperand> Ops;
837 Ops.push_back(getRoot());
838 Ops.push_back(getValue(I.getOperand(1)));
839 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
840 ISD::READPORT : ISD::READIO, VTs, Ops);
841
842 setValue(&I, Tmp);
843 DAG.setRoot(Tmp.getValue(1));
844 return 0;
845 }
846 case Intrinsic::writeport:
847 case Intrinsic::writeio:
848 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
849 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
850 getRoot(), getValue(I.getOperand(1)),
851 getValue(I.getOperand(2))));
852 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000853
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000854 case Intrinsic::dbg_stoppoint:
Chris Lattner435b4022005-11-29 06:21:05 +0000855 {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000856 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
857 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000858
859 std::string fname = "<unknown>";
860 std::vector<SDOperand> Ops;
861
862 // Pull the filename out of the the compilation unit.
863 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
864 if (cunit && cunit->hasInitializer()) {
865 ConstantStruct *CS = dyn_cast<ConstantStruct>(cunit->getInitializer());
866 if (CS->getNumOperands() > 0) {
867 std::string dirname = getStringValue(CS->getOperand(4));
868 fname = dirname + "/" + getStringValue(CS->getOperand(3));
869 }
870 }
871 // Input Chain
872 Ops.push_back(getRoot());
873
874 // line number
875 Ops.push_back(getValue(I.getOperand(2)));
876
877 // column
878 Ops.push_back(getValue(I.getOperand(3)));
879
880 // filename
881 Ops.push_back(DAG.getString(fname));
882 Ops.push_back(DAG.getString(""));
883 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000884 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000885 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000886 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000887 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
888 return "llvm_dbg_region_start";
889 if (I.getType() != Type::VoidTy)
890 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
891 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000892 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000893 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
894 return "llvm_dbg_region_end";
895 if (I.getType() != Type::VoidTy)
896 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
897 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000898 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000899 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
900 return "llvm_dbg_subprogram";
901 if (I.getType() != Type::VoidTy)
902 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
903 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000904 case Intrinsic::dbg_declare:
905 if (I.getType() != Type::VoidTy)
906 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
907 return 0;
908
909 case Intrinsic::isunordered:
910 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
911 getValue(I.getOperand(2)), ISD::SETUO));
912 return 0;
913
914 case Intrinsic::sqrt:
915 setValue(&I, DAG.getNode(ISD::FSQRT,
916 getValue(I.getOperand(1)).getValueType(),
917 getValue(I.getOperand(1))));
918 return 0;
919 case Intrinsic::pcmarker: {
920 SDOperand Tmp = getValue(I.getOperand(1));
921 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
922 return 0;
923 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000924 case Intrinsic::readcyclecounter: {
925 std::vector<MVT::ValueType> VTs;
926 VTs.push_back(MVT::i64);
927 VTs.push_back(MVT::Other);
928 std::vector<SDOperand> Ops;
929 Ops.push_back(getRoot());
930 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
931 setValue(&I, Tmp);
932 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000933 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000934 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000935 case Intrinsic::cttz:
936 setValue(&I, DAG.getNode(ISD::CTTZ,
937 getValue(I.getOperand(1)).getValueType(),
938 getValue(I.getOperand(1))));
939 return 0;
940 case Intrinsic::ctlz:
941 setValue(&I, DAG.getNode(ISD::CTLZ,
942 getValue(I.getOperand(1)).getValueType(),
943 getValue(I.getOperand(1))));
944 return 0;
945 case Intrinsic::ctpop:
946 setValue(&I, DAG.getNode(ISD::CTPOP,
947 getValue(I.getOperand(1)).getValueType(),
948 getValue(I.getOperand(1))));
949 return 0;
950 default:
951 std::cerr << I;
952 assert(0 && "This intrinsic is not implemented yet!");
953 return 0;
954 }
955}
956
957
Chris Lattner7a60d912005-01-07 07:47:53 +0000958void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000959 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000960 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +0000961 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000962 if (unsigned IID = F->getIntrinsicID()) {
963 RenameFn = visitIntrinsicCall(I, IID);
964 if (!RenameFn)
965 return;
966 } else { // Not an LLVM intrinsic.
967 const std::string &Name = F->getName();
968 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +0000969 if (I.getNumOperands() == 2 && // Basic sanity checks.
970 I.getOperand(1)->getType()->isFloatingPoint() &&
971 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000972 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000973 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
974 return;
975 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000976 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000977 if (I.getNumOperands() == 2 && // Basic sanity checks.
978 I.getOperand(1)->getType()->isFloatingPoint() &&
979 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000980 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000981 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
982 return;
983 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000984 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000985 if (I.getNumOperands() == 2 && // Basic sanity checks.
986 I.getOperand(1)->getType()->isFloatingPoint() &&
987 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000988 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000989 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
990 return;
991 }
992 }
Chris Lattnere4f71d02005-05-14 13:56:55 +0000993 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000994 }
Misha Brukman835702a2005-04-21 22:36:52 +0000995
Chris Lattner18d2b342005-01-08 22:48:57 +0000996 SDOperand Callee;
997 if (!RenameFn)
998 Callee = getValue(I.getOperand(0));
999 else
1000 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001001 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001002 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001003 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1004 Value *Arg = I.getOperand(i);
1005 SDOperand ArgNode = getValue(Arg);
1006 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1007 }
Misha Brukman835702a2005-04-21 22:36:52 +00001008
Nate Begemanf6565252005-03-26 01:29:23 +00001009 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1010 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001011
Chris Lattner1f45cd72005-01-08 19:26:18 +00001012 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001013 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001014 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001015 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001016 setValue(&I, Result.first);
1017 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001018}
1019
1020void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1021 SDOperand Src = getValue(I.getOperand(0));
1022
1023 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001024
1025 if (IntPtr < Src.getValueType())
1026 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1027 else if (IntPtr > Src.getValueType())
1028 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001029
1030 // Scale the source by the type size.
1031 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1032 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1033 Src, getIntPtrConstant(ElementSize));
1034
1035 std::vector<std::pair<SDOperand, const Type*> > Args;
1036 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001037
1038 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001039 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001040 DAG.getExternalSymbol("malloc", IntPtr),
1041 Args, DAG);
1042 setValue(&I, Result.first); // Pointers always fit in registers
1043 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001044}
1045
1046void SelectionDAGLowering::visitFree(FreeInst &I) {
1047 std::vector<std::pair<SDOperand, const Type*> > Args;
1048 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1049 TLI.getTargetData().getIntPtrType()));
1050 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001051 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001052 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001053 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1054 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001055}
1056
Chris Lattner13d7c252005-08-26 20:54:47 +00001057// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1058// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1059// instructions are special in various ways, which require special support to
1060// insert. The specified MachineInstr is created but not inserted into any
1061// basic blocks, and the scheduler passes ownership of it to this method.
1062MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1063 MachineBasicBlock *MBB) {
1064 std::cerr << "If a target marks an instruction with "
1065 "'usesCustomDAGSchedInserter', it must implement "
1066 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1067 abort();
1068 return 0;
1069}
1070
Nate Begeman78afac22005-10-18 23:23:37 +00001071SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1072 SelectionDAG &DAG) {
1073 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1074}
1075
Chris Lattnerf5473e42005-07-05 19:57:53 +00001076SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1077 SDOperand VAListP, Value *VAListV,
1078 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001079 // We have no sane default behavior, just emit a useful error message and bail
1080 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001081 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001082 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001083 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001084}
1085
Chris Lattnerf5473e42005-07-05 19:57:53 +00001086SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001087 SelectionDAG &DAG) {
1088 // Default to a noop.
1089 return Chain;
1090}
1091
Chris Lattnerf5473e42005-07-05 19:57:53 +00001092SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1093 SDOperand SrcP, Value *SrcV,
1094 SDOperand DestP, Value *DestV,
1095 SelectionDAG &DAG) {
1096 // Default to copying the input list.
1097 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1098 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001099 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001100 Val, DestP, DAG.getSrcValue(DestV));
1101 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001102}
1103
1104std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001105TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1106 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001107 // We have no sane default behavior, just emit a useful error message and bail
1108 // out.
1109 std::cerr << "Variable arguments handling not implemented on this target!\n";
1110 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001111 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001112}
1113
1114
1115void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001116 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1117 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001118}
1119
1120void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1121 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001122 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001123 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001124 setValue(&I, Result.first);
1125 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001126}
1127
1128void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001129 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001130 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001131}
1132
1133void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001134 SDOperand Result =
1135 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1136 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1137 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001138}
1139
Chris Lattner58cfd792005-01-09 00:00:49 +00001140
1141// It is always conservatively correct for llvm.returnaddress and
1142// llvm.frameaddress to return 0.
1143std::pair<SDOperand, SDOperand>
1144TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1145 unsigned Depth, SelectionDAG &DAG) {
1146 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001147}
1148
Chris Lattner29dcc712005-05-14 05:50:48 +00001149SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001150 assert(0 && "LowerOperation not implemented for this target!");
1151 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001152 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001153}
1154
Chris Lattner58cfd792005-01-09 00:00:49 +00001155void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1156 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1157 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001158 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001159 setValue(&I, Result.first);
1160 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001161}
1162
Chris Lattner875def92005-01-11 05:56:49 +00001163void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1164 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001165 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001166 Ops.push_back(getValue(I.getOperand(1)));
1167 Ops.push_back(getValue(I.getOperand(2)));
1168 Ops.push_back(getValue(I.getOperand(3)));
1169 Ops.push_back(getValue(I.getOperand(4)));
1170 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001171}
1172
Chris Lattner875def92005-01-11 05:56:49 +00001173//===----------------------------------------------------------------------===//
1174// SelectionDAGISel code
1175//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001176
1177unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1178 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1179}
1180
Chris Lattnerc9950c12005-08-17 06:37:43 +00001181void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001182 // FIXME: we only modify the CFG to split critical edges. This
1183 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001184}
Chris Lattner7a60d912005-01-07 07:47:53 +00001185
Chris Lattner7a60d912005-01-07 07:47:53 +00001186bool SelectionDAGISel::runOnFunction(Function &Fn) {
1187 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1188 RegMap = MF.getSSARegMap();
1189 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1190
Chris Lattnerc9950c12005-08-17 06:37:43 +00001191 // First pass, split all critical edges for PHI nodes with incoming values
1192 // that are constants, this way the load of the constant into a vreg will not
1193 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001194 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1195 PHINode *PN;
1196 for (BasicBlock::iterator BBI = BB->begin();
1197 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1198 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1199 if (isa<Constant>(PN->getIncomingValue(i)))
1200 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1201 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001202
Chris Lattner7a60d912005-01-07 07:47:53 +00001203 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1204
1205 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1206 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001207
Chris Lattner7a60d912005-01-07 07:47:53 +00001208 return true;
1209}
1210
1211
Chris Lattner718b5c22005-01-13 17:59:43 +00001212SDOperand SelectionDAGISel::
1213CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001214 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001215 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001216 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001217 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001218
1219 // If this type is not legal, we must make sure to not create an invalid
1220 // register use.
1221 MVT::ValueType SrcVT = Op.getValueType();
1222 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1223 SelectionDAG &DAG = SDL.DAG;
1224 if (SrcVT == DestVT) {
1225 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1226 } else if (SrcVT < DestVT) {
1227 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001228 if (MVT::isFloatingPoint(SrcVT))
1229 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1230 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001231 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001232 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1233 } else {
1234 // The src value is expanded into multiple registers.
1235 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1236 Op, DAG.getConstant(0, MVT::i32));
1237 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1238 Op, DAG.getConstant(1, MVT::i32));
1239 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1240 return DAG.getCopyToReg(Op, Reg+1, Hi);
1241 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001242}
1243
Chris Lattner16f64df2005-01-17 17:15:02 +00001244void SelectionDAGISel::
1245LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1246 std::vector<SDOperand> &UnorderedChains) {
1247 // If this is the entry block, emit arguments.
1248 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001249 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001250 SDOperand OldRoot = SDL.DAG.getRoot();
1251 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001252
Chris Lattner6871b232005-10-30 19:42:35 +00001253 unsigned a = 0;
1254 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1255 AI != E; ++AI, ++a)
1256 if (!AI->use_empty()) {
1257 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001258
Chris Lattner6871b232005-10-30 19:42:35 +00001259 // If this argument is live outside of the entry block, insert a copy from
1260 // whereever we got it to the vreg that other BB's will reference it as.
1261 if (FuncInfo.ValueMap.count(AI)) {
1262 SDOperand Copy =
1263 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1264 UnorderedChains.push_back(Copy);
1265 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001266 }
Chris Lattner6871b232005-10-30 19:42:35 +00001267
1268 // Next, if the function has live ins that need to be copied into vregs,
1269 // emit the copies now, into the top of the block.
1270 MachineFunction &MF = SDL.DAG.getMachineFunction();
1271 if (MF.livein_begin() != MF.livein_end()) {
1272 SSARegMap *RegMap = MF.getSSARegMap();
1273 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1274 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1275 E = MF.livein_end(); LI != E; ++LI)
1276 if (LI->second)
1277 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1278 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001279 }
Chris Lattner6871b232005-10-30 19:42:35 +00001280
1281 // Finally, if the target has anything special to do, allow it to do so.
1282 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001283}
1284
1285
Chris Lattner7a60d912005-01-07 07:47:53 +00001286void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1287 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1288 FunctionLoweringInfo &FuncInfo) {
1289 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001290
1291 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001292
Chris Lattner6871b232005-10-30 19:42:35 +00001293 // Lower any arguments needed in this block if this is the entry block.
1294 if (LLVMBB == &LLVMBB->getParent()->front())
1295 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001296
1297 BB = FuncInfo.MBBMap[LLVMBB];
1298 SDL.setCurrentBasicBlock(BB);
1299
1300 // Lower all of the non-terminator instructions.
1301 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1302 I != E; ++I)
1303 SDL.visit(*I);
1304
1305 // Ensure that all instructions which are used outside of their defining
1306 // blocks are available as virtual registers.
1307 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001308 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001309 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001310 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001311 UnorderedChains.push_back(
1312 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001313 }
1314
1315 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1316 // ensure constants are generated when needed. Remember the virtual registers
1317 // that need to be added to the Machine PHI nodes as input. We cannot just
1318 // directly add them, because expansion might result in multiple MBB's for one
1319 // BB. As such, the start of the BB might correspond to a different MBB than
1320 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001321 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001322
1323 // Emit constants only once even if used by multiple PHI nodes.
1324 std::map<Constant*, unsigned> ConstantsOut;
1325
1326 // Check successor nodes PHI nodes that expect a constant to be available from
1327 // this block.
1328 TerminatorInst *TI = LLVMBB->getTerminator();
1329 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1330 BasicBlock *SuccBB = TI->getSuccessor(succ);
1331 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1332 PHINode *PN;
1333
1334 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1335 // nodes and Machine PHI nodes, but the incoming operands have not been
1336 // emitted yet.
1337 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001338 (PN = dyn_cast<PHINode>(I)); ++I)
1339 if (!PN->use_empty()) {
1340 unsigned Reg;
1341 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1342 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1343 unsigned &RegOut = ConstantsOut[C];
1344 if (RegOut == 0) {
1345 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001346 UnorderedChains.push_back(
1347 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001348 }
1349 Reg = RegOut;
1350 } else {
1351 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001352 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001353 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001354 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1355 "Didn't codegen value into a register!??");
1356 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001357 UnorderedChains.push_back(
1358 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001359 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001360 }
Misha Brukman835702a2005-04-21 22:36:52 +00001361
Chris Lattner8ea875f2005-01-07 21:34:19 +00001362 // Remember that this register needs to added to the machine PHI node as
1363 // the input for this MBB.
1364 unsigned NumElements =
1365 TLI.getNumElements(TLI.getValueType(PN->getType()));
1366 for (unsigned i = 0, e = NumElements; i != e; ++i)
1367 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001368 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001369 }
1370 ConstantsOut.clear();
1371
Chris Lattner718b5c22005-01-13 17:59:43 +00001372 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001373 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001374 SDOperand Root = SDL.getRoot();
1375 if (Root.getOpcode() != ISD::EntryToken) {
1376 unsigned i = 0, e = UnorderedChains.size();
1377 for (; i != e; ++i) {
1378 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1379 if (UnorderedChains[i].Val->getOperand(0) == Root)
1380 break; // Don't add the root if we already indirectly depend on it.
1381 }
1382
1383 if (i == e)
1384 UnorderedChains.push_back(Root);
1385 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001386 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1387 }
1388
Chris Lattner7a60d912005-01-07 07:47:53 +00001389 // Lower the terminator after the copies are emitted.
1390 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001391
1392 // Make sure the root of the DAG is up-to-date.
1393 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001394}
1395
1396void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1397 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001398 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001399 CurDAG = &DAG;
1400 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1401
1402 // First step, lower LLVM code to some DAG. This DAG may use operations and
1403 // types that are not supported by the target.
1404 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1405
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001406 // Run the DAG combiner in pre-legalize mode.
1407 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001408
Chris Lattner7a60d912005-01-07 07:47:53 +00001409 DEBUG(std::cerr << "Lowered selection DAG:\n");
1410 DEBUG(DAG.dump());
1411
1412 // Second step, hack on the DAG until it only uses operations and types that
1413 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001414 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001415
1416 DEBUG(std::cerr << "Legalized selection DAG:\n");
1417 DEBUG(DAG.dump());
1418
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001419 // Run the DAG combiner in post-legalize mode.
1420 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001421
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001422 if (ViewDAGs) DAG.viewGraph();
1423
Chris Lattner5ca31d92005-03-30 01:10:47 +00001424 // Third, instruction select all of the operations to machine code, adding the
1425 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001426 InstructionSelectBasicBlock(DAG);
1427
Chris Lattner7a60d912005-01-07 07:47:53 +00001428 DEBUG(std::cerr << "Selected machine code:\n");
1429 DEBUG(BB->dump());
1430
Chris Lattner5ca31d92005-03-30 01:10:47 +00001431 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001432 // PHI nodes in successors.
1433 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1434 MachineInstr *PHI = PHINodesToUpdate[i].first;
1435 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1436 "This is not a machine PHI node that we are updating!");
1437 PHI->addRegOperand(PHINodesToUpdate[i].second);
1438 PHI->addMachineBasicBlockOperand(BB);
1439 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001440
1441 // Finally, add the CFG edges from the last selected MBB to the successor
1442 // MBBs.
1443 TerminatorInst *TI = LLVMBB->getTerminator();
1444 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1445 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1446 BB->addSuccessor(Succ0MBB);
1447 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001448}