blob: 0f5743860daf208872a8d5d4a47feaf2e7c96dc4 [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 Lattner35397782005-12-05 07:10:48 +000043static cl::opt<bool>
44GEPISelTest("enable-gep-isel-opt", cl::Hidden,
45 cl::desc("temporary for testing"));
46
Chris Lattner975f5c92005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000048static cl::opt<bool>
49ViewDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000052static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000053#endif
54
Chris Lattner7a60d912005-01-07 07:47:53 +000055namespace llvm {
56 //===--------------------------------------------------------------------===//
57 /// FunctionLoweringInfo - This contains information that is global to a
58 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000059 class FunctionLoweringInfo {
60 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000061 TargetLowering &TLI;
62 Function &Fn;
63 MachineFunction &MF;
64 SSARegMap *RegMap;
65
66 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
67
68 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
69 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
70
71 /// ValueMap - Since we emit code for the function a basic block at a time,
72 /// we must remember which virtual registers hold the values for
73 /// cross-basic-block values.
74 std::map<const Value*, unsigned> ValueMap;
75
76 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
77 /// the entry block. This allows the allocas to be efficiently referenced
78 /// anywhere in the function.
79 std::map<const AllocaInst*, int> StaticAllocaMap;
80
81 unsigned MakeReg(MVT::ValueType VT) {
82 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
83 }
Misha Brukman835702a2005-04-21 22:36:52 +000084
Chris Lattner7a60d912005-01-07 07:47:53 +000085 unsigned CreateRegForValue(const Value *V) {
86 MVT::ValueType VT = TLI.getValueType(V->getType());
87 // The common case is that we will only create one register for this
88 // value. If we have that case, create and return the virtual register.
89 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000090 if (NV == 1) {
91 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000092 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000093 }
Misha Brukman835702a2005-04-21 22:36:52 +000094
Chris Lattner7a60d912005-01-07 07:47:53 +000095 // If this value is represented with multiple target registers, make sure
96 // to create enough consequtive registers of the right (smaller) type.
97 unsigned NT = VT-1; // Find the type to use.
98 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
99 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000100
Chris Lattner7a60d912005-01-07 07:47:53 +0000101 unsigned R = MakeReg((MVT::ValueType)NT);
102 for (unsigned i = 1; i != NV; ++i)
103 MakeReg((MVT::ValueType)NT);
104 return R;
105 }
Misha Brukman835702a2005-04-21 22:36:52 +0000106
Chris Lattner7a60d912005-01-07 07:47:53 +0000107 unsigned InitializeRegForValue(const Value *V) {
108 unsigned &R = ValueMap[V];
109 assert(R == 0 && "Already initialized this value register!");
110 return R = CreateRegForValue(V);
111 }
112 };
113}
114
115/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
116/// PHI nodes or outside of the basic block that defines it.
117static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
118 if (isa<PHINode>(I)) return true;
119 BasicBlock *BB = I->getParent();
120 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
121 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
122 return true;
123 return false;
124}
125
Chris Lattner6871b232005-10-30 19:42:35 +0000126/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
127/// entry block, return true.
128static bool isOnlyUsedInEntryBlock(Argument *A) {
129 BasicBlock *Entry = A->getParent()->begin();
130 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
131 if (cast<Instruction>(*UI)->getParent() != Entry)
132 return false; // Use not in entry block.
133 return true;
134}
135
Chris Lattner7a60d912005-01-07 07:47:53 +0000136FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000137 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000138 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
139
Chris Lattner6871b232005-10-30 19:42:35 +0000140 // Create a vreg for each argument register that is not dead and is used
141 // outside of the entry block for the function.
142 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
143 AI != E; ++AI)
144 if (!isOnlyUsedInEntryBlock(AI))
145 InitializeRegForValue(AI);
146
Chris Lattner7a60d912005-01-07 07:47:53 +0000147 // Initialize the mapping of values to registers. This is only set up for
148 // instruction values that are used outside of the block that defines
149 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000150 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000151 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
152 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
153 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
154 const Type *Ty = AI->getAllocatedType();
155 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000156 unsigned Align =
157 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
158 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000159
160 // If the alignment of the value is smaller than the size of the value,
161 // and if the size of the value is particularly small (<= 8 bytes),
162 // round up to the size of the value for potentially better performance.
163 //
164 // FIXME: This could be made better with a preferred alignment hook in
165 // TargetData. It serves primarily to 8-byte align doubles for X86.
166 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000167 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000168 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000169 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000170 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000171 }
172
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000173 for (; BB != EB; ++BB)
174 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000175 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
176 if (!isa<AllocaInst>(I) ||
177 !StaticAllocaMap.count(cast<AllocaInst>(I)))
178 InitializeRegForValue(I);
179
180 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
181 // also creates the initial PHI MachineInstrs, though none of the input
182 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000183 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
185 MBBMap[BB] = MBB;
186 MF.getBasicBlockList().push_back(MBB);
187
188 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
189 // appropriate.
190 PHINode *PN;
191 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000192 (PN = dyn_cast<PHINode>(I)); ++I)
193 if (!PN->use_empty()) {
194 unsigned NumElements =
195 TLI.getNumElements(TLI.getValueType(PN->getType()));
196 unsigned PHIReg = ValueMap[PN];
197 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
198 for (unsigned i = 0; i != NumElements; ++i)
199 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
200 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000201 }
202}
203
204
205
206//===----------------------------------------------------------------------===//
207/// SelectionDAGLowering - This is the common target-independent lowering
208/// implementation that is parameterized by a TargetLowering object.
209/// Also, targets can overload any lowering method.
210///
211namespace llvm {
212class SelectionDAGLowering {
213 MachineBasicBlock *CurMBB;
214
215 std::map<const Value*, SDOperand> NodeMap;
216
Chris Lattner4d9651c2005-01-17 22:19:26 +0000217 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
218 /// them up and then emit token factor nodes when possible. This allows us to
219 /// get simple disambiguation between loads without worrying about alias
220 /// analysis.
221 std::vector<SDOperand> PendingLoads;
222
Chris Lattner7a60d912005-01-07 07:47:53 +0000223public:
224 // TLI - This is information that describes the available target features we
225 // need for lowering. This indicates when operations are unavailable,
226 // implemented with a libcall, etc.
227 TargetLowering &TLI;
228 SelectionDAG &DAG;
229 const TargetData &TD;
230
231 /// FuncInfo - Information about the function as a whole.
232 ///
233 FunctionLoweringInfo &FuncInfo;
234
235 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000236 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
238 FuncInfo(funcinfo) {
239 }
240
Chris Lattner4108bb02005-01-17 19:43:36 +0000241 /// getRoot - Return the current virtual root of the Selection DAG.
242 ///
243 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000244 if (PendingLoads.empty())
245 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000246
Chris Lattner4d9651c2005-01-17 22:19:26 +0000247 if (PendingLoads.size() == 1) {
248 SDOperand Root = PendingLoads[0];
249 DAG.setRoot(Root);
250 PendingLoads.clear();
251 return Root;
252 }
253
254 // Otherwise, we have to make a token factor node.
255 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
256 PendingLoads.clear();
257 DAG.setRoot(Root);
258 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000259 }
260
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 void visit(Instruction &I) { visit(I.getOpcode(), I); }
262
263 void visit(unsigned Opcode, User &I) {
264 switch (Opcode) {
265 default: assert(0 && "Unknown instruction type encountered!");
266 abort();
267 // Build the switch statement using the Instruction.def file.
268#define HANDLE_INST(NUM, OPCODE, CLASS) \
269 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
270#include "llvm/Instruction.def"
271 }
272 }
273
274 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
275
276
277 SDOperand getIntPtrConstant(uint64_t Val) {
278 return DAG.getConstant(Val, TLI.getPointerTy());
279 }
280
281 SDOperand getValue(const Value *V) {
282 SDOperand &N = NodeMap[V];
283 if (N.Val) return N;
284
285 MVT::ValueType VT = TLI.getValueType(V->getType());
286 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
287 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
288 visit(CE->getOpcode(), *CE);
289 assert(N.Val && "visit didn't populate the ValueMap!");
290 return N;
291 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
292 return N = DAG.getGlobalAddress(GV, VT);
293 } else if (isa<ConstantPointerNull>(C)) {
294 return N = DAG.getConstant(0, TLI.getPointerTy());
295 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000296 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000297 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
298 return N = DAG.getConstantFP(CFP->getValue(), VT);
299 } else {
300 // Canonicalize all constant ints to be unsigned.
301 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
302 }
303
304 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
305 std::map<const AllocaInst*, int>::iterator SI =
306 FuncInfo.StaticAllocaMap.find(AI);
307 if (SI != FuncInfo.StaticAllocaMap.end())
308 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
309 }
310
311 std::map<const Value*, unsigned>::const_iterator VMI =
312 FuncInfo.ValueMap.find(V);
313 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000314
Chris Lattner33182322005-08-16 21:55:35 +0000315 unsigned InReg = VMI->second;
316
317 // If this type is not legal, make it so now.
318 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
319
320 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
321 if (DestVT < VT) {
322 // Source must be expanded. This input value is actually coming from the
323 // register pair VMI->second and VMI->second+1.
324 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
325 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
326 } else {
327 if (DestVT > VT) { // Promotion case
328 if (MVT::isFloatingPoint(VT))
329 N = DAG.getNode(ISD::FP_ROUND, VT, N);
330 else
331 N = DAG.getNode(ISD::TRUNCATE, VT, N);
332 }
333 }
334
335 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000336 }
337
338 const SDOperand &setValue(const Value *V, SDOperand NewN) {
339 SDOperand &N = NodeMap[V];
340 assert(N.Val == 0 && "Already set a value for this node!");
341 return N = NewN;
342 }
343
344 // Terminator instructions.
345 void visitRet(ReturnInst &I);
346 void visitBr(BranchInst &I);
347 void visitUnreachable(UnreachableInst &I) { /* noop */ }
348
349 // These all get lowered before this pass.
350 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
351 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
352 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
353
354 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000355 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000356 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000357 void visitAdd(User &I) {
358 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000359 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000360 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000361 void visitMul(User &I) {
362 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000363 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000364 void visitDiv(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::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000367 }
368 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000369 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000370 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000371 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000372 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
373 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
374 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000375 void visitShl(User &I) { visitShift(I, ISD::SHL); }
376 void visitShr(User &I) {
377 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000378 }
379
380 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
381 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
382 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
383 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
384 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
385 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
386 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
387
388 void visitGetElementPtr(User &I);
389 void visitCast(User &I);
390 void visitSelect(User &I);
391 //
392
393 void visitMalloc(MallocInst &I);
394 void visitFree(FreeInst &I);
395 void visitAlloca(AllocaInst &I);
396 void visitLoad(LoadInst &I);
397 void visitStore(StoreInst &I);
398 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
399 void visitCall(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000400 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000401
Chris Lattner7a60d912005-01-07 07:47:53 +0000402 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000403 void visitVAArg(VAArgInst &I);
404 void visitVAEnd(CallInst &I);
405 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000406 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407
Chris Lattner875def92005-01-11 05:56:49 +0000408 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000409
410 void visitUserOp1(Instruction &I) {
411 assert(0 && "UserOp1 should not exist at instruction selection time!");
412 abort();
413 }
414 void visitUserOp2(Instruction &I) {
415 assert(0 && "UserOp2 should not exist at instruction selection time!");
416 abort();
417 }
418};
419} // end namespace llvm
420
421void SelectionDAGLowering::visitRet(ReturnInst &I) {
422 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000423 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000424 return;
425 }
426
427 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000428 MVT::ValueType TmpVT;
429
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 switch (Op1.getValueType()) {
431 default: assert(0 && "Unknown value type!");
432 case MVT::i1:
433 case MVT::i8:
434 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000435 case MVT::i32:
436 // If this is a machine where 32-bits is legal or expanded, promote to
437 // 32-bits, otherwise, promote to 64-bits.
438 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
439 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000441 TmpVT = MVT::i32;
442
443 // Extend integer types to result type.
444 if (I.getOperand(0)->getType()->isSigned())
445 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
446 else
447 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 break;
449 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 case MVT::i64:
451 case MVT::f64:
452 break; // No extension needed!
453 }
Nate Begeman78afac22005-10-18 23:23:37 +0000454 // Allow targets to lower this further to meet ABI requirements
455 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000456}
457
458void SelectionDAGLowering::visitBr(BranchInst &I) {
459 // Update machine-CFG edges.
460 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000461
462 // Figure out which block is immediately after the current one.
463 MachineBasicBlock *NextBlock = 0;
464 MachineFunction::iterator BBI = CurMBB;
465 if (++BBI != CurMBB->getParent()->end())
466 NextBlock = BBI;
467
468 if (I.isUnconditional()) {
469 // If this is not a fall-through branch, emit the branch.
470 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000471 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000472 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 } else {
474 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000475
476 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000477 if (Succ1MBB == NextBlock) {
478 // If the condition is false, fall through. This means we should branch
479 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000480 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000481 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000482 } else if (Succ0MBB == NextBlock) {
483 // If the condition is true, fall through. This means we should branch if
484 // the condition is false to Succ #1. Invert the condition first.
485 SDOperand True = DAG.getConstant(1, Cond.getValueType());
486 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000487 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000488 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000490 std::vector<SDOperand> Ops;
491 Ops.push_back(getRoot());
492 Ops.push_back(Cond);
493 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
494 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
495 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000496 }
497 }
498}
499
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000500void SelectionDAGLowering::visitSub(User &I) {
501 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000502 if (I.getType()->isFloatingPoint()) {
503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
504 if (CFP->isExactlyValue(-0.0)) {
505 SDOperand Op2 = getValue(I.getOperand(1));
506 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
507 return;
508 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000509 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000510 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000511}
512
Nate Begemanb2e089c2005-11-19 00:36:38 +0000513void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
514 unsigned VecOp) {
515 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 SDOperand Op1 = getValue(I.getOperand(0));
517 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000518
Chris Lattner19baba62005-11-19 18:40:42 +0000519 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000520 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
521 } else if (Ty->isFloatingPoint()) {
522 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
523 } else {
524 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000525 unsigned NumElements = PTy->getNumElements();
526 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000527 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000528
529 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000530 // the Legalize pass does not have to deal with them. Similarly, if the
531 // abstract vector is going to turn into one that the target natively
532 // supports, generate that type now so that Legalize doesn't have to deal
533 // with that either. These steps ensure that Legalize only has to handle
534 // vector types in its Expand case.
535 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000536 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000537 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000538 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
539 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000540 } else {
541 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
542 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000543 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000544 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000545 }
Nate Begeman127321b2005-11-18 07:42:56 +0000546}
Chris Lattner96c26752005-01-19 22:31:21 +0000547
Nate Begeman127321b2005-11-18 07:42:56 +0000548void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
549 SDOperand Op1 = getValue(I.getOperand(0));
550 SDOperand Op2 = getValue(I.getOperand(1));
551
552 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
553
Chris Lattner7a60d912005-01-07 07:47:53 +0000554 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
555}
556
557void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
558 ISD::CondCode UnsignedOpcode) {
559 SDOperand Op1 = getValue(I.getOperand(0));
560 SDOperand Op2 = getValue(I.getOperand(1));
561 ISD::CondCode Opcode = SignedOpcode;
562 if (I.getOperand(0)->getType()->isUnsigned())
563 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000564 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000565}
566
567void SelectionDAGLowering::visitSelect(User &I) {
568 SDOperand Cond = getValue(I.getOperand(0));
569 SDOperand TrueVal = getValue(I.getOperand(1));
570 SDOperand FalseVal = getValue(I.getOperand(2));
571 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
572 TrueVal, FalseVal));
573}
574
575void SelectionDAGLowering::visitCast(User &I) {
576 SDOperand N = getValue(I.getOperand(0));
577 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
578 MVT::ValueType DestTy = TLI.getValueType(I.getType());
579
580 if (N.getValueType() == DestTy) {
581 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000582 } else if (DestTy == MVT::i1) {
583 // Cast to bool is a comparison against zero, not truncation to zero.
584 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
585 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000586 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000587 } else if (isInteger(SrcTy)) {
588 if (isInteger(DestTy)) { // Int -> Int cast
589 if (DestTy < SrcTy) // Truncating cast?
590 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
591 else if (I.getOperand(0)->getType()->isSigned())
592 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
593 else
594 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
595 } else { // Int -> FP cast
596 if (I.getOperand(0)->getType()->isSigned())
597 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
598 else
599 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
600 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000602 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
603 if (isFloatingPoint(DestTy)) { // FP -> FP cast
604 if (DestTy < SrcTy) // Rounding cast?
605 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
606 else
607 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
608 } else { // FP -> Int cast.
609 if (I.getType()->isSigned())
610 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
611 else
612 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
613 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000614 }
615}
616
617void SelectionDAGLowering::visitGetElementPtr(User &I) {
618 SDOperand N = getValue(I.getOperand(0));
619 const Type *Ty = I.getOperand(0)->getType();
620 const Type *UIntPtrTy = TD.getIntPtrType();
621
622 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
623 OI != E; ++OI) {
624 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000625 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000626 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
627 if (Field) {
628 // N = N + Offset
629 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
630 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000631 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000632 }
633 Ty = StTy->getElementType(Field);
634 } else {
635 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000636
Chris Lattner43535a12005-11-09 04:45:33 +0000637 // If this is a constant subscript, handle it quickly.
638 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
639 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000640
Chris Lattner43535a12005-11-09 04:45:33 +0000641 uint64_t Offs;
642 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
643 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
644 else
645 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
646 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
647 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000648 }
Chris Lattner43535a12005-11-09 04:45:33 +0000649
650 // N = N + Idx * ElementSize;
651 uint64_t ElementSize = TD.getTypeSize(Ty);
652 SDOperand IdxN = getValue(Idx);
653
654 // If the index is smaller or larger than intptr_t, truncate or extend
655 // it.
656 if (IdxN.getValueType() < N.getValueType()) {
657 if (Idx->getType()->isSigned())
658 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
659 else
660 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
661 } else if (IdxN.getValueType() > N.getValueType())
662 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
663
664 // If this is a multiply by a power of two, turn it into a shl
665 // immediately. This is a very common case.
666 if (isPowerOf2_64(ElementSize)) {
667 unsigned Amt = Log2_64(ElementSize);
668 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000669 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000670 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
671 continue;
672 }
673
674 SDOperand Scale = getIntPtrConstant(ElementSize);
675 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
676 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000677 }
678 }
679 setValue(&I, N);
680}
681
682void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
683 // If this is a fixed sized alloca in the entry block of the function,
684 // allocate it statically on the stack.
685 if (FuncInfo.StaticAllocaMap.count(&I))
686 return; // getValue will auto-populate this.
687
688 const Type *Ty = I.getAllocatedType();
689 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000690 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
691 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000692
693 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000694 MVT::ValueType IntPtr = TLI.getPointerTy();
695 if (IntPtr < AllocSize.getValueType())
696 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
697 else if (IntPtr > AllocSize.getValueType())
698 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000699
Chris Lattnereccb73d2005-01-22 23:04:37 +0000700 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000701 getIntPtrConstant(TySize));
702
703 // Handle alignment. If the requested alignment is less than or equal to the
704 // stack alignment, ignore it and round the size of the allocation up to the
705 // stack alignment size. If the size is greater than the stack alignment, we
706 // note this in the DYNAMIC_STACKALLOC node.
707 unsigned StackAlign =
708 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
709 if (Align <= StackAlign) {
710 Align = 0;
711 // Add SA-1 to the size.
712 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
713 getIntPtrConstant(StackAlign-1));
714 // Mask out the low bits for alignment purposes.
715 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
716 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
717 }
718
Chris Lattner96c262e2005-05-14 07:29:57 +0000719 std::vector<MVT::ValueType> VTs;
720 VTs.push_back(AllocSize.getValueType());
721 VTs.push_back(MVT::Other);
722 std::vector<SDOperand> Ops;
723 Ops.push_back(getRoot());
724 Ops.push_back(AllocSize);
725 Ops.push_back(getIntPtrConstant(Align));
726 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000727 DAG.setRoot(setValue(&I, DSA).getValue(1));
728
729 // Inform the Frame Information that we have just allocated a variable-sized
730 // object.
731 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
732}
733
Chris Lattner435b4022005-11-29 06:21:05 +0000734/// getStringValue - Turn an LLVM constant pointer that eventually points to a
735/// global into a string value. Return an empty string if we can't do it.
736///
737static std::string getStringValue(Value *V, unsigned Offset = 0) {
738 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
739 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
740 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
741 if (Init->isString()) {
742 std::string Result = Init->getAsString();
743 if (Offset < Result.size()) {
744 // If we are pointing INTO The string, erase the beginning...
745 Result.erase(Result.begin(), Result.begin()+Offset);
746
747 // Take off the null terminator, and any string fragments after it.
748 std::string::size_type NullPos = Result.find_first_of((char)0);
749 if (NullPos != std::string::npos)
750 Result.erase(Result.begin()+NullPos, Result.end());
751 return Result;
752 }
753 }
754 }
755 } else if (Constant *C = dyn_cast<Constant>(V)) {
756 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
757 return getStringValue(GV, Offset);
758 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
759 if (CE->getOpcode() == Instruction::GetElementPtr) {
760 // Turn a gep into the specified offset.
761 if (CE->getNumOperands() == 3 &&
762 cast<Constant>(CE->getOperand(1))->isNullValue() &&
763 isa<ConstantInt>(CE->getOperand(2))) {
764 return getStringValue(CE->getOperand(0),
765 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
766 }
767 }
768 }
769 }
770 return "";
771}
Chris Lattner7a60d912005-01-07 07:47:53 +0000772
773void SelectionDAGLowering::visitLoad(LoadInst &I) {
774 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000775
Chris Lattner4d9651c2005-01-17 22:19:26 +0000776 SDOperand Root;
777 if (I.isVolatile())
778 Root = getRoot();
779 else {
780 // Do not serialize non-volatile loads against each other.
781 Root = DAG.getRoot();
782 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000783
784 const Type *Ty = I.getType();
785 SDOperand L;
786
787 if (Type::PackedTyID == Ty->getTypeID()) {
788 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000789 unsigned NumElements = PTy->getNumElements();
790 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000791 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000792
793 // Immediately scalarize packed types containing only one element, so that
794 // the Legalize pass does not have to deal with them.
795 if (NumElements == 1) {
796 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000797 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
798 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000799 } else {
800 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
801 DAG.getSrcValue(I.getOperand(0)));
802 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000803 } else {
804 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
805 DAG.getSrcValue(I.getOperand(0)));
806 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000807 setValue(&I, L);
808
809 if (I.isVolatile())
810 DAG.setRoot(L.getValue(1));
811 else
812 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000813}
814
815
816void SelectionDAGLowering::visitStore(StoreInst &I) {
817 Value *SrcV = I.getOperand(0);
818 SDOperand Src = getValue(SrcV);
819 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000820 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000821 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000822}
823
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000824/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
825/// we want to emit this as a call to a named external function, return the name
826/// otherwise lower it and return null.
827const char *
828SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
829 switch (Intrinsic) {
830 case Intrinsic::vastart: visitVAStart(I); return 0;
831 case Intrinsic::vaend: visitVAEnd(I); return 0;
832 case Intrinsic::vacopy: visitVACopy(I); return 0;
833 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
834 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
835 case Intrinsic::setjmp:
836 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
837 break;
838 case Intrinsic::longjmp:
839 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
840 break;
841 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
842 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
843 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
844
845 case Intrinsic::readport:
846 case Intrinsic::readio: {
847 std::vector<MVT::ValueType> VTs;
848 VTs.push_back(TLI.getValueType(I.getType()));
849 VTs.push_back(MVT::Other);
850 std::vector<SDOperand> Ops;
851 Ops.push_back(getRoot());
852 Ops.push_back(getValue(I.getOperand(1)));
853 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
854 ISD::READPORT : ISD::READIO, VTs, Ops);
855
856 setValue(&I, Tmp);
857 DAG.setRoot(Tmp.getValue(1));
858 return 0;
859 }
860 case Intrinsic::writeport:
861 case Intrinsic::writeio:
862 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
863 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
864 getRoot(), getValue(I.getOperand(1)),
865 getValue(I.getOperand(2))));
866 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000867
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000868 case Intrinsic::dbg_stoppoint:
Chris Lattner435b4022005-11-29 06:21:05 +0000869 {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000870 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
871 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000872
873 std::string fname = "<unknown>";
874 std::vector<SDOperand> Ops;
875
876 // Pull the filename out of the the compilation unit.
877 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
878 if (cunit && cunit->hasInitializer()) {
879 ConstantStruct *CS = dyn_cast<ConstantStruct>(cunit->getInitializer());
880 if (CS->getNumOperands() > 0) {
881 std::string dirname = getStringValue(CS->getOperand(4));
882 fname = dirname + "/" + getStringValue(CS->getOperand(3));
883 }
884 }
885 // Input Chain
886 Ops.push_back(getRoot());
887
888 // line number
889 Ops.push_back(getValue(I.getOperand(2)));
890
891 // column
892 Ops.push_back(getValue(I.getOperand(3)));
893
894 // filename
895 Ops.push_back(DAG.getString(fname));
896 Ops.push_back(DAG.getString(""));
897 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner8782b782005-12-03 18:50:48 +0000898 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000899 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000900 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000901 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000902 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
903 return "llvm_dbg_region_start";
904 if (I.getType() != Type::VoidTy)
905 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
906 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000907 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000908 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
909 return "llvm_dbg_region_end";
910 if (I.getType() != Type::VoidTy)
911 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
912 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000913 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000914 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
915 return "llvm_dbg_subprogram";
916 if (I.getType() != Type::VoidTy)
917 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
918 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000919 case Intrinsic::dbg_declare:
920 if (I.getType() != Type::VoidTy)
921 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
922 return 0;
923
924 case Intrinsic::isunordered:
925 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
926 getValue(I.getOperand(2)), ISD::SETUO));
927 return 0;
928
929 case Intrinsic::sqrt:
930 setValue(&I, DAG.getNode(ISD::FSQRT,
931 getValue(I.getOperand(1)).getValueType(),
932 getValue(I.getOperand(1))));
933 return 0;
934 case Intrinsic::pcmarker: {
935 SDOperand Tmp = getValue(I.getOperand(1));
936 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
937 return 0;
938 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000939 case Intrinsic::readcyclecounter: {
940 std::vector<MVT::ValueType> VTs;
941 VTs.push_back(MVT::i64);
942 VTs.push_back(MVT::Other);
943 std::vector<SDOperand> Ops;
944 Ops.push_back(getRoot());
945 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
946 setValue(&I, Tmp);
947 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000948 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000949 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000950 case Intrinsic::cttz:
951 setValue(&I, DAG.getNode(ISD::CTTZ,
952 getValue(I.getOperand(1)).getValueType(),
953 getValue(I.getOperand(1))));
954 return 0;
955 case Intrinsic::ctlz:
956 setValue(&I, DAG.getNode(ISD::CTLZ,
957 getValue(I.getOperand(1)).getValueType(),
958 getValue(I.getOperand(1))));
959 return 0;
960 case Intrinsic::ctpop:
961 setValue(&I, DAG.getNode(ISD::CTPOP,
962 getValue(I.getOperand(1)).getValueType(),
963 getValue(I.getOperand(1))));
964 return 0;
965 default:
966 std::cerr << I;
967 assert(0 && "This intrinsic is not implemented yet!");
968 return 0;
969 }
970}
971
972
Chris Lattner7a60d912005-01-07 07:47:53 +0000973void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000974 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000975 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +0000976 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000977 if (unsigned IID = F->getIntrinsicID()) {
978 RenameFn = visitIntrinsicCall(I, IID);
979 if (!RenameFn)
980 return;
981 } else { // Not an LLVM intrinsic.
982 const std::string &Name = F->getName();
983 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +0000984 if (I.getNumOperands() == 2 && // Basic sanity checks.
985 I.getOperand(1)->getType()->isFloatingPoint() &&
986 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000987 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000988 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
989 return;
990 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000991 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +0000992 if (I.getNumOperands() == 2 && // Basic sanity checks.
993 I.getOperand(1)->getType()->isFloatingPoint() &&
994 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000995 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000996 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
997 return;
998 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000999 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001000 if (I.getNumOperands() == 2 && // Basic sanity checks.
1001 I.getOperand(1)->getType()->isFloatingPoint() &&
1002 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001003 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001004 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1005 return;
1006 }
1007 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001008 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001009 }
Misha Brukman835702a2005-04-21 22:36:52 +00001010
Chris Lattner18d2b342005-01-08 22:48:57 +00001011 SDOperand Callee;
1012 if (!RenameFn)
1013 Callee = getValue(I.getOperand(0));
1014 else
1015 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001016 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001017 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001018 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1019 Value *Arg = I.getOperand(i);
1020 SDOperand ArgNode = getValue(Arg);
1021 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1022 }
Misha Brukman835702a2005-04-21 22:36:52 +00001023
Nate Begemanf6565252005-03-26 01:29:23 +00001024 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1025 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001026
Chris Lattner1f45cd72005-01-08 19:26:18 +00001027 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001028 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001029 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001030 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001031 setValue(&I, Result.first);
1032 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001033}
1034
1035void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1036 SDOperand Src = getValue(I.getOperand(0));
1037
1038 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001039
1040 if (IntPtr < Src.getValueType())
1041 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1042 else if (IntPtr > Src.getValueType())
1043 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001044
1045 // Scale the source by the type size.
1046 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1047 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1048 Src, getIntPtrConstant(ElementSize));
1049
1050 std::vector<std::pair<SDOperand, const Type*> > Args;
1051 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001052
1053 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001054 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001055 DAG.getExternalSymbol("malloc", IntPtr),
1056 Args, DAG);
1057 setValue(&I, Result.first); // Pointers always fit in registers
1058 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001059}
1060
1061void SelectionDAGLowering::visitFree(FreeInst &I) {
1062 std::vector<std::pair<SDOperand, const Type*> > Args;
1063 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1064 TLI.getTargetData().getIntPtrType()));
1065 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001066 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001067 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001068 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1069 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001070}
1071
Chris Lattner13d7c252005-08-26 20:54:47 +00001072// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1073// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1074// instructions are special in various ways, which require special support to
1075// insert. The specified MachineInstr is created but not inserted into any
1076// basic blocks, and the scheduler passes ownership of it to this method.
1077MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1078 MachineBasicBlock *MBB) {
1079 std::cerr << "If a target marks an instruction with "
1080 "'usesCustomDAGSchedInserter', it must implement "
1081 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1082 abort();
1083 return 0;
1084}
1085
Nate Begeman78afac22005-10-18 23:23:37 +00001086SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1087 SelectionDAG &DAG) {
1088 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1089}
1090
Chris Lattnerf5473e42005-07-05 19:57:53 +00001091SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1092 SDOperand VAListP, Value *VAListV,
1093 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001094 // We have no sane default behavior, just emit a useful error message and bail
1095 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001096 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001097 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001098 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001099}
1100
Chris Lattnerf5473e42005-07-05 19:57:53 +00001101SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001102 SelectionDAG &DAG) {
1103 // Default to a noop.
1104 return Chain;
1105}
1106
Chris Lattnerf5473e42005-07-05 19:57:53 +00001107SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1108 SDOperand SrcP, Value *SrcV,
1109 SDOperand DestP, Value *DestV,
1110 SelectionDAG &DAG) {
1111 // Default to copying the input list.
1112 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1113 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001114 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001115 Val, DestP, DAG.getSrcValue(DestV));
1116 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001117}
1118
1119std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001120TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1121 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001122 // We have no sane default behavior, just emit a useful error message and bail
1123 // out.
1124 std::cerr << "Variable arguments handling not implemented on this target!\n";
1125 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001126 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001127}
1128
1129
1130void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001131 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1132 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001133}
1134
1135void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1136 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001137 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001138 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001139 setValue(&I, Result.first);
1140 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001141}
1142
1143void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001144 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001145 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001146}
1147
1148void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001149 SDOperand Result =
1150 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1151 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1152 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001153}
1154
Chris Lattner58cfd792005-01-09 00:00:49 +00001155
1156// It is always conservatively correct for llvm.returnaddress and
1157// llvm.frameaddress to return 0.
1158std::pair<SDOperand, SDOperand>
1159TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1160 unsigned Depth, SelectionDAG &DAG) {
1161 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001162}
1163
Chris Lattner29dcc712005-05-14 05:50:48 +00001164SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001165 assert(0 && "LowerOperation not implemented for this target!");
1166 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001167 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001168}
1169
Chris Lattner58cfd792005-01-09 00:00:49 +00001170void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1171 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1172 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001173 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001174 setValue(&I, Result.first);
1175 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001176}
1177
Chris Lattner875def92005-01-11 05:56:49 +00001178void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer3fd1b4c2005-11-30 05:21:10 +00001179#if 0
1180 // If the size of the cpy/move/set is constant (known)
1181 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1182 uint64_t size = op3->getValue();
1183 switch (Op) {
1184 case ISD::MEMSET:
1185 if (size <= TLI.getMaxStoresPerMemSet()) {
1186 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1187 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1188 uint64_t align = op4.getValue();
1189 while (size > align) {
1190 size -=align;
1191 }
1192 Value *SrcV = I.getOperand(0);
1193 SDOperand Src = getValue(SrcV);
1194 SDOperand Ptr = getValue(I.getOperand(1));
1195 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1196 DAG.getSrcValue(I.getOperand(1))));
1197 }
1198 break;
1199 }
1200 break; // don't do this optimization, use a normal memset
1201 case ISD::MEMMOVE:
1202 case ISD::MEMCPY:
1203 break; // FIXME: not implemented yet
1204 }
1205 }
1206#endif
1207
1208 // Non-optimized version
Chris Lattner875def92005-01-11 05:56:49 +00001209 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001210 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001211 Ops.push_back(getValue(I.getOperand(1)));
1212 Ops.push_back(getValue(I.getOperand(2)));
1213 Ops.push_back(getValue(I.getOperand(3)));
1214 Ops.push_back(getValue(I.getOperand(4)));
1215 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001216}
1217
Chris Lattner875def92005-01-11 05:56:49 +00001218//===----------------------------------------------------------------------===//
1219// SelectionDAGISel code
1220//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001221
1222unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1223 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1224}
1225
Chris Lattnerc9950c12005-08-17 06:37:43 +00001226void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001227 // FIXME: we only modify the CFG to split critical edges. This
1228 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001229}
Chris Lattner7a60d912005-01-07 07:47:53 +00001230
Chris Lattner35397782005-12-05 07:10:48 +00001231
1232/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1233/// casting to the type of GEPI.
1234static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1235 Value *Ptr, Value *PtrOffset) {
1236 if (V) return V; // Already computed.
1237
1238 BasicBlock::iterator InsertPt;
1239 if (BB == GEPI->getParent()) {
1240 // If insert into the GEP's block, insert right after the GEP.
1241 InsertPt = GEPI;
1242 ++InsertPt;
1243 } else {
1244 // Otherwise, insert at the top of BB, after any PHI nodes
1245 InsertPt = BB->begin();
1246 while (isa<PHINode>(InsertPt)) ++InsertPt;
1247 }
1248
1249 // Add the offset, cast it to the right type.
1250 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1251 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1252 return V = Ptr;
1253}
1254
1255
1256/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1257/// selection, we want to be a bit careful about some things. In particular, if
1258/// we have a GEP instruction that is used in a different block than it is
1259/// defined, the addressing expression of the GEP cannot be folded into loads or
1260/// stores that use it. In this case, decompose the GEP and move constant
1261/// indices into blocks that use it.
1262static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1263 const TargetData &TD) {
1264 if (!GEPISelTest) return;
1265
1266 // If this GEP is only used inside the block it is defined in, there is no
1267 // need to rewrite it.
1268 bool isUsedOutsideDefBB = false;
1269 BasicBlock *DefBB = GEPI->getParent();
1270 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1271 UI != E; ++UI) {
1272 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1273 isUsedOutsideDefBB = true;
1274 break;
1275 }
1276 }
1277 if (!isUsedOutsideDefBB) return;
1278
1279 // If this GEP has no non-zero constant indices, there is nothing we can do,
1280 // ignore it.
1281 bool hasConstantIndex = false;
1282 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1283 E = GEPI->op_end(); OI != E; ++OI) {
1284 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1285 if (CI->getRawValue()) {
1286 hasConstantIndex = true;
1287 break;
1288 }
1289 }
1290 if (!hasConstantIndex) return;
1291
1292 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1293 // constant offset (which we now know is non-zero) and deal with it later.
1294 uint64_t ConstantOffset = 0;
1295 const Type *UIntPtrTy = TD.getIntPtrType();
1296 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1297 const Type *Ty = GEPI->getOperand(0)->getType();
1298
1299 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1300 E = GEPI->op_end(); OI != E; ++OI) {
1301 Value *Idx = *OI;
1302 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1303 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1304 if (Field)
1305 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1306 Ty = StTy->getElementType(Field);
1307 } else {
1308 Ty = cast<SequentialType>(Ty)->getElementType();
1309
1310 // Handle constant subscripts.
1311 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1312 if (CI->getRawValue() == 0) continue;
1313
1314 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1315 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1316 else
1317 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1318 continue;
1319 }
1320
1321 // Ptr = Ptr + Idx * ElementSize;
1322
1323 // Cast Idx to UIntPtrTy if needed.
1324 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1325
1326 uint64_t ElementSize = TD.getTypeSize(Ty);
1327 // Mask off bits that should not be set.
1328 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1329 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1330
1331 // Multiply by the element size and add to the base.
1332 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1333 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1334 }
1335 }
1336
1337 // Make sure that the offset fits in uintptr_t.
1338 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1339 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1340
1341 // Okay, we have now emitted all of the variable index parts to the BB that
1342 // the GEP is defined in. Loop over all of the using instructions, inserting
1343 // an "add Ptr, ConstantOffset" into each block that uses it and update the
1344 // instruction to use the newly computed value, making GEPI dead.
1345 std::map<BasicBlock*,Value*> InsertedExprs;
1346 while (!GEPI->use_empty()) {
1347 Instruction *User = cast<Instruction>(GEPI->use_back());
1348
1349 // Handle PHI's specially, as we need to insert code in the predecessor
1350 // blocks for uses, not in the PHI block.
1351 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1352 for (PHINode::op_iterator OI = PN->op_begin(), E = PN->op_end();
1353 OI != E; OI += 2) {
1354 if (*OI == GEPI) {
1355 BasicBlock *Pred = cast<BasicBlock>(OI[1]);
1356 *OI = InsertGEPComputeCode(InsertedExprs[Pred], Pred, GEPI,
1357 Ptr, PtrOffset);
1358 }
1359 }
1360 continue;
1361 }
1362
1363 // Otherwise, insert the code in the User's block so it can be folded into
1364 // any users in that block.
1365 Value *V = InsertGEPComputeCode(InsertedExprs[User->getParent()],
1366 User->getParent(), GEPI,
1367 Ptr, PtrOffset);
1368 User->replaceUsesOfWith(GEPI, V);
1369 }
1370
1371 // Finally, the GEP is dead, remove it.
1372 GEPI->eraseFromParent();
1373}
1374
Chris Lattner7a60d912005-01-07 07:47:53 +00001375bool SelectionDAGISel::runOnFunction(Function &Fn) {
1376 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1377 RegMap = MF.getSSARegMap();
1378 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1379
Chris Lattner35397782005-12-05 07:10:48 +00001380 // First, split all critical edges for PHI nodes with incoming values that are
1381 // constants, this way the load of the constant into a vreg will not be placed
1382 // into MBBs that are used some other way.
1383 //
1384 // In this pass we also look for GEP instructions that are used across basic
1385 // blocks and rewrites them to improve basic-block-at-a-time selection.
1386 //
Chris Lattner1a908c82005-08-18 17:35:14 +00001387 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1388 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00001389 BasicBlock::iterator BBI;
1390 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00001391 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1392 if (isa<Constant>(PN->getIncomingValue(i)))
1393 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00001394
1395 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1396 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1397 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00001398 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001399
Chris Lattner7a60d912005-01-07 07:47:53 +00001400 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1401
1402 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1403 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001404
Chris Lattner7a60d912005-01-07 07:47:53 +00001405 return true;
1406}
1407
1408
Chris Lattner718b5c22005-01-13 17:59:43 +00001409SDOperand SelectionDAGISel::
1410CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001411 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001412 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001413 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001414 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001415
1416 // If this type is not legal, we must make sure to not create an invalid
1417 // register use.
1418 MVT::ValueType SrcVT = Op.getValueType();
1419 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1420 SelectionDAG &DAG = SDL.DAG;
1421 if (SrcVT == DestVT) {
1422 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1423 } else if (SrcVT < DestVT) {
1424 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001425 if (MVT::isFloatingPoint(SrcVT))
1426 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1427 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001428 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001429 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1430 } else {
1431 // The src value is expanded into multiple registers.
1432 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1433 Op, DAG.getConstant(0, MVT::i32));
1434 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1435 Op, DAG.getConstant(1, MVT::i32));
1436 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1437 return DAG.getCopyToReg(Op, Reg+1, Hi);
1438 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001439}
1440
Chris Lattner16f64df2005-01-17 17:15:02 +00001441void SelectionDAGISel::
1442LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1443 std::vector<SDOperand> &UnorderedChains) {
1444 // If this is the entry block, emit arguments.
1445 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001446 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001447 SDOperand OldRoot = SDL.DAG.getRoot();
1448 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001449
Chris Lattner6871b232005-10-30 19:42:35 +00001450 unsigned a = 0;
1451 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1452 AI != E; ++AI, ++a)
1453 if (!AI->use_empty()) {
1454 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001455
Chris Lattner6871b232005-10-30 19:42:35 +00001456 // If this argument is live outside of the entry block, insert a copy from
1457 // whereever we got it to the vreg that other BB's will reference it as.
1458 if (FuncInfo.ValueMap.count(AI)) {
1459 SDOperand Copy =
1460 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1461 UnorderedChains.push_back(Copy);
1462 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001463 }
Chris Lattner6871b232005-10-30 19:42:35 +00001464
1465 // Next, if the function has live ins that need to be copied into vregs,
1466 // emit the copies now, into the top of the block.
1467 MachineFunction &MF = SDL.DAG.getMachineFunction();
1468 if (MF.livein_begin() != MF.livein_end()) {
1469 SSARegMap *RegMap = MF.getSSARegMap();
1470 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1471 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1472 E = MF.livein_end(); LI != E; ++LI)
1473 if (LI->second)
1474 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1475 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001476 }
Chris Lattner6871b232005-10-30 19:42:35 +00001477
1478 // Finally, if the target has anything special to do, allow it to do so.
1479 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001480}
1481
1482
Chris Lattner7a60d912005-01-07 07:47:53 +00001483void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1484 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1485 FunctionLoweringInfo &FuncInfo) {
1486 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001487
1488 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001489
Chris Lattner6871b232005-10-30 19:42:35 +00001490 // Lower any arguments needed in this block if this is the entry block.
1491 if (LLVMBB == &LLVMBB->getParent()->front())
1492 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001493
1494 BB = FuncInfo.MBBMap[LLVMBB];
1495 SDL.setCurrentBasicBlock(BB);
1496
1497 // Lower all of the non-terminator instructions.
1498 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1499 I != E; ++I)
1500 SDL.visit(*I);
1501
1502 // Ensure that all instructions which are used outside of their defining
1503 // blocks are available as virtual registers.
1504 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001505 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001506 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001507 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001508 UnorderedChains.push_back(
1509 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001510 }
1511
1512 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1513 // ensure constants are generated when needed. Remember the virtual registers
1514 // that need to be added to the Machine PHI nodes as input. We cannot just
1515 // directly add them, because expansion might result in multiple MBB's for one
1516 // BB. As such, the start of the BB might correspond to a different MBB than
1517 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001518 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001519
1520 // Emit constants only once even if used by multiple PHI nodes.
1521 std::map<Constant*, unsigned> ConstantsOut;
1522
1523 // Check successor nodes PHI nodes that expect a constant to be available from
1524 // this block.
1525 TerminatorInst *TI = LLVMBB->getTerminator();
1526 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1527 BasicBlock *SuccBB = TI->getSuccessor(succ);
1528 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1529 PHINode *PN;
1530
1531 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1532 // nodes and Machine PHI nodes, but the incoming operands have not been
1533 // emitted yet.
1534 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001535 (PN = dyn_cast<PHINode>(I)); ++I)
1536 if (!PN->use_empty()) {
1537 unsigned Reg;
1538 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1539 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1540 unsigned &RegOut = ConstantsOut[C];
1541 if (RegOut == 0) {
1542 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001543 UnorderedChains.push_back(
1544 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001545 }
1546 Reg = RegOut;
1547 } else {
1548 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001549 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001550 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001551 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1552 "Didn't codegen value into a register!??");
1553 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001554 UnorderedChains.push_back(
1555 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001556 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001557 }
Misha Brukman835702a2005-04-21 22:36:52 +00001558
Chris Lattner8ea875f2005-01-07 21:34:19 +00001559 // Remember that this register needs to added to the machine PHI node as
1560 // the input for this MBB.
1561 unsigned NumElements =
1562 TLI.getNumElements(TLI.getValueType(PN->getType()));
1563 for (unsigned i = 0, e = NumElements; i != e; ++i)
1564 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001565 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001566 }
1567 ConstantsOut.clear();
1568
Chris Lattner718b5c22005-01-13 17:59:43 +00001569 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001570 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001571 SDOperand Root = SDL.getRoot();
1572 if (Root.getOpcode() != ISD::EntryToken) {
1573 unsigned i = 0, e = UnorderedChains.size();
1574 for (; i != e; ++i) {
1575 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1576 if (UnorderedChains[i].Val->getOperand(0) == Root)
1577 break; // Don't add the root if we already indirectly depend on it.
1578 }
1579
1580 if (i == e)
1581 UnorderedChains.push_back(Root);
1582 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001583 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1584 }
1585
Chris Lattner7a60d912005-01-07 07:47:53 +00001586 // Lower the terminator after the copies are emitted.
1587 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001588
1589 // Make sure the root of the DAG is up-to-date.
1590 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001591}
1592
1593void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1594 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001595 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001596 CurDAG = &DAG;
1597 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1598
1599 // First step, lower LLVM code to some DAG. This DAG may use operations and
1600 // types that are not supported by the target.
1601 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1602
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001603 // Run the DAG combiner in pre-legalize mode.
1604 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001605
Chris Lattner7a60d912005-01-07 07:47:53 +00001606 DEBUG(std::cerr << "Lowered selection DAG:\n");
1607 DEBUG(DAG.dump());
1608
1609 // Second step, hack on the DAG until it only uses operations and types that
1610 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001611 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001612
1613 DEBUG(std::cerr << "Legalized selection DAG:\n");
1614 DEBUG(DAG.dump());
1615
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001616 // Run the DAG combiner in post-legalize mode.
1617 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001618
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001619 if (ViewDAGs) DAG.viewGraph();
1620
Chris Lattner5ca31d92005-03-30 01:10:47 +00001621 // Third, instruction select all of the operations to machine code, adding the
1622 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001623 InstructionSelectBasicBlock(DAG);
1624
Chris Lattner7a60d912005-01-07 07:47:53 +00001625 DEBUG(std::cerr << "Selected machine code:\n");
1626 DEBUG(BB->dump());
1627
Chris Lattner5ca31d92005-03-30 01:10:47 +00001628 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001629 // PHI nodes in successors.
1630 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1631 MachineInstr *PHI = PHINodesToUpdate[i].first;
1632 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1633 "This is not a machine PHI node that we are updating!");
1634 PHI->addRegOperand(PHINodesToUpdate[i].second);
1635 PHI->addMachineBasicBlockOperand(BB);
1636 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001637
1638 // Finally, add the CFG edges from the last selected MBB to the successor
1639 // MBBs.
1640 TerminatorInst *TI = LLVMBB->getTerminator();
1641 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1642 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1643 BB->addSuccessor(Succ0MBB);
1644 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001645}