blob: 8254f6ed921c0f965d1e045f0290efdeca2673ae [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 Lattner49409cb2006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
185/// PHI nodes or outside of the basic block that defines it.
186static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
187 if (isa<PHINode>(I)) return true;
188 BasicBlock *BB = I->getParent();
189 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
190 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
191 return true;
192 return false;
193}
194
Chris Lattner6871b232005-10-30 19:42:35 +0000195/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
196/// entry block, return true.
197static bool isOnlyUsedInEntryBlock(Argument *A) {
198 BasicBlock *Entry = A->getParent()->begin();
199 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != Entry)
201 return false; // Use not in entry block.
202 return true;
203}
204
Chris Lattner7a60d912005-01-07 07:47:53 +0000205FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000206 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
208
Chris Lattner6871b232005-10-30 19:42:35 +0000209 // Create a vreg for each argument register that is not dead and is used
210 // outside of the entry block for the function.
211 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
212 AI != E; ++AI)
213 if (!isOnlyUsedInEntryBlock(AI))
214 InitializeRegForValue(AI);
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216 // Initialize the mapping of values to registers. This is only set up for
217 // instruction values that are used outside of the block that defines
218 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000219 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
222 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
223 const Type *Ty = AI->getAllocatedType();
224 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000225 unsigned Align =
226 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
227 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000228
229 // If the alignment of the value is smaller than the size of the value,
230 // and if the size of the value is particularly small (<= 8 bytes),
231 // round up to the size of the value for potentially better performance.
232 //
233 // FIXME: This could be made better with a preferred alignment hook in
234 // TargetData. It serves primarily to 8-byte align doubles for X86.
235 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000236 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000237 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000239 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 }
241
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000242 for (; BB != EB; ++BB)
243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
245 if (!isa<AllocaInst>(I) ||
246 !StaticAllocaMap.count(cast<AllocaInst>(I)))
247 InitializeRegForValue(I);
248
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000252 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
254 MBBMap[BB] = MBB;
255 MF.getBasicBlockList().push_back(MBB);
256
257 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
258 // appropriate.
259 PHINode *PN;
260 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000261 (PN = dyn_cast<PHINode>(I)); ++I)
262 if (!PN->use_empty()) {
263 unsigned NumElements =
264 TLI.getNumElements(TLI.getValueType(PN->getType()));
265 unsigned PHIReg = ValueMap[PN];
266 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
267 for (unsigned i = 0; i != NumElements; ++i)
268 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
269 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000270 }
271}
272
Chris Lattner49409cb2006-03-16 19:51:18 +0000273/// CreateRegForValue - Allocate the appropriate number of virtual registers of
274/// the correctly promoted or expanded types. Assign these registers
275/// consecutive vreg numbers and return the first assigned number.
276unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278
279 // The number of multiples of registers that we need, to, e.g., split up
280 // a <2 x int64> -> 4 x i32 registers.
281 unsigned NumVectorRegs = 1;
282
283 // If this is a packed type, figure out what type it will decompose into
284 // and how many of the elements it will use.
285 if (VT == MVT::Vector) {
286 const PackedType *PTy = cast<PackedType>(V->getType());
287 unsigned NumElts = PTy->getNumElements();
288 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
289
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
293 NumElts >>= 1;
294 NumVectorRegs <<= 1;
295 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000296 if (NumElts == 1)
297 VT = EltTy;
298 else
299 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000300 }
301
302 // The common case is that we will only create one register for this
303 // value. If we have that case, create and return the virtual register.
304 unsigned NV = TLI.getNumElements(VT);
305 if (NV == 1) {
306 // If we are promoting this value, pick the next largest supported type.
307 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
308 unsigned Reg = MakeReg(PromotedType);
309 // If this is a vector of supported or promoted types (e.g. 4 x i16),
310 // create all of the registers.
311 for (unsigned i = 1; i != NumVectorRegs; ++i)
312 MakeReg(PromotedType);
313 return Reg;
314 }
315
316 // If this value is represented with multiple target registers, make sure
317 // to create enough consecutive registers of the right (smaller) type.
318 unsigned NT = VT-1; // Find the type to use.
319 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
320 --NT;
321
322 unsigned R = MakeReg((MVT::ValueType)NT);
323 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
324 MakeReg((MVT::ValueType)NT);
325 return R;
326}
Chris Lattner7a60d912005-01-07 07:47:53 +0000327
328//===----------------------------------------------------------------------===//
329/// SelectionDAGLowering - This is the common target-independent lowering
330/// implementation that is parameterized by a TargetLowering object.
331/// Also, targets can overload any lowering method.
332///
333namespace llvm {
334class SelectionDAGLowering {
335 MachineBasicBlock *CurMBB;
336
337 std::map<const Value*, SDOperand> NodeMap;
338
Chris Lattner4d9651c2005-01-17 22:19:26 +0000339 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
340 /// them up and then emit token factor nodes when possible. This allows us to
341 /// get simple disambiguation between loads without worrying about alias
342 /// analysis.
343 std::vector<SDOperand> PendingLoads;
344
Chris Lattner7a60d912005-01-07 07:47:53 +0000345public:
346 // TLI - This is information that describes the available target features we
347 // need for lowering. This indicates when operations are unavailable,
348 // implemented with a libcall, etc.
349 TargetLowering &TLI;
350 SelectionDAG &DAG;
351 const TargetData &TD;
352
353 /// FuncInfo - Information about the function as a whole.
354 ///
355 FunctionLoweringInfo &FuncInfo;
356
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000358 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000359 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
360 FuncInfo(funcinfo) {
361 }
362
Chris Lattner4108bb02005-01-17 19:43:36 +0000363 /// getRoot - Return the current virtual root of the Selection DAG.
364 ///
365 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000366 if (PendingLoads.empty())
367 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000368
Chris Lattner4d9651c2005-01-17 22:19:26 +0000369 if (PendingLoads.size() == 1) {
370 SDOperand Root = PendingLoads[0];
371 DAG.setRoot(Root);
372 PendingLoads.clear();
373 return Root;
374 }
375
376 // Otherwise, we have to make a token factor node.
377 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
378 PendingLoads.clear();
379 DAG.setRoot(Root);
380 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000381 }
382
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 void visit(Instruction &I) { visit(I.getOpcode(), I); }
384
385 void visit(unsigned Opcode, User &I) {
386 switch (Opcode) {
387 default: assert(0 && "Unknown instruction type encountered!");
388 abort();
389 // Build the switch statement using the Instruction.def file.
390#define HANDLE_INST(NUM, OPCODE, CLASS) \
391 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
392#include "llvm/Instruction.def"
393 }
394 }
395
396 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
397
Chris Lattner4024c002006-03-15 22:19:46 +0000398 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
399 SDOperand SrcValue, SDOperand Root,
400 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000401
402 SDOperand getIntPtrConstant(uint64_t Val) {
403 return DAG.getConstant(Val, TLI.getPointerTy());
404 }
405
Chris Lattner8471b152006-03-16 19:57:50 +0000406 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407
408 const SDOperand &setValue(const Value *V, SDOperand NewN) {
409 SDOperand &N = NodeMap[V];
410 assert(N.Val == 0 && "Already set a value for this node!");
411 return N = NewN;
412 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000413
Chris Lattner6f87d182006-02-22 22:37:12 +0000414 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
415 MVT::ValueType VT,
416 bool OutReg, bool InReg,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
419
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
424
425 // These all get lowered before this pass.
426 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
427 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
428 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
429
430 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000431 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000432 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000433 void visitAdd(User &I) {
434 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000435 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000436 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000437 void visitMul(User &I) {
438 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000439 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000441 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000442 visitBinary(I,
443 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
444 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 }
446 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000447 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000448 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000449 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000450 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
451 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
452 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000453 void visitShl(User &I) { visitShift(I, ISD::SHL); }
454 void visitShr(User &I) {
455 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 }
457
458 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
459 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
460 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
461 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
462 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
463 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
464 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
465
Chris Lattner32206f52006-03-18 01:44:44 +0000466 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
467 void visitInsertElement(InsertElementInst &I);
468
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 void visitGetElementPtr(User &I);
470 void visitCast(User &I);
471 void visitSelect(User &I);
472 //
473
474 void visitMalloc(MallocInst &I);
475 void visitFree(FreeInst &I);
476 void visitAlloca(AllocaInst &I);
477 void visitLoad(LoadInst &I);
478 void visitStore(StoreInst &I);
479 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
480 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000481 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000482 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000483
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 void visitVAArg(VAArgInst &I);
486 void visitVAEnd(CallInst &I);
487 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000488 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489
Chris Lattner875def92005-01-11 05:56:49 +0000490 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000491
492 void visitUserOp1(Instruction &I) {
493 assert(0 && "UserOp1 should not exist at instruction selection time!");
494 abort();
495 }
496 void visitUserOp2(Instruction &I) {
497 assert(0 && "UserOp2 should not exist at instruction selection time!");
498 abort();
499 }
500};
501} // end namespace llvm
502
Chris Lattner8471b152006-03-16 19:57:50 +0000503SDOperand SelectionDAGLowering::getValue(const Value *V) {
504 SDOperand &N = NodeMap[V];
505 if (N.Val) return N;
506
507 const Type *VTy = V->getType();
508 MVT::ValueType VT = TLI.getValueType(VTy);
509 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
511 visit(CE->getOpcode(), *CE);
512 assert(N.Val && "visit didn't populate the ValueMap!");
513 return N;
514 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
515 return N = DAG.getGlobalAddress(GV, VT);
516 } else if (isa<ConstantPointerNull>(C)) {
517 return N = DAG.getConstant(0, TLI.getPointerTy());
518 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000519 if (!isa<PackedType>(VTy))
520 return N = DAG.getNode(ISD::UNDEF, VT);
521
522 // Create a VConstant of undef nodes.
523 const PackedType *PTy = cast<PackedType>(VTy);
524 unsigned NumElements = PTy->getNumElements();
525 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
526
527 std::vector<SDOperand> Ops;
528 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
529
530 // Create a VConstant node with generic Vector type.
531 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
532 Ops.push_back(DAG.getValueType(PVT));
533 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000534 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
535 return N = DAG.getConstantFP(CFP->getValue(), VT);
536 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
537 unsigned NumElements = PTy->getNumElements();
538 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000539
540 // Now that we know the number and type of the elements, push a
541 // Constant or ConstantFP node onto the ops list for each element of
542 // the packed constant.
543 std::vector<SDOperand> Ops;
544 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
545 if (MVT::isFloatingPoint(PVT)) {
546 for (unsigned i = 0; i != NumElements; ++i) {
547 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
548 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
549 }
550 } else {
551 for (unsigned i = 0; i != NumElements; ++i) {
552 const ConstantIntegral *El =
553 cast<ConstantIntegral>(CP->getOperand(i));
554 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
555 }
556 }
557 } else {
558 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
559 SDOperand Op;
560 if (MVT::isFloatingPoint(PVT))
561 Op = DAG.getConstantFP(0, PVT);
562 else
563 Op = DAG.getConstant(0, PVT);
564 Ops.assign(NumElements, Op);
565 }
566
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000567 // Create a VConstant node with generic Vector type.
568 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
569 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner32206f52006-03-18 01:44:44 +0000570 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000571 } else {
572 // Canonicalize all constant ints to be unsigned.
573 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
574 }
575 }
576
577 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
578 std::map<const AllocaInst*, int>::iterator SI =
579 FuncInfo.StaticAllocaMap.find(AI);
580 if (SI != FuncInfo.StaticAllocaMap.end())
581 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
582 }
583
584 std::map<const Value*, unsigned>::const_iterator VMI =
585 FuncInfo.ValueMap.find(V);
586 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
587
588 unsigned InReg = VMI->second;
589
590 // If this type is not legal, make it so now.
591 if (VT == MVT::Vector) {
592 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
593 const PackedType *PTy = cast<PackedType>(VTy);
594 unsigned NumElements = PTy->getNumElements();
595 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
596 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
597 assert(TLI.isTypeLegal(TVT) &&
598 "FIXME: Cannot handle illegal vector types here yet!");
599 VT = TVT;
600 }
601
602 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
603
604 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
605 if (DestVT < VT) {
606 // Source must be expanded. This input value is actually coming from the
607 // register pair VMI->second and VMI->second+1.
608 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
609 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
610 } else {
611 if (DestVT > VT) { // Promotion case
612 if (MVT::isFloatingPoint(VT))
613 N = DAG.getNode(ISD::FP_ROUND, VT, N);
614 else
615 N = DAG.getNode(ISD::TRUNCATE, VT, N);
616 }
617 }
618
619 return N;
620}
621
622
Chris Lattner7a60d912005-01-07 07:47:53 +0000623void SelectionDAGLowering::visitRet(ReturnInst &I) {
624 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000625 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000626 return;
627 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000628 std::vector<SDOperand> NewValues;
629 NewValues.push_back(getRoot());
630 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
631 SDOperand RetOp = getValue(I.getOperand(i));
632
633 // If this is an integer return value, we need to promote it ourselves to
634 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
635 // than sign/zero.
636 if (MVT::isInteger(RetOp.getValueType()) &&
637 RetOp.getValueType() < MVT::i64) {
638 MVT::ValueType TmpVT;
639 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
640 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
641 else
642 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000643
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000644 if (I.getOperand(i)->getType()->isSigned())
645 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
646 else
647 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
648 }
649 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000650 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000651 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000652}
653
654void SelectionDAGLowering::visitBr(BranchInst &I) {
655 // Update machine-CFG edges.
656 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000657
658 // Figure out which block is immediately after the current one.
659 MachineBasicBlock *NextBlock = 0;
660 MachineFunction::iterator BBI = CurMBB;
661 if (++BBI != CurMBB->getParent()->end())
662 NextBlock = BBI;
663
664 if (I.isUnconditional()) {
665 // If this is not a fall-through branch, emit the branch.
666 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000667 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000668 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000669 } else {
670 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000671
672 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000673 if (Succ1MBB == NextBlock) {
674 // If the condition is false, fall through. This means we should branch
675 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000676 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000677 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000678 } else if (Succ0MBB == NextBlock) {
679 // If the condition is true, fall through. This means we should branch if
680 // the condition is false to Succ #1. Invert the condition first.
681 SDOperand True = DAG.getConstant(1, Cond.getValueType());
682 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000683 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000684 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000685 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000686 std::vector<SDOperand> Ops;
687 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000688 // If the false case is the current basic block, then this is a self
689 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
690 // adds an extra instruction in the loop. Instead, invert the
691 // condition and emit "Loop: ... br!cond Loop; br Out.
692 if (CurMBB == Succ1MBB) {
693 std::swap(Succ0MBB, Succ1MBB);
694 SDOperand True = DAG.getConstant(1, Cond.getValueType());
695 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
696 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000697 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
698 DAG.getBasicBlock(Succ0MBB));
699 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
700 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000701 }
702 }
703}
704
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000705void SelectionDAGLowering::visitSub(User &I) {
706 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000707 if (I.getType()->isFloatingPoint()) {
708 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
709 if (CFP->isExactlyValue(-0.0)) {
710 SDOperand Op2 = getValue(I.getOperand(1));
711 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
712 return;
713 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000714 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000715 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000716}
717
Nate Begemanb2e089c2005-11-19 00:36:38 +0000718void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
719 unsigned VecOp) {
720 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000721 SDOperand Op1 = getValue(I.getOperand(0));
722 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000723
Chris Lattner19baba62005-11-19 18:40:42 +0000724 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000725 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
726 } else if (Ty->isFloatingPoint()) {
727 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
728 } else {
729 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000730 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
731 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
732 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000733 }
Nate Begeman127321b2005-11-18 07:42:56 +0000734}
Chris Lattner96c26752005-01-19 22:31:21 +0000735
Nate Begeman127321b2005-11-18 07:42:56 +0000736void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
737 SDOperand Op1 = getValue(I.getOperand(0));
738 SDOperand Op2 = getValue(I.getOperand(1));
739
740 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
741
Chris Lattner7a60d912005-01-07 07:47:53 +0000742 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
743}
744
745void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
746 ISD::CondCode UnsignedOpcode) {
747 SDOperand Op1 = getValue(I.getOperand(0));
748 SDOperand Op2 = getValue(I.getOperand(1));
749 ISD::CondCode Opcode = SignedOpcode;
750 if (I.getOperand(0)->getType()->isUnsigned())
751 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000752 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000753}
754
755void SelectionDAGLowering::visitSelect(User &I) {
756 SDOperand Cond = getValue(I.getOperand(0));
757 SDOperand TrueVal = getValue(I.getOperand(1));
758 SDOperand FalseVal = getValue(I.getOperand(2));
759 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
760 TrueVal, FalseVal));
761}
762
763void SelectionDAGLowering::visitCast(User &I) {
764 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000765 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
766 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000767
Chris Lattner4024c002006-03-15 22:19:46 +0000768 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000769 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000770 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000771 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000772 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000773 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000774 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000775 } else if (isInteger(SrcVT)) {
776 if (isInteger(DestVT)) { // Int -> Int cast
777 if (DestVT < SrcVT) // Truncating cast?
778 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000779 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000780 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000781 else
Chris Lattner4024c002006-03-15 22:19:46 +0000782 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000783 } else { // Int -> FP cast
784 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000785 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000786 else
Chris Lattner4024c002006-03-15 22:19:46 +0000787 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000788 }
Chris Lattner4024c002006-03-15 22:19:46 +0000789 } else if (isFloatingPoint(SrcVT)) {
790 if (isFloatingPoint(DestVT)) { // FP -> FP cast
791 if (DestVT < SrcVT) // Rounding cast?
792 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000793 else
Chris Lattner4024c002006-03-15 22:19:46 +0000794 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000795 } else { // FP -> Int cast.
796 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000797 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000798 else
Chris Lattner4024c002006-03-15 22:19:46 +0000799 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
800 }
801 } else {
Chris Lattner32206f52006-03-18 01:44:44 +0000802 assert(0 && "Cannot bitconvert vectors yet!");
803#if 0
Chris Lattner4024c002006-03-15 22:19:46 +0000804 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
805 const PackedType *DstTy = cast<PackedType>(I.getType());
806
807 unsigned SrcNumElements = SrcTy->getNumElements();
808 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
809 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
810
811 unsigned DstNumElements = DstTy->getNumElements();
812 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
813 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
814
815 // If the input and output type are legal, convert this to a bit convert of
816 // the SrcTVT/DstTVT types.
817 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
818 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
819 assert(N.getValueType() == SrcTVT);
820 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
821 } else {
822 // Otherwise, convert this directly into a store/load.
823 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
824 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
825 // Create the stack frame object.
826 uint64_t ByteSize = TD.getTypeSize(SrcTy);
827 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
828 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
829 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
830 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
831
832 // Emit a store to the stack slot.
833 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
834 N, FIPtr, DAG.getSrcValue(NULL));
835 // Result is a load from the stack slot.
836 SDOperand Val =
837 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
838 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000839 }
Chris Lattner32206f52006-03-18 01:44:44 +0000840#endif
Chris Lattner7a60d912005-01-07 07:47:53 +0000841 }
842}
843
Chris Lattner32206f52006-03-18 01:44:44 +0000844void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
845 const PackedType *Ty = cast<PackedType>(I.getType());
846 unsigned NumElements = Ty->getNumElements();
847 MVT::ValueType PVT = TLI.getValueType(Ty->getElementType());
848 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
849
850 SDOperand InVec = getValue(I.getOperand(0));
851 SDOperand InVal = getValue(I.getOperand(1));
852 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
853 getValue(I.getOperand(2)));
854
855 // Immediately scalarize packed types containing only one element, so that
856 // the Legalize pass does not have to deal with them. Similarly, if the
857 // abstract vector is going to turn into one that the target natively
858 // supports, generate that type now so that Legalize doesn't have to deal
859 // with that either. These steps ensure that Legalize only has to handle
860 // vector types in its Expand case.
861 if (NumElements == 1) {
862 setValue(&I, InVal); // Must be insertelt(Vec, InVal, 0) -> InVal
863 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
864 TLI.isOperationLegal(ISD::INSERT_VECTOR_ELT, TVT)) {
865 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, TVT, InVec, InVal, InIdx));
866 } else {
867 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
868 SDOperand Typ = DAG.getValueType(PVT);
869 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
870 InVec, InVal, InIdx, Num, Typ));
871 }
872}
873
874
Chris Lattner7a60d912005-01-07 07:47:53 +0000875void SelectionDAGLowering::visitGetElementPtr(User &I) {
876 SDOperand N = getValue(I.getOperand(0));
877 const Type *Ty = I.getOperand(0)->getType();
878 const Type *UIntPtrTy = TD.getIntPtrType();
879
880 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
881 OI != E; ++OI) {
882 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000883 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000884 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
885 if (Field) {
886 // N = N + Offset
887 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
888 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000889 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000890 }
891 Ty = StTy->getElementType(Field);
892 } else {
893 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000894
Chris Lattner43535a12005-11-09 04:45:33 +0000895 // If this is a constant subscript, handle it quickly.
896 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
897 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000898
Chris Lattner43535a12005-11-09 04:45:33 +0000899 uint64_t Offs;
900 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
901 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
902 else
903 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
904 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
905 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000906 }
Chris Lattner43535a12005-11-09 04:45:33 +0000907
908 // N = N + Idx * ElementSize;
909 uint64_t ElementSize = TD.getTypeSize(Ty);
910 SDOperand IdxN = getValue(Idx);
911
912 // If the index is smaller or larger than intptr_t, truncate or extend
913 // it.
914 if (IdxN.getValueType() < N.getValueType()) {
915 if (Idx->getType()->isSigned())
916 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
917 else
918 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
919 } else if (IdxN.getValueType() > N.getValueType())
920 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
921
922 // If this is a multiply by a power of two, turn it into a shl
923 // immediately. This is a very common case.
924 if (isPowerOf2_64(ElementSize)) {
925 unsigned Amt = Log2_64(ElementSize);
926 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000927 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000928 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
929 continue;
930 }
931
932 SDOperand Scale = getIntPtrConstant(ElementSize);
933 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
934 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000935 }
936 }
937 setValue(&I, N);
938}
939
940void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
941 // If this is a fixed sized alloca in the entry block of the function,
942 // allocate it statically on the stack.
943 if (FuncInfo.StaticAllocaMap.count(&I))
944 return; // getValue will auto-populate this.
945
946 const Type *Ty = I.getAllocatedType();
947 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000948 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
949 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000950
951 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000952 MVT::ValueType IntPtr = TLI.getPointerTy();
953 if (IntPtr < AllocSize.getValueType())
954 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
955 else if (IntPtr > AllocSize.getValueType())
956 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000957
Chris Lattnereccb73d2005-01-22 23:04:37 +0000958 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000959 getIntPtrConstant(TySize));
960
961 // Handle alignment. If the requested alignment is less than or equal to the
962 // stack alignment, ignore it and round the size of the allocation up to the
963 // stack alignment size. If the size is greater than the stack alignment, we
964 // note this in the DYNAMIC_STACKALLOC node.
965 unsigned StackAlign =
966 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
967 if (Align <= StackAlign) {
968 Align = 0;
969 // Add SA-1 to the size.
970 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
971 getIntPtrConstant(StackAlign-1));
972 // Mask out the low bits for alignment purposes.
973 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
974 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
975 }
976
Chris Lattner96c262e2005-05-14 07:29:57 +0000977 std::vector<MVT::ValueType> VTs;
978 VTs.push_back(AllocSize.getValueType());
979 VTs.push_back(MVT::Other);
980 std::vector<SDOperand> Ops;
981 Ops.push_back(getRoot());
982 Ops.push_back(AllocSize);
983 Ops.push_back(getIntPtrConstant(Align));
984 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000985 DAG.setRoot(setValue(&I, DSA).getValue(1));
986
987 // Inform the Frame Information that we have just allocated a variable-sized
988 // object.
989 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
990}
991
Chris Lattner7a60d912005-01-07 07:47:53 +0000992void SelectionDAGLowering::visitLoad(LoadInst &I) {
993 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000994
Chris Lattner4d9651c2005-01-17 22:19:26 +0000995 SDOperand Root;
996 if (I.isVolatile())
997 Root = getRoot();
998 else {
999 // Do not serialize non-volatile loads against each other.
1000 Root = DAG.getRoot();
1001 }
Chris Lattner4024c002006-03-15 22:19:46 +00001002
1003 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1004 Root, I.isVolatile()));
1005}
1006
1007SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1008 SDOperand SrcValue, SDOperand Root,
1009 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001010 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001011 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001012 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001013 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001014 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001015 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001016 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001017
Chris Lattner4024c002006-03-15 22:19:46 +00001018 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001019 DAG.setRoot(L.getValue(1));
1020 else
1021 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001022
1023 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001024}
1025
1026
1027void SelectionDAGLowering::visitStore(StoreInst &I) {
1028 Value *SrcV = I.getOperand(0);
1029 SDOperand Src = getValue(SrcV);
1030 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001031 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001032 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001033}
1034
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001035/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1036/// we want to emit this as a call to a named external function, return the name
1037/// otherwise lower it and return null.
1038const char *
1039SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1040 switch (Intrinsic) {
1041 case Intrinsic::vastart: visitVAStart(I); return 0;
1042 case Intrinsic::vaend: visitVAEnd(I); return 0;
1043 case Intrinsic::vacopy: visitVACopy(I); return 0;
1044 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1045 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1046 case Intrinsic::setjmp:
1047 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1048 break;
1049 case Intrinsic::longjmp:
1050 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1051 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001052 case Intrinsic::memcpy_i32:
1053 case Intrinsic::memcpy_i64:
1054 visitMemIntrinsic(I, ISD::MEMCPY);
1055 return 0;
1056 case Intrinsic::memset_i32:
1057 case Intrinsic::memset_i64:
1058 visitMemIntrinsic(I, ISD::MEMSET);
1059 return 0;
1060 case Intrinsic::memmove_i32:
1061 case Intrinsic::memmove_i64:
1062 visitMemIntrinsic(I, ISD::MEMMOVE);
1063 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001064
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001065 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001066 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001067 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001068 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001069
Jim Laskey5995d012006-02-11 01:01:30 +00001070 // Input Chain
1071 Ops.push_back(getRoot());
1072
1073 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001074 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001075
1076 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001077 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001078
Jim Laskeyacb6e342006-03-13 13:07:37 +00001079 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001080 assert(DD && "Not a debug information descriptor");
1081 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1082 assert(CompileUnit && "Not a compile unit");
1083 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1084 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1085
1086 if (Ops.size() == 5) // Found filename/workingdir.
1087 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001088 }
1089
Chris Lattner8782b782005-12-03 18:50:48 +00001090 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001091 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001092 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001093 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001094 if (I.getType() != Type::VoidTy)
1095 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1096 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001097 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001098 if (I.getType() != Type::VoidTy)
1099 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1100 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001101 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001102 if (I.getType() != Type::VoidTy)
1103 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1104 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001105
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001106 case Intrinsic::isunordered_f32:
1107 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001108 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1109 getValue(I.getOperand(2)), ISD::SETUO));
1110 return 0;
1111
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001112 case Intrinsic::sqrt_f32:
1113 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001114 setValue(&I, DAG.getNode(ISD::FSQRT,
1115 getValue(I.getOperand(1)).getValueType(),
1116 getValue(I.getOperand(1))));
1117 return 0;
1118 case Intrinsic::pcmarker: {
1119 SDOperand Tmp = getValue(I.getOperand(1));
1120 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1121 return 0;
1122 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001123 case Intrinsic::readcyclecounter: {
1124 std::vector<MVT::ValueType> VTs;
1125 VTs.push_back(MVT::i64);
1126 VTs.push_back(MVT::Other);
1127 std::vector<SDOperand> Ops;
1128 Ops.push_back(getRoot());
1129 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1130 setValue(&I, Tmp);
1131 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001132 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001133 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001134 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001135 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001136 case Intrinsic::bswap_i64:
1137 setValue(&I, DAG.getNode(ISD::BSWAP,
1138 getValue(I.getOperand(1)).getValueType(),
1139 getValue(I.getOperand(1))));
1140 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001141 case Intrinsic::cttz_i8:
1142 case Intrinsic::cttz_i16:
1143 case Intrinsic::cttz_i32:
1144 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001145 setValue(&I, DAG.getNode(ISD::CTTZ,
1146 getValue(I.getOperand(1)).getValueType(),
1147 getValue(I.getOperand(1))));
1148 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001149 case Intrinsic::ctlz_i8:
1150 case Intrinsic::ctlz_i16:
1151 case Intrinsic::ctlz_i32:
1152 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001153 setValue(&I, DAG.getNode(ISD::CTLZ,
1154 getValue(I.getOperand(1)).getValueType(),
1155 getValue(I.getOperand(1))));
1156 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001157 case Intrinsic::ctpop_i8:
1158 case Intrinsic::ctpop_i16:
1159 case Intrinsic::ctpop_i32:
1160 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001161 setValue(&I, DAG.getNode(ISD::CTPOP,
1162 getValue(I.getOperand(1)).getValueType(),
1163 getValue(I.getOperand(1))));
1164 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001165 case Intrinsic::stacksave: {
1166 std::vector<MVT::ValueType> VTs;
1167 VTs.push_back(TLI.getPointerTy());
1168 VTs.push_back(MVT::Other);
1169 std::vector<SDOperand> Ops;
1170 Ops.push_back(getRoot());
1171 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1172 setValue(&I, Tmp);
1173 DAG.setRoot(Tmp.getValue(1));
1174 return 0;
1175 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001176 case Intrinsic::stackrestore: {
1177 SDOperand Tmp = getValue(I.getOperand(1));
1178 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001179 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001180 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001181 case Intrinsic::prefetch:
1182 // FIXME: Currently discarding prefetches.
1183 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001184 default:
1185 std::cerr << I;
1186 assert(0 && "This intrinsic is not implemented yet!");
1187 return 0;
1188 }
1189}
1190
1191
Chris Lattner7a60d912005-01-07 07:47:53 +00001192void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001193 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001194 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001195 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001196 if (unsigned IID = F->getIntrinsicID()) {
1197 RenameFn = visitIntrinsicCall(I, IID);
1198 if (!RenameFn)
1199 return;
1200 } else { // Not an LLVM intrinsic.
1201 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001202 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1203 if (I.getNumOperands() == 3 && // Basic sanity checks.
1204 I.getOperand(1)->getType()->isFloatingPoint() &&
1205 I.getType() == I.getOperand(1)->getType() &&
1206 I.getType() == I.getOperand(2)->getType()) {
1207 SDOperand LHS = getValue(I.getOperand(1));
1208 SDOperand RHS = getValue(I.getOperand(2));
1209 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1210 LHS, RHS));
1211 return;
1212 }
1213 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001214 if (I.getNumOperands() == 2 && // Basic sanity checks.
1215 I.getOperand(1)->getType()->isFloatingPoint() &&
1216 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001217 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001218 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1219 return;
1220 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001221 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001222 if (I.getNumOperands() == 2 && // Basic sanity checks.
1223 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001224 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001225 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001226 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1227 return;
1228 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001229 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001230 if (I.getNumOperands() == 2 && // Basic sanity checks.
1231 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001232 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001233 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001234 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1235 return;
1236 }
1237 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001238 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001239 } else if (isa<InlineAsm>(I.getOperand(0))) {
1240 visitInlineAsm(I);
1241 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001242 }
Misha Brukman835702a2005-04-21 22:36:52 +00001243
Chris Lattner18d2b342005-01-08 22:48:57 +00001244 SDOperand Callee;
1245 if (!RenameFn)
1246 Callee = getValue(I.getOperand(0));
1247 else
1248 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001249 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001250 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001251 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1252 Value *Arg = I.getOperand(i);
1253 SDOperand ArgNode = getValue(Arg);
1254 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1255 }
Misha Brukman835702a2005-04-21 22:36:52 +00001256
Nate Begemanf6565252005-03-26 01:29:23 +00001257 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1258 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001259
Chris Lattner1f45cd72005-01-08 19:26:18 +00001260 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001261 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001262 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001263 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001264 setValue(&I, Result.first);
1265 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001266}
1267
Chris Lattner6f87d182006-02-22 22:37:12 +00001268SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001269 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001270 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1271 Chain = Val.getValue(1);
1272 Flag = Val.getValue(2);
1273
1274 // If the result was expanded, copy from the top part.
1275 if (Regs.size() > 1) {
1276 assert(Regs.size() == 2 &&
1277 "Cannot expand to more than 2 elts yet!");
1278 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1279 Chain = Val.getValue(1);
1280 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001281 if (DAG.getTargetLoweringInfo().isLittleEndian())
1282 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1283 else
1284 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001285 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001286
Chris Lattner6f87d182006-02-22 22:37:12 +00001287 // Otherwise, if the return value was promoted, truncate it to the
1288 // appropriate type.
1289 if (RegVT == ValueVT)
1290 return Val;
1291
1292 if (MVT::isInteger(RegVT))
1293 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1294 else
1295 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1296}
1297
Chris Lattner571d9642006-02-23 19:21:04 +00001298/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1299/// specified value into the registers specified by this object. This uses
1300/// Chain/Flag as the input and updates them for the output Chain/Flag.
1301void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001302 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001303 if (Regs.size() == 1) {
1304 // If there is a single register and the types differ, this must be
1305 // a promotion.
1306 if (RegVT != ValueVT) {
1307 if (MVT::isInteger(RegVT))
1308 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1309 else
1310 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1311 }
1312 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1313 Flag = Chain.getValue(1);
1314 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001315 std::vector<unsigned> R(Regs);
1316 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1317 std::reverse(R.begin(), R.end());
1318
1319 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001320 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1321 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001322 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001323 Flag = Chain.getValue(1);
1324 }
1325 }
1326}
Chris Lattner6f87d182006-02-22 22:37:12 +00001327
Chris Lattner571d9642006-02-23 19:21:04 +00001328/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1329/// operand list. This adds the code marker and includes the number of
1330/// values added into it.
1331void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001332 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001333 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1334 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1335 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1336}
Chris Lattner6f87d182006-02-22 22:37:12 +00001337
1338/// isAllocatableRegister - If the specified register is safe to allocate,
1339/// i.e. it isn't a stack pointer or some other special register, return the
1340/// register class for the register. Otherwise, return null.
1341static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001342isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1343 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1344 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1345 E = MRI->regclass_end(); RCI != E; ++RCI) {
1346 const TargetRegisterClass *RC = *RCI;
1347 // If none of the the value types for this register class are valid, we
1348 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1349 bool isLegal = false;
1350 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1351 I != E; ++I) {
1352 if (TLI.isTypeLegal(*I)) {
1353 isLegal = true;
1354 break;
1355 }
1356 }
1357
1358 if (!isLegal) continue;
1359
Chris Lattner6f87d182006-02-22 22:37:12 +00001360 // NOTE: This isn't ideal. In particular, this might allocate the
1361 // frame pointer in functions that need it (due to them not being taken
1362 // out of allocation, because a variable sized allocation hasn't been seen
1363 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001364 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1365 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001366 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001367 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001368 }
1369 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001370}
1371
1372RegsForValue SelectionDAGLowering::
1373GetRegistersForValue(const std::string &ConstrCode,
1374 MVT::ValueType VT, bool isOutReg, bool isInReg,
1375 std::set<unsigned> &OutputRegs,
1376 std::set<unsigned> &InputRegs) {
1377 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1378 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1379 std::vector<unsigned> Regs;
1380
1381 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1382 MVT::ValueType RegVT;
1383 MVT::ValueType ValueVT = VT;
1384
1385 if (PhysReg.first) {
1386 if (VT == MVT::Other)
1387 ValueVT = *PhysReg.second->vt_begin();
1388 RegVT = VT;
1389
1390 // This is a explicit reference to a physical register.
1391 Regs.push_back(PhysReg.first);
1392
1393 // If this is an expanded reference, add the rest of the regs to Regs.
1394 if (NumRegs != 1) {
1395 RegVT = *PhysReg.second->vt_begin();
1396 TargetRegisterClass::iterator I = PhysReg.second->begin();
1397 TargetRegisterClass::iterator E = PhysReg.second->end();
1398 for (; *I != PhysReg.first; ++I)
1399 assert(I != E && "Didn't find reg!");
1400
1401 // Already added the first reg.
1402 --NumRegs; ++I;
1403 for (; NumRegs; --NumRegs, ++I) {
1404 assert(I != E && "Ran out of registers to allocate!");
1405 Regs.push_back(*I);
1406 }
1407 }
1408 return RegsForValue(Regs, RegVT, ValueVT);
1409 }
1410
1411 // This is a reference to a register class. Allocate NumRegs consecutive,
1412 // available, registers from the class.
1413 std::vector<unsigned> RegClassRegs =
1414 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1415
1416 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1417 MachineFunction &MF = *CurMBB->getParent();
1418 unsigned NumAllocated = 0;
1419 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1420 unsigned Reg = RegClassRegs[i];
1421 // See if this register is available.
1422 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1423 (isInReg && InputRegs.count(Reg))) { // Already used.
1424 // Make sure we find consecutive registers.
1425 NumAllocated = 0;
1426 continue;
1427 }
1428
1429 // Check to see if this register is allocatable (i.e. don't give out the
1430 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001431 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001432 if (!RC) {
1433 // Make sure we find consecutive registers.
1434 NumAllocated = 0;
1435 continue;
1436 }
1437
1438 // Okay, this register is good, we can use it.
1439 ++NumAllocated;
1440
1441 // If we allocated enough consecutive
1442 if (NumAllocated == NumRegs) {
1443 unsigned RegStart = (i-NumAllocated)+1;
1444 unsigned RegEnd = i+1;
1445 // Mark all of the allocated registers used.
1446 for (unsigned i = RegStart; i != RegEnd; ++i) {
1447 unsigned Reg = RegClassRegs[i];
1448 Regs.push_back(Reg);
1449 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1450 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1451 }
1452
1453 return RegsForValue(Regs, *RC->vt_begin(), VT);
1454 }
1455 }
1456
1457 // Otherwise, we couldn't allocate enough registers for this.
1458 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001459}
1460
Chris Lattner6f87d182006-02-22 22:37:12 +00001461
Chris Lattner476e67b2006-01-26 22:24:51 +00001462/// visitInlineAsm - Handle a call to an InlineAsm object.
1463///
1464void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1465 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1466
1467 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1468 MVT::Other);
1469
1470 // Note, we treat inline asms both with and without side-effects as the same.
1471 // If an inline asm doesn't have side effects and doesn't access memory, we
1472 // could not choose to not chain it.
1473 bool hasSideEffects = IA->hasSideEffects();
1474
Chris Lattner3a5ed552006-02-01 01:28:23 +00001475 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001476 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001477
1478 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1479 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1480 /// if it is a def of that register.
1481 std::vector<SDOperand> AsmNodeOperands;
1482 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1483 AsmNodeOperands.push_back(AsmStr);
1484
1485 SDOperand Chain = getRoot();
1486 SDOperand Flag;
1487
Chris Lattner1558fc62006-02-01 18:59:47 +00001488 // We fully assign registers here at isel time. This is not optimal, but
1489 // should work. For register classes that correspond to LLVM classes, we
1490 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1491 // over the constraints, collecting fixed registers that we know we can't use.
1492 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001493 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001494 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1495 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1496 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001497
Chris Lattner7ad77df2006-02-22 00:56:39 +00001498 MVT::ValueType OpVT;
1499
1500 // Compute the value type for each operand and add it to ConstraintVTs.
1501 switch (Constraints[i].Type) {
1502 case InlineAsm::isOutput:
1503 if (!Constraints[i].isIndirectOutput) {
1504 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1505 OpVT = TLI.getValueType(I.getType());
1506 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001507 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001508 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1509 OpNum++; // Consumes a call operand.
1510 }
1511 break;
1512 case InlineAsm::isInput:
1513 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1514 OpNum++; // Consumes a call operand.
1515 break;
1516 case InlineAsm::isClobber:
1517 OpVT = MVT::Other;
1518 break;
1519 }
1520
1521 ConstraintVTs.push_back(OpVT);
1522
Chris Lattner6f87d182006-02-22 22:37:12 +00001523 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1524 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001525
Chris Lattner6f87d182006-02-22 22:37:12 +00001526 // Build a list of regs that this operand uses. This always has a single
1527 // element for promoted/expanded operands.
1528 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1529 false, false,
1530 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001531
1532 switch (Constraints[i].Type) {
1533 case InlineAsm::isOutput:
1534 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001535 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001536 // If this is an early-clobber output, it cannot be assigned to the same
1537 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001538 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001539 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001540 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001541 case InlineAsm::isInput:
1542 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001543 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001544 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001545 case InlineAsm::isClobber:
1546 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001547 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1548 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001549 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001550 }
1551 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001552
Chris Lattner5c79f982006-02-21 23:12:12 +00001553 // Loop over all of the inputs, copying the operand values into the
1554 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001555 RegsForValue RetValRegs;
1556 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001557 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001558
Chris Lattner2e56e892006-01-31 02:03:41 +00001559 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001560 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1561 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001562
Chris Lattner3a5ed552006-02-01 01:28:23 +00001563 switch (Constraints[i].Type) {
1564 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001565 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1566 if (ConstraintCode.size() == 1) // not a physreg name.
1567 CTy = TLI.getConstraintType(ConstraintCode[0]);
1568
1569 if (CTy == TargetLowering::C_Memory) {
1570 // Memory output.
1571 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1572
1573 // Check that the operand (the address to store to) isn't a float.
1574 if (!MVT::isInteger(InOperandVal.getValueType()))
1575 assert(0 && "MATCH FAIL!");
1576
1577 if (!Constraints[i].isIndirectOutput)
1578 assert(0 && "MATCH FAIL!");
1579
1580 OpNum++; // Consumes a call operand.
1581
1582 // Extend/truncate to the right pointer type if needed.
1583 MVT::ValueType PtrType = TLI.getPointerTy();
1584 if (InOperandVal.getValueType() < PtrType)
1585 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1586 else if (InOperandVal.getValueType() > PtrType)
1587 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1588
1589 // Add information to the INLINEASM node to know about this output.
1590 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1591 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1592 AsmNodeOperands.push_back(InOperandVal);
1593 break;
1594 }
1595
1596 // Otherwise, this is a register output.
1597 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1598
Chris Lattner6f87d182006-02-22 22:37:12 +00001599 // If this is an early-clobber output, or if there is an input
1600 // constraint that matches this, we need to reserve the input register
1601 // so no other inputs allocate to it.
1602 bool UsesInputRegister = false;
1603 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1604 UsesInputRegister = true;
1605
1606 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001607 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001608 RegsForValue Regs =
1609 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1610 true, UsesInputRegister,
1611 OutputRegs, InputRegs);
1612 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001613
Chris Lattner3a5ed552006-02-01 01:28:23 +00001614 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001615 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001616 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001617 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001618 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001619 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001620 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1621 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001622 OpNum++; // Consumes a call operand.
1623 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001624
1625 // Add information to the INLINEASM node to know that this register is
1626 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001627 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001628 break;
1629 }
1630 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001631 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001632 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001633
Chris Lattner7f5880b2006-02-02 00:25:23 +00001634 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1635 // If this is required to match an output register we have already set,
1636 // just use its register.
1637 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001638
Chris Lattner571d9642006-02-23 19:21:04 +00001639 // Scan until we find the definition we already emitted of this operand.
1640 // When we find it, create a RegsForValue operand.
1641 unsigned CurOp = 2; // The first operand.
1642 for (; OperandNo; --OperandNo) {
1643 // Advance to the next operand.
1644 unsigned NumOps =
1645 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1646 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1647 "Skipped past definitions?");
1648 CurOp += (NumOps>>3)+1;
1649 }
1650
1651 unsigned NumOps =
1652 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1653 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1654 "Skipped past definitions?");
1655
1656 // Add NumOps>>3 registers to MatchedRegs.
1657 RegsForValue MatchedRegs;
1658 MatchedRegs.ValueVT = InOperandVal.getValueType();
1659 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1660 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1661 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1662 MatchedRegs.Regs.push_back(Reg);
1663 }
1664
1665 // Use the produced MatchedRegs object to
1666 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1667 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001668 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001669 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001670
1671 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1672 if (ConstraintCode.size() == 1) // not a physreg name.
1673 CTy = TLI.getConstraintType(ConstraintCode[0]);
1674
1675 if (CTy == TargetLowering::C_Other) {
1676 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1677 assert(0 && "MATCH FAIL!");
1678
1679 // Add information to the INLINEASM node to know about this input.
1680 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1681 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1682 AsmNodeOperands.push_back(InOperandVal);
1683 break;
1684 } else if (CTy == TargetLowering::C_Memory) {
1685 // Memory input.
1686
1687 // Check that the operand isn't a float.
1688 if (!MVT::isInteger(InOperandVal.getValueType()))
1689 assert(0 && "MATCH FAIL!");
1690
1691 // Extend/truncate to the right pointer type if needed.
1692 MVT::ValueType PtrType = TLI.getPointerTy();
1693 if (InOperandVal.getValueType() < PtrType)
1694 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1695 else if (InOperandVal.getValueType() > PtrType)
1696 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1697
1698 // Add information to the INLINEASM node to know about this input.
1699 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1700 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1701 AsmNodeOperands.push_back(InOperandVal);
1702 break;
1703 }
1704
1705 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1706
1707 // Copy the input into the appropriate registers.
1708 RegsForValue InRegs =
1709 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1710 false, true, OutputRegs, InputRegs);
1711 // FIXME: should be match fail.
1712 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1713
1714 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1715
1716 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001717 break;
1718 }
Chris Lattner571d9642006-02-23 19:21:04 +00001719 case InlineAsm::isClobber: {
1720 RegsForValue ClobberedRegs =
1721 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1722 OutputRegs, InputRegs);
1723 // Add the clobbered value to the operand list, so that the register
1724 // allocator is aware that the physreg got clobbered.
1725 if (!ClobberedRegs.Regs.empty())
1726 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001727 break;
1728 }
Chris Lattner571d9642006-02-23 19:21:04 +00001729 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001730 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001731
1732 // Finish up input operands.
1733 AsmNodeOperands[0] = Chain;
1734 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1735
1736 std::vector<MVT::ValueType> VTs;
1737 VTs.push_back(MVT::Other);
1738 VTs.push_back(MVT::Flag);
1739 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1740 Flag = Chain.getValue(1);
1741
Chris Lattner2e56e892006-01-31 02:03:41 +00001742 // If this asm returns a register value, copy the result from that register
1743 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001744 if (!RetValRegs.Regs.empty())
1745 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001746
Chris Lattner2e56e892006-01-31 02:03:41 +00001747 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1748
1749 // Process indirect outputs, first output all of the flagged copies out of
1750 // physregs.
1751 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001752 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001753 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001754 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1755 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001756 }
1757
1758 // Emit the non-flagged stores from the physregs.
1759 std::vector<SDOperand> OutChains;
1760 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1761 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1762 StoresToEmit[i].first,
1763 getValue(StoresToEmit[i].second),
1764 DAG.getSrcValue(StoresToEmit[i].second)));
1765 if (!OutChains.empty())
1766 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001767 DAG.setRoot(Chain);
1768}
1769
1770
Chris Lattner7a60d912005-01-07 07:47:53 +00001771void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1772 SDOperand Src = getValue(I.getOperand(0));
1773
1774 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001775
1776 if (IntPtr < Src.getValueType())
1777 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1778 else if (IntPtr > Src.getValueType())
1779 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001780
1781 // Scale the source by the type size.
1782 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1783 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1784 Src, getIntPtrConstant(ElementSize));
1785
1786 std::vector<std::pair<SDOperand, const Type*> > Args;
1787 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001788
1789 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001790 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001791 DAG.getExternalSymbol("malloc", IntPtr),
1792 Args, DAG);
1793 setValue(&I, Result.first); // Pointers always fit in registers
1794 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001795}
1796
1797void SelectionDAGLowering::visitFree(FreeInst &I) {
1798 std::vector<std::pair<SDOperand, const Type*> > Args;
1799 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1800 TLI.getTargetData().getIntPtrType()));
1801 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001802 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001803 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001804 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1805 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001806}
1807
Chris Lattner13d7c252005-08-26 20:54:47 +00001808// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1809// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1810// instructions are special in various ways, which require special support to
1811// insert. The specified MachineInstr is created but not inserted into any
1812// basic blocks, and the scheduler passes ownership of it to this method.
1813MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1814 MachineBasicBlock *MBB) {
1815 std::cerr << "If a target marks an instruction with "
1816 "'usesCustomDAGSchedInserter', it must implement "
1817 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1818 abort();
1819 return 0;
1820}
1821
Chris Lattner58cfd792005-01-09 00:00:49 +00001822void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001823 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1824 getValue(I.getOperand(1)),
1825 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001826}
1827
1828void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001829 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1830 getValue(I.getOperand(0)),
1831 DAG.getSrcValue(I.getOperand(0)));
1832 setValue(&I, V);
1833 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001834}
1835
1836void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001837 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1838 getValue(I.getOperand(1)),
1839 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001840}
1841
1842void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001843 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1844 getValue(I.getOperand(1)),
1845 getValue(I.getOperand(2)),
1846 DAG.getSrcValue(I.getOperand(1)),
1847 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001848}
1849
Chris Lattner58cfd792005-01-09 00:00:49 +00001850// It is always conservatively correct for llvm.returnaddress and
1851// llvm.frameaddress to return 0.
1852std::pair<SDOperand, SDOperand>
1853TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1854 unsigned Depth, SelectionDAG &DAG) {
1855 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001856}
1857
Chris Lattner29dcc712005-05-14 05:50:48 +00001858SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001859 assert(0 && "LowerOperation not implemented for this target!");
1860 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001861 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001862}
1863
Nate Begeman595ec732006-01-28 03:14:31 +00001864SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1865 SelectionDAG &DAG) {
1866 assert(0 && "CustomPromoteOperation not implemented for this target!");
1867 abort();
1868 return SDOperand();
1869}
1870
Chris Lattner58cfd792005-01-09 00:00:49 +00001871void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1872 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1873 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001874 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001875 setValue(&I, Result.first);
1876 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001877}
1878
Evan Cheng6781b6e2006-02-15 21:59:04 +00001879/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001880/// operand.
1881static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001882 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001883 MVT::ValueType CurVT = VT;
1884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1885 uint64_t Val = C->getValue() & 255;
1886 unsigned Shift = 8;
1887 while (CurVT != MVT::i8) {
1888 Val = (Val << Shift) | Val;
1889 Shift <<= 1;
1890 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001891 }
1892 return DAG.getConstant(Val, VT);
1893 } else {
1894 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1895 unsigned Shift = 8;
1896 while (CurVT != MVT::i8) {
1897 Value =
1898 DAG.getNode(ISD::OR, VT,
1899 DAG.getNode(ISD::SHL, VT, Value,
1900 DAG.getConstant(Shift, MVT::i8)), Value);
1901 Shift <<= 1;
1902 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001903 }
1904
1905 return Value;
1906 }
1907}
1908
Evan Cheng6781b6e2006-02-15 21:59:04 +00001909/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1910/// used when a memcpy is turned into a memset when the source is a constant
1911/// string ptr.
1912static SDOperand getMemsetStringVal(MVT::ValueType VT,
1913 SelectionDAG &DAG, TargetLowering &TLI,
1914 std::string &Str, unsigned Offset) {
1915 MVT::ValueType CurVT = VT;
1916 uint64_t Val = 0;
1917 unsigned MSB = getSizeInBits(VT) / 8;
1918 if (TLI.isLittleEndian())
1919 Offset = Offset + MSB - 1;
1920 for (unsigned i = 0; i != MSB; ++i) {
1921 Val = (Val << 8) | Str[Offset];
1922 Offset += TLI.isLittleEndian() ? -1 : 1;
1923 }
1924 return DAG.getConstant(Val, VT);
1925}
1926
Evan Cheng81fcea82006-02-14 08:22:34 +00001927/// getMemBasePlusOffset - Returns base and offset node for the
1928static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1929 SelectionDAG &DAG, TargetLowering &TLI) {
1930 MVT::ValueType VT = Base.getValueType();
1931 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1932}
1933
Evan Chengdb2a7a72006-02-14 20:12:38 +00001934/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001935/// to replace the memset / memcpy is below the threshold. It also returns the
1936/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001937static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1938 unsigned Limit, uint64_t Size,
1939 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001940 MVT::ValueType VT;
1941
1942 if (TLI.allowsUnalignedMemoryAccesses()) {
1943 VT = MVT::i64;
1944 } else {
1945 switch (Align & 7) {
1946 case 0:
1947 VT = MVT::i64;
1948 break;
1949 case 4:
1950 VT = MVT::i32;
1951 break;
1952 case 2:
1953 VT = MVT::i16;
1954 break;
1955 default:
1956 VT = MVT::i8;
1957 break;
1958 }
1959 }
1960
Evan Chengd5026102006-02-14 09:11:59 +00001961 MVT::ValueType LVT = MVT::i64;
1962 while (!TLI.isTypeLegal(LVT))
1963 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1964 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001965
Evan Chengd5026102006-02-14 09:11:59 +00001966 if (VT > LVT)
1967 VT = LVT;
1968
Evan Cheng04514992006-02-14 23:05:54 +00001969 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001970 while (Size != 0) {
1971 unsigned VTSize = getSizeInBits(VT) / 8;
1972 while (VTSize > Size) {
1973 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001974 VTSize >>= 1;
1975 }
Evan Chengd5026102006-02-14 09:11:59 +00001976 assert(MVT::isInteger(VT));
1977
1978 if (++NumMemOps > Limit)
1979 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001980 MemOps.push_back(VT);
1981 Size -= VTSize;
1982 }
Evan Chengd5026102006-02-14 09:11:59 +00001983
1984 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001985}
1986
Chris Lattner875def92005-01-11 05:56:49 +00001987void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001988 SDOperand Op1 = getValue(I.getOperand(1));
1989 SDOperand Op2 = getValue(I.getOperand(2));
1990 SDOperand Op3 = getValue(I.getOperand(3));
1991 SDOperand Op4 = getValue(I.getOperand(4));
1992 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1993 if (Align == 0) Align = 1;
1994
1995 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1996 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001997
1998 // Expand memset / memcpy to a series of load / store ops
1999 // if the size operand falls below a certain threshold.
2000 std::vector<SDOperand> OutChains;
2001 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002002 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002003 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002004 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2005 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002006 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002007 unsigned Offset = 0;
2008 for (unsigned i = 0; i < NumMemOps; i++) {
2009 MVT::ValueType VT = MemOps[i];
2010 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002011 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002012 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2013 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002014 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2015 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002016 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002017 Offset += VTSize;
2018 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002019 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002020 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002021 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002022 case ISD::MEMCPY: {
2023 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2024 Size->getValue(), Align, TLI)) {
2025 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002026 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002027 GlobalAddressSDNode *G = NULL;
2028 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002029 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002030
2031 if (Op2.getOpcode() == ISD::GlobalAddress)
2032 G = cast<GlobalAddressSDNode>(Op2);
2033 else if (Op2.getOpcode() == ISD::ADD &&
2034 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2035 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2036 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002037 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002038 }
2039 if (G) {
2040 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002041 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002042 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002043 if (!Str.empty()) {
2044 CopyFromStr = true;
2045 SrcOff += SrcDelta;
2046 }
2047 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002048 }
2049
Evan Chenge2038bd2006-02-15 01:54:51 +00002050 for (unsigned i = 0; i < NumMemOps; i++) {
2051 MVT::ValueType VT = MemOps[i];
2052 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002053 SDOperand Value, Chain, Store;
2054
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002055 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002056 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2057 Chain = getRoot();
2058 Store =
2059 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2060 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2061 DAG.getSrcValue(I.getOperand(1), DstOff));
2062 } else {
2063 Value = DAG.getLoad(VT, getRoot(),
2064 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2065 DAG.getSrcValue(I.getOperand(2), SrcOff));
2066 Chain = Value.getValue(1);
2067 Store =
2068 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2069 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2070 DAG.getSrcValue(I.getOperand(1), DstOff));
2071 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002072 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002073 SrcOff += VTSize;
2074 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002075 }
2076 }
2077 break;
2078 }
2079 }
2080
2081 if (!OutChains.empty()) {
2082 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2083 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002084 }
2085 }
2086
Chris Lattner875def92005-01-11 05:56:49 +00002087 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002088 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002089 Ops.push_back(Op1);
2090 Ops.push_back(Op2);
2091 Ops.push_back(Op3);
2092 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002093 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002094}
2095
Chris Lattner875def92005-01-11 05:56:49 +00002096//===----------------------------------------------------------------------===//
2097// SelectionDAGISel code
2098//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002099
2100unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2101 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2102}
2103
Chris Lattnerc9950c12005-08-17 06:37:43 +00002104void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002105 // FIXME: we only modify the CFG to split critical edges. This
2106 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002107}
Chris Lattner7a60d912005-01-07 07:47:53 +00002108
Chris Lattner35397782005-12-05 07:10:48 +00002109
2110/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2111/// casting to the type of GEPI.
2112static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2113 Value *Ptr, Value *PtrOffset) {
2114 if (V) return V; // Already computed.
2115
2116 BasicBlock::iterator InsertPt;
2117 if (BB == GEPI->getParent()) {
2118 // If insert into the GEP's block, insert right after the GEP.
2119 InsertPt = GEPI;
2120 ++InsertPt;
2121 } else {
2122 // Otherwise, insert at the top of BB, after any PHI nodes
2123 InsertPt = BB->begin();
2124 while (isa<PHINode>(InsertPt)) ++InsertPt;
2125 }
2126
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002127 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2128 // BB so that there is only one value live across basic blocks (the cast
2129 // operand).
2130 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2131 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2132 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2133
Chris Lattner35397782005-12-05 07:10:48 +00002134 // Add the offset, cast it to the right type.
2135 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2136 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2137 return V = Ptr;
2138}
2139
2140
2141/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2142/// selection, we want to be a bit careful about some things. In particular, if
2143/// we have a GEP instruction that is used in a different block than it is
2144/// defined, the addressing expression of the GEP cannot be folded into loads or
2145/// stores that use it. In this case, decompose the GEP and move constant
2146/// indices into blocks that use it.
2147static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2148 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002149 // If this GEP is only used inside the block it is defined in, there is no
2150 // need to rewrite it.
2151 bool isUsedOutsideDefBB = false;
2152 BasicBlock *DefBB = GEPI->getParent();
2153 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2154 UI != E; ++UI) {
2155 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2156 isUsedOutsideDefBB = true;
2157 break;
2158 }
2159 }
2160 if (!isUsedOutsideDefBB) return;
2161
2162 // If this GEP has no non-zero constant indices, there is nothing we can do,
2163 // ignore it.
2164 bool hasConstantIndex = false;
2165 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2166 E = GEPI->op_end(); OI != E; ++OI) {
2167 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2168 if (CI->getRawValue()) {
2169 hasConstantIndex = true;
2170 break;
2171 }
2172 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002173 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2174 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002175
2176 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2177 // constant offset (which we now know is non-zero) and deal with it later.
2178 uint64_t ConstantOffset = 0;
2179 const Type *UIntPtrTy = TD.getIntPtrType();
2180 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2181 const Type *Ty = GEPI->getOperand(0)->getType();
2182
2183 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2184 E = GEPI->op_end(); OI != E; ++OI) {
2185 Value *Idx = *OI;
2186 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2187 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2188 if (Field)
2189 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2190 Ty = StTy->getElementType(Field);
2191 } else {
2192 Ty = cast<SequentialType>(Ty)->getElementType();
2193
2194 // Handle constant subscripts.
2195 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2196 if (CI->getRawValue() == 0) continue;
2197
2198 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2199 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2200 else
2201 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2202 continue;
2203 }
2204
2205 // Ptr = Ptr + Idx * ElementSize;
2206
2207 // Cast Idx to UIntPtrTy if needed.
2208 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2209
2210 uint64_t ElementSize = TD.getTypeSize(Ty);
2211 // Mask off bits that should not be set.
2212 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2213 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2214
2215 // Multiply by the element size and add to the base.
2216 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2217 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2218 }
2219 }
2220
2221 // Make sure that the offset fits in uintptr_t.
2222 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2223 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2224
2225 // Okay, we have now emitted all of the variable index parts to the BB that
2226 // the GEP is defined in. Loop over all of the using instructions, inserting
2227 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002228 // instruction to use the newly computed value, making GEPI dead. When the
2229 // user is a load or store instruction address, we emit the add into the user
2230 // block, otherwise we use a canonical version right next to the gep (these
2231 // won't be foldable as addresses, so we might as well share the computation).
2232
Chris Lattner35397782005-12-05 07:10:48 +00002233 std::map<BasicBlock*,Value*> InsertedExprs;
2234 while (!GEPI->use_empty()) {
2235 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002236
2237 // If this use is not foldable into the addressing mode, use a version
2238 // emitted in the GEP block.
2239 Value *NewVal;
2240 if (!isa<LoadInst>(User) &&
2241 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2242 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2243 Ptr, PtrOffset);
2244 } else {
2245 // Otherwise, insert the code in the User's block so it can be folded into
2246 // any users in that block.
2247 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002248 User->getParent(), GEPI,
2249 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002250 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002251 User->replaceUsesOfWith(GEPI, NewVal);
2252 }
Chris Lattner35397782005-12-05 07:10:48 +00002253
2254 // Finally, the GEP is dead, remove it.
2255 GEPI->eraseFromParent();
2256}
2257
Chris Lattner7a60d912005-01-07 07:47:53 +00002258bool SelectionDAGISel::runOnFunction(Function &Fn) {
2259 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2260 RegMap = MF.getSSARegMap();
2261 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2262
Chris Lattner35397782005-12-05 07:10:48 +00002263 // First, split all critical edges for PHI nodes with incoming values that are
2264 // constants, this way the load of the constant into a vreg will not be placed
2265 // into MBBs that are used some other way.
2266 //
2267 // In this pass we also look for GEP instructions that are used across basic
2268 // blocks and rewrites them to improve basic-block-at-a-time selection.
2269 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002270 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2271 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002272 BasicBlock::iterator BBI;
2273 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002274 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2275 if (isa<Constant>(PN->getIncomingValue(i)))
2276 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002277
2278 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2279 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2280 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002281 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002282
Chris Lattner7a60d912005-01-07 07:47:53 +00002283 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2284
2285 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2286 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002287
Chris Lattner7a60d912005-01-07 07:47:53 +00002288 return true;
2289}
2290
2291
Chris Lattner718b5c22005-01-13 17:59:43 +00002292SDOperand SelectionDAGISel::
2293CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002294 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002295 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002296 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002297 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002298
2299 // If this type is not legal, we must make sure to not create an invalid
2300 // register use.
2301 MVT::ValueType SrcVT = Op.getValueType();
2302 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2303 SelectionDAG &DAG = SDL.DAG;
2304 if (SrcVT == DestVT) {
2305 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2306 } else if (SrcVT < DestVT) {
2307 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002308 if (MVT::isFloatingPoint(SrcVT))
2309 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2310 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002311 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002312 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2313 } else {
2314 // The src value is expanded into multiple registers.
2315 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2316 Op, DAG.getConstant(0, MVT::i32));
2317 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2318 Op, DAG.getConstant(1, MVT::i32));
2319 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2320 return DAG.getCopyToReg(Op, Reg+1, Hi);
2321 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002322}
2323
Chris Lattner16f64df2005-01-17 17:15:02 +00002324void SelectionDAGISel::
2325LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2326 std::vector<SDOperand> &UnorderedChains) {
2327 // If this is the entry block, emit arguments.
2328 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002329 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002330 SDOperand OldRoot = SDL.DAG.getRoot();
2331 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002332
Chris Lattner6871b232005-10-30 19:42:35 +00002333 unsigned a = 0;
2334 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2335 AI != E; ++AI, ++a)
2336 if (!AI->use_empty()) {
2337 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002338
Chris Lattner6871b232005-10-30 19:42:35 +00002339 // If this argument is live outside of the entry block, insert a copy from
2340 // whereever we got it to the vreg that other BB's will reference it as.
2341 if (FuncInfo.ValueMap.count(AI)) {
2342 SDOperand Copy =
2343 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2344 UnorderedChains.push_back(Copy);
2345 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002346 }
Chris Lattner6871b232005-10-30 19:42:35 +00002347
2348 // Next, if the function has live ins that need to be copied into vregs,
2349 // emit the copies now, into the top of the block.
2350 MachineFunction &MF = SDL.DAG.getMachineFunction();
2351 if (MF.livein_begin() != MF.livein_end()) {
2352 SSARegMap *RegMap = MF.getSSARegMap();
2353 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2354 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2355 E = MF.livein_end(); LI != E; ++LI)
2356 if (LI->second)
2357 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2358 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002359 }
Chris Lattner6871b232005-10-30 19:42:35 +00002360
2361 // Finally, if the target has anything special to do, allow it to do so.
2362 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002363}
2364
2365
Chris Lattner7a60d912005-01-07 07:47:53 +00002366void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2367 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2368 FunctionLoweringInfo &FuncInfo) {
2369 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002370
2371 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002372
Chris Lattner6871b232005-10-30 19:42:35 +00002373 // Lower any arguments needed in this block if this is the entry block.
2374 if (LLVMBB == &LLVMBB->getParent()->front())
2375 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002376
2377 BB = FuncInfo.MBBMap[LLVMBB];
2378 SDL.setCurrentBasicBlock(BB);
2379
2380 // Lower all of the non-terminator instructions.
2381 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2382 I != E; ++I)
2383 SDL.visit(*I);
2384
2385 // Ensure that all instructions which are used outside of their defining
2386 // blocks are available as virtual registers.
2387 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002388 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002389 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002390 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002391 UnorderedChains.push_back(
2392 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002393 }
2394
2395 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2396 // ensure constants are generated when needed. Remember the virtual registers
2397 // that need to be added to the Machine PHI nodes as input. We cannot just
2398 // directly add them, because expansion might result in multiple MBB's for one
2399 // BB. As such, the start of the BB might correspond to a different MBB than
2400 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002401 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002402
2403 // Emit constants only once even if used by multiple PHI nodes.
2404 std::map<Constant*, unsigned> ConstantsOut;
2405
2406 // Check successor nodes PHI nodes that expect a constant to be available from
2407 // this block.
2408 TerminatorInst *TI = LLVMBB->getTerminator();
2409 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2410 BasicBlock *SuccBB = TI->getSuccessor(succ);
2411 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2412 PHINode *PN;
2413
2414 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2415 // nodes and Machine PHI nodes, but the incoming operands have not been
2416 // emitted yet.
2417 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002418 (PN = dyn_cast<PHINode>(I)); ++I)
2419 if (!PN->use_empty()) {
2420 unsigned Reg;
2421 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2422 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2423 unsigned &RegOut = ConstantsOut[C];
2424 if (RegOut == 0) {
2425 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002426 UnorderedChains.push_back(
2427 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002428 }
2429 Reg = RegOut;
2430 } else {
2431 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002432 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002433 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002434 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2435 "Didn't codegen value into a register!??");
2436 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002437 UnorderedChains.push_back(
2438 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002439 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002440 }
Misha Brukman835702a2005-04-21 22:36:52 +00002441
Chris Lattner8ea875f2005-01-07 21:34:19 +00002442 // Remember that this register needs to added to the machine PHI node as
2443 // the input for this MBB.
2444 unsigned NumElements =
2445 TLI.getNumElements(TLI.getValueType(PN->getType()));
2446 for (unsigned i = 0, e = NumElements; i != e; ++i)
2447 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002448 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002449 }
2450 ConstantsOut.clear();
2451
Chris Lattner718b5c22005-01-13 17:59:43 +00002452 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002453 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002454 SDOperand Root = SDL.getRoot();
2455 if (Root.getOpcode() != ISD::EntryToken) {
2456 unsigned i = 0, e = UnorderedChains.size();
2457 for (; i != e; ++i) {
2458 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2459 if (UnorderedChains[i].Val->getOperand(0) == Root)
2460 break; // Don't add the root if we already indirectly depend on it.
2461 }
2462
2463 if (i == e)
2464 UnorderedChains.push_back(Root);
2465 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002466 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2467 }
2468
Chris Lattner7a60d912005-01-07 07:47:53 +00002469 // Lower the terminator after the copies are emitted.
2470 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002471
2472 // Make sure the root of the DAG is up-to-date.
2473 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002474}
2475
2476void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2477 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002478 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002479 CurDAG = &DAG;
2480 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2481
2482 // First step, lower LLVM code to some DAG. This DAG may use operations and
2483 // types that are not supported by the target.
2484 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2485
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002486 // Run the DAG combiner in pre-legalize mode.
2487 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002488
Chris Lattner7a60d912005-01-07 07:47:53 +00002489 DEBUG(std::cerr << "Lowered selection DAG:\n");
2490 DEBUG(DAG.dump());
2491
2492 // Second step, hack on the DAG until it only uses operations and types that
2493 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002494 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002495
2496 DEBUG(std::cerr << "Legalized selection DAG:\n");
2497 DEBUG(DAG.dump());
2498
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002499 // Run the DAG combiner in post-legalize mode.
2500 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002501
Evan Cheng739a6a42006-01-21 02:32:06 +00002502 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002503
Chris Lattner5ca31d92005-03-30 01:10:47 +00002504 // Third, instruction select all of the operations to machine code, adding the
2505 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002506 InstructionSelectBasicBlock(DAG);
2507
Chris Lattner7a60d912005-01-07 07:47:53 +00002508 DEBUG(std::cerr << "Selected machine code:\n");
2509 DEBUG(BB->dump());
2510
Chris Lattner5ca31d92005-03-30 01:10:47 +00002511 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002512 // PHI nodes in successors.
2513 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2514 MachineInstr *PHI = PHINodesToUpdate[i].first;
2515 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2516 "This is not a machine PHI node that we are updating!");
2517 PHI->addRegOperand(PHINodesToUpdate[i].second);
2518 PHI->addMachineBasicBlockOperand(BB);
2519 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002520
2521 // Finally, add the CFG edges from the last selected MBB to the successor
2522 // MBBs.
2523 TerminatorInst *TI = LLVMBB->getTerminator();
2524 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2525 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2526 BB->addSuccessor(Succ0MBB);
2527 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002528}
Evan Cheng739a6a42006-01-21 02:32:06 +00002529
2530//===----------------------------------------------------------------------===//
2531/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2532/// target node in the graph.
2533void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2534 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002535 ScheduleDAG *SL = NULL;
2536
2537 switch (ISHeuristic) {
2538 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002539 case defaultScheduling:
2540 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2541 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2542 else /* TargetLowering::SchedulingForRegPressure */
2543 SL = createBURRListDAGScheduler(DAG, BB);
2544 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002545 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002546 SL = createBFS_DAGScheduler(DAG, BB);
2547 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002548 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002549 SL = createSimpleDAGScheduler(false, DAG, BB);
2550 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002551 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002552 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002553 break;
Evan Cheng31272342006-01-23 08:26:10 +00002554 case listSchedulingBURR:
2555 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002556 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002557 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002558 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002559 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002560 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002561 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002562 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002563}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002564
Chris Lattner543832d2006-03-08 04:25:59 +00002565HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2566 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002567}
2568
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002569/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2570/// by tblgen. Others should not call it.
2571void SelectionDAGISel::
2572SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2573 std::vector<SDOperand> InOps;
2574 std::swap(InOps, Ops);
2575
2576 Ops.push_back(InOps[0]); // input chain.
2577 Ops.push_back(InOps[1]); // input asm string.
2578
2579 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2580 unsigned i = 2, e = InOps.size();
2581 if (InOps[e-1].getValueType() == MVT::Flag)
2582 --e; // Don't process a flag operand if it is here.
2583
2584 while (i != e) {
2585 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2586 if ((Flags & 7) != 4 /*MEM*/) {
2587 // Just skip over this operand, copying the operands verbatim.
2588 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2589 i += (Flags >> 3) + 1;
2590 } else {
2591 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2592 // Otherwise, this is a memory operand. Ask the target to select it.
2593 std::vector<SDOperand> SelOps;
2594 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2595 std::cerr << "Could not match memory address. Inline asm failure!\n";
2596 exit(1);
2597 }
2598
2599 // Add this to the output node.
2600 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2601 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2602 i += 2;
2603 }
2604 }
2605
2606 // Add the flag input back if present.
2607 if (e != InOps.size())
2608 Ops.push_back(InOps.back());
2609}