blob: d905b5543d123cedc3770608a9a1b8b783fa5521 [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>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 unsigned CreateRegForValue(const Value *V) {
175 MVT::ValueType VT = TLI.getValueType(V->getType());
176 // The common case is that we will only create one register for this
177 // value. If we have that case, create and return the virtual register.
178 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000179 if (NV == 1) {
180 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000181 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000182 }
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000185 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000186 unsigned NT = VT-1; // Find the type to use.
187 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
188 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000189
Chris Lattner7a60d912005-01-07 07:47:53 +0000190 unsigned R = MakeReg((MVT::ValueType)NT);
191 for (unsigned i = 1; i != NV; ++i)
192 MakeReg((MVT::ValueType)NT);
193 return R;
194 }
Misha Brukman835702a2005-04-21 22:36:52 +0000195
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
205/// PHI nodes or outside of the basic block that defines it.
206static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
207 if (isa<PHINode>(I)) return true;
208 BasicBlock *BB = I->getParent();
209 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
210 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216/// entry block, return true.
217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
220 if (cast<Instruction>(*UI)->getParent() != Entry)
221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner7a60d912005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattner6871b232005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner7a60d912005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
242 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
243 const Type *Ty = AI->getAllocatedType();
244 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000245 unsigned Align =
246 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
247 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000248
249 // If the alignment of the value is smaller than the size of the value,
250 // and if the size of the value is particularly small (<= 8 bytes),
251 // round up to the size of the value for potentially better performance.
252 //
253 // FIXME: This could be made better with a preferred alignment hook in
254 // TargetData. It serves primarily to 8-byte align doubles for X86.
255 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000256 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000257 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000259 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000260 }
261
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000262 for (; BB != EB; ++BB)
263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000264 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
265 if (!isa<AllocaInst>(I) ||
266 !StaticAllocaMap.count(cast<AllocaInst>(I)))
267 InitializeRegForValue(I);
268
269 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
270 // also creates the initial PHI MachineInstrs, though none of the input
271 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000272 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000273 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
274 MBBMap[BB] = MBB;
275 MF.getBasicBlockList().push_back(MBB);
276
277 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
278 // appropriate.
279 PHINode *PN;
280 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000281 (PN = dyn_cast<PHINode>(I)); ++I)
282 if (!PN->use_empty()) {
283 unsigned NumElements =
284 TLI.getNumElements(TLI.getValueType(PN->getType()));
285 unsigned PHIReg = ValueMap[PN];
286 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
287 for (unsigned i = 0; i != NumElements; ++i)
288 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
289 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000290 }
291}
292
293
294
295//===----------------------------------------------------------------------===//
296/// SelectionDAGLowering - This is the common target-independent lowering
297/// implementation that is parameterized by a TargetLowering object.
298/// Also, targets can overload any lowering method.
299///
300namespace llvm {
301class SelectionDAGLowering {
302 MachineBasicBlock *CurMBB;
303
304 std::map<const Value*, SDOperand> NodeMap;
305
Chris Lattner4d9651c2005-01-17 22:19:26 +0000306 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
307 /// them up and then emit token factor nodes when possible. This allows us to
308 /// get simple disambiguation between loads without worrying about alias
309 /// analysis.
310 std::vector<SDOperand> PendingLoads;
311
Chris Lattner7a60d912005-01-07 07:47:53 +0000312public:
313 // TLI - This is information that describes the available target features we
314 // need for lowering. This indicates when operations are unavailable,
315 // implemented with a libcall, etc.
316 TargetLowering &TLI;
317 SelectionDAG &DAG;
318 const TargetData &TD;
319
320 /// FuncInfo - Information about the function as a whole.
321 ///
322 FunctionLoweringInfo &FuncInfo;
323
324 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000325 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000326 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
327 FuncInfo(funcinfo) {
328 }
329
Chris Lattner4108bb02005-01-17 19:43:36 +0000330 /// getRoot - Return the current virtual root of the Selection DAG.
331 ///
332 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000333 if (PendingLoads.empty())
334 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000335
Chris Lattner4d9651c2005-01-17 22:19:26 +0000336 if (PendingLoads.size() == 1) {
337 SDOperand Root = PendingLoads[0];
338 DAG.setRoot(Root);
339 PendingLoads.clear();
340 return Root;
341 }
342
343 // Otherwise, we have to make a token factor node.
344 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
345 PendingLoads.clear();
346 DAG.setRoot(Root);
347 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000348 }
349
Chris Lattner7a60d912005-01-07 07:47:53 +0000350 void visit(Instruction &I) { visit(I.getOpcode(), I); }
351
352 void visit(unsigned Opcode, User &I) {
353 switch (Opcode) {
354 default: assert(0 && "Unknown instruction type encountered!");
355 abort();
356 // Build the switch statement using the Instruction.def file.
357#define HANDLE_INST(NUM, OPCODE, CLASS) \
358 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
359#include "llvm/Instruction.def"
360 }
361 }
362
363 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
364
Chris Lattner4024c002006-03-15 22:19:46 +0000365 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
366 SDOperand SrcValue, SDOperand Root,
367 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000368
369 SDOperand getIntPtrConstant(uint64_t Val) {
370 return DAG.getConstant(Val, TLI.getPointerTy());
371 }
372
373 SDOperand getValue(const Value *V) {
374 SDOperand &N = NodeMap[V];
375 if (N.Val) return N;
376
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000377 const Type *VTy = V->getType();
378 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000379 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
380 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
381 visit(CE->getOpcode(), *CE);
382 assert(N.Val && "visit didn't populate the ValueMap!");
383 return N;
384 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
385 return N = DAG.getGlobalAddress(GV, VT);
386 } else if (isa<ConstantPointerNull>(C)) {
387 return N = DAG.getConstant(0, TLI.getPointerTy());
388 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000389 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000390 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
391 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000392 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
393 unsigned NumElements = PTy->getNumElements();
394 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
395 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
396
397 // Now that we know the number and type of the elements, push a
398 // Constant or ConstantFP node onto the ops list for each element of
399 // the packed constant.
400 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000401 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
402 if (MVT::isFloatingPoint(PVT)) {
403 for (unsigned i = 0; i != NumElements; ++i) {
404 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
405 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
406 }
407 } else {
408 for (unsigned i = 0; i != NumElements; ++i) {
409 const ConstantIntegral *El =
410 cast<ConstantIntegral>(CP->getOperand(i));
411 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
412 }
413 }
414 } else {
415 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
416 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000417 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000418 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000419 else
Chris Lattner803a5752005-12-21 02:43:26 +0000420 Op = DAG.getConstant(0, PVT);
421 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000422 }
Chris Lattner803a5752005-12-21 02:43:26 +0000423
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000424 // Handle the case where we have a 1-element vector, in which
425 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000426 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000427 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000428 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
429 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
430 } else {
431 // If the packed type isn't legal, then create a ConstantVec node with
432 // generic Vector type instead.
Evan Chengb97aab42006-03-01 01:09:54 +0000433 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
434 SDOperand Typ = DAG.getValueType(PVT);
435 Ops.insert(Ops.begin(), Typ);
436 Ops.insert(Ops.begin(), Num);
437 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemanae89d862005-12-07 19:48:11 +0000438 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000439 } else {
440 // Canonicalize all constant ints to be unsigned.
441 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
442 }
443
444 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
445 std::map<const AllocaInst*, int>::iterator SI =
446 FuncInfo.StaticAllocaMap.find(AI);
447 if (SI != FuncInfo.StaticAllocaMap.end())
448 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
449 }
450
451 std::map<const Value*, unsigned>::const_iterator VMI =
452 FuncInfo.ValueMap.find(V);
453 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000454
Chris Lattner33182322005-08-16 21:55:35 +0000455 unsigned InReg = VMI->second;
456
457 // If this type is not legal, make it so now.
458 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
459
460 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
461 if (DestVT < VT) {
462 // Source must be expanded. This input value is actually coming from the
463 // register pair VMI->second and VMI->second+1.
464 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
465 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
466 } else {
467 if (DestVT > VT) { // Promotion case
468 if (MVT::isFloatingPoint(VT))
469 N = DAG.getNode(ISD::FP_ROUND, VT, N);
470 else
471 N = DAG.getNode(ISD::TRUNCATE, VT, N);
472 }
473 }
474
475 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000476 }
477
478 const SDOperand &setValue(const Value *V, SDOperand NewN) {
479 SDOperand &N = NodeMap[V];
480 assert(N.Val == 0 && "Already set a value for this node!");
481 return N = NewN;
482 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000483
Chris Lattner6f87d182006-02-22 22:37:12 +0000484 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
485 MVT::ValueType VT,
486 bool OutReg, bool InReg,
487 std::set<unsigned> &OutputRegs,
488 std::set<unsigned> &InputRegs);
489
Chris Lattner7a60d912005-01-07 07:47:53 +0000490 // Terminator instructions.
491 void visitRet(ReturnInst &I);
492 void visitBr(BranchInst &I);
493 void visitUnreachable(UnreachableInst &I) { /* noop */ }
494
495 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000496 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000497 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
502 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000503 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000504 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000505 void visitAdd(User &I) {
506 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000507 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000508 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000509 void visitMul(User &I) {
510 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000511 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000513 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000514 visitBinary(I,
515 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
516 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000517 }
518 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000519 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000520 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000521 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000522 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
523 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
524 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000525 void visitShl(User &I) { visitShift(I, ISD::SHL); }
526 void visitShr(User &I) {
527 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000528 }
529
530 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
531 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
532 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
533 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
534 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
535 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
536 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
537
538 void visitGetElementPtr(User &I);
539 void visitCast(User &I);
540 void visitSelect(User &I);
541 //
542
543 void visitMalloc(MallocInst &I);
544 void visitFree(FreeInst &I);
545 void visitAlloca(AllocaInst &I);
546 void visitLoad(LoadInst &I);
547 void visitStore(StoreInst &I);
548 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
549 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000550 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000551 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000552
Chris Lattner7a60d912005-01-07 07:47:53 +0000553 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000554 void visitVAArg(VAArgInst &I);
555 void visitVAEnd(CallInst &I);
556 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000557 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000558
Chris Lattner875def92005-01-11 05:56:49 +0000559 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000560
561 void visitUserOp1(Instruction &I) {
562 assert(0 && "UserOp1 should not exist at instruction selection time!");
563 abort();
564 }
565 void visitUserOp2(Instruction &I) {
566 assert(0 && "UserOp2 should not exist at instruction selection time!");
567 abort();
568 }
569};
570} // end namespace llvm
571
572void SelectionDAGLowering::visitRet(ReturnInst &I) {
573 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000574 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000575 return;
576 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000577 std::vector<SDOperand> NewValues;
578 NewValues.push_back(getRoot());
579 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
580 SDOperand RetOp = getValue(I.getOperand(i));
581
582 // If this is an integer return value, we need to promote it ourselves to
583 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
584 // than sign/zero.
585 if (MVT::isInteger(RetOp.getValueType()) &&
586 RetOp.getValueType() < MVT::i64) {
587 MVT::ValueType TmpVT;
588 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
589 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
590 else
591 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000592
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000593 if (I.getOperand(i)->getType()->isSigned())
594 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
595 else
596 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
597 }
598 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000599 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000600 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000601}
602
603void SelectionDAGLowering::visitBr(BranchInst &I) {
604 // Update machine-CFG edges.
605 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000606
607 // Figure out which block is immediately after the current one.
608 MachineBasicBlock *NextBlock = 0;
609 MachineFunction::iterator BBI = CurMBB;
610 if (++BBI != CurMBB->getParent()->end())
611 NextBlock = BBI;
612
613 if (I.isUnconditional()) {
614 // If this is not a fall-through branch, emit the branch.
615 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000616 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000617 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000618 } else {
619 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000620
621 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000622 if (Succ1MBB == NextBlock) {
623 // If the condition is false, fall through. This means we should branch
624 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000625 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000626 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000627 } else if (Succ0MBB == NextBlock) {
628 // If the condition is true, fall through. This means we should branch if
629 // the condition is false to Succ #1. Invert the condition first.
630 SDOperand True = DAG.getConstant(1, Cond.getValueType());
631 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000632 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000633 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000634 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000635 std::vector<SDOperand> Ops;
636 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000637 // If the false case is the current basic block, then this is a self
638 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
639 // adds an extra instruction in the loop. Instead, invert the
640 // condition and emit "Loop: ... br!cond Loop; br Out.
641 if (CurMBB == Succ1MBB) {
642 std::swap(Succ0MBB, Succ1MBB);
643 SDOperand True = DAG.getConstant(1, Cond.getValueType());
644 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
645 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000646 Ops.push_back(Cond);
647 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
648 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
649 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000650 }
651 }
652}
653
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000654void SelectionDAGLowering::visitSub(User &I) {
655 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000656 if (I.getType()->isFloatingPoint()) {
657 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
658 if (CFP->isExactlyValue(-0.0)) {
659 SDOperand Op2 = getValue(I.getOperand(1));
660 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
661 return;
662 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000663 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000664 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000665}
666
Nate Begemanb2e089c2005-11-19 00:36:38 +0000667void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
668 unsigned VecOp) {
669 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000670 SDOperand Op1 = getValue(I.getOperand(0));
671 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000672
Chris Lattner19baba62005-11-19 18:40:42 +0000673 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000674 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
675 } else if (Ty->isFloatingPoint()) {
676 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
677 } else {
678 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000679 unsigned NumElements = PTy->getNumElements();
680 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000681 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000682
683 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000684 // the Legalize pass does not have to deal with them. Similarly, if the
685 // abstract vector is going to turn into one that the target natively
686 // supports, generate that type now so that Legalize doesn't have to deal
687 // with that either. These steps ensure that Legalize only has to handle
688 // vector types in its Expand case.
689 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000690 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000691 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Chengb97aab42006-03-01 01:09:54 +0000692 } else if (TVT != MVT::Other &&
693 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000694 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000695 } else {
696 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
697 SDOperand Typ = DAG.getValueType(PVT);
Evan Chengb97aab42006-03-01 01:09:54 +0000698 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000699 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000700 }
Nate Begeman127321b2005-11-18 07:42:56 +0000701}
Chris Lattner96c26752005-01-19 22:31:21 +0000702
Nate Begeman127321b2005-11-18 07:42:56 +0000703void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
704 SDOperand Op1 = getValue(I.getOperand(0));
705 SDOperand Op2 = getValue(I.getOperand(1));
706
707 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
708
Chris Lattner7a60d912005-01-07 07:47:53 +0000709 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
710}
711
712void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
713 ISD::CondCode UnsignedOpcode) {
714 SDOperand Op1 = getValue(I.getOperand(0));
715 SDOperand Op2 = getValue(I.getOperand(1));
716 ISD::CondCode Opcode = SignedOpcode;
717 if (I.getOperand(0)->getType()->isUnsigned())
718 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000719 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000720}
721
722void SelectionDAGLowering::visitSelect(User &I) {
723 SDOperand Cond = getValue(I.getOperand(0));
724 SDOperand TrueVal = getValue(I.getOperand(1));
725 SDOperand FalseVal = getValue(I.getOperand(2));
726 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
727 TrueVal, FalseVal));
728}
729
730void SelectionDAGLowering::visitCast(User &I) {
731 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000732 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
733 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000734
Chris Lattner4024c002006-03-15 22:19:46 +0000735 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000736 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000737 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000738 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000739 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000740 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000741 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000742 } else if (isInteger(SrcVT)) {
743 if (isInteger(DestVT)) { // Int -> Int cast
744 if (DestVT < SrcVT) // Truncating cast?
745 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000746 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000747 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000748 else
Chris Lattner4024c002006-03-15 22:19:46 +0000749 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000750 } else { // Int -> FP cast
751 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000752 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000753 else
Chris Lattner4024c002006-03-15 22:19:46 +0000754 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000755 }
Chris Lattner4024c002006-03-15 22:19:46 +0000756 } else if (isFloatingPoint(SrcVT)) {
757 if (isFloatingPoint(DestVT)) { // FP -> FP cast
758 if (DestVT < SrcVT) // Rounding cast?
759 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000760 else
Chris Lattner4024c002006-03-15 22:19:46 +0000761 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000762 } else { // FP -> Int cast.
763 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000764 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000765 else
Chris Lattner4024c002006-03-15 22:19:46 +0000766 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
767 }
768 } else {
769 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
770 const PackedType *DstTy = cast<PackedType>(I.getType());
771
772 unsigned SrcNumElements = SrcTy->getNumElements();
773 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
774 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
775
776 unsigned DstNumElements = DstTy->getNumElements();
777 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
778 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
779
780 // If the input and output type are legal, convert this to a bit convert of
781 // the SrcTVT/DstTVT types.
782 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
783 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
784 assert(N.getValueType() == SrcTVT);
785 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
786 } else {
787 // Otherwise, convert this directly into a store/load.
788 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
789 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
790 // Create the stack frame object.
791 uint64_t ByteSize = TD.getTypeSize(SrcTy);
792 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
793 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
794 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
795 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
796
797 // Emit a store to the stack slot.
798 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
799 N, FIPtr, DAG.getSrcValue(NULL));
800 // Result is a load from the stack slot.
801 SDOperand Val =
802 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
803 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000804 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000805 }
806}
807
808void SelectionDAGLowering::visitGetElementPtr(User &I) {
809 SDOperand N = getValue(I.getOperand(0));
810 const Type *Ty = I.getOperand(0)->getType();
811 const Type *UIntPtrTy = TD.getIntPtrType();
812
813 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
814 OI != E; ++OI) {
815 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000816 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000817 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
818 if (Field) {
819 // N = N + Offset
820 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
821 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000822 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000823 }
824 Ty = StTy->getElementType(Field);
825 } else {
826 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000827
Chris Lattner43535a12005-11-09 04:45:33 +0000828 // If this is a constant subscript, handle it quickly.
829 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
830 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000831
Chris Lattner43535a12005-11-09 04:45:33 +0000832 uint64_t Offs;
833 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
834 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
835 else
836 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
837 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
838 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000839 }
Chris Lattner43535a12005-11-09 04:45:33 +0000840
841 // N = N + Idx * ElementSize;
842 uint64_t ElementSize = TD.getTypeSize(Ty);
843 SDOperand IdxN = getValue(Idx);
844
845 // If the index is smaller or larger than intptr_t, truncate or extend
846 // it.
847 if (IdxN.getValueType() < N.getValueType()) {
848 if (Idx->getType()->isSigned())
849 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
850 else
851 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
852 } else if (IdxN.getValueType() > N.getValueType())
853 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
854
855 // If this is a multiply by a power of two, turn it into a shl
856 // immediately. This is a very common case.
857 if (isPowerOf2_64(ElementSize)) {
858 unsigned Amt = Log2_64(ElementSize);
859 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000860 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000861 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
862 continue;
863 }
864
865 SDOperand Scale = getIntPtrConstant(ElementSize);
866 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
867 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000868 }
869 }
870 setValue(&I, N);
871}
872
873void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
874 // If this is a fixed sized alloca in the entry block of the function,
875 // allocate it statically on the stack.
876 if (FuncInfo.StaticAllocaMap.count(&I))
877 return; // getValue will auto-populate this.
878
879 const Type *Ty = I.getAllocatedType();
880 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000881 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
882 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000883
884 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000885 MVT::ValueType IntPtr = TLI.getPointerTy();
886 if (IntPtr < AllocSize.getValueType())
887 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
888 else if (IntPtr > AllocSize.getValueType())
889 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000890
Chris Lattnereccb73d2005-01-22 23:04:37 +0000891 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000892 getIntPtrConstant(TySize));
893
894 // Handle alignment. If the requested alignment is less than or equal to the
895 // stack alignment, ignore it and round the size of the allocation up to the
896 // stack alignment size. If the size is greater than the stack alignment, we
897 // note this in the DYNAMIC_STACKALLOC node.
898 unsigned StackAlign =
899 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
900 if (Align <= StackAlign) {
901 Align = 0;
902 // Add SA-1 to the size.
903 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
904 getIntPtrConstant(StackAlign-1));
905 // Mask out the low bits for alignment purposes.
906 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
907 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
908 }
909
Chris Lattner96c262e2005-05-14 07:29:57 +0000910 std::vector<MVT::ValueType> VTs;
911 VTs.push_back(AllocSize.getValueType());
912 VTs.push_back(MVT::Other);
913 std::vector<SDOperand> Ops;
914 Ops.push_back(getRoot());
915 Ops.push_back(AllocSize);
916 Ops.push_back(getIntPtrConstant(Align));
917 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000918 DAG.setRoot(setValue(&I, DSA).getValue(1));
919
920 // Inform the Frame Information that we have just allocated a variable-sized
921 // object.
922 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
923}
924
Chris Lattner7a60d912005-01-07 07:47:53 +0000925void SelectionDAGLowering::visitLoad(LoadInst &I) {
926 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000927
Chris Lattner4d9651c2005-01-17 22:19:26 +0000928 SDOperand Root;
929 if (I.isVolatile())
930 Root = getRoot();
931 else {
932 // Do not serialize non-volatile loads against each other.
933 Root = DAG.getRoot();
934 }
Chris Lattner4024c002006-03-15 22:19:46 +0000935
936 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
937 Root, I.isVolatile()));
938}
939
940SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
941 SDOperand SrcValue, SDOperand Root,
942 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000943 SDOperand L;
944
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000945 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000946 unsigned NumElements = PTy->getNumElements();
947 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000948 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000949
950 // Immediately scalarize packed types containing only one element, so that
951 // the Legalize pass does not have to deal with them.
952 if (NumElements == 1) {
Chris Lattner4024c002006-03-15 22:19:46 +0000953 L = DAG.getLoad(PVT, Root, Ptr, SrcValue);
954 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
955 TLI.isOperationLegal(ISD::LOAD, TVT)) {
956 L = DAG.getLoad(TVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +0000957 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000958 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +0000959 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000960 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000961 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000962 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000963
Chris Lattner4024c002006-03-15 22:19:46 +0000964 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +0000965 DAG.setRoot(L.getValue(1));
966 else
967 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +0000968
969 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +0000970}
971
972
973void SelectionDAGLowering::visitStore(StoreInst &I) {
974 Value *SrcV = I.getOperand(0);
975 SDOperand Src = getValue(SrcV);
976 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000977 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000978 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000979}
980
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000981/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
982/// we want to emit this as a call to a named external function, return the name
983/// otherwise lower it and return null.
984const char *
985SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
986 switch (Intrinsic) {
987 case Intrinsic::vastart: visitVAStart(I); return 0;
988 case Intrinsic::vaend: visitVAEnd(I); return 0;
989 case Intrinsic::vacopy: visitVACopy(I); return 0;
990 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
991 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
992 case Intrinsic::setjmp:
993 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
994 break;
995 case Intrinsic::longjmp:
996 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
997 break;
Chris Lattner093c1592006-03-03 00:00:25 +0000998 case Intrinsic::memcpy_i32:
999 case Intrinsic::memcpy_i64:
1000 visitMemIntrinsic(I, ISD::MEMCPY);
1001 return 0;
1002 case Intrinsic::memset_i32:
1003 case Intrinsic::memset_i64:
1004 visitMemIntrinsic(I, ISD::MEMSET);
1005 return 0;
1006 case Intrinsic::memmove_i32:
1007 case Intrinsic::memmove_i64:
1008 visitMemIntrinsic(I, ISD::MEMMOVE);
1009 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001010
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001011 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001012 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001013 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001014 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001015
Jim Laskey5995d012006-02-11 01:01:30 +00001016 // Input Chain
1017 Ops.push_back(getRoot());
1018
1019 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001020 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001021
1022 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001023 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001024
Jim Laskeyacb6e342006-03-13 13:07:37 +00001025 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001026 assert(DD && "Not a debug information descriptor");
1027 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1028 assert(CompileUnit && "Not a compile unit");
1029 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1030 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1031
1032 if (Ops.size() == 5) // Found filename/workingdir.
1033 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001034 }
1035
Chris Lattner8782b782005-12-03 18:50:48 +00001036 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001037 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001038 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001039 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001040 if (I.getType() != Type::VoidTy)
1041 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1042 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001043 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001044 if (I.getType() != Type::VoidTy)
1045 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1046 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001047 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001048 if (I.getType() != Type::VoidTy)
1049 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1050 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001051
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001052 case Intrinsic::isunordered_f32:
1053 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001054 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1055 getValue(I.getOperand(2)), ISD::SETUO));
1056 return 0;
1057
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001058 case Intrinsic::sqrt_f32:
1059 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001060 setValue(&I, DAG.getNode(ISD::FSQRT,
1061 getValue(I.getOperand(1)).getValueType(),
1062 getValue(I.getOperand(1))));
1063 return 0;
1064 case Intrinsic::pcmarker: {
1065 SDOperand Tmp = getValue(I.getOperand(1));
1066 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1067 return 0;
1068 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001069 case Intrinsic::readcyclecounter: {
1070 std::vector<MVT::ValueType> VTs;
1071 VTs.push_back(MVT::i64);
1072 VTs.push_back(MVT::Other);
1073 std::vector<SDOperand> Ops;
1074 Ops.push_back(getRoot());
1075 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1076 setValue(&I, Tmp);
1077 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001078 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001079 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001080 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001081 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001082 case Intrinsic::bswap_i64:
1083 setValue(&I, DAG.getNode(ISD::BSWAP,
1084 getValue(I.getOperand(1)).getValueType(),
1085 getValue(I.getOperand(1))));
1086 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001087 case Intrinsic::cttz_i8:
1088 case Intrinsic::cttz_i16:
1089 case Intrinsic::cttz_i32:
1090 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001091 setValue(&I, DAG.getNode(ISD::CTTZ,
1092 getValue(I.getOperand(1)).getValueType(),
1093 getValue(I.getOperand(1))));
1094 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001095 case Intrinsic::ctlz_i8:
1096 case Intrinsic::ctlz_i16:
1097 case Intrinsic::ctlz_i32:
1098 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001099 setValue(&I, DAG.getNode(ISD::CTLZ,
1100 getValue(I.getOperand(1)).getValueType(),
1101 getValue(I.getOperand(1))));
1102 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001103 case Intrinsic::ctpop_i8:
1104 case Intrinsic::ctpop_i16:
1105 case Intrinsic::ctpop_i32:
1106 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001107 setValue(&I, DAG.getNode(ISD::CTPOP,
1108 getValue(I.getOperand(1)).getValueType(),
1109 getValue(I.getOperand(1))));
1110 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001111 case Intrinsic::stacksave: {
1112 std::vector<MVT::ValueType> VTs;
1113 VTs.push_back(TLI.getPointerTy());
1114 VTs.push_back(MVT::Other);
1115 std::vector<SDOperand> Ops;
1116 Ops.push_back(getRoot());
1117 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1118 setValue(&I, Tmp);
1119 DAG.setRoot(Tmp.getValue(1));
1120 return 0;
1121 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001122 case Intrinsic::stackrestore: {
1123 SDOperand Tmp = getValue(I.getOperand(1));
1124 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001125 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001126 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001127 case Intrinsic::prefetch:
1128 // FIXME: Currently discarding prefetches.
1129 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001130 default:
1131 std::cerr << I;
1132 assert(0 && "This intrinsic is not implemented yet!");
1133 return 0;
1134 }
1135}
1136
1137
Chris Lattner7a60d912005-01-07 07:47:53 +00001138void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001139 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001140 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001141 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001142 if (unsigned IID = F->getIntrinsicID()) {
1143 RenameFn = visitIntrinsicCall(I, IID);
1144 if (!RenameFn)
1145 return;
1146 } else { // Not an LLVM intrinsic.
1147 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001148 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1149 if (I.getNumOperands() == 3 && // Basic sanity checks.
1150 I.getOperand(1)->getType()->isFloatingPoint() &&
1151 I.getType() == I.getOperand(1)->getType() &&
1152 I.getType() == I.getOperand(2)->getType()) {
1153 SDOperand LHS = getValue(I.getOperand(1));
1154 SDOperand RHS = getValue(I.getOperand(2));
1155 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1156 LHS, RHS));
1157 return;
1158 }
1159 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001160 if (I.getNumOperands() == 2 && // Basic sanity checks.
1161 I.getOperand(1)->getType()->isFloatingPoint() &&
1162 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001163 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001164 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1165 return;
1166 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001167 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001168 if (I.getNumOperands() == 2 && // Basic sanity checks.
1169 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001170 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001171 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001172 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1173 return;
1174 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001175 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001176 if (I.getNumOperands() == 2 && // Basic sanity checks.
1177 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001178 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001179 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001180 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1181 return;
1182 }
1183 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001184 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001185 } else if (isa<InlineAsm>(I.getOperand(0))) {
1186 visitInlineAsm(I);
1187 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001188 }
Misha Brukman835702a2005-04-21 22:36:52 +00001189
Chris Lattner18d2b342005-01-08 22:48:57 +00001190 SDOperand Callee;
1191 if (!RenameFn)
1192 Callee = getValue(I.getOperand(0));
1193 else
1194 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001195 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001196 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001197 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1198 Value *Arg = I.getOperand(i);
1199 SDOperand ArgNode = getValue(Arg);
1200 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1201 }
Misha Brukman835702a2005-04-21 22:36:52 +00001202
Nate Begemanf6565252005-03-26 01:29:23 +00001203 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1204 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001205
Chris Lattner1f45cd72005-01-08 19:26:18 +00001206 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001207 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001208 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001209 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001210 setValue(&I, Result.first);
1211 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001212}
1213
Chris Lattner6f87d182006-02-22 22:37:12 +00001214SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001215 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001216 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1217 Chain = Val.getValue(1);
1218 Flag = Val.getValue(2);
1219
1220 // If the result was expanded, copy from the top part.
1221 if (Regs.size() > 1) {
1222 assert(Regs.size() == 2 &&
1223 "Cannot expand to more than 2 elts yet!");
1224 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1225 Chain = Val.getValue(1);
1226 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001227 if (DAG.getTargetLoweringInfo().isLittleEndian())
1228 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1229 else
1230 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001231 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001232
Chris Lattner6f87d182006-02-22 22:37:12 +00001233 // Otherwise, if the return value was promoted, truncate it to the
1234 // appropriate type.
1235 if (RegVT == ValueVT)
1236 return Val;
1237
1238 if (MVT::isInteger(RegVT))
1239 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1240 else
1241 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1242}
1243
Chris Lattner571d9642006-02-23 19:21:04 +00001244/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1245/// specified value into the registers specified by this object. This uses
1246/// Chain/Flag as the input and updates them for the output Chain/Flag.
1247void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001248 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001249 if (Regs.size() == 1) {
1250 // If there is a single register and the types differ, this must be
1251 // a promotion.
1252 if (RegVT != ValueVT) {
1253 if (MVT::isInteger(RegVT))
1254 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1255 else
1256 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1257 }
1258 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1259 Flag = Chain.getValue(1);
1260 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001261 std::vector<unsigned> R(Regs);
1262 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1263 std::reverse(R.begin(), R.end());
1264
1265 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001266 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1267 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001268 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001269 Flag = Chain.getValue(1);
1270 }
1271 }
1272}
Chris Lattner6f87d182006-02-22 22:37:12 +00001273
Chris Lattner571d9642006-02-23 19:21:04 +00001274/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1275/// operand list. This adds the code marker and includes the number of
1276/// values added into it.
1277void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001278 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001279 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1280 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1281 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1282}
Chris Lattner6f87d182006-02-22 22:37:12 +00001283
1284/// isAllocatableRegister - If the specified register is safe to allocate,
1285/// i.e. it isn't a stack pointer or some other special register, return the
1286/// register class for the register. Otherwise, return null.
1287static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001288isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1289 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1290 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1291 E = MRI->regclass_end(); RCI != E; ++RCI) {
1292 const TargetRegisterClass *RC = *RCI;
1293 // If none of the the value types for this register class are valid, we
1294 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1295 bool isLegal = false;
1296 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1297 I != E; ++I) {
1298 if (TLI.isTypeLegal(*I)) {
1299 isLegal = true;
1300 break;
1301 }
1302 }
1303
1304 if (!isLegal) continue;
1305
Chris Lattner6f87d182006-02-22 22:37:12 +00001306 // NOTE: This isn't ideal. In particular, this might allocate the
1307 // frame pointer in functions that need it (due to them not being taken
1308 // out of allocation, because a variable sized allocation hasn't been seen
1309 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001310 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1311 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001312 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001313 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001314 }
1315 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001316}
1317
1318RegsForValue SelectionDAGLowering::
1319GetRegistersForValue(const std::string &ConstrCode,
1320 MVT::ValueType VT, bool isOutReg, bool isInReg,
1321 std::set<unsigned> &OutputRegs,
1322 std::set<unsigned> &InputRegs) {
1323 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1324 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1325 std::vector<unsigned> Regs;
1326
1327 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1328 MVT::ValueType RegVT;
1329 MVT::ValueType ValueVT = VT;
1330
1331 if (PhysReg.first) {
1332 if (VT == MVT::Other)
1333 ValueVT = *PhysReg.second->vt_begin();
1334 RegVT = VT;
1335
1336 // This is a explicit reference to a physical register.
1337 Regs.push_back(PhysReg.first);
1338
1339 // If this is an expanded reference, add the rest of the regs to Regs.
1340 if (NumRegs != 1) {
1341 RegVT = *PhysReg.second->vt_begin();
1342 TargetRegisterClass::iterator I = PhysReg.second->begin();
1343 TargetRegisterClass::iterator E = PhysReg.second->end();
1344 for (; *I != PhysReg.first; ++I)
1345 assert(I != E && "Didn't find reg!");
1346
1347 // Already added the first reg.
1348 --NumRegs; ++I;
1349 for (; NumRegs; --NumRegs, ++I) {
1350 assert(I != E && "Ran out of registers to allocate!");
1351 Regs.push_back(*I);
1352 }
1353 }
1354 return RegsForValue(Regs, RegVT, ValueVT);
1355 }
1356
1357 // This is a reference to a register class. Allocate NumRegs consecutive,
1358 // available, registers from the class.
1359 std::vector<unsigned> RegClassRegs =
1360 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1361
1362 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1363 MachineFunction &MF = *CurMBB->getParent();
1364 unsigned NumAllocated = 0;
1365 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1366 unsigned Reg = RegClassRegs[i];
1367 // See if this register is available.
1368 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1369 (isInReg && InputRegs.count(Reg))) { // Already used.
1370 // Make sure we find consecutive registers.
1371 NumAllocated = 0;
1372 continue;
1373 }
1374
1375 // Check to see if this register is allocatable (i.e. don't give out the
1376 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001377 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001378 if (!RC) {
1379 // Make sure we find consecutive registers.
1380 NumAllocated = 0;
1381 continue;
1382 }
1383
1384 // Okay, this register is good, we can use it.
1385 ++NumAllocated;
1386
1387 // If we allocated enough consecutive
1388 if (NumAllocated == NumRegs) {
1389 unsigned RegStart = (i-NumAllocated)+1;
1390 unsigned RegEnd = i+1;
1391 // Mark all of the allocated registers used.
1392 for (unsigned i = RegStart; i != RegEnd; ++i) {
1393 unsigned Reg = RegClassRegs[i];
1394 Regs.push_back(Reg);
1395 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1396 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1397 }
1398
1399 return RegsForValue(Regs, *RC->vt_begin(), VT);
1400 }
1401 }
1402
1403 // Otherwise, we couldn't allocate enough registers for this.
1404 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001405}
1406
Chris Lattner6f87d182006-02-22 22:37:12 +00001407
Chris Lattner476e67b2006-01-26 22:24:51 +00001408/// visitInlineAsm - Handle a call to an InlineAsm object.
1409///
1410void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1411 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1412
1413 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1414 MVT::Other);
1415
1416 // Note, we treat inline asms both with and without side-effects as the same.
1417 // If an inline asm doesn't have side effects and doesn't access memory, we
1418 // could not choose to not chain it.
1419 bool hasSideEffects = IA->hasSideEffects();
1420
Chris Lattner3a5ed552006-02-01 01:28:23 +00001421 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001422 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001423
1424 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1425 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1426 /// if it is a def of that register.
1427 std::vector<SDOperand> AsmNodeOperands;
1428 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1429 AsmNodeOperands.push_back(AsmStr);
1430
1431 SDOperand Chain = getRoot();
1432 SDOperand Flag;
1433
Chris Lattner1558fc62006-02-01 18:59:47 +00001434 // We fully assign registers here at isel time. This is not optimal, but
1435 // should work. For register classes that correspond to LLVM classes, we
1436 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1437 // over the constraints, collecting fixed registers that we know we can't use.
1438 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001439 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001440 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1441 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1442 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001443
Chris Lattner7ad77df2006-02-22 00:56:39 +00001444 MVT::ValueType OpVT;
1445
1446 // Compute the value type for each operand and add it to ConstraintVTs.
1447 switch (Constraints[i].Type) {
1448 case InlineAsm::isOutput:
1449 if (!Constraints[i].isIndirectOutput) {
1450 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1451 OpVT = TLI.getValueType(I.getType());
1452 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001453 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001454 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1455 OpNum++; // Consumes a call operand.
1456 }
1457 break;
1458 case InlineAsm::isInput:
1459 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1460 OpNum++; // Consumes a call operand.
1461 break;
1462 case InlineAsm::isClobber:
1463 OpVT = MVT::Other;
1464 break;
1465 }
1466
1467 ConstraintVTs.push_back(OpVT);
1468
Chris Lattner6f87d182006-02-22 22:37:12 +00001469 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1470 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001471
Chris Lattner6f87d182006-02-22 22:37:12 +00001472 // Build a list of regs that this operand uses. This always has a single
1473 // element for promoted/expanded operands.
1474 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1475 false, false,
1476 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001477
1478 switch (Constraints[i].Type) {
1479 case InlineAsm::isOutput:
1480 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001481 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001482 // If this is an early-clobber output, it cannot be assigned to the same
1483 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001484 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001485 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001486 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001487 case InlineAsm::isInput:
1488 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001489 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001490 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001491 case InlineAsm::isClobber:
1492 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001493 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1494 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001495 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001496 }
1497 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001498
Chris Lattner5c79f982006-02-21 23:12:12 +00001499 // Loop over all of the inputs, copying the operand values into the
1500 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001501 RegsForValue RetValRegs;
1502 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001503 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001504
Chris Lattner2e56e892006-01-31 02:03:41 +00001505 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001506 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1507 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001508
Chris Lattner3a5ed552006-02-01 01:28:23 +00001509 switch (Constraints[i].Type) {
1510 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001511 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1512 if (ConstraintCode.size() == 1) // not a physreg name.
1513 CTy = TLI.getConstraintType(ConstraintCode[0]);
1514
1515 if (CTy == TargetLowering::C_Memory) {
1516 // Memory output.
1517 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1518
1519 // Check that the operand (the address to store to) isn't a float.
1520 if (!MVT::isInteger(InOperandVal.getValueType()))
1521 assert(0 && "MATCH FAIL!");
1522
1523 if (!Constraints[i].isIndirectOutput)
1524 assert(0 && "MATCH FAIL!");
1525
1526 OpNum++; // Consumes a call operand.
1527
1528 // Extend/truncate to the right pointer type if needed.
1529 MVT::ValueType PtrType = TLI.getPointerTy();
1530 if (InOperandVal.getValueType() < PtrType)
1531 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1532 else if (InOperandVal.getValueType() > PtrType)
1533 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1534
1535 // Add information to the INLINEASM node to know about this output.
1536 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1537 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1538 AsmNodeOperands.push_back(InOperandVal);
1539 break;
1540 }
1541
1542 // Otherwise, this is a register output.
1543 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1544
Chris Lattner6f87d182006-02-22 22:37:12 +00001545 // If this is an early-clobber output, or if there is an input
1546 // constraint that matches this, we need to reserve the input register
1547 // so no other inputs allocate to it.
1548 bool UsesInputRegister = false;
1549 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1550 UsesInputRegister = true;
1551
1552 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001553 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001554 RegsForValue Regs =
1555 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1556 true, UsesInputRegister,
1557 OutputRegs, InputRegs);
1558 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001559
Chris Lattner3a5ed552006-02-01 01:28:23 +00001560 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001561 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001562 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001563 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001564 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001565 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001566 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1567 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001568 OpNum++; // Consumes a call operand.
1569 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001570
1571 // Add information to the INLINEASM node to know that this register is
1572 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001573 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001574 break;
1575 }
1576 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001577 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001578 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001579
Chris Lattner7f5880b2006-02-02 00:25:23 +00001580 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1581 // If this is required to match an output register we have already set,
1582 // just use its register.
1583 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001584
Chris Lattner571d9642006-02-23 19:21:04 +00001585 // Scan until we find the definition we already emitted of this operand.
1586 // When we find it, create a RegsForValue operand.
1587 unsigned CurOp = 2; // The first operand.
1588 for (; OperandNo; --OperandNo) {
1589 // Advance to the next operand.
1590 unsigned NumOps =
1591 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1592 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1593 "Skipped past definitions?");
1594 CurOp += (NumOps>>3)+1;
1595 }
1596
1597 unsigned NumOps =
1598 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1599 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1600 "Skipped past definitions?");
1601
1602 // Add NumOps>>3 registers to MatchedRegs.
1603 RegsForValue MatchedRegs;
1604 MatchedRegs.ValueVT = InOperandVal.getValueType();
1605 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1606 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1607 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1608 MatchedRegs.Regs.push_back(Reg);
1609 }
1610
1611 // Use the produced MatchedRegs object to
1612 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1613 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001614 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001615 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001616
1617 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1618 if (ConstraintCode.size() == 1) // not a physreg name.
1619 CTy = TLI.getConstraintType(ConstraintCode[0]);
1620
1621 if (CTy == TargetLowering::C_Other) {
1622 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1623 assert(0 && "MATCH FAIL!");
1624
1625 // Add information to the INLINEASM node to know about this input.
1626 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1627 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1628 AsmNodeOperands.push_back(InOperandVal);
1629 break;
1630 } else if (CTy == TargetLowering::C_Memory) {
1631 // Memory input.
1632
1633 // Check that the operand isn't a float.
1634 if (!MVT::isInteger(InOperandVal.getValueType()))
1635 assert(0 && "MATCH FAIL!");
1636
1637 // Extend/truncate to the right pointer type if needed.
1638 MVT::ValueType PtrType = TLI.getPointerTy();
1639 if (InOperandVal.getValueType() < PtrType)
1640 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1641 else if (InOperandVal.getValueType() > PtrType)
1642 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1643
1644 // Add information to the INLINEASM node to know about this input.
1645 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1646 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1647 AsmNodeOperands.push_back(InOperandVal);
1648 break;
1649 }
1650
1651 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1652
1653 // Copy the input into the appropriate registers.
1654 RegsForValue InRegs =
1655 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1656 false, true, OutputRegs, InputRegs);
1657 // FIXME: should be match fail.
1658 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1659
1660 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1661
1662 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001663 break;
1664 }
Chris Lattner571d9642006-02-23 19:21:04 +00001665 case InlineAsm::isClobber: {
1666 RegsForValue ClobberedRegs =
1667 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1668 OutputRegs, InputRegs);
1669 // Add the clobbered value to the operand list, so that the register
1670 // allocator is aware that the physreg got clobbered.
1671 if (!ClobberedRegs.Regs.empty())
1672 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001673 break;
1674 }
Chris Lattner571d9642006-02-23 19:21:04 +00001675 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001676 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001677
1678 // Finish up input operands.
1679 AsmNodeOperands[0] = Chain;
1680 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1681
1682 std::vector<MVT::ValueType> VTs;
1683 VTs.push_back(MVT::Other);
1684 VTs.push_back(MVT::Flag);
1685 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1686 Flag = Chain.getValue(1);
1687
Chris Lattner2e56e892006-01-31 02:03:41 +00001688 // If this asm returns a register value, copy the result from that register
1689 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001690 if (!RetValRegs.Regs.empty())
1691 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001692
Chris Lattner2e56e892006-01-31 02:03:41 +00001693 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1694
1695 // Process indirect outputs, first output all of the flagged copies out of
1696 // physregs.
1697 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001698 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001699 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001700 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1701 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001702 }
1703
1704 // Emit the non-flagged stores from the physregs.
1705 std::vector<SDOperand> OutChains;
1706 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1707 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1708 StoresToEmit[i].first,
1709 getValue(StoresToEmit[i].second),
1710 DAG.getSrcValue(StoresToEmit[i].second)));
1711 if (!OutChains.empty())
1712 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001713 DAG.setRoot(Chain);
1714}
1715
1716
Chris Lattner7a60d912005-01-07 07:47:53 +00001717void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1718 SDOperand Src = getValue(I.getOperand(0));
1719
1720 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001721
1722 if (IntPtr < Src.getValueType())
1723 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1724 else if (IntPtr > Src.getValueType())
1725 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001726
1727 // Scale the source by the type size.
1728 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1729 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1730 Src, getIntPtrConstant(ElementSize));
1731
1732 std::vector<std::pair<SDOperand, const Type*> > Args;
1733 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001734
1735 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001736 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001737 DAG.getExternalSymbol("malloc", IntPtr),
1738 Args, DAG);
1739 setValue(&I, Result.first); // Pointers always fit in registers
1740 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001741}
1742
1743void SelectionDAGLowering::visitFree(FreeInst &I) {
1744 std::vector<std::pair<SDOperand, const Type*> > Args;
1745 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1746 TLI.getTargetData().getIntPtrType()));
1747 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001748 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001749 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001750 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1751 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001752}
1753
Chris Lattner13d7c252005-08-26 20:54:47 +00001754// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1755// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1756// instructions are special in various ways, which require special support to
1757// insert. The specified MachineInstr is created but not inserted into any
1758// basic blocks, and the scheduler passes ownership of it to this method.
1759MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1760 MachineBasicBlock *MBB) {
1761 std::cerr << "If a target marks an instruction with "
1762 "'usesCustomDAGSchedInserter', it must implement "
1763 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1764 abort();
1765 return 0;
1766}
1767
Chris Lattner58cfd792005-01-09 00:00:49 +00001768void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001769 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1770 getValue(I.getOperand(1)),
1771 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001772}
1773
1774void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001775 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1776 getValue(I.getOperand(0)),
1777 DAG.getSrcValue(I.getOperand(0)));
1778 setValue(&I, V);
1779 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001780}
1781
1782void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001783 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1784 getValue(I.getOperand(1)),
1785 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001786}
1787
1788void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001789 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1790 getValue(I.getOperand(1)),
1791 getValue(I.getOperand(2)),
1792 DAG.getSrcValue(I.getOperand(1)),
1793 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001794}
1795
Chris Lattner58cfd792005-01-09 00:00:49 +00001796// It is always conservatively correct for llvm.returnaddress and
1797// llvm.frameaddress to return 0.
1798std::pair<SDOperand, SDOperand>
1799TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1800 unsigned Depth, SelectionDAG &DAG) {
1801 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001802}
1803
Chris Lattner29dcc712005-05-14 05:50:48 +00001804SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001805 assert(0 && "LowerOperation not implemented for this target!");
1806 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001807 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001808}
1809
Nate Begeman595ec732006-01-28 03:14:31 +00001810SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1811 SelectionDAG &DAG) {
1812 assert(0 && "CustomPromoteOperation not implemented for this target!");
1813 abort();
1814 return SDOperand();
1815}
1816
Chris Lattner58cfd792005-01-09 00:00:49 +00001817void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1818 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1819 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001820 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001821 setValue(&I, Result.first);
1822 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001823}
1824
Evan Cheng6781b6e2006-02-15 21:59:04 +00001825/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001826/// operand.
1827static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001828 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001829 MVT::ValueType CurVT = VT;
1830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1831 uint64_t Val = C->getValue() & 255;
1832 unsigned Shift = 8;
1833 while (CurVT != MVT::i8) {
1834 Val = (Val << Shift) | Val;
1835 Shift <<= 1;
1836 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001837 }
1838 return DAG.getConstant(Val, VT);
1839 } else {
1840 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1841 unsigned Shift = 8;
1842 while (CurVT != MVT::i8) {
1843 Value =
1844 DAG.getNode(ISD::OR, VT,
1845 DAG.getNode(ISD::SHL, VT, Value,
1846 DAG.getConstant(Shift, MVT::i8)), Value);
1847 Shift <<= 1;
1848 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001849 }
1850
1851 return Value;
1852 }
1853}
1854
Evan Cheng6781b6e2006-02-15 21:59:04 +00001855/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1856/// used when a memcpy is turned into a memset when the source is a constant
1857/// string ptr.
1858static SDOperand getMemsetStringVal(MVT::ValueType VT,
1859 SelectionDAG &DAG, TargetLowering &TLI,
1860 std::string &Str, unsigned Offset) {
1861 MVT::ValueType CurVT = VT;
1862 uint64_t Val = 0;
1863 unsigned MSB = getSizeInBits(VT) / 8;
1864 if (TLI.isLittleEndian())
1865 Offset = Offset + MSB - 1;
1866 for (unsigned i = 0; i != MSB; ++i) {
1867 Val = (Val << 8) | Str[Offset];
1868 Offset += TLI.isLittleEndian() ? -1 : 1;
1869 }
1870 return DAG.getConstant(Val, VT);
1871}
1872
Evan Cheng81fcea82006-02-14 08:22:34 +00001873/// getMemBasePlusOffset - Returns base and offset node for the
1874static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1875 SelectionDAG &DAG, TargetLowering &TLI) {
1876 MVT::ValueType VT = Base.getValueType();
1877 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1878}
1879
Evan Chengdb2a7a72006-02-14 20:12:38 +00001880/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001881/// to replace the memset / memcpy is below the threshold. It also returns the
1882/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001883static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1884 unsigned Limit, uint64_t Size,
1885 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001886 MVT::ValueType VT;
1887
1888 if (TLI.allowsUnalignedMemoryAccesses()) {
1889 VT = MVT::i64;
1890 } else {
1891 switch (Align & 7) {
1892 case 0:
1893 VT = MVT::i64;
1894 break;
1895 case 4:
1896 VT = MVT::i32;
1897 break;
1898 case 2:
1899 VT = MVT::i16;
1900 break;
1901 default:
1902 VT = MVT::i8;
1903 break;
1904 }
1905 }
1906
Evan Chengd5026102006-02-14 09:11:59 +00001907 MVT::ValueType LVT = MVT::i64;
1908 while (!TLI.isTypeLegal(LVT))
1909 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1910 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001911
Evan Chengd5026102006-02-14 09:11:59 +00001912 if (VT > LVT)
1913 VT = LVT;
1914
Evan Cheng04514992006-02-14 23:05:54 +00001915 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001916 while (Size != 0) {
1917 unsigned VTSize = getSizeInBits(VT) / 8;
1918 while (VTSize > Size) {
1919 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001920 VTSize >>= 1;
1921 }
Evan Chengd5026102006-02-14 09:11:59 +00001922 assert(MVT::isInteger(VT));
1923
1924 if (++NumMemOps > Limit)
1925 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001926 MemOps.push_back(VT);
1927 Size -= VTSize;
1928 }
Evan Chengd5026102006-02-14 09:11:59 +00001929
1930 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001931}
1932
Chris Lattner875def92005-01-11 05:56:49 +00001933void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001934 SDOperand Op1 = getValue(I.getOperand(1));
1935 SDOperand Op2 = getValue(I.getOperand(2));
1936 SDOperand Op3 = getValue(I.getOperand(3));
1937 SDOperand Op4 = getValue(I.getOperand(4));
1938 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1939 if (Align == 0) Align = 1;
1940
1941 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1942 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001943
1944 // Expand memset / memcpy to a series of load / store ops
1945 // if the size operand falls below a certain threshold.
1946 std::vector<SDOperand> OutChains;
1947 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001948 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001949 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001950 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1951 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001952 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001953 unsigned Offset = 0;
1954 for (unsigned i = 0; i < NumMemOps; i++) {
1955 MVT::ValueType VT = MemOps[i];
1956 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001957 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001958 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1959 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001960 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1961 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001962 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001963 Offset += VTSize;
1964 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001965 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001966 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001967 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001968 case ISD::MEMCPY: {
1969 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1970 Size->getValue(), Align, TLI)) {
1971 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001972 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001973 GlobalAddressSDNode *G = NULL;
1974 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001975 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001976
1977 if (Op2.getOpcode() == ISD::GlobalAddress)
1978 G = cast<GlobalAddressSDNode>(Op2);
1979 else if (Op2.getOpcode() == ISD::ADD &&
1980 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1981 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1982 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001983 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001984 }
1985 if (G) {
1986 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001987 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00001988 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001989 if (!Str.empty()) {
1990 CopyFromStr = true;
1991 SrcOff += SrcDelta;
1992 }
1993 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001994 }
1995
Evan Chenge2038bd2006-02-15 01:54:51 +00001996 for (unsigned i = 0; i < NumMemOps; i++) {
1997 MVT::ValueType VT = MemOps[i];
1998 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001999 SDOperand Value, Chain, Store;
2000
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002001 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002002 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2003 Chain = getRoot();
2004 Store =
2005 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2006 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2007 DAG.getSrcValue(I.getOperand(1), DstOff));
2008 } else {
2009 Value = DAG.getLoad(VT, getRoot(),
2010 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2011 DAG.getSrcValue(I.getOperand(2), SrcOff));
2012 Chain = Value.getValue(1);
2013 Store =
2014 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2015 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2016 DAG.getSrcValue(I.getOperand(1), DstOff));
2017 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002018 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002019 SrcOff += VTSize;
2020 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002021 }
2022 }
2023 break;
2024 }
2025 }
2026
2027 if (!OutChains.empty()) {
2028 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2029 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002030 }
2031 }
2032
Chris Lattner875def92005-01-11 05:56:49 +00002033 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002034 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002035 Ops.push_back(Op1);
2036 Ops.push_back(Op2);
2037 Ops.push_back(Op3);
2038 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002039 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002040}
2041
Chris Lattner875def92005-01-11 05:56:49 +00002042//===----------------------------------------------------------------------===//
2043// SelectionDAGISel code
2044//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002045
2046unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2047 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2048}
2049
Chris Lattnerc9950c12005-08-17 06:37:43 +00002050void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002051 // FIXME: we only modify the CFG to split critical edges. This
2052 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002053}
Chris Lattner7a60d912005-01-07 07:47:53 +00002054
Chris Lattner35397782005-12-05 07:10:48 +00002055
2056/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2057/// casting to the type of GEPI.
2058static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2059 Value *Ptr, Value *PtrOffset) {
2060 if (V) return V; // Already computed.
2061
2062 BasicBlock::iterator InsertPt;
2063 if (BB == GEPI->getParent()) {
2064 // If insert into the GEP's block, insert right after the GEP.
2065 InsertPt = GEPI;
2066 ++InsertPt;
2067 } else {
2068 // Otherwise, insert at the top of BB, after any PHI nodes
2069 InsertPt = BB->begin();
2070 while (isa<PHINode>(InsertPt)) ++InsertPt;
2071 }
2072
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002073 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2074 // BB so that there is only one value live across basic blocks (the cast
2075 // operand).
2076 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2077 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2078 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2079
Chris Lattner35397782005-12-05 07:10:48 +00002080 // Add the offset, cast it to the right type.
2081 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2082 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2083 return V = Ptr;
2084}
2085
2086
2087/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2088/// selection, we want to be a bit careful about some things. In particular, if
2089/// we have a GEP instruction that is used in a different block than it is
2090/// defined, the addressing expression of the GEP cannot be folded into loads or
2091/// stores that use it. In this case, decompose the GEP and move constant
2092/// indices into blocks that use it.
2093static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2094 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002095 // If this GEP is only used inside the block it is defined in, there is no
2096 // need to rewrite it.
2097 bool isUsedOutsideDefBB = false;
2098 BasicBlock *DefBB = GEPI->getParent();
2099 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2100 UI != E; ++UI) {
2101 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2102 isUsedOutsideDefBB = true;
2103 break;
2104 }
2105 }
2106 if (!isUsedOutsideDefBB) return;
2107
2108 // If this GEP has no non-zero constant indices, there is nothing we can do,
2109 // ignore it.
2110 bool hasConstantIndex = false;
2111 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2112 E = GEPI->op_end(); OI != E; ++OI) {
2113 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2114 if (CI->getRawValue()) {
2115 hasConstantIndex = true;
2116 break;
2117 }
2118 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002119 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2120 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002121
2122 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2123 // constant offset (which we now know is non-zero) and deal with it later.
2124 uint64_t ConstantOffset = 0;
2125 const Type *UIntPtrTy = TD.getIntPtrType();
2126 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2127 const Type *Ty = GEPI->getOperand(0)->getType();
2128
2129 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2130 E = GEPI->op_end(); OI != E; ++OI) {
2131 Value *Idx = *OI;
2132 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2133 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2134 if (Field)
2135 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2136 Ty = StTy->getElementType(Field);
2137 } else {
2138 Ty = cast<SequentialType>(Ty)->getElementType();
2139
2140 // Handle constant subscripts.
2141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2142 if (CI->getRawValue() == 0) continue;
2143
2144 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2145 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2146 else
2147 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2148 continue;
2149 }
2150
2151 // Ptr = Ptr + Idx * ElementSize;
2152
2153 // Cast Idx to UIntPtrTy if needed.
2154 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2155
2156 uint64_t ElementSize = TD.getTypeSize(Ty);
2157 // Mask off bits that should not be set.
2158 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2159 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2160
2161 // Multiply by the element size and add to the base.
2162 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2163 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2164 }
2165 }
2166
2167 // Make sure that the offset fits in uintptr_t.
2168 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2169 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2170
2171 // Okay, we have now emitted all of the variable index parts to the BB that
2172 // the GEP is defined in. Loop over all of the using instructions, inserting
2173 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002174 // instruction to use the newly computed value, making GEPI dead. When the
2175 // user is a load or store instruction address, we emit the add into the user
2176 // block, otherwise we use a canonical version right next to the gep (these
2177 // won't be foldable as addresses, so we might as well share the computation).
2178
Chris Lattner35397782005-12-05 07:10:48 +00002179 std::map<BasicBlock*,Value*> InsertedExprs;
2180 while (!GEPI->use_empty()) {
2181 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002182
2183 // If this use is not foldable into the addressing mode, use a version
2184 // emitted in the GEP block.
2185 Value *NewVal;
2186 if (!isa<LoadInst>(User) &&
2187 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2188 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2189 Ptr, PtrOffset);
2190 } else {
2191 // Otherwise, insert the code in the User's block so it can be folded into
2192 // any users in that block.
2193 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002194 User->getParent(), GEPI,
2195 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002196 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002197 User->replaceUsesOfWith(GEPI, NewVal);
2198 }
Chris Lattner35397782005-12-05 07:10:48 +00002199
2200 // Finally, the GEP is dead, remove it.
2201 GEPI->eraseFromParent();
2202}
2203
Chris Lattner7a60d912005-01-07 07:47:53 +00002204bool SelectionDAGISel::runOnFunction(Function &Fn) {
2205 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2206 RegMap = MF.getSSARegMap();
2207 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2208
Chris Lattner35397782005-12-05 07:10:48 +00002209 // First, split all critical edges for PHI nodes with incoming values that are
2210 // constants, this way the load of the constant into a vreg will not be placed
2211 // into MBBs that are used some other way.
2212 //
2213 // In this pass we also look for GEP instructions that are used across basic
2214 // blocks and rewrites them to improve basic-block-at-a-time selection.
2215 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002216 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2217 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002218 BasicBlock::iterator BBI;
2219 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002220 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2221 if (isa<Constant>(PN->getIncomingValue(i)))
2222 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002223
2224 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2225 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2226 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002227 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002228
Chris Lattner7a60d912005-01-07 07:47:53 +00002229 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2230
2231 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2232 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002233
Chris Lattner7a60d912005-01-07 07:47:53 +00002234 return true;
2235}
2236
2237
Chris Lattner718b5c22005-01-13 17:59:43 +00002238SDOperand SelectionDAGISel::
2239CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002240 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002241 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002242 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002243 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002244
2245 // If this type is not legal, we must make sure to not create an invalid
2246 // register use.
2247 MVT::ValueType SrcVT = Op.getValueType();
2248 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2249 SelectionDAG &DAG = SDL.DAG;
2250 if (SrcVT == DestVT) {
2251 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2252 } else if (SrcVT < DestVT) {
2253 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002254 if (MVT::isFloatingPoint(SrcVT))
2255 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2256 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002257 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002258 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2259 } else {
2260 // The src value is expanded into multiple registers.
2261 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2262 Op, DAG.getConstant(0, MVT::i32));
2263 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2264 Op, DAG.getConstant(1, MVT::i32));
2265 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2266 return DAG.getCopyToReg(Op, Reg+1, Hi);
2267 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002268}
2269
Chris Lattner16f64df2005-01-17 17:15:02 +00002270void SelectionDAGISel::
2271LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2272 std::vector<SDOperand> &UnorderedChains) {
2273 // If this is the entry block, emit arguments.
2274 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002275 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002276 SDOperand OldRoot = SDL.DAG.getRoot();
2277 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002278
Chris Lattner6871b232005-10-30 19:42:35 +00002279 unsigned a = 0;
2280 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2281 AI != E; ++AI, ++a)
2282 if (!AI->use_empty()) {
2283 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002284
Chris Lattner6871b232005-10-30 19:42:35 +00002285 // If this argument is live outside of the entry block, insert a copy from
2286 // whereever we got it to the vreg that other BB's will reference it as.
2287 if (FuncInfo.ValueMap.count(AI)) {
2288 SDOperand Copy =
2289 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2290 UnorderedChains.push_back(Copy);
2291 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002292 }
Chris Lattner6871b232005-10-30 19:42:35 +00002293
2294 // Next, if the function has live ins that need to be copied into vregs,
2295 // emit the copies now, into the top of the block.
2296 MachineFunction &MF = SDL.DAG.getMachineFunction();
2297 if (MF.livein_begin() != MF.livein_end()) {
2298 SSARegMap *RegMap = MF.getSSARegMap();
2299 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2300 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2301 E = MF.livein_end(); LI != E; ++LI)
2302 if (LI->second)
2303 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2304 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002305 }
Chris Lattner6871b232005-10-30 19:42:35 +00002306
2307 // Finally, if the target has anything special to do, allow it to do so.
2308 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002309}
2310
2311
Chris Lattner7a60d912005-01-07 07:47:53 +00002312void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2313 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2314 FunctionLoweringInfo &FuncInfo) {
2315 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002316
2317 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002318
Chris Lattner6871b232005-10-30 19:42:35 +00002319 // Lower any arguments needed in this block if this is the entry block.
2320 if (LLVMBB == &LLVMBB->getParent()->front())
2321 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002322
2323 BB = FuncInfo.MBBMap[LLVMBB];
2324 SDL.setCurrentBasicBlock(BB);
2325
2326 // Lower all of the non-terminator instructions.
2327 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2328 I != E; ++I)
2329 SDL.visit(*I);
2330
2331 // Ensure that all instructions which are used outside of their defining
2332 // blocks are available as virtual registers.
2333 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002334 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002335 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002336 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002337 UnorderedChains.push_back(
2338 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002339 }
2340
2341 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2342 // ensure constants are generated when needed. Remember the virtual registers
2343 // that need to be added to the Machine PHI nodes as input. We cannot just
2344 // directly add them, because expansion might result in multiple MBB's for one
2345 // BB. As such, the start of the BB might correspond to a different MBB than
2346 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002347 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002348
2349 // Emit constants only once even if used by multiple PHI nodes.
2350 std::map<Constant*, unsigned> ConstantsOut;
2351
2352 // Check successor nodes PHI nodes that expect a constant to be available from
2353 // this block.
2354 TerminatorInst *TI = LLVMBB->getTerminator();
2355 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2356 BasicBlock *SuccBB = TI->getSuccessor(succ);
2357 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2358 PHINode *PN;
2359
2360 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2361 // nodes and Machine PHI nodes, but the incoming operands have not been
2362 // emitted yet.
2363 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002364 (PN = dyn_cast<PHINode>(I)); ++I)
2365 if (!PN->use_empty()) {
2366 unsigned Reg;
2367 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2368 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2369 unsigned &RegOut = ConstantsOut[C];
2370 if (RegOut == 0) {
2371 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002372 UnorderedChains.push_back(
2373 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002374 }
2375 Reg = RegOut;
2376 } else {
2377 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002378 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002379 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002380 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2381 "Didn't codegen value into a register!??");
2382 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002383 UnorderedChains.push_back(
2384 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002385 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002386 }
Misha Brukman835702a2005-04-21 22:36:52 +00002387
Chris Lattner8ea875f2005-01-07 21:34:19 +00002388 // Remember that this register needs to added to the machine PHI node as
2389 // the input for this MBB.
2390 unsigned NumElements =
2391 TLI.getNumElements(TLI.getValueType(PN->getType()));
2392 for (unsigned i = 0, e = NumElements; i != e; ++i)
2393 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002394 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002395 }
2396 ConstantsOut.clear();
2397
Chris Lattner718b5c22005-01-13 17:59:43 +00002398 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002399 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002400 SDOperand Root = SDL.getRoot();
2401 if (Root.getOpcode() != ISD::EntryToken) {
2402 unsigned i = 0, e = UnorderedChains.size();
2403 for (; i != e; ++i) {
2404 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2405 if (UnorderedChains[i].Val->getOperand(0) == Root)
2406 break; // Don't add the root if we already indirectly depend on it.
2407 }
2408
2409 if (i == e)
2410 UnorderedChains.push_back(Root);
2411 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002412 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2413 }
2414
Chris Lattner7a60d912005-01-07 07:47:53 +00002415 // Lower the terminator after the copies are emitted.
2416 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002417
2418 // Make sure the root of the DAG is up-to-date.
2419 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002420}
2421
2422void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2423 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002424 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002425 CurDAG = &DAG;
2426 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2427
2428 // First step, lower LLVM code to some DAG. This DAG may use operations and
2429 // types that are not supported by the target.
2430 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2431
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002432 // Run the DAG combiner in pre-legalize mode.
2433 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002434
Chris Lattner7a60d912005-01-07 07:47:53 +00002435 DEBUG(std::cerr << "Lowered selection DAG:\n");
2436 DEBUG(DAG.dump());
2437
2438 // Second step, hack on the DAG until it only uses operations and types that
2439 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002440 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002441
2442 DEBUG(std::cerr << "Legalized selection DAG:\n");
2443 DEBUG(DAG.dump());
2444
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002445 // Run the DAG combiner in post-legalize mode.
2446 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002447
Evan Cheng739a6a42006-01-21 02:32:06 +00002448 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002449
Chris Lattner5ca31d92005-03-30 01:10:47 +00002450 // Third, instruction select all of the operations to machine code, adding the
2451 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002452 InstructionSelectBasicBlock(DAG);
2453
Chris Lattner7a60d912005-01-07 07:47:53 +00002454 DEBUG(std::cerr << "Selected machine code:\n");
2455 DEBUG(BB->dump());
2456
Chris Lattner5ca31d92005-03-30 01:10:47 +00002457 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002458 // PHI nodes in successors.
2459 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2460 MachineInstr *PHI = PHINodesToUpdate[i].first;
2461 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2462 "This is not a machine PHI node that we are updating!");
2463 PHI->addRegOperand(PHINodesToUpdate[i].second);
2464 PHI->addMachineBasicBlockOperand(BB);
2465 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002466
2467 // Finally, add the CFG edges from the last selected MBB to the successor
2468 // MBBs.
2469 TerminatorInst *TI = LLVMBB->getTerminator();
2470 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2471 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2472 BB->addSuccessor(Succ0MBB);
2473 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002474}
Evan Cheng739a6a42006-01-21 02:32:06 +00002475
2476//===----------------------------------------------------------------------===//
2477/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2478/// target node in the graph.
2479void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2480 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002481 ScheduleDAG *SL = NULL;
2482
2483 switch (ISHeuristic) {
2484 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002485 case defaultScheduling:
2486 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2487 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2488 else /* TargetLowering::SchedulingForRegPressure */
2489 SL = createBURRListDAGScheduler(DAG, BB);
2490 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002491 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002492 SL = createBFS_DAGScheduler(DAG, BB);
2493 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002494 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002495 SL = createSimpleDAGScheduler(false, DAG, BB);
2496 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002497 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002498 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002499 break;
Evan Cheng31272342006-01-23 08:26:10 +00002500 case listSchedulingBURR:
2501 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002502 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002503 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002504 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002505 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002506 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002507 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002508 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002509}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002510
Chris Lattner543832d2006-03-08 04:25:59 +00002511HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2512 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002513}
2514
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002515/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2516/// by tblgen. Others should not call it.
2517void SelectionDAGISel::
2518SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2519 std::vector<SDOperand> InOps;
2520 std::swap(InOps, Ops);
2521
2522 Ops.push_back(InOps[0]); // input chain.
2523 Ops.push_back(InOps[1]); // input asm string.
2524
2525 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2526 unsigned i = 2, e = InOps.size();
2527 if (InOps[e-1].getValueType() == MVT::Flag)
2528 --e; // Don't process a flag operand if it is here.
2529
2530 while (i != e) {
2531 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2532 if ((Flags & 7) != 4 /*MEM*/) {
2533 // Just skip over this operand, copying the operands verbatim.
2534 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2535 i += (Flags >> 3) + 1;
2536 } else {
2537 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2538 // Otherwise, this is a memory operand. Ask the target to select it.
2539 std::vector<SDOperand> SelOps;
2540 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2541 std::cerr << "Could not match memory address. Inline asm failure!\n";
2542 exit(1);
2543 }
2544
2545 // Add this to the output node.
2546 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2547 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2548 i += 2;
2549 }
2550 }
2551
2552 // Add the flag input back if present.
2553 if (e != InOps.size())
2554 Ops.push_back(InOps.back());
2555}