blob: 0b32352c689ae3da9cee0445fa238cb47fd11da2 [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"
Jim Laskeya8bdac82006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/SelectionDAG.h"
32#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000033#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetFrameInfo.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000040#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
43#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000044#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattner975f5c92005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000051ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
53static cl::opt<bool>
54ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000056#else
Evan Cheng739a6a42006-01-21 02:32:06 +000057static const bool ViewISelDAGs = 0;
58static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Chris Lattner5255d042006-03-10 07:49:12 +000061// Scheduling heuristics
62enum SchedHeuristics {
63 defaultScheduling, // Let the target specify its preference.
64 noScheduling, // No scheduling, emit breadth first sequence.
65 simpleScheduling, // Two pass, min. critical path, max. utilization.
66 simpleNoItinScheduling, // Same as above exact using generic latency.
67 listSchedulingBURR, // Bottom up reg reduction list scheduling.
68 listSchedulingTD // Top-down list scheduler.
69};
70
Evan Chengc1e1d972006-01-23 07:01:07 +000071namespace {
72 cl::opt<SchedHeuristics>
73 ISHeuristic(
74 "sched",
75 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000076 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000077 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000078 clEnumValN(defaultScheduling, "default",
79 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000080 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000081 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000082 clEnumValN(simpleScheduling, "simple",
83 "Simple two pass scheduling: minimize critical path "
84 "and maximize processor utilization"),
85 clEnumValN(simpleNoItinScheduling, "simple-noitin",
86 "Simple two pass scheduling: Same as simple "
87 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000088 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000089 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000090 clEnumValN(listSchedulingTD, "list-td",
91 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000092 clEnumValEnd));
93} // namespace
94
Chris Lattner6f87d182006-02-22 22:37:12 +000095namespace {
96 /// RegsForValue - This struct represents the physical registers that a
97 /// particular value is assigned and the type information about the value.
98 /// This is needed because values can be promoted into larger registers and
99 /// expanded into multiple smaller registers than the value.
100 struct RegsForValue {
101 /// Regs - This list hold the register (for legal and promoted values)
102 /// or register set (for expanded values) that the value should be assigned
103 /// to.
104 std::vector<unsigned> Regs;
105
106 /// RegVT - The value type of each register.
107 ///
108 MVT::ValueType RegVT;
109
110 /// ValueVT - The value type of the LLVM value, which may be promoted from
111 /// RegVT or made from merging the two expanded parts.
112 MVT::ValueType ValueVT;
113
114 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
115
116 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117 : RegVT(regvt), ValueVT(valuevt) {
118 Regs.push_back(Reg);
119 }
120 RegsForValue(const std::vector<unsigned> &regs,
121 MVT::ValueType regvt, MVT::ValueType valuevt)
122 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
123 }
124
125 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126 /// this value and returns the result as a ValueVT value. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000129 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000130
131 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132 /// specified value into the registers specified by this object. This uses
133 /// Chain/Flag as the input and updates them for the output Chain/Flag.
134 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000135 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000136
137 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138 /// operand list. This adds the code marker and includes the number of
139 /// values added into it.
140 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000141 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000142 };
143}
Evan Chengc1e1d972006-01-23 07:01:07 +0000144
Chris Lattner7a60d912005-01-07 07:47:53 +0000145namespace llvm {
146 //===--------------------------------------------------------------------===//
147 /// FunctionLoweringInfo - This contains information that is global to a
148 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000149 class FunctionLoweringInfo {
150 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000151 TargetLowering &TLI;
152 Function &Fn;
153 MachineFunction &MF;
154 SSARegMap *RegMap;
155
156 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
157
158 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
160
161 /// ValueMap - Since we emit code for the function a basic block at a time,
162 /// we must remember which virtual registers hold the values for
163 /// cross-basic-block values.
164 std::map<const Value*, unsigned> ValueMap;
165
166 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167 /// the entry block. This allows the allocas to be efficiently referenced
168 /// anywhere in the function.
169 std::map<const AllocaInst*, int> StaticAllocaMap;
170
171 unsigned MakeReg(MVT::ValueType VT) {
172 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
173 }
Misha Brukman835702a2005-04-21 22:36:52 +0000174
Chris Lattner49409cb2006-03-16 19:51:18 +0000175 unsigned CreateRegForValue(const Value *V);
176
Chris Lattner7a60d912005-01-07 07:47:53 +0000177 unsigned InitializeRegForValue(const Value *V) {
178 unsigned &R = ValueMap[V];
179 assert(R == 0 && "Already initialized this value register!");
180 return R = CreateRegForValue(V);
181 }
182 };
183}
184
185/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000186/// PHI nodes or outside of the basic block that defines it, or used by a
187/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000188static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
189 if (isa<PHINode>(I)) return true;
190 BasicBlock *BB = I->getParent();
191 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000192 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
193 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000194 return true;
195 return false;
196}
197
Chris Lattner6871b232005-10-30 19:42:35 +0000198/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000199/// entry block, return true. This includes arguments used by switches, since
200/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000201static bool isOnlyUsedInEntryBlock(Argument *A) {
202 BasicBlock *Entry = A->getParent()->begin();
203 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000204 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000205 return false; // Use not in entry block.
206 return true;
207}
208
Chris Lattner7a60d912005-01-07 07:47:53 +0000209FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000210 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
212
Chris Lattner6871b232005-10-30 19:42:35 +0000213 // Create a vreg for each argument register that is not dead and is used
214 // outside of the entry block for the function.
215 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
216 AI != E; ++AI)
217 if (!isOnlyUsedInEntryBlock(AI))
218 InitializeRegForValue(AI);
219
Chris Lattner7a60d912005-01-07 07:47:53 +0000220 // Initialize the mapping of values to registers. This is only set up for
221 // instruction values that are used outside of the block that defines
222 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000223 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
225 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
226 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
227 const Type *Ty = AI->getAllocatedType();
228 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000229 unsigned Align =
230 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
231 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000232
233 // If the alignment of the value is smaller than the size of the value,
234 // and if the size of the value is particularly small (<= 8 bytes),
235 // round up to the size of the value for potentially better performance.
236 //
237 // FIXME: This could be made better with a preferred alignment hook in
238 // TargetData. It serves primarily to 8-byte align doubles for X86.
239 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000240 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000241 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000242 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000243 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 }
245
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000246 for (; BB != EB; ++BB)
247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
249 if (!isa<AllocaInst>(I) ||
250 !StaticAllocaMap.count(cast<AllocaInst>(I)))
251 InitializeRegForValue(I);
252
253 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
254 // also creates the initial PHI MachineInstrs, though none of the input
255 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000257 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
258 MBBMap[BB] = MBB;
259 MF.getBasicBlockList().push_back(MBB);
260
261 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
262 // appropriate.
263 PHINode *PN;
264 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000265 (PN = dyn_cast<PHINode>(I)); ++I)
266 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000267 MVT::ValueType VT = TLI.getValueType(PN->getType());
268 unsigned NumElements;
269 if (VT != MVT::Vector)
270 NumElements = TLI.getNumElements(VT);
271 else {
272 MVT::ValueType VT1,VT2;
273 NumElements =
274 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
275 VT1, VT2);
276 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000277 unsigned PHIReg = ValueMap[PN];
278 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
279 for (unsigned i = 0; i != NumElements; ++i)
280 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
281 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000282 }
283}
284
Chris Lattner49409cb2006-03-16 19:51:18 +0000285/// CreateRegForValue - Allocate the appropriate number of virtual registers of
286/// the correctly promoted or expanded types. Assign these registers
287/// consecutive vreg numbers and return the first assigned number.
288unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
289 MVT::ValueType VT = TLI.getValueType(V->getType());
290
291 // The number of multiples of registers that we need, to, e.g., split up
292 // a <2 x int64> -> 4 x i32 registers.
293 unsigned NumVectorRegs = 1;
294
295 // If this is a packed type, figure out what type it will decompose into
296 // and how many of the elements it will use.
297 if (VT == MVT::Vector) {
298 const PackedType *PTy = cast<PackedType>(V->getType());
299 unsigned NumElts = PTy->getNumElements();
300 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
301
302 // Divide the input until we get to a supported size. This will always
303 // end with a scalar if the target doesn't support vectors.
304 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
305 NumElts >>= 1;
306 NumVectorRegs <<= 1;
307 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000308 if (NumElts == 1)
309 VT = EltTy;
310 else
311 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000312 }
313
314 // The common case is that we will only create one register for this
315 // value. If we have that case, create and return the virtual register.
316 unsigned NV = TLI.getNumElements(VT);
317 if (NV == 1) {
318 // If we are promoting this value, pick the next largest supported type.
319 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
320 unsigned Reg = MakeReg(PromotedType);
321 // If this is a vector of supported or promoted types (e.g. 4 x i16),
322 // create all of the registers.
323 for (unsigned i = 1; i != NumVectorRegs; ++i)
324 MakeReg(PromotedType);
325 return Reg;
326 }
327
328 // If this value is represented with multiple target registers, make sure
329 // to create enough consecutive registers of the right (smaller) type.
330 unsigned NT = VT-1; // Find the type to use.
331 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
332 --NT;
333
334 unsigned R = MakeReg((MVT::ValueType)NT);
335 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
336 MakeReg((MVT::ValueType)NT);
337 return R;
338}
Chris Lattner7a60d912005-01-07 07:47:53 +0000339
340//===----------------------------------------------------------------------===//
341/// SelectionDAGLowering - This is the common target-independent lowering
342/// implementation that is parameterized by a TargetLowering object.
343/// Also, targets can overload any lowering method.
344///
345namespace llvm {
346class SelectionDAGLowering {
347 MachineBasicBlock *CurMBB;
348
349 std::map<const Value*, SDOperand> NodeMap;
350
Chris Lattner4d9651c2005-01-17 22:19:26 +0000351 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
352 /// them up and then emit token factor nodes when possible. This allows us to
353 /// get simple disambiguation between loads without worrying about alias
354 /// analysis.
355 std::vector<SDOperand> PendingLoads;
356
Nate Begemaned728c12006-03-27 01:32:24 +0000357 /// Case - A pair of values to record the Value for a switch case, and the
358 /// case's target basic block.
359 typedef std::pair<Constant*, MachineBasicBlock*> Case;
360 typedef std::vector<Case>::iterator CaseItr;
361 typedef std::pair<CaseItr, CaseItr> CaseRange;
362
363 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
364 /// of conditional branches.
365 struct CaseRec {
366 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
367 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
368
369 /// CaseBB - The MBB in which to emit the compare and branch
370 MachineBasicBlock *CaseBB;
371 /// LT, GE - If nonzero, we know the current case value must be less-than or
372 /// greater-than-or-equal-to these Constants.
373 Constant *LT;
374 Constant *GE;
375 /// Range - A pair of iterators representing the range of case values to be
376 /// processed at this point in the binary search tree.
377 CaseRange Range;
378 };
379
380 /// The comparison function for sorting Case values.
381 struct CaseCmp {
382 bool operator () (const Case& C1, const Case& C2) {
383 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
384 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
385
386 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
387 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
388 }
389 };
390
Chris Lattner7a60d912005-01-07 07:47:53 +0000391public:
392 // TLI - This is information that describes the available target features we
393 // need for lowering. This indicates when operations are unavailable,
394 // implemented with a libcall, etc.
395 TargetLowering &TLI;
396 SelectionDAG &DAG;
397 const TargetData &TD;
398
Nate Begemaned728c12006-03-27 01:32:24 +0000399 /// SwitchCases - Vector of CaseBlock structures used to communicate
400 /// SwitchInst code generation information.
401 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
402
Chris Lattner7a60d912005-01-07 07:47:53 +0000403 /// FuncInfo - Information about the function as a whole.
404 ///
405 FunctionLoweringInfo &FuncInfo;
406
407 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000408 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000409 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
410 FuncInfo(funcinfo) {
411 }
412
Chris Lattner4108bb02005-01-17 19:43:36 +0000413 /// getRoot - Return the current virtual root of the Selection DAG.
414 ///
415 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000416 if (PendingLoads.empty())
417 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000418
Chris Lattner4d9651c2005-01-17 22:19:26 +0000419 if (PendingLoads.size() == 1) {
420 SDOperand Root = PendingLoads[0];
421 DAG.setRoot(Root);
422 PendingLoads.clear();
423 return Root;
424 }
425
426 // Otherwise, we have to make a token factor node.
427 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
428 PendingLoads.clear();
429 DAG.setRoot(Root);
430 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000431 }
432
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 void visit(Instruction &I) { visit(I.getOpcode(), I); }
434
435 void visit(unsigned Opcode, User &I) {
436 switch (Opcode) {
437 default: assert(0 && "Unknown instruction type encountered!");
438 abort();
439 // Build the switch statement using the Instruction.def file.
440#define HANDLE_INST(NUM, OPCODE, CLASS) \
441 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
442#include "llvm/Instruction.def"
443 }
444 }
445
446 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
447
Chris Lattner4024c002006-03-15 22:19:46 +0000448 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
449 SDOperand SrcValue, SDOperand Root,
450 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000451
452 SDOperand getIntPtrConstant(uint64_t Val) {
453 return DAG.getConstant(Val, TLI.getPointerTy());
454 }
455
Chris Lattner8471b152006-03-16 19:57:50 +0000456 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000457
458 const SDOperand &setValue(const Value *V, SDOperand NewN) {
459 SDOperand &N = NodeMap[V];
460 assert(N.Val == 0 && "Already set a value for this node!");
461 return N = NewN;
462 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000463
Chris Lattner6f87d182006-02-22 22:37:12 +0000464 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
465 MVT::ValueType VT,
466 bool OutReg, bool InReg,
467 std::set<unsigned> &OutputRegs,
468 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000469
Chris Lattner7a60d912005-01-07 07:47:53 +0000470 // Terminator instructions.
471 void visitRet(ReturnInst &I);
472 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000473 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 void visitUnreachable(UnreachableInst &I) { /* noop */ }
475
Nate Begemaned728c12006-03-27 01:32:24 +0000476 // Helper for visitSwitch
477 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
478
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000480 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
481 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
482
Nate Begemanb2e089c2005-11-19 00:36:38 +0000483 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000484 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000485 void visitAdd(User &I) {
486 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000487 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000488 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000489 void visitMul(User &I) {
490 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000491 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000493 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000494 visitBinary(I,
495 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
496 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000497 }
498 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000499 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000500 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000501 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000502 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
503 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
504 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000505 void visitShl(User &I) { visitShift(I, ISD::SHL); }
506 void visitShr(User &I) {
507 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000508 }
509
510 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
511 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
512 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
513 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
514 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
515 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
516 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
517
Chris Lattner67271862006-03-29 00:11:43 +0000518 void visitExtractElement(User &I);
519 void visitInsertElement(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000520
Chris Lattner7a60d912005-01-07 07:47:53 +0000521 void visitGetElementPtr(User &I);
522 void visitCast(User &I);
523 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000524
525 void visitMalloc(MallocInst &I);
526 void visitFree(FreeInst &I);
527 void visitAlloca(AllocaInst &I);
528 void visitLoad(LoadInst &I);
529 void visitStore(StoreInst &I);
530 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
531 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000532 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000533 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000534 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000535
Chris Lattner7a60d912005-01-07 07:47:53 +0000536 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000537 void visitVAArg(VAArgInst &I);
538 void visitVAEnd(CallInst &I);
539 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000540 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000541
Chris Lattner875def92005-01-11 05:56:49 +0000542 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
544 void visitUserOp1(Instruction &I) {
545 assert(0 && "UserOp1 should not exist at instruction selection time!");
546 abort();
547 }
548 void visitUserOp2(Instruction &I) {
549 assert(0 && "UserOp2 should not exist at instruction selection time!");
550 abort();
551 }
552};
553} // end namespace llvm
554
Chris Lattner8471b152006-03-16 19:57:50 +0000555SDOperand SelectionDAGLowering::getValue(const Value *V) {
556 SDOperand &N = NodeMap[V];
557 if (N.Val) return N;
558
559 const Type *VTy = V->getType();
560 MVT::ValueType VT = TLI.getValueType(VTy);
561 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
562 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
563 visit(CE->getOpcode(), *CE);
564 assert(N.Val && "visit didn't populate the ValueMap!");
565 return N;
566 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
567 return N = DAG.getGlobalAddress(GV, VT);
568 } else if (isa<ConstantPointerNull>(C)) {
569 return N = DAG.getConstant(0, TLI.getPointerTy());
570 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000571 if (!isa<PackedType>(VTy))
572 return N = DAG.getNode(ISD::UNDEF, VT);
573
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000574 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000575 const PackedType *PTy = cast<PackedType>(VTy);
576 unsigned NumElements = PTy->getNumElements();
577 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
578
579 std::vector<SDOperand> Ops;
580 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
581
582 // Create a VConstant node with generic Vector type.
583 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
584 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000585 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000586 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
587 return N = DAG.getConstantFP(CFP->getValue(), VT);
588 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
589 unsigned NumElements = PTy->getNumElements();
590 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000591
592 // Now that we know the number and type of the elements, push a
593 // Constant or ConstantFP node onto the ops list for each element of
594 // the packed constant.
595 std::vector<SDOperand> Ops;
596 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000597 for (unsigned i = 0; i != NumElements; ++i)
598 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000599 } else {
600 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
601 SDOperand Op;
602 if (MVT::isFloatingPoint(PVT))
603 Op = DAG.getConstantFP(0, PVT);
604 else
605 Op = DAG.getConstant(0, PVT);
606 Ops.assign(NumElements, Op);
607 }
608
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000609 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000613 } else {
614 // Canonicalize all constant ints to be unsigned.
615 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
616 }
617 }
618
619 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
620 std::map<const AllocaInst*, int>::iterator SI =
621 FuncInfo.StaticAllocaMap.find(AI);
622 if (SI != FuncInfo.StaticAllocaMap.end())
623 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
624 }
625
626 std::map<const Value*, unsigned>::const_iterator VMI =
627 FuncInfo.ValueMap.find(V);
628 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
629
630 unsigned InReg = VMI->second;
631
632 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000633 if (VT != MVT::Vector) {
634 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000635
Chris Lattner5fe1f542006-03-31 02:06:56 +0000636 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
637 if (DestVT < VT) {
638 // Source must be expanded. This input value is actually coming from the
639 // register pair VMI->second and VMI->second+1.
640 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
641 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
642 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000643 if (MVT::isFloatingPoint(VT))
644 N = DAG.getNode(ISD::FP_ROUND, VT, N);
645 else
646 N = DAG.getNode(ISD::TRUNCATE, VT, N);
647 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000648 } else {
649 // Otherwise, if this is a vector, make it available as a generic vector
650 // here.
651 MVT::ValueType PTyElementVT, PTyLegalElementVT;
652 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(VTy),PTyElementVT,
653 PTyLegalElementVT);
654
655 // Build a VBUILD_VECTOR with the input registers.
656 std::vector<SDOperand> Ops;
657 if (PTyElementVT == PTyLegalElementVT) {
658 // If the value types are legal, just VBUILD the CopyFromReg nodes.
659 for (unsigned i = 0; i != NE; ++i)
660 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
661 PTyElementVT));
662 } else if (PTyElementVT < PTyLegalElementVT) {
663 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
664 for (unsigned i = 0; i != NE; ++i) {
665 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
666 PTyElementVT);
667 if (MVT::isFloatingPoint(PTyElementVT))
668 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
669 else
670 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
671 Ops.push_back(Op);
672 }
673 } else {
674 // If the register was expanded, use BUILD_PAIR.
675 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
676 for (unsigned i = 0; i != NE/2; ++i) {
677 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
678 PTyElementVT);
679 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
680 PTyElementVT);
681 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
682 }
683 }
684
685 Ops.push_back(DAG.getConstant(NE, MVT::i32));
686 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
687 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000688 }
689
690 return N;
691}
692
693
Chris Lattner7a60d912005-01-07 07:47:53 +0000694void SelectionDAGLowering::visitRet(ReturnInst &I) {
695 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000696 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000697 return;
698 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000699 std::vector<SDOperand> NewValues;
700 NewValues.push_back(getRoot());
701 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
702 SDOperand RetOp = getValue(I.getOperand(i));
703
704 // If this is an integer return value, we need to promote it ourselves to
705 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
706 // than sign/zero.
707 if (MVT::isInteger(RetOp.getValueType()) &&
708 RetOp.getValueType() < MVT::i64) {
709 MVT::ValueType TmpVT;
710 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
711 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
712 else
713 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000714
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000715 if (I.getOperand(i)->getType()->isSigned())
716 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
717 else
718 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
719 }
720 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000721 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000722 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000723}
724
725void SelectionDAGLowering::visitBr(BranchInst &I) {
726 // Update machine-CFG edges.
727 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000728 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000729
730 // Figure out which block is immediately after the current one.
731 MachineBasicBlock *NextBlock = 0;
732 MachineFunction::iterator BBI = CurMBB;
733 if (++BBI != CurMBB->getParent()->end())
734 NextBlock = BBI;
735
736 if (I.isUnconditional()) {
737 // If this is not a fall-through branch, emit the branch.
738 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000739 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000740 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000741 } else {
742 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000743 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000744
745 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000746 if (Succ1MBB == NextBlock) {
747 // If the condition is false, fall through. This means we should branch
748 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000749 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000750 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000751 } else if (Succ0MBB == NextBlock) {
752 // If the condition is true, fall through. This means we should branch if
753 // the condition is false to Succ #1. Invert the condition first.
754 SDOperand True = DAG.getConstant(1, Cond.getValueType());
755 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000756 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000757 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000758 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000759 std::vector<SDOperand> Ops;
760 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000761 // If the false case is the current basic block, then this is a self
762 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
763 // adds an extra instruction in the loop. Instead, invert the
764 // condition and emit "Loop: ... br!cond Loop; br Out.
765 if (CurMBB == Succ1MBB) {
766 std::swap(Succ0MBB, Succ1MBB);
767 SDOperand True = DAG.getConstant(1, Cond.getValueType());
768 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
769 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000770 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
771 DAG.getBasicBlock(Succ0MBB));
772 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
773 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000774 }
775 }
776}
777
Nate Begemaned728c12006-03-27 01:32:24 +0000778/// visitSwitchCase - Emits the necessary code to represent a single node in
779/// the binary search tree resulting from lowering a switch instruction.
780void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
781 SDOperand SwitchOp = getValue(CB.SwitchV);
782 SDOperand CaseOp = getValue(CB.CaseC);
783 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
784
785 // Set NextBlock to be the MBB immediately after the current one, if any.
786 // This is used to avoid emitting unnecessary branches to the next block.
787 MachineBasicBlock *NextBlock = 0;
788 MachineFunction::iterator BBI = CurMBB;
789 if (++BBI != CurMBB->getParent()->end())
790 NextBlock = BBI;
791
792 // If the lhs block is the next block, invert the condition so that we can
793 // fall through to the lhs instead of the rhs block.
794 if (CB.LHSBB == NextBlock) {
795 std::swap(CB.LHSBB, CB.RHSBB);
796 SDOperand True = DAG.getConstant(1, Cond.getValueType());
797 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
798 }
799 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
800 DAG.getBasicBlock(CB.LHSBB));
801 if (CB.RHSBB == NextBlock)
802 DAG.setRoot(BrCond);
803 else
804 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
805 DAG.getBasicBlock(CB.RHSBB)));
806 // Update successor info
807 CurMBB->addSuccessor(CB.LHSBB);
808 CurMBB->addSuccessor(CB.RHSBB);
809}
810
811void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
812 // Figure out which block is immediately after the current one.
813 MachineBasicBlock *NextBlock = 0;
814 MachineFunction::iterator BBI = CurMBB;
815 if (++BBI != CurMBB->getParent()->end())
816 NextBlock = BBI;
817
818 // If there is only the default destination, branch to it if it is not the
819 // next basic block. Otherwise, just fall through.
820 if (I.getNumOperands() == 2) {
821 // Update machine-CFG edges.
822 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
823 // If this is not a fall-through branch, emit the branch.
824 if (DefaultMBB != NextBlock)
825 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
826 DAG.getBasicBlock(DefaultMBB)));
827 return;
828 }
829
830 // If there are any non-default case statements, create a vector of Cases
831 // representing each one, and sort the vector so that we can efficiently
832 // create a binary search tree from them.
833 std::vector<Case> Cases;
834 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
835 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
836 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
837 }
838 std::sort(Cases.begin(), Cases.end(), CaseCmp());
839
840 // Get the Value to be switched on and default basic blocks, which will be
841 // inserted into CaseBlock records, representing basic blocks in the binary
842 // search tree.
843 Value *SV = I.getOperand(0);
844 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
845
846 // Get the current MachineFunction and LLVM basic block, for use in creating
847 // and inserting new MBBs during the creation of the binary search tree.
848 MachineFunction *CurMF = CurMBB->getParent();
849 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
850
851 // Push the initial CaseRec onto the worklist
852 std::vector<CaseRec> CaseVec;
853 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
854
855 while (!CaseVec.empty()) {
856 // Grab a record representing a case range to process off the worklist
857 CaseRec CR = CaseVec.back();
858 CaseVec.pop_back();
859
860 // Size is the number of Cases represented by this range. If Size is 1,
861 // then we are processing a leaf of the binary search tree. Otherwise,
862 // we need to pick a pivot, and push left and right ranges onto the
863 // worklist.
864 unsigned Size = CR.Range.second - CR.Range.first;
865
866 if (Size == 1) {
867 // Create a CaseBlock record representing a conditional branch to
868 // the Case's target mbb if the value being switched on SV is equal
869 // to C. Otherwise, branch to default.
870 Constant *C = CR.Range.first->first;
871 MachineBasicBlock *Target = CR.Range.first->second;
872 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
873 CR.CaseBB);
874 // If the MBB representing the leaf node is the current MBB, then just
875 // call visitSwitchCase to emit the code into the current block.
876 // Otherwise, push the CaseBlock onto the vector to be later processed
877 // by SDISel, and insert the node's MBB before the next MBB.
878 if (CR.CaseBB == CurMBB)
879 visitSwitchCase(CB);
880 else {
881 SwitchCases.push_back(CB);
882 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
883 }
884 } else {
885 // split case range at pivot
886 CaseItr Pivot = CR.Range.first + (Size / 2);
887 CaseRange LHSR(CR.Range.first, Pivot);
888 CaseRange RHSR(Pivot, CR.Range.second);
889 Constant *C = Pivot->first;
890 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
891 // We know that we branch to the LHS if the Value being switched on is
892 // less than the Pivot value, C. We use this to optimize our binary
893 // tree a bit, by recognizing that if SV is greater than or equal to the
894 // LHS's Case Value, and that Case Value is exactly one less than the
895 // Pivot's Value, then we can branch directly to the LHS's Target,
896 // rather than creating a leaf node for it.
897 if ((LHSR.second - LHSR.first) == 1 &&
898 LHSR.first->first == CR.GE &&
899 cast<ConstantIntegral>(C)->getRawValue() ==
900 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
901 LHSBB = LHSR.first->second;
902 } else {
903 LHSBB = new MachineBasicBlock(LLVMBB);
904 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
905 }
906 // Similar to the optimization above, if the Value being switched on is
907 // known to be less than the Constant CR.LT, and the current Case Value
908 // is CR.LT - 1, then we can branch directly to the target block for
909 // the current Case Value, rather than emitting a RHS leaf node for it.
910 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
911 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
912 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
913 RHSBB = RHSR.first->second;
914 } else {
915 RHSBB = new MachineBasicBlock(LLVMBB);
916 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
917 }
918 // Create a CaseBlock record representing a conditional branch to
919 // the LHS node if the value being switched on SV is less than C.
920 // Otherwise, branch to LHS.
921 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
922 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
923 if (CR.CaseBB == CurMBB)
924 visitSwitchCase(CB);
925 else {
926 SwitchCases.push_back(CB);
927 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
928 }
929 }
930 }
931}
932
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000933void SelectionDAGLowering::visitSub(User &I) {
934 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000935 if (I.getType()->isFloatingPoint()) {
936 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
937 if (CFP->isExactlyValue(-0.0)) {
938 SDOperand Op2 = getValue(I.getOperand(1));
939 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
940 return;
941 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000942 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000943 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000944}
945
Nate Begemanb2e089c2005-11-19 00:36:38 +0000946void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
947 unsigned VecOp) {
948 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000949 SDOperand Op1 = getValue(I.getOperand(0));
950 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000951
Chris Lattner19baba62005-11-19 18:40:42 +0000952 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000953 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
954 } else if (Ty->isFloatingPoint()) {
955 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
956 } else {
957 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000958 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
959 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
960 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000961 }
Nate Begeman127321b2005-11-18 07:42:56 +0000962}
Chris Lattner96c26752005-01-19 22:31:21 +0000963
Nate Begeman127321b2005-11-18 07:42:56 +0000964void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
965 SDOperand Op1 = getValue(I.getOperand(0));
966 SDOperand Op2 = getValue(I.getOperand(1));
967
968 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
969
Chris Lattner7a60d912005-01-07 07:47:53 +0000970 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
971}
972
973void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
974 ISD::CondCode UnsignedOpcode) {
975 SDOperand Op1 = getValue(I.getOperand(0));
976 SDOperand Op2 = getValue(I.getOperand(1));
977 ISD::CondCode Opcode = SignedOpcode;
978 if (I.getOperand(0)->getType()->isUnsigned())
979 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000980 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000981}
982
983void SelectionDAGLowering::visitSelect(User &I) {
984 SDOperand Cond = getValue(I.getOperand(0));
985 SDOperand TrueVal = getValue(I.getOperand(1));
986 SDOperand FalseVal = getValue(I.getOperand(2));
987 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
988 TrueVal, FalseVal));
989}
990
991void SelectionDAGLowering::visitCast(User &I) {
992 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000993 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +0000994 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000995
Chris Lattner2f4119a2006-03-22 20:09:35 +0000996 if (DestVT == MVT::Vector) {
997 // This is a cast to a vector from something else. This is always a bit
998 // convert. Get information about the input vector.
999 const PackedType *DestTy = cast<PackedType>(I.getType());
1000 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1001 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1002 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1003 DAG.getValueType(EltVT)));
1004 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001005 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001006 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001007 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001008 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001009 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001010 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001011 } else if (isInteger(SrcVT)) {
1012 if (isInteger(DestVT)) { // Int -> Int cast
1013 if (DestVT < SrcVT) // Truncating cast?
1014 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001015 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001016 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001017 else
Chris Lattner4024c002006-03-15 22:19:46 +00001018 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001019 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001020 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001021 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001022 else
Chris Lattner4024c002006-03-15 22:19:46 +00001023 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001024 } else {
1025 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001026 }
Chris Lattner4024c002006-03-15 22:19:46 +00001027 } else if (isFloatingPoint(SrcVT)) {
1028 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1029 if (DestVT < SrcVT) // Rounding cast?
1030 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001031 else
Chris Lattner4024c002006-03-15 22:19:46 +00001032 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001033 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001034 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001035 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001036 else
Chris Lattner4024c002006-03-15 22:19:46 +00001037 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001038 } else {
1039 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001040 }
1041 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001042 assert(SrcVT == MVT::Vector && "Unknown cast!");
1043 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1044 // This is a cast from a vector to something else. This is always a bit
1045 // convert. Get information about the input vector.
1046 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001047 }
1048}
1049
Chris Lattner67271862006-03-29 00:11:43 +00001050void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001051 SDOperand InVec = getValue(I.getOperand(0));
1052 SDOperand InVal = getValue(I.getOperand(1));
1053 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1054 getValue(I.getOperand(2)));
1055
Chris Lattner29b23012006-03-19 01:17:20 +00001056 SDOperand Num = *(InVec.Val->op_end()-2);
1057 SDOperand Typ = *(InVec.Val->op_end()-1);
1058 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1059 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001060}
1061
Chris Lattner67271862006-03-29 00:11:43 +00001062void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001063 SDOperand InVec = getValue(I.getOperand(0));
1064 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1065 getValue(I.getOperand(1)));
1066 SDOperand Typ = *(InVec.Val->op_end()-1);
1067 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1068 TLI.getValueType(I.getType()), InVec, InIdx));
1069}
Chris Lattner32206f52006-03-18 01:44:44 +00001070
Chris Lattner7a60d912005-01-07 07:47:53 +00001071void SelectionDAGLowering::visitGetElementPtr(User &I) {
1072 SDOperand N = getValue(I.getOperand(0));
1073 const Type *Ty = I.getOperand(0)->getType();
1074 const Type *UIntPtrTy = TD.getIntPtrType();
1075
1076 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1077 OI != E; ++OI) {
1078 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001079 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001080 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1081 if (Field) {
1082 // N = N + Offset
1083 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1084 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001085 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001086 }
1087 Ty = StTy->getElementType(Field);
1088 } else {
1089 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001090
Chris Lattner43535a12005-11-09 04:45:33 +00001091 // If this is a constant subscript, handle it quickly.
1092 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1093 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001094
Chris Lattner43535a12005-11-09 04:45:33 +00001095 uint64_t Offs;
1096 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1097 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1098 else
1099 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1100 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1101 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001102 }
Chris Lattner43535a12005-11-09 04:45:33 +00001103
1104 // N = N + Idx * ElementSize;
1105 uint64_t ElementSize = TD.getTypeSize(Ty);
1106 SDOperand IdxN = getValue(Idx);
1107
1108 // If the index is smaller or larger than intptr_t, truncate or extend
1109 // it.
1110 if (IdxN.getValueType() < N.getValueType()) {
1111 if (Idx->getType()->isSigned())
1112 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1113 else
1114 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1115 } else if (IdxN.getValueType() > N.getValueType())
1116 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1117
1118 // If this is a multiply by a power of two, turn it into a shl
1119 // immediately. This is a very common case.
1120 if (isPowerOf2_64(ElementSize)) {
1121 unsigned Amt = Log2_64(ElementSize);
1122 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001123 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001124 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1125 continue;
1126 }
1127
1128 SDOperand Scale = getIntPtrConstant(ElementSize);
1129 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1130 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001131 }
1132 }
1133 setValue(&I, N);
1134}
1135
1136void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1137 // If this is a fixed sized alloca in the entry block of the function,
1138 // allocate it statically on the stack.
1139 if (FuncInfo.StaticAllocaMap.count(&I))
1140 return; // getValue will auto-populate this.
1141
1142 const Type *Ty = I.getAllocatedType();
1143 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +00001144 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1145 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001146
1147 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001148 MVT::ValueType IntPtr = TLI.getPointerTy();
1149 if (IntPtr < AllocSize.getValueType())
1150 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1151 else if (IntPtr > AllocSize.getValueType())
1152 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001153
Chris Lattnereccb73d2005-01-22 23:04:37 +00001154 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001155 getIntPtrConstant(TySize));
1156
1157 // Handle alignment. If the requested alignment is less than or equal to the
1158 // stack alignment, ignore it and round the size of the allocation up to the
1159 // stack alignment size. If the size is greater than the stack alignment, we
1160 // note this in the DYNAMIC_STACKALLOC node.
1161 unsigned StackAlign =
1162 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1163 if (Align <= StackAlign) {
1164 Align = 0;
1165 // Add SA-1 to the size.
1166 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1167 getIntPtrConstant(StackAlign-1));
1168 // Mask out the low bits for alignment purposes.
1169 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1170 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1171 }
1172
Chris Lattner96c262e2005-05-14 07:29:57 +00001173 std::vector<MVT::ValueType> VTs;
1174 VTs.push_back(AllocSize.getValueType());
1175 VTs.push_back(MVT::Other);
1176 std::vector<SDOperand> Ops;
1177 Ops.push_back(getRoot());
1178 Ops.push_back(AllocSize);
1179 Ops.push_back(getIntPtrConstant(Align));
1180 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +00001181 DAG.setRoot(setValue(&I, DSA).getValue(1));
1182
1183 // Inform the Frame Information that we have just allocated a variable-sized
1184 // object.
1185 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1186}
1187
Chris Lattner7a60d912005-01-07 07:47:53 +00001188void SelectionDAGLowering::visitLoad(LoadInst &I) {
1189 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001190
Chris Lattner4d9651c2005-01-17 22:19:26 +00001191 SDOperand Root;
1192 if (I.isVolatile())
1193 Root = getRoot();
1194 else {
1195 // Do not serialize non-volatile loads against each other.
1196 Root = DAG.getRoot();
1197 }
Chris Lattner4024c002006-03-15 22:19:46 +00001198
1199 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1200 Root, I.isVolatile()));
1201}
1202
1203SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1204 SDOperand SrcValue, SDOperand Root,
1205 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001206 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001207 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001208 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001209 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001210 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001211 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001212 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001213
Chris Lattner4024c002006-03-15 22:19:46 +00001214 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001215 DAG.setRoot(L.getValue(1));
1216 else
1217 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001218
1219 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001220}
1221
1222
1223void SelectionDAGLowering::visitStore(StoreInst &I) {
1224 Value *SrcV = I.getOperand(0);
1225 SDOperand Src = getValue(SrcV);
1226 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001227 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001228 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001229}
1230
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001231/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1232/// access memory and has no other side effects at all.
1233static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1234#define GET_NO_MEMORY_INTRINSICS
1235#include "llvm/Intrinsics.gen"
1236#undef GET_NO_MEMORY_INTRINSICS
1237 return false;
1238}
1239
1240/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1241/// node.
1242void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1243 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001244 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001245
1246 // Build the operand list.
1247 std::vector<SDOperand> Ops;
1248 if (HasChain) // If this intrinsic has side-effects, chainify it.
1249 Ops.push_back(getRoot());
1250
1251 // Add the intrinsic ID as an integer operand.
1252 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1253
1254 // Add all operands of the call to the operand list.
1255 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1256 SDOperand Op = getValue(I.getOperand(i));
1257
1258 // If this is a vector type, force it to the right packed type.
1259 if (Op.getValueType() == MVT::Vector) {
1260 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1261 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1262
1263 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1264 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1265 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1266 }
1267
1268 assert(TLI.isTypeLegal(Op.getValueType()) &&
1269 "Intrinsic uses a non-legal type?");
1270 Ops.push_back(Op);
1271 }
1272
1273 std::vector<MVT::ValueType> VTs;
1274 if (I.getType() != Type::VoidTy) {
1275 MVT::ValueType VT = TLI.getValueType(I.getType());
1276 if (VT == MVT::Vector) {
1277 const PackedType *DestTy = cast<PackedType>(I.getType());
1278 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1279
1280 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1281 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1282 }
1283
1284 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1285 VTs.push_back(VT);
1286 }
1287 if (HasChain)
1288 VTs.push_back(MVT::Other);
1289
1290 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001291 SDOperand Result;
1292 if (!HasChain)
1293 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1294 else if (I.getType() != Type::VoidTy)
1295 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1296 else
1297 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1298
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001299 if (HasChain)
1300 DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1301 if (I.getType() != Type::VoidTy) {
1302 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1303 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1304 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1305 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1306 DAG.getValueType(EVT));
1307 }
1308 setValue(&I, Result);
1309 }
1310}
1311
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001312/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1313/// we want to emit this as a call to a named external function, return the name
1314/// otherwise lower it and return null.
1315const char *
1316SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1317 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001318 default:
1319 // By default, turn this into a target intrinsic node.
1320 visitTargetIntrinsic(I, Intrinsic);
1321 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001322 case Intrinsic::vastart: visitVAStart(I); return 0;
1323 case Intrinsic::vaend: visitVAEnd(I); return 0;
1324 case Intrinsic::vacopy: visitVACopy(I); return 0;
1325 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1326 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1327 case Intrinsic::setjmp:
1328 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1329 break;
1330 case Intrinsic::longjmp:
1331 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1332 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001333 case Intrinsic::memcpy_i32:
1334 case Intrinsic::memcpy_i64:
1335 visitMemIntrinsic(I, ISD::MEMCPY);
1336 return 0;
1337 case Intrinsic::memset_i32:
1338 case Intrinsic::memset_i64:
1339 visitMemIntrinsic(I, ISD::MEMSET);
1340 return 0;
1341 case Intrinsic::memmove_i32:
1342 case Intrinsic::memmove_i64:
1343 visitMemIntrinsic(I, ISD::MEMMOVE);
1344 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001345
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001346 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001347 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001348 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001349 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001350 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001351
Jim Laskey5995d012006-02-11 01:01:30 +00001352 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001353 Ops.push_back(getValue(SPI.getLineValue()));
1354 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001355
Jim Laskeya8bdac82006-03-23 18:06:46 +00001356 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001357 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001358 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1359
Jim Laskey5995d012006-02-11 01:01:30 +00001360 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1361 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1362
Jim Laskeya8bdac82006-03-23 18:06:46 +00001363 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001364 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001365
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001366 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001367 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001368 case Intrinsic::dbg_region_start: {
1369 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1370 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001371 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001372 std::vector<SDOperand> Ops;
1373
1374 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1375
1376 Ops.push_back(getRoot());
1377 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1378
1379 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1380 }
1381
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001382 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001383 }
1384 case Intrinsic::dbg_region_end: {
1385 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1386 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001387 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001388 std::vector<SDOperand> Ops;
1389
1390 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1391
1392 Ops.push_back(getRoot());
1393 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1394
1395 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1396 }
1397
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001398 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001399 }
1400 case Intrinsic::dbg_func_start: {
1401 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1402 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001403 if (DebugInfo && FSI.getSubprogram() &&
1404 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001405 std::vector<SDOperand> Ops;
1406
1407 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1408
1409 Ops.push_back(getRoot());
1410 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1411
1412 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1413 }
1414
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001415 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001416 }
1417 case Intrinsic::dbg_declare: {
1418 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1419 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001420 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001421 std::vector<SDOperand> Ops;
1422
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001423 SDOperand AddressOp = getValue(DI.getAddress());
1424 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001425 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1426 }
1427 }
1428
1429 return 0;
1430 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001431
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001432 case Intrinsic::isunordered_f32:
1433 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001434 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1435 getValue(I.getOperand(2)), ISD::SETUO));
1436 return 0;
1437
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001438 case Intrinsic::sqrt_f32:
1439 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001440 setValue(&I, DAG.getNode(ISD::FSQRT,
1441 getValue(I.getOperand(1)).getValueType(),
1442 getValue(I.getOperand(1))));
1443 return 0;
1444 case Intrinsic::pcmarker: {
1445 SDOperand Tmp = getValue(I.getOperand(1));
1446 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1447 return 0;
1448 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001449 case Intrinsic::readcyclecounter: {
1450 std::vector<MVT::ValueType> VTs;
1451 VTs.push_back(MVT::i64);
1452 VTs.push_back(MVT::Other);
1453 std::vector<SDOperand> Ops;
1454 Ops.push_back(getRoot());
1455 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1456 setValue(&I, Tmp);
1457 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001458 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001459 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001460 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001461 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001462 case Intrinsic::bswap_i64:
1463 setValue(&I, DAG.getNode(ISD::BSWAP,
1464 getValue(I.getOperand(1)).getValueType(),
1465 getValue(I.getOperand(1))));
1466 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001467 case Intrinsic::cttz_i8:
1468 case Intrinsic::cttz_i16:
1469 case Intrinsic::cttz_i32:
1470 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001471 setValue(&I, DAG.getNode(ISD::CTTZ,
1472 getValue(I.getOperand(1)).getValueType(),
1473 getValue(I.getOperand(1))));
1474 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001475 case Intrinsic::ctlz_i8:
1476 case Intrinsic::ctlz_i16:
1477 case Intrinsic::ctlz_i32:
1478 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001479 setValue(&I, DAG.getNode(ISD::CTLZ,
1480 getValue(I.getOperand(1)).getValueType(),
1481 getValue(I.getOperand(1))));
1482 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001483 case Intrinsic::ctpop_i8:
1484 case Intrinsic::ctpop_i16:
1485 case Intrinsic::ctpop_i32:
1486 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001487 setValue(&I, DAG.getNode(ISD::CTPOP,
1488 getValue(I.getOperand(1)).getValueType(),
1489 getValue(I.getOperand(1))));
1490 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001491 case Intrinsic::stacksave: {
1492 std::vector<MVT::ValueType> VTs;
1493 VTs.push_back(TLI.getPointerTy());
1494 VTs.push_back(MVT::Other);
1495 std::vector<SDOperand> Ops;
1496 Ops.push_back(getRoot());
1497 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1498 setValue(&I, Tmp);
1499 DAG.setRoot(Tmp.getValue(1));
1500 return 0;
1501 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001502 case Intrinsic::stackrestore: {
1503 SDOperand Tmp = getValue(I.getOperand(1));
1504 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001505 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001506 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001507 case Intrinsic::prefetch:
1508 // FIXME: Currently discarding prefetches.
1509 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001510 }
1511}
1512
1513
Chris Lattner7a60d912005-01-07 07:47:53 +00001514void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001515 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001516 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001517 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001518 if (unsigned IID = F->getIntrinsicID()) {
1519 RenameFn = visitIntrinsicCall(I, IID);
1520 if (!RenameFn)
1521 return;
1522 } else { // Not an LLVM intrinsic.
1523 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001524 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1525 if (I.getNumOperands() == 3 && // Basic sanity checks.
1526 I.getOperand(1)->getType()->isFloatingPoint() &&
1527 I.getType() == I.getOperand(1)->getType() &&
1528 I.getType() == I.getOperand(2)->getType()) {
1529 SDOperand LHS = getValue(I.getOperand(1));
1530 SDOperand RHS = getValue(I.getOperand(2));
1531 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1532 LHS, RHS));
1533 return;
1534 }
1535 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001536 if (I.getNumOperands() == 2 && // Basic sanity checks.
1537 I.getOperand(1)->getType()->isFloatingPoint() &&
1538 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001539 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001540 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1541 return;
1542 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001543 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001544 if (I.getNumOperands() == 2 && // Basic sanity checks.
1545 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001546 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001547 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001548 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1549 return;
1550 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001551 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001552 if (I.getNumOperands() == 2 && // Basic sanity checks.
1553 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001554 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001555 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001556 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1557 return;
1558 }
1559 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001560 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001561 } else if (isa<InlineAsm>(I.getOperand(0))) {
1562 visitInlineAsm(I);
1563 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001564 }
Misha Brukman835702a2005-04-21 22:36:52 +00001565
Chris Lattner18d2b342005-01-08 22:48:57 +00001566 SDOperand Callee;
1567 if (!RenameFn)
1568 Callee = getValue(I.getOperand(0));
1569 else
1570 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001571 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001572 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001573 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1574 Value *Arg = I.getOperand(i);
1575 SDOperand ArgNode = getValue(Arg);
1576 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1577 }
Misha Brukman835702a2005-04-21 22:36:52 +00001578
Nate Begemanf6565252005-03-26 01:29:23 +00001579 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1580 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001581
Chris Lattner1f45cd72005-01-08 19:26:18 +00001582 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001583 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001584 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001585 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001586 setValue(&I, Result.first);
1587 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001588}
1589
Chris Lattner6f87d182006-02-22 22:37:12 +00001590SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001591 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001592 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1593 Chain = Val.getValue(1);
1594 Flag = Val.getValue(2);
1595
1596 // If the result was expanded, copy from the top part.
1597 if (Regs.size() > 1) {
1598 assert(Regs.size() == 2 &&
1599 "Cannot expand to more than 2 elts yet!");
1600 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1601 Chain = Val.getValue(1);
1602 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001603 if (DAG.getTargetLoweringInfo().isLittleEndian())
1604 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1605 else
1606 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001607 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001608
Chris Lattner6f87d182006-02-22 22:37:12 +00001609 // Otherwise, if the return value was promoted, truncate it to the
1610 // appropriate type.
1611 if (RegVT == ValueVT)
1612 return Val;
1613
1614 if (MVT::isInteger(RegVT))
1615 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1616 else
1617 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1618}
1619
Chris Lattner571d9642006-02-23 19:21:04 +00001620/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1621/// specified value into the registers specified by this object. This uses
1622/// Chain/Flag as the input and updates them for the output Chain/Flag.
1623void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001624 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001625 if (Regs.size() == 1) {
1626 // If there is a single register and the types differ, this must be
1627 // a promotion.
1628 if (RegVT != ValueVT) {
1629 if (MVT::isInteger(RegVT))
1630 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1631 else
1632 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1633 }
1634 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1635 Flag = Chain.getValue(1);
1636 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001637 std::vector<unsigned> R(Regs);
1638 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1639 std::reverse(R.begin(), R.end());
1640
1641 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001642 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1643 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001644 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001645 Flag = Chain.getValue(1);
1646 }
1647 }
1648}
Chris Lattner6f87d182006-02-22 22:37:12 +00001649
Chris Lattner571d9642006-02-23 19:21:04 +00001650/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1651/// operand list. This adds the code marker and includes the number of
1652/// values added into it.
1653void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001654 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001655 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1656 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1657 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1658}
Chris Lattner6f87d182006-02-22 22:37:12 +00001659
1660/// isAllocatableRegister - If the specified register is safe to allocate,
1661/// i.e. it isn't a stack pointer or some other special register, return the
1662/// register class for the register. Otherwise, return null.
1663static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001664isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1665 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1666 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1667 E = MRI->regclass_end(); RCI != E; ++RCI) {
1668 const TargetRegisterClass *RC = *RCI;
1669 // If none of the the value types for this register class are valid, we
1670 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1671 bool isLegal = false;
1672 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1673 I != E; ++I) {
1674 if (TLI.isTypeLegal(*I)) {
1675 isLegal = true;
1676 break;
1677 }
1678 }
1679
1680 if (!isLegal) continue;
1681
Chris Lattner6f87d182006-02-22 22:37:12 +00001682 // NOTE: This isn't ideal. In particular, this might allocate the
1683 // frame pointer in functions that need it (due to them not being taken
1684 // out of allocation, because a variable sized allocation hasn't been seen
1685 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001686 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1687 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001688 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001689 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001690 }
1691 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001692}
1693
1694RegsForValue SelectionDAGLowering::
1695GetRegistersForValue(const std::string &ConstrCode,
1696 MVT::ValueType VT, bool isOutReg, bool isInReg,
1697 std::set<unsigned> &OutputRegs,
1698 std::set<unsigned> &InputRegs) {
1699 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1700 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1701 std::vector<unsigned> Regs;
1702
1703 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1704 MVT::ValueType RegVT;
1705 MVT::ValueType ValueVT = VT;
1706
1707 if (PhysReg.first) {
1708 if (VT == MVT::Other)
1709 ValueVT = *PhysReg.second->vt_begin();
1710 RegVT = VT;
1711
1712 // This is a explicit reference to a physical register.
1713 Regs.push_back(PhysReg.first);
1714
1715 // If this is an expanded reference, add the rest of the regs to Regs.
1716 if (NumRegs != 1) {
1717 RegVT = *PhysReg.second->vt_begin();
1718 TargetRegisterClass::iterator I = PhysReg.second->begin();
1719 TargetRegisterClass::iterator E = PhysReg.second->end();
1720 for (; *I != PhysReg.first; ++I)
1721 assert(I != E && "Didn't find reg!");
1722
1723 // Already added the first reg.
1724 --NumRegs; ++I;
1725 for (; NumRegs; --NumRegs, ++I) {
1726 assert(I != E && "Ran out of registers to allocate!");
1727 Regs.push_back(*I);
1728 }
1729 }
1730 return RegsForValue(Regs, RegVT, ValueVT);
1731 }
1732
1733 // This is a reference to a register class. Allocate NumRegs consecutive,
1734 // available, registers from the class.
1735 std::vector<unsigned> RegClassRegs =
1736 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1737
1738 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1739 MachineFunction &MF = *CurMBB->getParent();
1740 unsigned NumAllocated = 0;
1741 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1742 unsigned Reg = RegClassRegs[i];
1743 // See if this register is available.
1744 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1745 (isInReg && InputRegs.count(Reg))) { // Already used.
1746 // Make sure we find consecutive registers.
1747 NumAllocated = 0;
1748 continue;
1749 }
1750
1751 // Check to see if this register is allocatable (i.e. don't give out the
1752 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001753 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001754 if (!RC) {
1755 // Make sure we find consecutive registers.
1756 NumAllocated = 0;
1757 continue;
1758 }
1759
1760 // Okay, this register is good, we can use it.
1761 ++NumAllocated;
1762
1763 // If we allocated enough consecutive
1764 if (NumAllocated == NumRegs) {
1765 unsigned RegStart = (i-NumAllocated)+1;
1766 unsigned RegEnd = i+1;
1767 // Mark all of the allocated registers used.
1768 for (unsigned i = RegStart; i != RegEnd; ++i) {
1769 unsigned Reg = RegClassRegs[i];
1770 Regs.push_back(Reg);
1771 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1772 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1773 }
1774
1775 return RegsForValue(Regs, *RC->vt_begin(), VT);
1776 }
1777 }
1778
1779 // Otherwise, we couldn't allocate enough registers for this.
1780 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001781}
1782
Chris Lattner6f87d182006-02-22 22:37:12 +00001783
Chris Lattner476e67b2006-01-26 22:24:51 +00001784/// visitInlineAsm - Handle a call to an InlineAsm object.
1785///
1786void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1787 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1788
1789 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1790 MVT::Other);
1791
1792 // Note, we treat inline asms both with and without side-effects as the same.
1793 // If an inline asm doesn't have side effects and doesn't access memory, we
1794 // could not choose to not chain it.
1795 bool hasSideEffects = IA->hasSideEffects();
1796
Chris Lattner3a5ed552006-02-01 01:28:23 +00001797 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001798 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001799
1800 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1801 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1802 /// if it is a def of that register.
1803 std::vector<SDOperand> AsmNodeOperands;
1804 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1805 AsmNodeOperands.push_back(AsmStr);
1806
1807 SDOperand Chain = getRoot();
1808 SDOperand Flag;
1809
Chris Lattner1558fc62006-02-01 18:59:47 +00001810 // We fully assign registers here at isel time. This is not optimal, but
1811 // should work. For register classes that correspond to LLVM classes, we
1812 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1813 // over the constraints, collecting fixed registers that we know we can't use.
1814 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001815 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001816 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1817 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1818 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001819
Chris Lattner7ad77df2006-02-22 00:56:39 +00001820 MVT::ValueType OpVT;
1821
1822 // Compute the value type for each operand and add it to ConstraintVTs.
1823 switch (Constraints[i].Type) {
1824 case InlineAsm::isOutput:
1825 if (!Constraints[i].isIndirectOutput) {
1826 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1827 OpVT = TLI.getValueType(I.getType());
1828 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001829 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001830 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1831 OpNum++; // Consumes a call operand.
1832 }
1833 break;
1834 case InlineAsm::isInput:
1835 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1836 OpNum++; // Consumes a call operand.
1837 break;
1838 case InlineAsm::isClobber:
1839 OpVT = MVT::Other;
1840 break;
1841 }
1842
1843 ConstraintVTs.push_back(OpVT);
1844
Chris Lattner6f87d182006-02-22 22:37:12 +00001845 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1846 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001847
Chris Lattner6f87d182006-02-22 22:37:12 +00001848 // Build a list of regs that this operand uses. This always has a single
1849 // element for promoted/expanded operands.
1850 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1851 false, false,
1852 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001853
1854 switch (Constraints[i].Type) {
1855 case InlineAsm::isOutput:
1856 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001857 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001858 // If this is an early-clobber output, it cannot be assigned to the same
1859 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001860 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001861 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001862 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001863 case InlineAsm::isInput:
1864 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001865 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001866 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001867 case InlineAsm::isClobber:
1868 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001869 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1870 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001871 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001872 }
1873 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001874
Chris Lattner5c79f982006-02-21 23:12:12 +00001875 // Loop over all of the inputs, copying the operand values into the
1876 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001877 RegsForValue RetValRegs;
1878 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001879 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001880
Chris Lattner2e56e892006-01-31 02:03:41 +00001881 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001882 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1883 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001884
Chris Lattner3a5ed552006-02-01 01:28:23 +00001885 switch (Constraints[i].Type) {
1886 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001887 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1888 if (ConstraintCode.size() == 1) // not a physreg name.
1889 CTy = TLI.getConstraintType(ConstraintCode[0]);
1890
1891 if (CTy == TargetLowering::C_Memory) {
1892 // Memory output.
1893 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1894
1895 // Check that the operand (the address to store to) isn't a float.
1896 if (!MVT::isInteger(InOperandVal.getValueType()))
1897 assert(0 && "MATCH FAIL!");
1898
1899 if (!Constraints[i].isIndirectOutput)
1900 assert(0 && "MATCH FAIL!");
1901
1902 OpNum++; // Consumes a call operand.
1903
1904 // Extend/truncate to the right pointer type if needed.
1905 MVT::ValueType PtrType = TLI.getPointerTy();
1906 if (InOperandVal.getValueType() < PtrType)
1907 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1908 else if (InOperandVal.getValueType() > PtrType)
1909 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1910
1911 // Add information to the INLINEASM node to know about this output.
1912 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1913 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1914 AsmNodeOperands.push_back(InOperandVal);
1915 break;
1916 }
1917
1918 // Otherwise, this is a register output.
1919 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1920
Chris Lattner6f87d182006-02-22 22:37:12 +00001921 // If this is an early-clobber output, or if there is an input
1922 // constraint that matches this, we need to reserve the input register
1923 // so no other inputs allocate to it.
1924 bool UsesInputRegister = false;
1925 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1926 UsesInputRegister = true;
1927
1928 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001929 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001930 RegsForValue Regs =
1931 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1932 true, UsesInputRegister,
1933 OutputRegs, InputRegs);
1934 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001935
Chris Lattner3a5ed552006-02-01 01:28:23 +00001936 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001937 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001938 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001939 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001940 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001941 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001942 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1943 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001944 OpNum++; // Consumes a call operand.
1945 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001946
1947 // Add information to the INLINEASM node to know that this register is
1948 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001949 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001950 break;
1951 }
1952 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001953 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001954 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001955
Chris Lattner7f5880b2006-02-02 00:25:23 +00001956 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1957 // If this is required to match an output register we have already set,
1958 // just use its register.
1959 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001960
Chris Lattner571d9642006-02-23 19:21:04 +00001961 // Scan until we find the definition we already emitted of this operand.
1962 // When we find it, create a RegsForValue operand.
1963 unsigned CurOp = 2; // The first operand.
1964 for (; OperandNo; --OperandNo) {
1965 // Advance to the next operand.
1966 unsigned NumOps =
1967 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1968 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1969 "Skipped past definitions?");
1970 CurOp += (NumOps>>3)+1;
1971 }
1972
1973 unsigned NumOps =
1974 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1975 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1976 "Skipped past definitions?");
1977
1978 // Add NumOps>>3 registers to MatchedRegs.
1979 RegsForValue MatchedRegs;
1980 MatchedRegs.ValueVT = InOperandVal.getValueType();
1981 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1982 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1983 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1984 MatchedRegs.Regs.push_back(Reg);
1985 }
1986
1987 // Use the produced MatchedRegs object to
1988 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1989 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001990 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001991 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001992
1993 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1994 if (ConstraintCode.size() == 1) // not a physreg name.
1995 CTy = TLI.getConstraintType(ConstraintCode[0]);
1996
1997 if (CTy == TargetLowering::C_Other) {
1998 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1999 assert(0 && "MATCH FAIL!");
2000
2001 // Add information to the INLINEASM node to know about this input.
2002 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2003 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2004 AsmNodeOperands.push_back(InOperandVal);
2005 break;
2006 } else if (CTy == TargetLowering::C_Memory) {
2007 // Memory input.
2008
2009 // Check that the operand isn't a float.
2010 if (!MVT::isInteger(InOperandVal.getValueType()))
2011 assert(0 && "MATCH FAIL!");
2012
2013 // Extend/truncate to the right pointer type if needed.
2014 MVT::ValueType PtrType = TLI.getPointerTy();
2015 if (InOperandVal.getValueType() < PtrType)
2016 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2017 else if (InOperandVal.getValueType() > PtrType)
2018 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2019
2020 // Add information to the INLINEASM node to know about this input.
2021 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2022 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2023 AsmNodeOperands.push_back(InOperandVal);
2024 break;
2025 }
2026
2027 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2028
2029 // Copy the input into the appropriate registers.
2030 RegsForValue InRegs =
2031 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2032 false, true, OutputRegs, InputRegs);
2033 // FIXME: should be match fail.
2034 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2035
2036 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2037
2038 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002039 break;
2040 }
Chris Lattner571d9642006-02-23 19:21:04 +00002041 case InlineAsm::isClobber: {
2042 RegsForValue ClobberedRegs =
2043 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2044 OutputRegs, InputRegs);
2045 // Add the clobbered value to the operand list, so that the register
2046 // allocator is aware that the physreg got clobbered.
2047 if (!ClobberedRegs.Regs.empty())
2048 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002049 break;
2050 }
Chris Lattner571d9642006-02-23 19:21:04 +00002051 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002052 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002053
2054 // Finish up input operands.
2055 AsmNodeOperands[0] = Chain;
2056 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2057
2058 std::vector<MVT::ValueType> VTs;
2059 VTs.push_back(MVT::Other);
2060 VTs.push_back(MVT::Flag);
2061 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2062 Flag = Chain.getValue(1);
2063
Chris Lattner2e56e892006-01-31 02:03:41 +00002064 // If this asm returns a register value, copy the result from that register
2065 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002066 if (!RetValRegs.Regs.empty())
2067 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002068
Chris Lattner2e56e892006-01-31 02:03:41 +00002069 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2070
2071 // Process indirect outputs, first output all of the flagged copies out of
2072 // physregs.
2073 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002074 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002075 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002076 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2077 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002078 }
2079
2080 // Emit the non-flagged stores from the physregs.
2081 std::vector<SDOperand> OutChains;
2082 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2083 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2084 StoresToEmit[i].first,
2085 getValue(StoresToEmit[i].second),
2086 DAG.getSrcValue(StoresToEmit[i].second)));
2087 if (!OutChains.empty())
2088 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00002089 DAG.setRoot(Chain);
2090}
2091
2092
Chris Lattner7a60d912005-01-07 07:47:53 +00002093void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2094 SDOperand Src = getValue(I.getOperand(0));
2095
2096 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002097
2098 if (IntPtr < Src.getValueType())
2099 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2100 else if (IntPtr > Src.getValueType())
2101 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002102
2103 // Scale the source by the type size.
2104 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2105 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2106 Src, getIntPtrConstant(ElementSize));
2107
2108 std::vector<std::pair<SDOperand, const Type*> > Args;
2109 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002110
2111 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002112 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002113 DAG.getExternalSymbol("malloc", IntPtr),
2114 Args, DAG);
2115 setValue(&I, Result.first); // Pointers always fit in registers
2116 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002117}
2118
2119void SelectionDAGLowering::visitFree(FreeInst &I) {
2120 std::vector<std::pair<SDOperand, const Type*> > Args;
2121 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2122 TLI.getTargetData().getIntPtrType()));
2123 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002124 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002125 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002126 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2127 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002128}
2129
Chris Lattner13d7c252005-08-26 20:54:47 +00002130// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2131// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2132// instructions are special in various ways, which require special support to
2133// insert. The specified MachineInstr is created but not inserted into any
2134// basic blocks, and the scheduler passes ownership of it to this method.
2135MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2136 MachineBasicBlock *MBB) {
2137 std::cerr << "If a target marks an instruction with "
2138 "'usesCustomDAGSchedInserter', it must implement "
2139 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2140 abort();
2141 return 0;
2142}
2143
Chris Lattner58cfd792005-01-09 00:00:49 +00002144void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002145 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2146 getValue(I.getOperand(1)),
2147 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002148}
2149
2150void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002151 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2152 getValue(I.getOperand(0)),
2153 DAG.getSrcValue(I.getOperand(0)));
2154 setValue(&I, V);
2155 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002156}
2157
2158void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002159 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2160 getValue(I.getOperand(1)),
2161 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002162}
2163
2164void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002165 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2166 getValue(I.getOperand(1)),
2167 getValue(I.getOperand(2)),
2168 DAG.getSrcValue(I.getOperand(1)),
2169 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002170}
2171
Chris Lattner58cfd792005-01-09 00:00:49 +00002172// It is always conservatively correct for llvm.returnaddress and
2173// llvm.frameaddress to return 0.
2174std::pair<SDOperand, SDOperand>
2175TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2176 unsigned Depth, SelectionDAG &DAG) {
2177 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002178}
2179
Chris Lattner29dcc712005-05-14 05:50:48 +00002180SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002181 assert(0 && "LowerOperation not implemented for this target!");
2182 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002183 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002184}
2185
Nate Begeman595ec732006-01-28 03:14:31 +00002186SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2187 SelectionDAG &DAG) {
2188 assert(0 && "CustomPromoteOperation not implemented for this target!");
2189 abort();
2190 return SDOperand();
2191}
2192
Chris Lattner58cfd792005-01-09 00:00:49 +00002193void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2194 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2195 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002196 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002197 setValue(&I, Result.first);
2198 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002199}
2200
Evan Cheng6781b6e2006-02-15 21:59:04 +00002201/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002202/// operand.
2203static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002204 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002205 MVT::ValueType CurVT = VT;
2206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2207 uint64_t Val = C->getValue() & 255;
2208 unsigned Shift = 8;
2209 while (CurVT != MVT::i8) {
2210 Val = (Val << Shift) | Val;
2211 Shift <<= 1;
2212 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002213 }
2214 return DAG.getConstant(Val, VT);
2215 } else {
2216 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2217 unsigned Shift = 8;
2218 while (CurVT != MVT::i8) {
2219 Value =
2220 DAG.getNode(ISD::OR, VT,
2221 DAG.getNode(ISD::SHL, VT, Value,
2222 DAG.getConstant(Shift, MVT::i8)), Value);
2223 Shift <<= 1;
2224 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002225 }
2226
2227 return Value;
2228 }
2229}
2230
Evan Cheng6781b6e2006-02-15 21:59:04 +00002231/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2232/// used when a memcpy is turned into a memset when the source is a constant
2233/// string ptr.
2234static SDOperand getMemsetStringVal(MVT::ValueType VT,
2235 SelectionDAG &DAG, TargetLowering &TLI,
2236 std::string &Str, unsigned Offset) {
2237 MVT::ValueType CurVT = VT;
2238 uint64_t Val = 0;
2239 unsigned MSB = getSizeInBits(VT) / 8;
2240 if (TLI.isLittleEndian())
2241 Offset = Offset + MSB - 1;
2242 for (unsigned i = 0; i != MSB; ++i) {
2243 Val = (Val << 8) | Str[Offset];
2244 Offset += TLI.isLittleEndian() ? -1 : 1;
2245 }
2246 return DAG.getConstant(Val, VT);
2247}
2248
Evan Cheng81fcea82006-02-14 08:22:34 +00002249/// getMemBasePlusOffset - Returns base and offset node for the
2250static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2251 SelectionDAG &DAG, TargetLowering &TLI) {
2252 MVT::ValueType VT = Base.getValueType();
2253 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2254}
2255
Evan Chengdb2a7a72006-02-14 20:12:38 +00002256/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002257/// to replace the memset / memcpy is below the threshold. It also returns the
2258/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002259static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2260 unsigned Limit, uint64_t Size,
2261 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002262 MVT::ValueType VT;
2263
2264 if (TLI.allowsUnalignedMemoryAccesses()) {
2265 VT = MVT::i64;
2266 } else {
2267 switch (Align & 7) {
2268 case 0:
2269 VT = MVT::i64;
2270 break;
2271 case 4:
2272 VT = MVT::i32;
2273 break;
2274 case 2:
2275 VT = MVT::i16;
2276 break;
2277 default:
2278 VT = MVT::i8;
2279 break;
2280 }
2281 }
2282
Evan Chengd5026102006-02-14 09:11:59 +00002283 MVT::ValueType LVT = MVT::i64;
2284 while (!TLI.isTypeLegal(LVT))
2285 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2286 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002287
Evan Chengd5026102006-02-14 09:11:59 +00002288 if (VT > LVT)
2289 VT = LVT;
2290
Evan Cheng04514992006-02-14 23:05:54 +00002291 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002292 while (Size != 0) {
2293 unsigned VTSize = getSizeInBits(VT) / 8;
2294 while (VTSize > Size) {
2295 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002296 VTSize >>= 1;
2297 }
Evan Chengd5026102006-02-14 09:11:59 +00002298 assert(MVT::isInteger(VT));
2299
2300 if (++NumMemOps > Limit)
2301 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002302 MemOps.push_back(VT);
2303 Size -= VTSize;
2304 }
Evan Chengd5026102006-02-14 09:11:59 +00002305
2306 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002307}
2308
Chris Lattner875def92005-01-11 05:56:49 +00002309void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002310 SDOperand Op1 = getValue(I.getOperand(1));
2311 SDOperand Op2 = getValue(I.getOperand(2));
2312 SDOperand Op3 = getValue(I.getOperand(3));
2313 SDOperand Op4 = getValue(I.getOperand(4));
2314 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2315 if (Align == 0) Align = 1;
2316
2317 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2318 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002319
2320 // Expand memset / memcpy to a series of load / store ops
2321 // if the size operand falls below a certain threshold.
2322 std::vector<SDOperand> OutChains;
2323 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002324 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002325 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002326 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2327 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002328 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002329 unsigned Offset = 0;
2330 for (unsigned i = 0; i < NumMemOps; i++) {
2331 MVT::ValueType VT = MemOps[i];
2332 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002333 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002334 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2335 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002336 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2337 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002338 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002339 Offset += VTSize;
2340 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002341 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002342 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002343 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002344 case ISD::MEMCPY: {
2345 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2346 Size->getValue(), Align, TLI)) {
2347 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002348 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002349 GlobalAddressSDNode *G = NULL;
2350 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002351 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002352
2353 if (Op2.getOpcode() == ISD::GlobalAddress)
2354 G = cast<GlobalAddressSDNode>(Op2);
2355 else if (Op2.getOpcode() == ISD::ADD &&
2356 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2357 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2358 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002359 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002360 }
2361 if (G) {
2362 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002363 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002364 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002365 if (!Str.empty()) {
2366 CopyFromStr = true;
2367 SrcOff += SrcDelta;
2368 }
2369 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002370 }
2371
Evan Chenge2038bd2006-02-15 01:54:51 +00002372 for (unsigned i = 0; i < NumMemOps; i++) {
2373 MVT::ValueType VT = MemOps[i];
2374 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002375 SDOperand Value, Chain, Store;
2376
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002377 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002378 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2379 Chain = getRoot();
2380 Store =
2381 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2382 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2383 DAG.getSrcValue(I.getOperand(1), DstOff));
2384 } else {
2385 Value = DAG.getLoad(VT, getRoot(),
2386 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2387 DAG.getSrcValue(I.getOperand(2), SrcOff));
2388 Chain = Value.getValue(1);
2389 Store =
2390 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2391 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2392 DAG.getSrcValue(I.getOperand(1), DstOff));
2393 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002394 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002395 SrcOff += VTSize;
2396 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002397 }
2398 }
2399 break;
2400 }
2401 }
2402
2403 if (!OutChains.empty()) {
2404 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2405 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002406 }
2407 }
2408
Chris Lattner875def92005-01-11 05:56:49 +00002409 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002410 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002411 Ops.push_back(Op1);
2412 Ops.push_back(Op2);
2413 Ops.push_back(Op3);
2414 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002415 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002416}
2417
Chris Lattner875def92005-01-11 05:56:49 +00002418//===----------------------------------------------------------------------===//
2419// SelectionDAGISel code
2420//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002421
2422unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2423 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2424}
2425
Chris Lattnerc9950c12005-08-17 06:37:43 +00002426void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002427 // FIXME: we only modify the CFG to split critical edges. This
2428 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002429}
Chris Lattner7a60d912005-01-07 07:47:53 +00002430
Chris Lattner35397782005-12-05 07:10:48 +00002431
2432/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2433/// casting to the type of GEPI.
2434static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2435 Value *Ptr, Value *PtrOffset) {
2436 if (V) return V; // Already computed.
2437
2438 BasicBlock::iterator InsertPt;
2439 if (BB == GEPI->getParent()) {
2440 // If insert into the GEP's block, insert right after the GEP.
2441 InsertPt = GEPI;
2442 ++InsertPt;
2443 } else {
2444 // Otherwise, insert at the top of BB, after any PHI nodes
2445 InsertPt = BB->begin();
2446 while (isa<PHINode>(InsertPt)) ++InsertPt;
2447 }
2448
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002449 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2450 // BB so that there is only one value live across basic blocks (the cast
2451 // operand).
2452 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2453 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2454 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2455
Chris Lattner35397782005-12-05 07:10:48 +00002456 // Add the offset, cast it to the right type.
2457 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2458 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2459 return V = Ptr;
2460}
2461
2462
2463/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2464/// selection, we want to be a bit careful about some things. In particular, if
2465/// we have a GEP instruction that is used in a different block than it is
2466/// defined, the addressing expression of the GEP cannot be folded into loads or
2467/// stores that use it. In this case, decompose the GEP and move constant
2468/// indices into blocks that use it.
2469static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2470 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002471 // If this GEP is only used inside the block it is defined in, there is no
2472 // need to rewrite it.
2473 bool isUsedOutsideDefBB = false;
2474 BasicBlock *DefBB = GEPI->getParent();
2475 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2476 UI != E; ++UI) {
2477 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2478 isUsedOutsideDefBB = true;
2479 break;
2480 }
2481 }
2482 if (!isUsedOutsideDefBB) return;
2483
2484 // If this GEP has no non-zero constant indices, there is nothing we can do,
2485 // ignore it.
2486 bool hasConstantIndex = false;
2487 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2488 E = GEPI->op_end(); OI != E; ++OI) {
2489 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2490 if (CI->getRawValue()) {
2491 hasConstantIndex = true;
2492 break;
2493 }
2494 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002495 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2496 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002497
2498 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2499 // constant offset (which we now know is non-zero) and deal with it later.
2500 uint64_t ConstantOffset = 0;
2501 const Type *UIntPtrTy = TD.getIntPtrType();
2502 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2503 const Type *Ty = GEPI->getOperand(0)->getType();
2504
2505 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2506 E = GEPI->op_end(); OI != E; ++OI) {
2507 Value *Idx = *OI;
2508 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2509 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2510 if (Field)
2511 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2512 Ty = StTy->getElementType(Field);
2513 } else {
2514 Ty = cast<SequentialType>(Ty)->getElementType();
2515
2516 // Handle constant subscripts.
2517 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2518 if (CI->getRawValue() == 0) continue;
2519
2520 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2521 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2522 else
2523 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2524 continue;
2525 }
2526
2527 // Ptr = Ptr + Idx * ElementSize;
2528
2529 // Cast Idx to UIntPtrTy if needed.
2530 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2531
2532 uint64_t ElementSize = TD.getTypeSize(Ty);
2533 // Mask off bits that should not be set.
2534 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2535 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2536
2537 // Multiply by the element size and add to the base.
2538 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2539 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2540 }
2541 }
2542
2543 // Make sure that the offset fits in uintptr_t.
2544 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2545 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2546
2547 // Okay, we have now emitted all of the variable index parts to the BB that
2548 // the GEP is defined in. Loop over all of the using instructions, inserting
2549 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002550 // instruction to use the newly computed value, making GEPI dead. When the
2551 // user is a load or store instruction address, we emit the add into the user
2552 // block, otherwise we use a canonical version right next to the gep (these
2553 // won't be foldable as addresses, so we might as well share the computation).
2554
Chris Lattner35397782005-12-05 07:10:48 +00002555 std::map<BasicBlock*,Value*> InsertedExprs;
2556 while (!GEPI->use_empty()) {
2557 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002558
2559 // If this use is not foldable into the addressing mode, use a version
2560 // emitted in the GEP block.
2561 Value *NewVal;
2562 if (!isa<LoadInst>(User) &&
2563 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2564 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2565 Ptr, PtrOffset);
2566 } else {
2567 // Otherwise, insert the code in the User's block so it can be folded into
2568 // any users in that block.
2569 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002570 User->getParent(), GEPI,
2571 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002572 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002573 User->replaceUsesOfWith(GEPI, NewVal);
2574 }
Chris Lattner35397782005-12-05 07:10:48 +00002575
2576 // Finally, the GEP is dead, remove it.
2577 GEPI->eraseFromParent();
2578}
2579
Chris Lattner7a60d912005-01-07 07:47:53 +00002580bool SelectionDAGISel::runOnFunction(Function &Fn) {
2581 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2582 RegMap = MF.getSSARegMap();
2583 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2584
Chris Lattner35397782005-12-05 07:10:48 +00002585 // First, split all critical edges for PHI nodes with incoming values that are
2586 // constants, this way the load of the constant into a vreg will not be placed
2587 // into MBBs that are used some other way.
2588 //
2589 // In this pass we also look for GEP instructions that are used across basic
2590 // blocks and rewrites them to improve basic-block-at-a-time selection.
2591 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002592 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2593 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002594 BasicBlock::iterator BBI;
2595 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002596 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2597 if (isa<Constant>(PN->getIncomingValue(i)))
2598 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002599
2600 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2602 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002603 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002604
Chris Lattner7a60d912005-01-07 07:47:53 +00002605 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2606
2607 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2608 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002609
Chris Lattner7a60d912005-01-07 07:47:53 +00002610 return true;
2611}
2612
2613
Chris Lattner718b5c22005-01-13 17:59:43 +00002614SDOperand SelectionDAGISel::
2615CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002616 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002617 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002618 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002619 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002620
2621 // If this type is not legal, we must make sure to not create an invalid
2622 // register use.
2623 MVT::ValueType SrcVT = Op.getValueType();
2624 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2625 SelectionDAG &DAG = SDL.DAG;
2626 if (SrcVT == DestVT) {
2627 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002628 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00002629 // Handle copies from generic vectors to registers.
2630 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2631 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2632 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00002633
Chris Lattner5fe1f542006-03-31 02:06:56 +00002634 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2635 // MVT::Vector type.
2636 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2637 DAG.getConstant(NE, MVT::i32),
2638 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00002639
Chris Lattner5fe1f542006-03-31 02:06:56 +00002640 // Loop over all of the elements of the resultant vector,
2641 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2642 // copying them into output registers.
2643 std::vector<SDOperand> OutChains;
2644 SDOperand Root = SDL.getRoot();
2645 for (unsigned i = 0; i != NE; ++i) {
2646 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2647 Op, DAG.getConstant(i, MVT::i32));
2648 if (PTyElementVT == PTyLegalElementVT) {
2649 // Elements are legal.
2650 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2651 } else if (PTyLegalElementVT > PTyElementVT) {
2652 // Elements are promoted.
2653 if (MVT::isFloatingPoint(PTyLegalElementVT))
2654 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2655 else
2656 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2657 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2658 } else {
2659 // Elements are expanded.
2660 // The src value is expanded into multiple registers.
2661 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2662 Elt, DAG.getConstant(0, MVT::i32));
2663 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2664 Elt, DAG.getConstant(1, MVT::i32));
2665 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2666 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2667 }
Chris Lattner672a42d2006-03-21 19:20:37 +00002668 }
Chris Lattner5fe1f542006-03-31 02:06:56 +00002669 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner33182322005-08-16 21:55:35 +00002670 } else if (SrcVT < DestVT) {
2671 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002672 if (MVT::isFloatingPoint(SrcVT))
2673 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2674 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002675 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002676 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2677 } else {
2678 // The src value is expanded into multiple registers.
2679 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2680 Op, DAG.getConstant(0, MVT::i32));
2681 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2682 Op, DAG.getConstant(1, MVT::i32));
2683 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2684 return DAG.getCopyToReg(Op, Reg+1, Hi);
2685 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002686}
2687
Chris Lattner16f64df2005-01-17 17:15:02 +00002688void SelectionDAGISel::
2689LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2690 std::vector<SDOperand> &UnorderedChains) {
2691 // If this is the entry block, emit arguments.
2692 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002693 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002694 SDOperand OldRoot = SDL.DAG.getRoot();
2695 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002696
Chris Lattner6871b232005-10-30 19:42:35 +00002697 unsigned a = 0;
2698 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2699 AI != E; ++AI, ++a)
2700 if (!AI->use_empty()) {
2701 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002702
Chris Lattner6871b232005-10-30 19:42:35 +00002703 // If this argument is live outside of the entry block, insert a copy from
2704 // whereever we got it to the vreg that other BB's will reference it as.
2705 if (FuncInfo.ValueMap.count(AI)) {
2706 SDOperand Copy =
2707 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2708 UnorderedChains.push_back(Copy);
2709 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002710 }
Chris Lattner6871b232005-10-30 19:42:35 +00002711
2712 // Next, if the function has live ins that need to be copied into vregs,
2713 // emit the copies now, into the top of the block.
2714 MachineFunction &MF = SDL.DAG.getMachineFunction();
2715 if (MF.livein_begin() != MF.livein_end()) {
2716 SSARegMap *RegMap = MF.getSSARegMap();
2717 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2718 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2719 E = MF.livein_end(); LI != E; ++LI)
2720 if (LI->second)
2721 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2722 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002723 }
Chris Lattner6871b232005-10-30 19:42:35 +00002724
2725 // Finally, if the target has anything special to do, allow it to do so.
2726 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002727}
2728
2729
Chris Lattner7a60d912005-01-07 07:47:53 +00002730void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2731 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00002732 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00002733 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002734
2735 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002736
Chris Lattner6871b232005-10-30 19:42:35 +00002737 // Lower any arguments needed in this block if this is the entry block.
2738 if (LLVMBB == &LLVMBB->getParent()->front())
2739 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002740
2741 BB = FuncInfo.MBBMap[LLVMBB];
2742 SDL.setCurrentBasicBlock(BB);
2743
2744 // Lower all of the non-terminator instructions.
2745 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2746 I != E; ++I)
2747 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00002748
Chris Lattner7a60d912005-01-07 07:47:53 +00002749 // Ensure that all instructions which are used outside of their defining
2750 // blocks are available as virtual registers.
2751 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002752 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002753 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002754 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002755 UnorderedChains.push_back(
2756 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002757 }
2758
2759 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2760 // ensure constants are generated when needed. Remember the virtual registers
2761 // that need to be added to the Machine PHI nodes as input. We cannot just
2762 // directly add them, because expansion might result in multiple MBB's for one
2763 // BB. As such, the start of the BB might correspond to a different MBB than
2764 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002765 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002766
2767 // Emit constants only once even if used by multiple PHI nodes.
2768 std::map<Constant*, unsigned> ConstantsOut;
2769
2770 // Check successor nodes PHI nodes that expect a constant to be available from
2771 // this block.
2772 TerminatorInst *TI = LLVMBB->getTerminator();
2773 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2774 BasicBlock *SuccBB = TI->getSuccessor(succ);
2775 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2776 PHINode *PN;
2777
2778 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2779 // nodes and Machine PHI nodes, but the incoming operands have not been
2780 // emitted yet.
2781 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002782 (PN = dyn_cast<PHINode>(I)); ++I)
2783 if (!PN->use_empty()) {
2784 unsigned Reg;
2785 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2786 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2787 unsigned &RegOut = ConstantsOut[C];
2788 if (RegOut == 0) {
2789 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002790 UnorderedChains.push_back(
2791 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002792 }
2793 Reg = RegOut;
2794 } else {
2795 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002796 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002797 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002798 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2799 "Didn't codegen value into a register!??");
2800 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002801 UnorderedChains.push_back(
2802 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002803 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002804 }
Misha Brukman835702a2005-04-21 22:36:52 +00002805
Chris Lattner8ea875f2005-01-07 21:34:19 +00002806 // Remember that this register needs to added to the machine PHI node as
2807 // the input for this MBB.
2808 unsigned NumElements =
2809 TLI.getNumElements(TLI.getValueType(PN->getType()));
2810 for (unsigned i = 0, e = NumElements; i != e; ++i)
2811 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002812 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002813 }
2814 ConstantsOut.clear();
2815
Chris Lattner718b5c22005-01-13 17:59:43 +00002816 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002817 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002818 SDOperand Root = SDL.getRoot();
2819 if (Root.getOpcode() != ISD::EntryToken) {
2820 unsigned i = 0, e = UnorderedChains.size();
2821 for (; i != e; ++i) {
2822 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2823 if (UnorderedChains[i].Val->getOperand(0) == Root)
2824 break; // Don't add the root if we already indirectly depend on it.
2825 }
2826
2827 if (i == e)
2828 UnorderedChains.push_back(Root);
2829 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002830 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2831 }
2832
Chris Lattner7a60d912005-01-07 07:47:53 +00002833 // Lower the terminator after the copies are emitted.
2834 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002835
Nate Begemaned728c12006-03-27 01:32:24 +00002836 // Copy over any CaseBlock records that may now exist due to SwitchInst
2837 // lowering.
2838 SwitchCases.clear();
2839 SwitchCases = SDL.SwitchCases;
2840
Chris Lattner4108bb02005-01-17 19:43:36 +00002841 // Make sure the root of the DAG is up-to-date.
2842 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002843}
2844
Nate Begemaned728c12006-03-27 01:32:24 +00002845void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002846 // Run the DAG combiner in pre-legalize mode.
2847 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002848
Chris Lattner7a60d912005-01-07 07:47:53 +00002849 DEBUG(std::cerr << "Lowered selection DAG:\n");
2850 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002851
Chris Lattner7a60d912005-01-07 07:47:53 +00002852 // Second step, hack on the DAG until it only uses operations and types that
2853 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002854 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00002855
Chris Lattner7a60d912005-01-07 07:47:53 +00002856 DEBUG(std::cerr << "Legalized selection DAG:\n");
2857 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002858
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002859 // Run the DAG combiner in post-legalize mode.
2860 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002861
Evan Cheng739a6a42006-01-21 02:32:06 +00002862 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002863
Chris Lattner5ca31d92005-03-30 01:10:47 +00002864 // Third, instruction select all of the operations to machine code, adding the
2865 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002866 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00002867
Chris Lattner7a60d912005-01-07 07:47:53 +00002868 DEBUG(std::cerr << "Selected machine code:\n");
2869 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002870}
Chris Lattner7a60d912005-01-07 07:47:53 +00002871
Nate Begemaned728c12006-03-27 01:32:24 +00002872void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2873 FunctionLoweringInfo &FuncInfo) {
2874 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2875 {
2876 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2877 CurDAG = &DAG;
2878
2879 // First step, lower LLVM code to some DAG. This DAG may use operations and
2880 // types that are not supported by the target.
2881 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2882
2883 // Second step, emit the lowered DAG as machine code.
2884 CodeGenAndEmitDAG(DAG);
2885 }
2886
Chris Lattner5ca31d92005-03-30 01:10:47 +00002887 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002888 // PHI nodes in successors.
Nate Begemaned728c12006-03-27 01:32:24 +00002889 if (SwitchCases.empty()) {
2890 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2891 MachineInstr *PHI = PHINodesToUpdate[i].first;
2892 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2893 "This is not a machine PHI node that we are updating!");
2894 PHI->addRegOperand(PHINodesToUpdate[i].second);
2895 PHI->addMachineBasicBlockOperand(BB);
2896 }
2897 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002898 }
Nate Begemaned728c12006-03-27 01:32:24 +00002899
2900 // If we generated any switch lowering information, build and codegen any
2901 // additional DAGs necessary.
2902 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2903 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2904 CurDAG = &SDAG;
2905 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2906 // Set the current basic block to the mbb we wish to insert the code into
2907 BB = SwitchCases[i].ThisBB;
2908 SDL.setCurrentBasicBlock(BB);
2909 // Emit the code
2910 SDL.visitSwitchCase(SwitchCases[i]);
2911 SDAG.setRoot(SDL.getRoot());
2912 CodeGenAndEmitDAG(SDAG);
2913 // Iterate over the phi nodes, if there is a phi node in a successor of this
2914 // block (for instance, the default block), then add a pair of operands to
2915 // the phi node for this block, as if we were coming from the original
2916 // BB before switch expansion.
2917 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2918 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2919 MachineBasicBlock *PHIBB = PHI->getParent();
2920 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2921 "This is not a machine PHI node that we are updating!");
2922 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2923 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2924 PHI->addMachineBasicBlockOperand(BB);
2925 }
2926 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002927 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002928}
Evan Cheng739a6a42006-01-21 02:32:06 +00002929
2930//===----------------------------------------------------------------------===//
2931/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2932/// target node in the graph.
2933void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2934 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002935 ScheduleDAG *SL = NULL;
2936
2937 switch (ISHeuristic) {
2938 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002939 case defaultScheduling:
2940 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2941 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2942 else /* TargetLowering::SchedulingForRegPressure */
2943 SL = createBURRListDAGScheduler(DAG, BB);
2944 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002945 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002946 SL = createBFS_DAGScheduler(DAG, BB);
2947 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002948 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002949 SL = createSimpleDAGScheduler(false, DAG, BB);
2950 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002951 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002952 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002953 break;
Evan Cheng31272342006-01-23 08:26:10 +00002954 case listSchedulingBURR:
2955 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002956 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002957 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002958 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002959 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002960 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002961 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002962 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002963}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002964
Chris Lattner543832d2006-03-08 04:25:59 +00002965HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2966 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002967}
2968
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002969/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2970/// by tblgen. Others should not call it.
2971void SelectionDAGISel::
2972SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2973 std::vector<SDOperand> InOps;
2974 std::swap(InOps, Ops);
2975
2976 Ops.push_back(InOps[0]); // input chain.
2977 Ops.push_back(InOps[1]); // input asm string.
2978
2979 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2980 unsigned i = 2, e = InOps.size();
2981 if (InOps[e-1].getValueType() == MVT::Flag)
2982 --e; // Don't process a flag operand if it is here.
2983
2984 while (i != e) {
2985 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2986 if ((Flags & 7) != 4 /*MEM*/) {
2987 // Just skip over this operand, copying the operands verbatim.
2988 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2989 i += (Flags >> 3) + 1;
2990 } else {
2991 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2992 // Otherwise, this is a memory operand. Ask the target to select it.
2993 std::vector<SDOperand> SelOps;
2994 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2995 std::cerr << "Could not match memory address. Inline asm failure!\n";
2996 exit(1);
2997 }
2998
2999 // Add this to the output node.
3000 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3001 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3002 i += 2;
3003 }
3004 }
3005
3006 // Add the flag input back if present.
3007 if (e != InOps.size())
3008 Ops.push_back(InOps.back());
3009}