blob: 78f5623aed9d42ebcc0535fbcbe5387068bd9b5b [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"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
45using namespace llvm;
46
Chris Lattner975f5c92005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000048static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000049ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51static cl::opt<bool>
52ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000054#else
Evan Cheng739a6a42006-01-21 02:32:06 +000055static const bool ViewISelDAGs = 0;
56static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000057#endif
58
Evan Chengc1e1d972006-01-23 07:01:07 +000059namespace {
60 cl::opt<SchedHeuristics>
61 ISHeuristic(
62 "sched",
63 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000064 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000065 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000066 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000068 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000069 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000070 clEnumValN(simpleScheduling, "simple",
71 "Simple two pass scheduling: minimize critical path "
72 "and maximize processor utilization"),
73 clEnumValN(simpleNoItinScheduling, "simple-noitin",
74 "Simple two pass scheduling: Same as simple "
75 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000076 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000077 "Bottom up register reduction list scheduling"),
Evan Chengc1e1d972006-01-23 07:01:07 +000078 clEnumValEnd));
79} // namespace
80
81
Chris Lattner7a60d912005-01-07 07:47:53 +000082namespace llvm {
83 //===--------------------------------------------------------------------===//
84 /// FunctionLoweringInfo - This contains information that is global to a
85 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000086 class FunctionLoweringInfo {
87 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000088 TargetLowering &TLI;
89 Function &Fn;
90 MachineFunction &MF;
91 SSARegMap *RegMap;
92
93 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
94
95 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
96 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
97
98 /// ValueMap - Since we emit code for the function a basic block at a time,
99 /// we must remember which virtual registers hold the values for
100 /// cross-basic-block values.
101 std::map<const Value*, unsigned> ValueMap;
102
103 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
104 /// the entry block. This allows the allocas to be efficiently referenced
105 /// anywhere in the function.
106 std::map<const AllocaInst*, int> StaticAllocaMap;
107
108 unsigned MakeReg(MVT::ValueType VT) {
109 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
110 }
Misha Brukman835702a2005-04-21 22:36:52 +0000111
Chris Lattner7a60d912005-01-07 07:47:53 +0000112 unsigned CreateRegForValue(const Value *V) {
113 MVT::ValueType VT = TLI.getValueType(V->getType());
114 // The common case is that we will only create one register for this
115 // value. If we have that case, create and return the virtual register.
116 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000117 if (NV == 1) {
118 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000119 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000120 }
Misha Brukman835702a2005-04-21 22:36:52 +0000121
Chris Lattner7a60d912005-01-07 07:47:53 +0000122 // If this value is represented with multiple target registers, make sure
123 // to create enough consequtive registers of the right (smaller) type.
124 unsigned NT = VT-1; // Find the type to use.
125 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
126 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000127
Chris Lattner7a60d912005-01-07 07:47:53 +0000128 unsigned R = MakeReg((MVT::ValueType)NT);
129 for (unsigned i = 1; i != NV; ++i)
130 MakeReg((MVT::ValueType)NT);
131 return R;
132 }
Misha Brukman835702a2005-04-21 22:36:52 +0000133
Chris Lattner7a60d912005-01-07 07:47:53 +0000134 unsigned InitializeRegForValue(const Value *V) {
135 unsigned &R = ValueMap[V];
136 assert(R == 0 && "Already initialized this value register!");
137 return R = CreateRegForValue(V);
138 }
139 };
140}
141
142/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
143/// PHI nodes or outside of the basic block that defines it.
144static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
145 if (isa<PHINode>(I)) return true;
146 BasicBlock *BB = I->getParent();
147 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
148 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
149 return true;
150 return false;
151}
152
Chris Lattner6871b232005-10-30 19:42:35 +0000153/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
154/// entry block, return true.
155static bool isOnlyUsedInEntryBlock(Argument *A) {
156 BasicBlock *Entry = A->getParent()->begin();
157 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
158 if (cast<Instruction>(*UI)->getParent() != Entry)
159 return false; // Use not in entry block.
160 return true;
161}
162
Chris Lattner7a60d912005-01-07 07:47:53 +0000163FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000164 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000165 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
166
Chris Lattner6871b232005-10-30 19:42:35 +0000167 // Create a vreg for each argument register that is not dead and is used
168 // outside of the entry block for the function.
169 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
170 AI != E; ++AI)
171 if (!isOnlyUsedInEntryBlock(AI))
172 InitializeRegForValue(AI);
173
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 // Initialize the mapping of values to registers. This is only set up for
175 // instruction values that are used outside of the block that defines
176 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000177 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000178 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
179 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
180 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
181 const Type *Ty = AI->getAllocatedType();
182 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000183 unsigned Align =
184 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
185 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000186
187 // If the alignment of the value is smaller than the size of the value,
188 // and if the size of the value is particularly small (<= 8 bytes),
189 // round up to the size of the value for potentially better performance.
190 //
191 // FIXME: This could be made better with a preferred alignment hook in
192 // TargetData. It serves primarily to 8-byte align doubles for X86.
193 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000194 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000195 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000197 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000198 }
199
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000200 for (; BB != EB; ++BB)
201 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000202 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
203 if (!isa<AllocaInst>(I) ||
204 !StaticAllocaMap.count(cast<AllocaInst>(I)))
205 InitializeRegForValue(I);
206
207 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
208 // also creates the initial PHI MachineInstrs, though none of the input
209 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000210 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
212 MBBMap[BB] = MBB;
213 MF.getBasicBlockList().push_back(MBB);
214
215 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
216 // appropriate.
217 PHINode *PN;
218 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000219 (PN = dyn_cast<PHINode>(I)); ++I)
220 if (!PN->use_empty()) {
221 unsigned NumElements =
222 TLI.getNumElements(TLI.getValueType(PN->getType()));
223 unsigned PHIReg = ValueMap[PN];
224 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
225 for (unsigned i = 0; i != NumElements; ++i)
226 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
227 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 }
229}
230
231
232
233//===----------------------------------------------------------------------===//
234/// SelectionDAGLowering - This is the common target-independent lowering
235/// implementation that is parameterized by a TargetLowering object.
236/// Also, targets can overload any lowering method.
237///
238namespace llvm {
239class SelectionDAGLowering {
240 MachineBasicBlock *CurMBB;
241
242 std::map<const Value*, SDOperand> NodeMap;
243
Chris Lattner4d9651c2005-01-17 22:19:26 +0000244 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
245 /// them up and then emit token factor nodes when possible. This allows us to
246 /// get simple disambiguation between loads without worrying about alias
247 /// analysis.
248 std::vector<SDOperand> PendingLoads;
249
Chris Lattner7a60d912005-01-07 07:47:53 +0000250public:
251 // TLI - This is information that describes the available target features we
252 // need for lowering. This indicates when operations are unavailable,
253 // implemented with a libcall, etc.
254 TargetLowering &TLI;
255 SelectionDAG &DAG;
256 const TargetData &TD;
257
258 /// FuncInfo - Information about the function as a whole.
259 ///
260 FunctionLoweringInfo &FuncInfo;
261
262 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000263 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000264 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
265 FuncInfo(funcinfo) {
266 }
267
Chris Lattner4108bb02005-01-17 19:43:36 +0000268 /// getRoot - Return the current virtual root of the Selection DAG.
269 ///
270 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000271 if (PendingLoads.empty())
272 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000273
Chris Lattner4d9651c2005-01-17 22:19:26 +0000274 if (PendingLoads.size() == 1) {
275 SDOperand Root = PendingLoads[0];
276 DAG.setRoot(Root);
277 PendingLoads.clear();
278 return Root;
279 }
280
281 // Otherwise, we have to make a token factor node.
282 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
283 PendingLoads.clear();
284 DAG.setRoot(Root);
285 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000286 }
287
Chris Lattner7a60d912005-01-07 07:47:53 +0000288 void visit(Instruction &I) { visit(I.getOpcode(), I); }
289
290 void visit(unsigned Opcode, User &I) {
291 switch (Opcode) {
292 default: assert(0 && "Unknown instruction type encountered!");
293 abort();
294 // Build the switch statement using the Instruction.def file.
295#define HANDLE_INST(NUM, OPCODE, CLASS) \
296 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
297#include "llvm/Instruction.def"
298 }
299 }
300
301 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
302
303
304 SDOperand getIntPtrConstant(uint64_t Val) {
305 return DAG.getConstant(Val, TLI.getPointerTy());
306 }
307
308 SDOperand getValue(const Value *V) {
309 SDOperand &N = NodeMap[V];
310 if (N.Val) return N;
311
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000312 const Type *VTy = V->getType();
313 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000314 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
316 visit(CE->getOpcode(), *CE);
317 assert(N.Val && "visit didn't populate the ValueMap!");
318 return N;
319 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
320 return N = DAG.getGlobalAddress(GV, VT);
321 } else if (isa<ConstantPointerNull>(C)) {
322 return N = DAG.getConstant(0, TLI.getPointerTy());
323 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000324 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000325 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
326 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000327 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
328 unsigned NumElements = PTy->getNumElements();
329 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
330 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
331
332 // Now that we know the number and type of the elements, push a
333 // Constant or ConstantFP node onto the ops list for each element of
334 // the packed constant.
335 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000336 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
337 if (MVT::isFloatingPoint(PVT)) {
338 for (unsigned i = 0; i != NumElements; ++i) {
339 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
340 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
341 }
342 } else {
343 for (unsigned i = 0; i != NumElements; ++i) {
344 const ConstantIntegral *El =
345 cast<ConstantIntegral>(CP->getOperand(i));
346 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
347 }
348 }
349 } else {
350 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
351 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000352 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000353 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000354 else
Chris Lattner803a5752005-12-21 02:43:26 +0000355 Op = DAG.getConstant(0, PVT);
356 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000357 }
Chris Lattner803a5752005-12-21 02:43:26 +0000358
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000359 // Handle the case where we have a 1-element vector, in which
360 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000361 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000362 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000363 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
364 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
365 } else {
366 // If the packed type isn't legal, then create a ConstantVec node with
367 // generic Vector type instead.
368 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
369 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000370 } else {
371 // Canonicalize all constant ints to be unsigned.
372 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
373 }
374
375 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
376 std::map<const AllocaInst*, int>::iterator SI =
377 FuncInfo.StaticAllocaMap.find(AI);
378 if (SI != FuncInfo.StaticAllocaMap.end())
379 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
380 }
381
382 std::map<const Value*, unsigned>::const_iterator VMI =
383 FuncInfo.ValueMap.find(V);
384 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000385
Chris Lattner33182322005-08-16 21:55:35 +0000386 unsigned InReg = VMI->second;
387
388 // If this type is not legal, make it so now.
389 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
390
391 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
392 if (DestVT < VT) {
393 // Source must be expanded. This input value is actually coming from the
394 // register pair VMI->second and VMI->second+1.
395 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
396 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
397 } else {
398 if (DestVT > VT) { // Promotion case
399 if (MVT::isFloatingPoint(VT))
400 N = DAG.getNode(ISD::FP_ROUND, VT, N);
401 else
402 N = DAG.getNode(ISD::TRUNCATE, VT, N);
403 }
404 }
405
406 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000407 }
408
409 const SDOperand &setValue(const Value *V, SDOperand NewN) {
410 SDOperand &N = NodeMap[V];
411 assert(N.Val == 0 && "Already set a value for this node!");
412 return N = NewN;
413 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000414
415 unsigned GetAvailableRegister(bool OutReg, bool InReg,
416 const std::vector<unsigned> &RegChoices,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
Chris Lattner7a60d912005-01-07 07:47:53 +0000419
420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
424
425 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000426 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000427 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
429 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
430 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
431
432 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000433 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000434 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000435 void visitAdd(User &I) {
436 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000437 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000438 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000439 void visitMul(User &I) {
440 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000441 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000442 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000443 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000444 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 }
446 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000447 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000448 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000449 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000450 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
451 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
452 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000453 void visitShl(User &I) { visitShift(I, ISD::SHL); }
454 void visitShr(User &I) {
455 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 }
457
458 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
459 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
460 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
461 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
462 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
463 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
464 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
465
466 void visitGetElementPtr(User &I);
467 void visitCast(User &I);
468 void visitSelect(User &I);
469 //
470
471 void visitMalloc(MallocInst &I);
472 void visitFree(FreeInst &I);
473 void visitAlloca(AllocaInst &I);
474 void visitLoad(LoadInst &I);
475 void visitStore(StoreInst &I);
476 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
477 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000478 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000479 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000480
Chris Lattner7a60d912005-01-07 07:47:53 +0000481 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000482 void visitVAArg(VAArgInst &I);
483 void visitVAEnd(CallInst &I);
484 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000485 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000486
Chris Lattner875def92005-01-11 05:56:49 +0000487 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000488
489 void visitUserOp1(Instruction &I) {
490 assert(0 && "UserOp1 should not exist at instruction selection time!");
491 abort();
492 }
493 void visitUserOp2(Instruction &I) {
494 assert(0 && "UserOp2 should not exist at instruction selection time!");
495 abort();
496 }
497};
498} // end namespace llvm
499
500void SelectionDAGLowering::visitRet(ReturnInst &I) {
501 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000502 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000503 return;
504 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000505 std::vector<SDOperand> NewValues;
506 NewValues.push_back(getRoot());
507 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
508 SDOperand RetOp = getValue(I.getOperand(i));
509
510 // If this is an integer return value, we need to promote it ourselves to
511 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
512 // than sign/zero.
513 if (MVT::isInteger(RetOp.getValueType()) &&
514 RetOp.getValueType() < MVT::i64) {
515 MVT::ValueType TmpVT;
516 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
517 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
518 else
519 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000520
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000521 if (I.getOperand(i)->getType()->isSigned())
522 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
523 else
524 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
525 }
526 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000528 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000529}
530
531void SelectionDAGLowering::visitBr(BranchInst &I) {
532 // Update machine-CFG edges.
533 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000534
535 // Figure out which block is immediately after the current one.
536 MachineBasicBlock *NextBlock = 0;
537 MachineFunction::iterator BBI = CurMBB;
538 if (++BBI != CurMBB->getParent()->end())
539 NextBlock = BBI;
540
541 if (I.isUnconditional()) {
542 // If this is not a fall-through branch, emit the branch.
543 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000544 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000545 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000546 } else {
547 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000548
549 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000550 if (Succ1MBB == NextBlock) {
551 // If the condition is false, fall through. This means we should branch
552 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000553 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000554 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000555 } else if (Succ0MBB == NextBlock) {
556 // If the condition is true, fall through. This means we should branch if
557 // the condition is false to Succ #1. Invert the condition first.
558 SDOperand True = DAG.getConstant(1, Cond.getValueType());
559 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000560 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000561 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000562 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000563 std::vector<SDOperand> Ops;
564 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000565 // If the false case is the current basic block, then this is a self
566 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
567 // adds an extra instruction in the loop. Instead, invert the
568 // condition and emit "Loop: ... br!cond Loop; br Out.
569 if (CurMBB == Succ1MBB) {
570 std::swap(Succ0MBB, Succ1MBB);
571 SDOperand True = DAG.getConstant(1, Cond.getValueType());
572 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
573 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000574 Ops.push_back(Cond);
575 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
576 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
577 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000578 }
579 }
580}
581
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000582void SelectionDAGLowering::visitSub(User &I) {
583 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000584 if (I.getType()->isFloatingPoint()) {
585 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
586 if (CFP->isExactlyValue(-0.0)) {
587 SDOperand Op2 = getValue(I.getOperand(1));
588 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
589 return;
590 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000591 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000592 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000593}
594
Nate Begemanb2e089c2005-11-19 00:36:38 +0000595void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
596 unsigned VecOp) {
597 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000598 SDOperand Op1 = getValue(I.getOperand(0));
599 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000600
Chris Lattner19baba62005-11-19 18:40:42 +0000601 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000602 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
603 } else if (Ty->isFloatingPoint()) {
604 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
605 } else {
606 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000607 unsigned NumElements = PTy->getNumElements();
608 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000609 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000610
611 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000612 // the Legalize pass does not have to deal with them. Similarly, if the
613 // abstract vector is going to turn into one that the target natively
614 // supports, generate that type now so that Legalize doesn't have to deal
615 // with that either. These steps ensure that Legalize only has to handle
616 // vector types in its Expand case.
617 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000618 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000619 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000620 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
621 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000622 } else {
623 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
624 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000625 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000626 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000627 }
Nate Begeman127321b2005-11-18 07:42:56 +0000628}
Chris Lattner96c26752005-01-19 22:31:21 +0000629
Nate Begeman127321b2005-11-18 07:42:56 +0000630void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
631 SDOperand Op1 = getValue(I.getOperand(0));
632 SDOperand Op2 = getValue(I.getOperand(1));
633
634 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
635
Chris Lattner7a60d912005-01-07 07:47:53 +0000636 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
637}
638
639void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
640 ISD::CondCode UnsignedOpcode) {
641 SDOperand Op1 = getValue(I.getOperand(0));
642 SDOperand Op2 = getValue(I.getOperand(1));
643 ISD::CondCode Opcode = SignedOpcode;
644 if (I.getOperand(0)->getType()->isUnsigned())
645 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000646 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000647}
648
649void SelectionDAGLowering::visitSelect(User &I) {
650 SDOperand Cond = getValue(I.getOperand(0));
651 SDOperand TrueVal = getValue(I.getOperand(1));
652 SDOperand FalseVal = getValue(I.getOperand(2));
653 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
654 TrueVal, FalseVal));
655}
656
657void SelectionDAGLowering::visitCast(User &I) {
658 SDOperand N = getValue(I.getOperand(0));
659 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
660 MVT::ValueType DestTy = TLI.getValueType(I.getType());
661
662 if (N.getValueType() == DestTy) {
663 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000664 } else if (DestTy == MVT::i1) {
665 // Cast to bool is a comparison against zero, not truncation to zero.
666 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
667 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000668 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000669 } else if (isInteger(SrcTy)) {
670 if (isInteger(DestTy)) { // Int -> Int cast
671 if (DestTy < SrcTy) // Truncating cast?
672 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
673 else if (I.getOperand(0)->getType()->isSigned())
674 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
675 else
676 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
677 } else { // Int -> FP cast
678 if (I.getOperand(0)->getType()->isSigned())
679 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
680 else
681 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
682 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000683 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000684 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
685 if (isFloatingPoint(DestTy)) { // FP -> FP cast
686 if (DestTy < SrcTy) // Rounding cast?
687 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
688 else
689 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
690 } else { // FP -> Int cast.
691 if (I.getType()->isSigned())
692 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
693 else
694 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
695 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000696 }
697}
698
699void SelectionDAGLowering::visitGetElementPtr(User &I) {
700 SDOperand N = getValue(I.getOperand(0));
701 const Type *Ty = I.getOperand(0)->getType();
702 const Type *UIntPtrTy = TD.getIntPtrType();
703
704 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
705 OI != E; ++OI) {
706 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000707 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000708 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
709 if (Field) {
710 // N = N + Offset
711 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
712 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000713 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000714 }
715 Ty = StTy->getElementType(Field);
716 } else {
717 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000718
Chris Lattner43535a12005-11-09 04:45:33 +0000719 // If this is a constant subscript, handle it quickly.
720 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
721 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000722
Chris Lattner43535a12005-11-09 04:45:33 +0000723 uint64_t Offs;
724 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
725 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
726 else
727 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
728 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
729 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000730 }
Chris Lattner43535a12005-11-09 04:45:33 +0000731
732 // N = N + Idx * ElementSize;
733 uint64_t ElementSize = TD.getTypeSize(Ty);
734 SDOperand IdxN = getValue(Idx);
735
736 // If the index is smaller or larger than intptr_t, truncate or extend
737 // it.
738 if (IdxN.getValueType() < N.getValueType()) {
739 if (Idx->getType()->isSigned())
740 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
741 else
742 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
743 } else if (IdxN.getValueType() > N.getValueType())
744 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
745
746 // If this is a multiply by a power of two, turn it into a shl
747 // immediately. This is a very common case.
748 if (isPowerOf2_64(ElementSize)) {
749 unsigned Amt = Log2_64(ElementSize);
750 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000751 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000752 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
753 continue;
754 }
755
756 SDOperand Scale = getIntPtrConstant(ElementSize);
757 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
758 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000759 }
760 }
761 setValue(&I, N);
762}
763
764void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
765 // If this is a fixed sized alloca in the entry block of the function,
766 // allocate it statically on the stack.
767 if (FuncInfo.StaticAllocaMap.count(&I))
768 return; // getValue will auto-populate this.
769
770 const Type *Ty = I.getAllocatedType();
771 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000772 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
773 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000774
775 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000776 MVT::ValueType IntPtr = TLI.getPointerTy();
777 if (IntPtr < AllocSize.getValueType())
778 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
779 else if (IntPtr > AllocSize.getValueType())
780 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000781
Chris Lattnereccb73d2005-01-22 23:04:37 +0000782 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000783 getIntPtrConstant(TySize));
784
785 // Handle alignment. If the requested alignment is less than or equal to the
786 // stack alignment, ignore it and round the size of the allocation up to the
787 // stack alignment size. If the size is greater than the stack alignment, we
788 // note this in the DYNAMIC_STACKALLOC node.
789 unsigned StackAlign =
790 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
791 if (Align <= StackAlign) {
792 Align = 0;
793 // Add SA-1 to the size.
794 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
795 getIntPtrConstant(StackAlign-1));
796 // Mask out the low bits for alignment purposes.
797 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
798 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
799 }
800
Chris Lattner96c262e2005-05-14 07:29:57 +0000801 std::vector<MVT::ValueType> VTs;
802 VTs.push_back(AllocSize.getValueType());
803 VTs.push_back(MVT::Other);
804 std::vector<SDOperand> Ops;
805 Ops.push_back(getRoot());
806 Ops.push_back(AllocSize);
807 Ops.push_back(getIntPtrConstant(Align));
808 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000809 DAG.setRoot(setValue(&I, DSA).getValue(1));
810
811 // Inform the Frame Information that we have just allocated a variable-sized
812 // object.
813 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
814}
815
Chris Lattner435b4022005-11-29 06:21:05 +0000816/// getStringValue - Turn an LLVM constant pointer that eventually points to a
817/// global into a string value. Return an empty string if we can't do it.
818///
Evan Cheng6781b6e2006-02-15 21:59:04 +0000819static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
820 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
821 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
822 if (Init->isString()) {
823 std::string Result = Init->getAsString();
824 if (Offset < Result.size()) {
825 // If we are pointing INTO The string, erase the beginning...
826 Result.erase(Result.begin(), Result.begin()+Offset);
827 return Result;
Chris Lattner435b4022005-11-29 06:21:05 +0000828 }
829 }
830 }
831 return "";
832}
Chris Lattner7a60d912005-01-07 07:47:53 +0000833
834void SelectionDAGLowering::visitLoad(LoadInst &I) {
835 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000836
Chris Lattner4d9651c2005-01-17 22:19:26 +0000837 SDOperand Root;
838 if (I.isVolatile())
839 Root = getRoot();
840 else {
841 // Do not serialize non-volatile loads against each other.
842 Root = DAG.getRoot();
843 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000844
845 const Type *Ty = I.getType();
846 SDOperand L;
847
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000848 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000849 unsigned NumElements = PTy->getNumElements();
850 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000851 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000852
853 // Immediately scalarize packed types containing only one element, so that
854 // the Legalize pass does not have to deal with them.
855 if (NumElements == 1) {
856 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000857 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
858 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000859 } else {
860 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
861 DAG.getSrcValue(I.getOperand(0)));
862 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000863 } else {
864 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
865 DAG.getSrcValue(I.getOperand(0)));
866 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000867 setValue(&I, L);
868
869 if (I.isVolatile())
870 DAG.setRoot(L.getValue(1));
871 else
872 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000873}
874
875
876void SelectionDAGLowering::visitStore(StoreInst &I) {
877 Value *SrcV = I.getOperand(0);
878 SDOperand Src = getValue(SrcV);
879 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000880 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000881 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000882}
883
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000884/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
885/// we want to emit this as a call to a named external function, return the name
886/// otherwise lower it and return null.
887const char *
888SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
889 switch (Intrinsic) {
890 case Intrinsic::vastart: visitVAStart(I); return 0;
891 case Intrinsic::vaend: visitVAEnd(I); return 0;
892 case Intrinsic::vacopy: visitVACopy(I); return 0;
893 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
894 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
895 case Intrinsic::setjmp:
896 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
897 break;
898 case Intrinsic::longjmp:
899 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
900 break;
901 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
902 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
903 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
904
905 case Intrinsic::readport:
906 case Intrinsic::readio: {
907 std::vector<MVT::ValueType> VTs;
908 VTs.push_back(TLI.getValueType(I.getType()));
909 VTs.push_back(MVT::Other);
910 std::vector<SDOperand> Ops;
911 Ops.push_back(getRoot());
912 Ops.push_back(getValue(I.getOperand(1)));
913 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
914 ISD::READPORT : ISD::READIO, VTs, Ops);
915
916 setValue(&I, Tmp);
917 DAG.setRoot(Tmp.getValue(1));
918 return 0;
919 }
920 case Intrinsic::writeport:
921 case Intrinsic::writeio:
922 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
923 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
924 getRoot(), getValue(I.getOperand(1)),
925 getValue(I.getOperand(2))));
926 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000927
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000928 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000929 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
930 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000931
Jim Laskey5995d012006-02-11 01:01:30 +0000932 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
933 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
934 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +0000935
Jim Laskey5995d012006-02-11 01:01:30 +0000936 // Input Chain
937 Ops.push_back(getRoot());
938
939 // line number
940 Ops.push_back(getValue(I.getOperand(2)));
941
942 // column
943 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +0000944
Jim Laskey390c63e2006-02-13 12:50:39 +0000945 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +0000946 assert(DD && "Not a debug information descriptor");
947 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
948 assert(CompileUnit && "Not a compile unit");
949 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
950 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
951
952 if (Ops.size() == 5) // Found filename/workingdir.
953 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000954 }
955
Chris Lattner8782b782005-12-03 18:50:48 +0000956 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000957 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000958 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000959 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000960 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
961 return "llvm_dbg_region_start";
962 if (I.getType() != Type::VoidTy)
963 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
964 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000965 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000966 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
967 return "llvm_dbg_region_end";
968 if (I.getType() != Type::VoidTy)
969 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
970 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000971 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000972 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
973 return "llvm_dbg_subprogram";
974 if (I.getType() != Type::VoidTy)
975 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
976 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000977 case Intrinsic::dbg_declare:
978 if (I.getType() != Type::VoidTy)
979 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
980 return 0;
981
Reid Spencerb4f9a6f2006-01-16 21:12:35 +0000982 case Intrinsic::isunordered_f32:
983 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000984 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
985 getValue(I.getOperand(2)), ISD::SETUO));
986 return 0;
987
Reid Spencerb4f9a6f2006-01-16 21:12:35 +0000988 case Intrinsic::sqrt_f32:
989 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000990 setValue(&I, DAG.getNode(ISD::FSQRT,
991 getValue(I.getOperand(1)).getValueType(),
992 getValue(I.getOperand(1))));
993 return 0;
994 case Intrinsic::pcmarker: {
995 SDOperand Tmp = getValue(I.getOperand(1));
996 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
997 return 0;
998 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000999 case Intrinsic::readcyclecounter: {
1000 std::vector<MVT::ValueType> VTs;
1001 VTs.push_back(MVT::i64);
1002 VTs.push_back(MVT::Other);
1003 std::vector<SDOperand> Ops;
1004 Ops.push_back(getRoot());
1005 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1006 setValue(&I, Tmp);
1007 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001008 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001009 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001010 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001011 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001012 case Intrinsic::bswap_i64:
1013 setValue(&I, DAG.getNode(ISD::BSWAP,
1014 getValue(I.getOperand(1)).getValueType(),
1015 getValue(I.getOperand(1))));
1016 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001017 case Intrinsic::cttz_i8:
1018 case Intrinsic::cttz_i16:
1019 case Intrinsic::cttz_i32:
1020 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001021 setValue(&I, DAG.getNode(ISD::CTTZ,
1022 getValue(I.getOperand(1)).getValueType(),
1023 getValue(I.getOperand(1))));
1024 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001025 case Intrinsic::ctlz_i8:
1026 case Intrinsic::ctlz_i16:
1027 case Intrinsic::ctlz_i32:
1028 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001029 setValue(&I, DAG.getNode(ISD::CTLZ,
1030 getValue(I.getOperand(1)).getValueType(),
1031 getValue(I.getOperand(1))));
1032 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001033 case Intrinsic::ctpop_i8:
1034 case Intrinsic::ctpop_i16:
1035 case Intrinsic::ctpop_i32:
1036 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001037 setValue(&I, DAG.getNode(ISD::CTPOP,
1038 getValue(I.getOperand(1)).getValueType(),
1039 getValue(I.getOperand(1))));
1040 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001041 case Intrinsic::stacksave: {
1042 std::vector<MVT::ValueType> VTs;
1043 VTs.push_back(TLI.getPointerTy());
1044 VTs.push_back(MVT::Other);
1045 std::vector<SDOperand> Ops;
1046 Ops.push_back(getRoot());
1047 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1048 setValue(&I, Tmp);
1049 DAG.setRoot(Tmp.getValue(1));
1050 return 0;
1051 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001052 case Intrinsic::stackrestore: {
1053 SDOperand Tmp = getValue(I.getOperand(1));
1054 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001055 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001056 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001057 case Intrinsic::prefetch:
1058 // FIXME: Currently discarding prefetches.
1059 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001060 default:
1061 std::cerr << I;
1062 assert(0 && "This intrinsic is not implemented yet!");
1063 return 0;
1064 }
1065}
1066
1067
Chris Lattner7a60d912005-01-07 07:47:53 +00001068void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001069 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001070 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001071 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001072 if (unsigned IID = F->getIntrinsicID()) {
1073 RenameFn = visitIntrinsicCall(I, IID);
1074 if (!RenameFn)
1075 return;
1076 } else { // Not an LLVM intrinsic.
1077 const std::string &Name = F->getName();
1078 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001079 if (I.getNumOperands() == 2 && // Basic sanity checks.
1080 I.getOperand(1)->getType()->isFloatingPoint() &&
1081 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001082 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001083 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1084 return;
1085 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001086 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001087 if (I.getNumOperands() == 2 && // Basic sanity checks.
1088 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001089 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001090 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001091 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1092 return;
1093 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001094 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001095 if (I.getNumOperands() == 2 && // Basic sanity checks.
1096 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001097 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001098 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001099 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1100 return;
1101 }
1102 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001103 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001104 } else if (isa<InlineAsm>(I.getOperand(0))) {
1105 visitInlineAsm(I);
1106 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001107 }
Misha Brukman835702a2005-04-21 22:36:52 +00001108
Chris Lattner18d2b342005-01-08 22:48:57 +00001109 SDOperand Callee;
1110 if (!RenameFn)
1111 Callee = getValue(I.getOperand(0));
1112 else
1113 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001114 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001115 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001116 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1117 Value *Arg = I.getOperand(i);
1118 SDOperand ArgNode = getValue(Arg);
1119 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1120 }
Misha Brukman835702a2005-04-21 22:36:52 +00001121
Nate Begemanf6565252005-03-26 01:29:23 +00001122 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1123 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001124
Chris Lattner1f45cd72005-01-08 19:26:18 +00001125 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001126 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001127 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001128 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001129 setValue(&I, Result.first);
1130 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001131}
1132
Chris Lattner1558fc62006-02-01 18:59:47 +00001133/// GetAvailableRegister - Pick a register from RegChoices that is available
1134/// for input and/or output as specified by isOutReg/isInReg. If an allocatable
1135/// register is found, it is returned and added to the specified set of used
1136/// registers. If not, zero is returned.
1137unsigned SelectionDAGLowering::
1138GetAvailableRegister(bool isOutReg, bool isInReg,
1139 const std::vector<unsigned> &RegChoices,
1140 std::set<unsigned> &OutputRegs,
1141 std::set<unsigned> &InputRegs) {
1142 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1143 MachineFunction &MF = *CurMBB->getParent();
1144 for (unsigned i = 0, e = RegChoices.size(); i != e; ++i) {
1145 unsigned Reg = RegChoices[i];
1146 // See if this register is available.
1147 if (isOutReg && OutputRegs.count(Reg)) continue; // Already used.
1148 if (isInReg && InputRegs.count(Reg)) continue; // Already used.
1149
1150 // Check to see if this register is allocatable (i.e. don't give out the
1151 // stack pointer).
1152 bool Found = false;
1153 for (MRegisterInfo::regclass_iterator RC = MRI->regclass_begin(),
1154 E = MRI->regclass_end(); !Found && RC != E; ++RC) {
1155 // NOTE: This isn't ideal. In particular, this might allocate the
1156 // frame pointer in functions that need it (due to them not being taken
1157 // out of allocation, because a variable sized allocation hasn't been seen
1158 // yet). This is a slight code pessimization, but should still work.
1159 for (TargetRegisterClass::iterator I = (*RC)->allocation_order_begin(MF),
1160 E = (*RC)->allocation_order_end(MF); I != E; ++I)
1161 if (*I == Reg) {
1162 Found = true;
1163 break;
1164 }
1165 }
1166 if (!Found) continue;
1167
1168 // Okay, this register is good, return it.
1169 if (isOutReg) OutputRegs.insert(Reg); // Mark used.
1170 if (isInReg) InputRegs.insert(Reg); // Mark used.
1171 return Reg;
1172 }
1173 return 0;
1174}
1175
Chris Lattner476e67b2006-01-26 22:24:51 +00001176/// visitInlineAsm - Handle a call to an InlineAsm object.
1177///
1178void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1179 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1180
1181 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1182 MVT::Other);
1183
1184 // Note, we treat inline asms both with and without side-effects as the same.
1185 // If an inline asm doesn't have side effects and doesn't access memory, we
1186 // could not choose to not chain it.
1187 bool hasSideEffects = IA->hasSideEffects();
1188
Chris Lattner3a5ed552006-02-01 01:28:23 +00001189 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner476e67b2006-01-26 22:24:51 +00001190
1191 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1192 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1193 /// if it is a def of that register.
1194 std::vector<SDOperand> AsmNodeOperands;
1195 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1196 AsmNodeOperands.push_back(AsmStr);
1197
1198 SDOperand Chain = getRoot();
1199 SDOperand Flag;
1200
Chris Lattner2e56e892006-01-31 02:03:41 +00001201 // Loop over all of the inputs, copying the operand values into the
1202 // appropriate registers and processing the output regs.
1203 unsigned RetValReg = 0;
1204 std::vector<std::pair<unsigned, Value*> > IndirectStoresToEmit;
1205 unsigned OpNum = 1;
1206 bool FoundOutputConstraint = false;
Chris Lattner1558fc62006-02-01 18:59:47 +00001207
1208 // We fully assign registers here at isel time. This is not optimal, but
1209 // should work. For register classes that correspond to LLVM classes, we
1210 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1211 // over the constraints, collecting fixed registers that we know we can't use.
1212 std::set<unsigned> OutputRegs, InputRegs;
1213 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1214 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1215 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001216
Chris Lattner1558fc62006-02-01 18:59:47 +00001217 std::vector<unsigned> Regs =
1218 TLI.getRegForInlineAsmConstraint(ConstraintCode);
1219 if (Regs.size() != 1) continue; // Not assigned a fixed reg.
1220 unsigned TheReg = Regs[0];
1221
1222 switch (Constraints[i].Type) {
1223 case InlineAsm::isOutput:
1224 // We can't assign any other output to this register.
1225 OutputRegs.insert(TheReg);
1226 // If this is an early-clobber output, it cannot be assigned to the same
1227 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001228 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner1558fc62006-02-01 18:59:47 +00001229 InputRegs.insert(TheReg);
1230 break;
1231 case InlineAsm::isClobber:
1232 // Clobbered regs cannot be used as inputs or outputs.
1233 InputRegs.insert(TheReg);
1234 OutputRegs.insert(TheReg);
1235 break;
1236 case InlineAsm::isInput:
1237 // We can't assign any other input to this register.
1238 InputRegs.insert(TheReg);
1239 break;
1240 }
1241 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001242
Chris Lattner2e56e892006-01-31 02:03:41 +00001243 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001244 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1245 std::string &ConstraintCode = Constraints[i].Codes[0];
1246 switch (Constraints[i].Type) {
1247 case InlineAsm::isOutput: {
Chris Lattner2e56e892006-01-31 02:03:41 +00001248 // Copy the output from the appropriate register.
1249 std::vector<unsigned> Regs =
Chris Lattner3a5ed552006-02-01 01:28:23 +00001250 TLI.getRegForInlineAsmConstraint(ConstraintCode);
Chris Lattner1558fc62006-02-01 18:59:47 +00001251
1252 // Find a regsister that we can use.
1253 unsigned DestReg;
1254 if (Regs.size() == 1)
1255 DestReg = Regs[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001256 else {
1257 bool UsesInputRegister = false;
1258 // If this is an early-clobber output, or if there is an input
1259 // constraint that matches this, we need to reserve the input register
1260 // so no other inputs allocate to it.
1261 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1262 UsesInputRegister = true;
1263 DestReg = GetAvailableRegister(true, UsesInputRegister,
Chris Lattner1558fc62006-02-01 18:59:47 +00001264 Regs, OutputRegs, InputRegs);
Chris Lattner7f5880b2006-02-02 00:25:23 +00001265 }
1266
Chris Lattner1558fc62006-02-01 18:59:47 +00001267 assert(DestReg && "Couldn't allocate output reg!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001268
1269 const Type *OpTy;
1270 if (!Constraints[i].isIndirectOutput) {
1271 assert(!FoundOutputConstraint &&
1272 "Cannot have multiple output constraints yet!");
1273 FoundOutputConstraint = true;
1274 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1275
1276 RetValReg = DestReg;
1277 OpTy = I.getType();
1278 } else {
1279 IndirectStoresToEmit.push_back(std::make_pair(DestReg,
1280 I.getOperand(OpNum)));
1281 OpTy = I.getOperand(OpNum)->getType();
1282 OpTy = cast<PointerType>(OpTy)->getElementType();
1283 OpNum++; // Consumes a call operand.
1284 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001285
1286 // Add information to the INLINEASM node to know that this register is
1287 // set.
Chris Lattner3a5ed552006-02-01 01:28:23 +00001288 AsmNodeOperands.push_back(DAG.getRegister(DestReg,
1289 TLI.getValueType(OpTy)));
Chris Lattner2e56e892006-01-31 02:03:41 +00001290 AsmNodeOperands.push_back(DAG.getConstant(2, MVT::i32)); // ISDEF
Chris Lattner2e56e892006-01-31 02:03:41 +00001291
Chris Lattner2e56e892006-01-31 02:03:41 +00001292 break;
1293 }
1294 case InlineAsm::isInput: {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001295 Value *Operand = I.getOperand(OpNum);
1296 const Type *OpTy = Operand->getType();
Chris Lattner1558fc62006-02-01 18:59:47 +00001297 OpNum++; // Consumes a call operand.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001298
Chris Lattner1558fc62006-02-01 18:59:47 +00001299 unsigned SrcReg;
Chris Lattner65ad53f2006-02-04 02:16:44 +00001300 SDOperand ResOp;
1301 unsigned ResOpType;
1302 SDOperand InOperandVal = getValue(Operand);
1303
Chris Lattner7f5880b2006-02-02 00:25:23 +00001304 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1305 // If this is required to match an output register we have already set,
1306 // just use its register.
1307 unsigned OperandNo = atoi(ConstraintCode.c_str());
1308 SrcReg = cast<RegisterSDNode>(AsmNodeOperands[OperandNo*2+2])->getReg();
Chris Lattner65ad53f2006-02-04 02:16:44 +00001309 ResOp = DAG.getRegister(SrcReg, TLI.getValueType(OpTy));
1310 ResOpType = 1;
1311
1312 Chain = DAG.getCopyToReg(Chain, SrcReg, InOperandVal, Flag);
1313 Flag = Chain.getValue(1);
Chris Lattner7f5880b2006-02-02 00:25:23 +00001314 } else {
Chris Lattner65ad53f2006-02-04 02:16:44 +00001315 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1316 if (ConstraintCode.size() == 1) // not a physreg name.
1317 CTy = TLI.getConstraintType(ConstraintCode[0]);
1318
1319 switch (CTy) {
1320 default: assert(0 && "Unknown constraint type! FAIL!");
1321 case TargetLowering::C_RegisterClass: {
1322 // Copy the input into the appropriate register.
1323 std::vector<unsigned> Regs =
1324 TLI.getRegForInlineAsmConstraint(ConstraintCode);
1325 if (Regs.size() == 1)
1326 SrcReg = Regs[0];
1327 else
1328 SrcReg = GetAvailableRegister(false, true, Regs,
1329 OutputRegs, InputRegs);
1330 // FIXME: should be match fail.
1331 assert(SrcReg && "Wasn't able to allocate register!");
1332 Chain = DAG.getCopyToReg(Chain, SrcReg, InOperandVal, Flag);
1333 Flag = Chain.getValue(1);
1334
1335 ResOp = DAG.getRegister(SrcReg, TLI.getValueType(OpTy));
1336 ResOpType = 1;
1337 break;
1338 }
1339 case TargetLowering::C_Other:
1340 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1341 assert(0 && "MATCH FAIL!");
1342 ResOp = InOperandVal;
1343 ResOpType = 3;
1344 break;
1345 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00001346 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001347
Chris Lattner65ad53f2006-02-04 02:16:44 +00001348 // Add information to the INLINEASM node to know about this input.
1349 AsmNodeOperands.push_back(ResOp);
Chris Lattner3b484312006-02-04 02:26:14 +00001350 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
Chris Lattner2e56e892006-01-31 02:03:41 +00001351 break;
1352 }
1353 case InlineAsm::isClobber:
1354 // Nothing to do.
1355 break;
1356 }
1357 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001358
1359 // Finish up input operands.
1360 AsmNodeOperands[0] = Chain;
1361 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1362
1363 std::vector<MVT::ValueType> VTs;
1364 VTs.push_back(MVT::Other);
1365 VTs.push_back(MVT::Flag);
1366 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1367 Flag = Chain.getValue(1);
1368
Chris Lattner2e56e892006-01-31 02:03:41 +00001369 // If this asm returns a register value, copy the result from that register
1370 // and set it as the value of the call.
1371 if (RetValReg) {
1372 SDOperand Val = DAG.getCopyFromReg(Chain, RetValReg,
1373 TLI.getValueType(I.getType()), Flag);
1374 Chain = Val.getValue(1);
1375 Flag = Val.getValue(2);
1376 setValue(&I, Val);
1377 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001378
Chris Lattner2e56e892006-01-31 02:03:41 +00001379 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1380
1381 // Process indirect outputs, first output all of the flagged copies out of
1382 // physregs.
1383 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
1384 Value *Ptr = IndirectStoresToEmit[i].second;
1385 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1386 SDOperand Val = DAG.getCopyFromReg(Chain, IndirectStoresToEmit[i].first,
1387 TLI.getValueType(Ty), Flag);
1388 Chain = Val.getValue(1);
1389 Flag = Val.getValue(2);
1390 StoresToEmit.push_back(std::make_pair(Val, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001391 }
1392
1393 // Emit the non-flagged stores from the physregs.
1394 std::vector<SDOperand> OutChains;
1395 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1396 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1397 StoresToEmit[i].first,
1398 getValue(StoresToEmit[i].second),
1399 DAG.getSrcValue(StoresToEmit[i].second)));
1400 if (!OutChains.empty())
1401 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001402 DAG.setRoot(Chain);
1403}
1404
1405
Chris Lattner7a60d912005-01-07 07:47:53 +00001406void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1407 SDOperand Src = getValue(I.getOperand(0));
1408
1409 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001410
1411 if (IntPtr < Src.getValueType())
1412 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1413 else if (IntPtr > Src.getValueType())
1414 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001415
1416 // Scale the source by the type size.
1417 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1418 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1419 Src, getIntPtrConstant(ElementSize));
1420
1421 std::vector<std::pair<SDOperand, const Type*> > Args;
1422 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001423
1424 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001425 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001426 DAG.getExternalSymbol("malloc", IntPtr),
1427 Args, DAG);
1428 setValue(&I, Result.first); // Pointers always fit in registers
1429 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001430}
1431
1432void SelectionDAGLowering::visitFree(FreeInst &I) {
1433 std::vector<std::pair<SDOperand, const Type*> > Args;
1434 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1435 TLI.getTargetData().getIntPtrType()));
1436 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001437 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001438 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001439 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1440 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001441}
1442
Chris Lattner13d7c252005-08-26 20:54:47 +00001443// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1444// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1445// instructions are special in various ways, which require special support to
1446// insert. The specified MachineInstr is created but not inserted into any
1447// basic blocks, and the scheduler passes ownership of it to this method.
1448MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1449 MachineBasicBlock *MBB) {
1450 std::cerr << "If a target marks an instruction with "
1451 "'usesCustomDAGSchedInserter', it must implement "
1452 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1453 abort();
1454 return 0;
1455}
1456
Chris Lattner58cfd792005-01-09 00:00:49 +00001457void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001458 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1459 getValue(I.getOperand(1)),
1460 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001461}
1462
1463void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001464 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1465 getValue(I.getOperand(0)),
1466 DAG.getSrcValue(I.getOperand(0)));
1467 setValue(&I, V);
1468 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001469}
1470
1471void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001472 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1473 getValue(I.getOperand(1)),
1474 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001475}
1476
1477void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001478 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1479 getValue(I.getOperand(1)),
1480 getValue(I.getOperand(2)),
1481 DAG.getSrcValue(I.getOperand(1)),
1482 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001483}
1484
Chris Lattner58cfd792005-01-09 00:00:49 +00001485// It is always conservatively correct for llvm.returnaddress and
1486// llvm.frameaddress to return 0.
1487std::pair<SDOperand, SDOperand>
1488TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1489 unsigned Depth, SelectionDAG &DAG) {
1490 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001491}
1492
Chris Lattner29dcc712005-05-14 05:50:48 +00001493SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001494 assert(0 && "LowerOperation not implemented for this target!");
1495 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001496 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001497}
1498
Nate Begeman595ec732006-01-28 03:14:31 +00001499SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1500 SelectionDAG &DAG) {
1501 assert(0 && "CustomPromoteOperation not implemented for this target!");
1502 abort();
1503 return SDOperand();
1504}
1505
Chris Lattner58cfd792005-01-09 00:00:49 +00001506void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1507 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1508 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001509 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001510 setValue(&I, Result.first);
1511 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001512}
1513
Evan Cheng6781b6e2006-02-15 21:59:04 +00001514/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001515/// operand.
1516static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001517 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001518 MVT::ValueType CurVT = VT;
1519 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1520 uint64_t Val = C->getValue() & 255;
1521 unsigned Shift = 8;
1522 while (CurVT != MVT::i8) {
1523 Val = (Val << Shift) | Val;
1524 Shift <<= 1;
1525 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001526 }
1527 return DAG.getConstant(Val, VT);
1528 } else {
1529 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1530 unsigned Shift = 8;
1531 while (CurVT != MVT::i8) {
1532 Value =
1533 DAG.getNode(ISD::OR, VT,
1534 DAG.getNode(ISD::SHL, VT, Value,
1535 DAG.getConstant(Shift, MVT::i8)), Value);
1536 Shift <<= 1;
1537 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001538 }
1539
1540 return Value;
1541 }
1542}
1543
Evan Cheng6781b6e2006-02-15 21:59:04 +00001544/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1545/// used when a memcpy is turned into a memset when the source is a constant
1546/// string ptr.
1547static SDOperand getMemsetStringVal(MVT::ValueType VT,
1548 SelectionDAG &DAG, TargetLowering &TLI,
1549 std::string &Str, unsigned Offset) {
1550 MVT::ValueType CurVT = VT;
1551 uint64_t Val = 0;
1552 unsigned MSB = getSizeInBits(VT) / 8;
1553 if (TLI.isLittleEndian())
1554 Offset = Offset + MSB - 1;
1555 for (unsigned i = 0; i != MSB; ++i) {
1556 Val = (Val << 8) | Str[Offset];
1557 Offset += TLI.isLittleEndian() ? -1 : 1;
1558 }
1559 return DAG.getConstant(Val, VT);
1560}
1561
Evan Cheng81fcea82006-02-14 08:22:34 +00001562/// getMemBasePlusOffset - Returns base and offset node for the
1563static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1564 SelectionDAG &DAG, TargetLowering &TLI) {
1565 MVT::ValueType VT = Base.getValueType();
1566 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1567}
1568
Evan Chengdb2a7a72006-02-14 20:12:38 +00001569/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001570/// to replace the memset / memcpy is below the threshold. It also returns the
1571/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001572static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1573 unsigned Limit, uint64_t Size,
1574 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001575 MVT::ValueType VT;
1576
1577 if (TLI.allowsUnalignedMemoryAccesses()) {
1578 VT = MVT::i64;
1579 } else {
1580 switch (Align & 7) {
1581 case 0:
1582 VT = MVT::i64;
1583 break;
1584 case 4:
1585 VT = MVT::i32;
1586 break;
1587 case 2:
1588 VT = MVT::i16;
1589 break;
1590 default:
1591 VT = MVT::i8;
1592 break;
1593 }
1594 }
1595
Evan Chengd5026102006-02-14 09:11:59 +00001596 MVT::ValueType LVT = MVT::i64;
1597 while (!TLI.isTypeLegal(LVT))
1598 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1599 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001600
Evan Chengd5026102006-02-14 09:11:59 +00001601 if (VT > LVT)
1602 VT = LVT;
1603
Evan Cheng04514992006-02-14 23:05:54 +00001604 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001605 while (Size != 0) {
1606 unsigned VTSize = getSizeInBits(VT) / 8;
1607 while (VTSize > Size) {
1608 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001609 VTSize >>= 1;
1610 }
Evan Chengd5026102006-02-14 09:11:59 +00001611 assert(MVT::isInteger(VT));
1612
1613 if (++NumMemOps > Limit)
1614 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001615 MemOps.push_back(VT);
1616 Size -= VTSize;
1617 }
Evan Chengd5026102006-02-14 09:11:59 +00001618
1619 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001620}
1621
Chris Lattner875def92005-01-11 05:56:49 +00001622void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001623 SDOperand Op1 = getValue(I.getOperand(1));
1624 SDOperand Op2 = getValue(I.getOperand(2));
1625 SDOperand Op3 = getValue(I.getOperand(3));
1626 SDOperand Op4 = getValue(I.getOperand(4));
1627 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1628 if (Align == 0) Align = 1;
1629
1630 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1631 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001632
1633 // Expand memset / memcpy to a series of load / store ops
1634 // if the size operand falls below a certain threshold.
1635 std::vector<SDOperand> OutChains;
1636 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001637 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001638 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001639 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1640 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001641 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001642 unsigned Offset = 0;
1643 for (unsigned i = 0; i < NumMemOps; i++) {
1644 MVT::ValueType VT = MemOps[i];
1645 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001646 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001647 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1648 Value,
1649 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1650 DAG.getSrcValue(I.getOperand(1), Offset));
1651 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001652 Offset += VTSize;
1653 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001654 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001655 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001656 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001657 case ISD::MEMCPY: {
1658 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1659 Size->getValue(), Align, TLI)) {
1660 unsigned NumMemOps = MemOps.size();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001661 unsigned SrcOff = 0, DstOff = 0;
1662 GlobalAddressSDNode *G = NULL;
1663 std::string Str;
1664
1665 if (Op2.getOpcode() == ISD::GlobalAddress)
1666 G = cast<GlobalAddressSDNode>(Op2);
1667 else if (Op2.getOpcode() == ISD::ADD &&
1668 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1669 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1670 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
1671 SrcOff += cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
1672 }
1673 if (G) {
1674 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
1675 if (GV)
1676 Str = getStringValue(GV);
1677 }
1678
Evan Chenge2038bd2006-02-15 01:54:51 +00001679 for (unsigned i = 0; i < NumMemOps; i++) {
1680 MVT::ValueType VT = MemOps[i];
1681 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001682 SDOperand Value, Chain, Store;
1683
1684 if (!Str.empty()) {
1685 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1686 Chain = getRoot();
1687 Store =
1688 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1689 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1690 DAG.getSrcValue(I.getOperand(1), DstOff));
1691 } else {
1692 Value = DAG.getLoad(VT, getRoot(),
1693 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1694 DAG.getSrcValue(I.getOperand(2), SrcOff));
1695 Chain = Value.getValue(1);
1696 Store =
1697 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1698 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1699 DAG.getSrcValue(I.getOperand(1), DstOff));
1700 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001701 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00001702 SrcOff += VTSize;
1703 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00001704 }
1705 }
1706 break;
1707 }
1708 }
1709
1710 if (!OutChains.empty()) {
1711 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1712 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00001713 }
1714 }
1715
Chris Lattner875def92005-01-11 05:56:49 +00001716 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001717 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00001718 Ops.push_back(Op1);
1719 Ops.push_back(Op2);
1720 Ops.push_back(Op3);
1721 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00001722 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001723}
1724
Chris Lattner875def92005-01-11 05:56:49 +00001725//===----------------------------------------------------------------------===//
1726// SelectionDAGISel code
1727//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001728
1729unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1730 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1731}
1732
Chris Lattnerc9950c12005-08-17 06:37:43 +00001733void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001734 // FIXME: we only modify the CFG to split critical edges. This
1735 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001736}
Chris Lattner7a60d912005-01-07 07:47:53 +00001737
Chris Lattner35397782005-12-05 07:10:48 +00001738
1739/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1740/// casting to the type of GEPI.
1741static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1742 Value *Ptr, Value *PtrOffset) {
1743 if (V) return V; // Already computed.
1744
1745 BasicBlock::iterator InsertPt;
1746 if (BB == GEPI->getParent()) {
1747 // If insert into the GEP's block, insert right after the GEP.
1748 InsertPt = GEPI;
1749 ++InsertPt;
1750 } else {
1751 // Otherwise, insert at the top of BB, after any PHI nodes
1752 InsertPt = BB->begin();
1753 while (isa<PHINode>(InsertPt)) ++InsertPt;
1754 }
1755
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001756 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1757 // BB so that there is only one value live across basic blocks (the cast
1758 // operand).
1759 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1760 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1761 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1762
Chris Lattner35397782005-12-05 07:10:48 +00001763 // Add the offset, cast it to the right type.
1764 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1765 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1766 return V = Ptr;
1767}
1768
1769
1770/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1771/// selection, we want to be a bit careful about some things. In particular, if
1772/// we have a GEP instruction that is used in a different block than it is
1773/// defined, the addressing expression of the GEP cannot be folded into loads or
1774/// stores that use it. In this case, decompose the GEP and move constant
1775/// indices into blocks that use it.
1776static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1777 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00001778 // If this GEP is only used inside the block it is defined in, there is no
1779 // need to rewrite it.
1780 bool isUsedOutsideDefBB = false;
1781 BasicBlock *DefBB = GEPI->getParent();
1782 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1783 UI != E; ++UI) {
1784 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1785 isUsedOutsideDefBB = true;
1786 break;
1787 }
1788 }
1789 if (!isUsedOutsideDefBB) return;
1790
1791 // If this GEP has no non-zero constant indices, there is nothing we can do,
1792 // ignore it.
1793 bool hasConstantIndex = false;
1794 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1795 E = GEPI->op_end(); OI != E; ++OI) {
1796 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1797 if (CI->getRawValue()) {
1798 hasConstantIndex = true;
1799 break;
1800 }
1801 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00001802 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1803 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00001804
1805 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1806 // constant offset (which we now know is non-zero) and deal with it later.
1807 uint64_t ConstantOffset = 0;
1808 const Type *UIntPtrTy = TD.getIntPtrType();
1809 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1810 const Type *Ty = GEPI->getOperand(0)->getType();
1811
1812 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1813 E = GEPI->op_end(); OI != E; ++OI) {
1814 Value *Idx = *OI;
1815 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1816 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1817 if (Field)
1818 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1819 Ty = StTy->getElementType(Field);
1820 } else {
1821 Ty = cast<SequentialType>(Ty)->getElementType();
1822
1823 // Handle constant subscripts.
1824 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1825 if (CI->getRawValue() == 0) continue;
1826
1827 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1828 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1829 else
1830 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1831 continue;
1832 }
1833
1834 // Ptr = Ptr + Idx * ElementSize;
1835
1836 // Cast Idx to UIntPtrTy if needed.
1837 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1838
1839 uint64_t ElementSize = TD.getTypeSize(Ty);
1840 // Mask off bits that should not be set.
1841 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1842 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1843
1844 // Multiply by the element size and add to the base.
1845 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1846 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1847 }
1848 }
1849
1850 // Make sure that the offset fits in uintptr_t.
1851 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1852 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1853
1854 // Okay, we have now emitted all of the variable index parts to the BB that
1855 // the GEP is defined in. Loop over all of the using instructions, inserting
1856 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001857 // instruction to use the newly computed value, making GEPI dead. When the
1858 // user is a load or store instruction address, we emit the add into the user
1859 // block, otherwise we use a canonical version right next to the gep (these
1860 // won't be foldable as addresses, so we might as well share the computation).
1861
Chris Lattner35397782005-12-05 07:10:48 +00001862 std::map<BasicBlock*,Value*> InsertedExprs;
1863 while (!GEPI->use_empty()) {
1864 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001865
1866 // If this use is not foldable into the addressing mode, use a version
1867 // emitted in the GEP block.
1868 Value *NewVal;
1869 if (!isa<LoadInst>(User) &&
1870 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1871 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1872 Ptr, PtrOffset);
1873 } else {
1874 // Otherwise, insert the code in the User's block so it can be folded into
1875 // any users in that block.
1876 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00001877 User->getParent(), GEPI,
1878 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00001879 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001880 User->replaceUsesOfWith(GEPI, NewVal);
1881 }
Chris Lattner35397782005-12-05 07:10:48 +00001882
1883 // Finally, the GEP is dead, remove it.
1884 GEPI->eraseFromParent();
1885}
1886
Chris Lattner7a60d912005-01-07 07:47:53 +00001887bool SelectionDAGISel::runOnFunction(Function &Fn) {
1888 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1889 RegMap = MF.getSSARegMap();
1890 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1891
Chris Lattner35397782005-12-05 07:10:48 +00001892 // First, split all critical edges for PHI nodes with incoming values that are
1893 // constants, this way the load of the constant into a vreg will not be placed
1894 // into MBBs that are used some other way.
1895 //
1896 // In this pass we also look for GEP instructions that are used across basic
1897 // blocks and rewrites them to improve basic-block-at-a-time selection.
1898 //
Chris Lattner1a908c82005-08-18 17:35:14 +00001899 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1900 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00001901 BasicBlock::iterator BBI;
1902 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00001903 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1904 if (isa<Constant>(PN->getIncomingValue(i)))
1905 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00001906
1907 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1908 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1909 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00001910 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001911
Chris Lattner7a60d912005-01-07 07:47:53 +00001912 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1913
1914 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1915 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001916
Chris Lattner7a60d912005-01-07 07:47:53 +00001917 return true;
1918}
1919
1920
Chris Lattner718b5c22005-01-13 17:59:43 +00001921SDOperand SelectionDAGISel::
1922CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001923 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001924 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001925 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001926 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001927
1928 // If this type is not legal, we must make sure to not create an invalid
1929 // register use.
1930 MVT::ValueType SrcVT = Op.getValueType();
1931 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1932 SelectionDAG &DAG = SDL.DAG;
1933 if (SrcVT == DestVT) {
1934 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1935 } else if (SrcVT < DestVT) {
1936 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001937 if (MVT::isFloatingPoint(SrcVT))
1938 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1939 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001940 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001941 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1942 } else {
1943 // The src value is expanded into multiple registers.
1944 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1945 Op, DAG.getConstant(0, MVT::i32));
1946 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1947 Op, DAG.getConstant(1, MVT::i32));
1948 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1949 return DAG.getCopyToReg(Op, Reg+1, Hi);
1950 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001951}
1952
Chris Lattner16f64df2005-01-17 17:15:02 +00001953void SelectionDAGISel::
1954LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1955 std::vector<SDOperand> &UnorderedChains) {
1956 // If this is the entry block, emit arguments.
1957 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001958 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001959 SDOperand OldRoot = SDL.DAG.getRoot();
1960 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001961
Chris Lattner6871b232005-10-30 19:42:35 +00001962 unsigned a = 0;
1963 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1964 AI != E; ++AI, ++a)
1965 if (!AI->use_empty()) {
1966 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001967
Chris Lattner6871b232005-10-30 19:42:35 +00001968 // If this argument is live outside of the entry block, insert a copy from
1969 // whereever we got it to the vreg that other BB's will reference it as.
1970 if (FuncInfo.ValueMap.count(AI)) {
1971 SDOperand Copy =
1972 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1973 UnorderedChains.push_back(Copy);
1974 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001975 }
Chris Lattner6871b232005-10-30 19:42:35 +00001976
1977 // Next, if the function has live ins that need to be copied into vregs,
1978 // emit the copies now, into the top of the block.
1979 MachineFunction &MF = SDL.DAG.getMachineFunction();
1980 if (MF.livein_begin() != MF.livein_end()) {
1981 SSARegMap *RegMap = MF.getSSARegMap();
1982 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1983 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1984 E = MF.livein_end(); LI != E; ++LI)
1985 if (LI->second)
1986 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1987 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001988 }
Chris Lattner6871b232005-10-30 19:42:35 +00001989
1990 // Finally, if the target has anything special to do, allow it to do so.
1991 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001992}
1993
1994
Chris Lattner7a60d912005-01-07 07:47:53 +00001995void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1996 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1997 FunctionLoweringInfo &FuncInfo) {
1998 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001999
2000 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002001
Chris Lattner6871b232005-10-30 19:42:35 +00002002 // Lower any arguments needed in this block if this is the entry block.
2003 if (LLVMBB == &LLVMBB->getParent()->front())
2004 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002005
2006 BB = FuncInfo.MBBMap[LLVMBB];
2007 SDL.setCurrentBasicBlock(BB);
2008
2009 // Lower all of the non-terminator instructions.
2010 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2011 I != E; ++I)
2012 SDL.visit(*I);
2013
2014 // Ensure that all instructions which are used outside of their defining
2015 // blocks are available as virtual registers.
2016 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002017 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002018 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002019 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002020 UnorderedChains.push_back(
2021 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002022 }
2023
2024 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2025 // ensure constants are generated when needed. Remember the virtual registers
2026 // that need to be added to the Machine PHI nodes as input. We cannot just
2027 // directly add them, because expansion might result in multiple MBB's for one
2028 // BB. As such, the start of the BB might correspond to a different MBB than
2029 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002030 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002031
2032 // Emit constants only once even if used by multiple PHI nodes.
2033 std::map<Constant*, unsigned> ConstantsOut;
2034
2035 // Check successor nodes PHI nodes that expect a constant to be available from
2036 // this block.
2037 TerminatorInst *TI = LLVMBB->getTerminator();
2038 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2039 BasicBlock *SuccBB = TI->getSuccessor(succ);
2040 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2041 PHINode *PN;
2042
2043 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2044 // nodes and Machine PHI nodes, but the incoming operands have not been
2045 // emitted yet.
2046 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002047 (PN = dyn_cast<PHINode>(I)); ++I)
2048 if (!PN->use_empty()) {
2049 unsigned Reg;
2050 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2051 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2052 unsigned &RegOut = ConstantsOut[C];
2053 if (RegOut == 0) {
2054 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002055 UnorderedChains.push_back(
2056 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002057 }
2058 Reg = RegOut;
2059 } else {
2060 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002061 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002062 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002063 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2064 "Didn't codegen value into a register!??");
2065 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002066 UnorderedChains.push_back(
2067 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002068 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002069 }
Misha Brukman835702a2005-04-21 22:36:52 +00002070
Chris Lattner8ea875f2005-01-07 21:34:19 +00002071 // Remember that this register needs to added to the machine PHI node as
2072 // the input for this MBB.
2073 unsigned NumElements =
2074 TLI.getNumElements(TLI.getValueType(PN->getType()));
2075 for (unsigned i = 0, e = NumElements; i != e; ++i)
2076 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002077 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002078 }
2079 ConstantsOut.clear();
2080
Chris Lattner718b5c22005-01-13 17:59:43 +00002081 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002082 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002083 SDOperand Root = SDL.getRoot();
2084 if (Root.getOpcode() != ISD::EntryToken) {
2085 unsigned i = 0, e = UnorderedChains.size();
2086 for (; i != e; ++i) {
2087 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2088 if (UnorderedChains[i].Val->getOperand(0) == Root)
2089 break; // Don't add the root if we already indirectly depend on it.
2090 }
2091
2092 if (i == e)
2093 UnorderedChains.push_back(Root);
2094 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002095 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2096 }
2097
Chris Lattner7a60d912005-01-07 07:47:53 +00002098 // Lower the terminator after the copies are emitted.
2099 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002100
2101 // Make sure the root of the DAG is up-to-date.
2102 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002103}
2104
2105void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2106 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002107 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002108 CurDAG = &DAG;
2109 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2110
2111 // First step, lower LLVM code to some DAG. This DAG may use operations and
2112 // types that are not supported by the target.
2113 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2114
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002115 // Run the DAG combiner in pre-legalize mode.
2116 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002117
Chris Lattner7a60d912005-01-07 07:47:53 +00002118 DEBUG(std::cerr << "Lowered selection DAG:\n");
2119 DEBUG(DAG.dump());
2120
2121 // Second step, hack on the DAG until it only uses operations and types that
2122 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002123 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002124
2125 DEBUG(std::cerr << "Legalized selection DAG:\n");
2126 DEBUG(DAG.dump());
2127
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002128 // Run the DAG combiner in post-legalize mode.
2129 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002130
Evan Cheng739a6a42006-01-21 02:32:06 +00002131 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002132
Chris Lattner5ca31d92005-03-30 01:10:47 +00002133 // Third, instruction select all of the operations to machine code, adding the
2134 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002135 InstructionSelectBasicBlock(DAG);
2136
Chris Lattner7a60d912005-01-07 07:47:53 +00002137 DEBUG(std::cerr << "Selected machine code:\n");
2138 DEBUG(BB->dump());
2139
Chris Lattner5ca31d92005-03-30 01:10:47 +00002140 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002141 // PHI nodes in successors.
2142 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2143 MachineInstr *PHI = PHINodesToUpdate[i].first;
2144 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2145 "This is not a machine PHI node that we are updating!");
2146 PHI->addRegOperand(PHINodesToUpdate[i].second);
2147 PHI->addMachineBasicBlockOperand(BB);
2148 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002149
2150 // Finally, add the CFG edges from the last selected MBB to the successor
2151 // MBBs.
2152 TerminatorInst *TI = LLVMBB->getTerminator();
2153 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2154 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2155 BB->addSuccessor(Succ0MBB);
2156 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002157}
Evan Cheng739a6a42006-01-21 02:32:06 +00002158
2159//===----------------------------------------------------------------------===//
2160/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2161/// target node in the graph.
2162void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2163 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002164 ScheduleDAG *SL = NULL;
2165
2166 switch (ISHeuristic) {
2167 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002168 case defaultScheduling:
2169 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2170 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2171 else /* TargetLowering::SchedulingForRegPressure */
2172 SL = createBURRListDAGScheduler(DAG, BB);
2173 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002174 case noScheduling:
2175 case simpleScheduling:
2176 case simpleNoItinScheduling:
2177 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2178 break;
Evan Cheng31272342006-01-23 08:26:10 +00002179 case listSchedulingBURR:
2180 SL = createBURRListDAGScheduler(DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002181 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002182 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002183 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002184}