blob: 3c633266bf90c733118e0682166d600e783e490a [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()) {
267 unsigned NumElements =
268 TLI.getNumElements(TLI.getValueType(PN->getType()));
269 unsigned PHIReg = ValueMap[PN];
270 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
271 for (unsigned i = 0; i != NumElements; ++i)
272 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
273 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000274 }
275}
276
Chris Lattner49409cb2006-03-16 19:51:18 +0000277/// CreateRegForValue - Allocate the appropriate number of virtual registers of
278/// the correctly promoted or expanded types. Assign these registers
279/// consecutive vreg numbers and return the first assigned number.
280unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
281 MVT::ValueType VT = TLI.getValueType(V->getType());
282
283 // The number of multiples of registers that we need, to, e.g., split up
284 // a <2 x int64> -> 4 x i32 registers.
285 unsigned NumVectorRegs = 1;
286
287 // If this is a packed type, figure out what type it will decompose into
288 // and how many of the elements it will use.
289 if (VT == MVT::Vector) {
290 const PackedType *PTy = cast<PackedType>(V->getType());
291 unsigned NumElts = PTy->getNumElements();
292 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
293
294 // Divide the input until we get to a supported size. This will always
295 // end with a scalar if the target doesn't support vectors.
296 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
297 NumElts >>= 1;
298 NumVectorRegs <<= 1;
299 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000300 if (NumElts == 1)
301 VT = EltTy;
302 else
303 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000304 }
305
306 // The common case is that we will only create one register for this
307 // value. If we have that case, create and return the virtual register.
308 unsigned NV = TLI.getNumElements(VT);
309 if (NV == 1) {
310 // If we are promoting this value, pick the next largest supported type.
311 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
312 unsigned Reg = MakeReg(PromotedType);
313 // If this is a vector of supported or promoted types (e.g. 4 x i16),
314 // create all of the registers.
315 for (unsigned i = 1; i != NumVectorRegs; ++i)
316 MakeReg(PromotedType);
317 return Reg;
318 }
319
320 // If this value is represented with multiple target registers, make sure
321 // to create enough consecutive registers of the right (smaller) type.
322 unsigned NT = VT-1; // Find the type to use.
323 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
324 --NT;
325
326 unsigned R = MakeReg((MVT::ValueType)NT);
327 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
328 MakeReg((MVT::ValueType)NT);
329 return R;
330}
Chris Lattner7a60d912005-01-07 07:47:53 +0000331
332//===----------------------------------------------------------------------===//
333/// SelectionDAGLowering - This is the common target-independent lowering
334/// implementation that is parameterized by a TargetLowering object.
335/// Also, targets can overload any lowering method.
336///
337namespace llvm {
338class SelectionDAGLowering {
339 MachineBasicBlock *CurMBB;
340
341 std::map<const Value*, SDOperand> NodeMap;
342
Chris Lattner4d9651c2005-01-17 22:19:26 +0000343 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
344 /// them up and then emit token factor nodes when possible. This allows us to
345 /// get simple disambiguation between loads without worrying about alias
346 /// analysis.
347 std::vector<SDOperand> PendingLoads;
348
Nate Begemaned728c12006-03-27 01:32:24 +0000349 /// Case - A pair of values to record the Value for a switch case, and the
350 /// case's target basic block.
351 typedef std::pair<Constant*, MachineBasicBlock*> Case;
352 typedef std::vector<Case>::iterator CaseItr;
353 typedef std::pair<CaseItr, CaseItr> CaseRange;
354
355 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
356 /// of conditional branches.
357 struct CaseRec {
358 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
359 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
360
361 /// CaseBB - The MBB in which to emit the compare and branch
362 MachineBasicBlock *CaseBB;
363 /// LT, GE - If nonzero, we know the current case value must be less-than or
364 /// greater-than-or-equal-to these Constants.
365 Constant *LT;
366 Constant *GE;
367 /// Range - A pair of iterators representing the range of case values to be
368 /// processed at this point in the binary search tree.
369 CaseRange Range;
370 };
371
372 /// The comparison function for sorting Case values.
373 struct CaseCmp {
374 bool operator () (const Case& C1, const Case& C2) {
375 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
376 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
377
378 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
379 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
380 }
381 };
382
Chris Lattner7a60d912005-01-07 07:47:53 +0000383public:
384 // TLI - This is information that describes the available target features we
385 // need for lowering. This indicates when operations are unavailable,
386 // implemented with a libcall, etc.
387 TargetLowering &TLI;
388 SelectionDAG &DAG;
389 const TargetData &TD;
390
Nate Begemaned728c12006-03-27 01:32:24 +0000391 /// SwitchCases - Vector of CaseBlock structures used to communicate
392 /// SwitchInst code generation information.
393 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
394
Chris Lattner7a60d912005-01-07 07:47:53 +0000395 /// FuncInfo - Information about the function as a whole.
396 ///
397 FunctionLoweringInfo &FuncInfo;
398
399 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000400 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000401 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
402 FuncInfo(funcinfo) {
403 }
404
Chris Lattner4108bb02005-01-17 19:43:36 +0000405 /// getRoot - Return the current virtual root of the Selection DAG.
406 ///
407 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000408 if (PendingLoads.empty())
409 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000410
Chris Lattner4d9651c2005-01-17 22:19:26 +0000411 if (PendingLoads.size() == 1) {
412 SDOperand Root = PendingLoads[0];
413 DAG.setRoot(Root);
414 PendingLoads.clear();
415 return Root;
416 }
417
418 // Otherwise, we have to make a token factor node.
419 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
420 PendingLoads.clear();
421 DAG.setRoot(Root);
422 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000423 }
424
Chris Lattner7a60d912005-01-07 07:47:53 +0000425 void visit(Instruction &I) { visit(I.getOpcode(), I); }
426
427 void visit(unsigned Opcode, User &I) {
428 switch (Opcode) {
429 default: assert(0 && "Unknown instruction type encountered!");
430 abort();
431 // Build the switch statement using the Instruction.def file.
432#define HANDLE_INST(NUM, OPCODE, CLASS) \
433 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
434#include "llvm/Instruction.def"
435 }
436 }
437
438 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
439
Chris Lattner4024c002006-03-15 22:19:46 +0000440 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
441 SDOperand SrcValue, SDOperand Root,
442 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000443
444 SDOperand getIntPtrConstant(uint64_t Val) {
445 return DAG.getConstant(Val, TLI.getPointerTy());
446 }
447
Chris Lattner8471b152006-03-16 19:57:50 +0000448 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000449
450 const SDOperand &setValue(const Value *V, SDOperand NewN) {
451 SDOperand &N = NodeMap[V];
452 assert(N.Val == 0 && "Already set a value for this node!");
453 return N = NewN;
454 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000455
Chris Lattner6f87d182006-02-22 22:37:12 +0000456 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
457 MVT::ValueType VT,
458 bool OutReg, bool InReg,
459 std::set<unsigned> &OutputRegs,
460 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000461
Chris Lattner7a60d912005-01-07 07:47:53 +0000462 // Terminator instructions.
463 void visitRet(ReturnInst &I);
464 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000465 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000466 void visitUnreachable(UnreachableInst &I) { /* noop */ }
467
Nate Begemaned728c12006-03-27 01:32:24 +0000468 // Helper for visitSwitch
469 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
470
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000472 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
473 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
474
Nate Begemanb2e089c2005-11-19 00:36:38 +0000475 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000476 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000477 void visitAdd(User &I) {
478 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000479 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000480 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000481 void visitMul(User &I) {
482 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000483 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000485 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000486 visitBinary(I,
487 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
488 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 }
490 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000491 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000492 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000494 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
495 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
496 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000497 void visitShl(User &I) { visitShift(I, ISD::SHL); }
498 void visitShr(User &I) {
499 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
501
502 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
503 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
504 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
505 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
506 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
507 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
508 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
509
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000510 void visitExtractElement(ExtractElementInst &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000511 void visitInsertElement(InsertElementInst &I);
512
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 void visitGetElementPtr(User &I);
514 void visitCast(User &I);
515 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000516
517 void visitMalloc(MallocInst &I);
518 void visitFree(FreeInst &I);
519 void visitAlloca(AllocaInst &I);
520 void visitLoad(LoadInst &I);
521 void visitStore(StoreInst &I);
522 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
523 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000524 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000525 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000526 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527
Chris Lattner7a60d912005-01-07 07:47:53 +0000528 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000529 void visitVAArg(VAArgInst &I);
530 void visitVAEnd(CallInst &I);
531 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000532 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000533
Chris Lattner875def92005-01-11 05:56:49 +0000534 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000535
536 void visitUserOp1(Instruction &I) {
537 assert(0 && "UserOp1 should not exist at instruction selection time!");
538 abort();
539 }
540 void visitUserOp2(Instruction &I) {
541 assert(0 && "UserOp2 should not exist at instruction selection time!");
542 abort();
543 }
544};
545} // end namespace llvm
546
Chris Lattner8471b152006-03-16 19:57:50 +0000547SDOperand SelectionDAGLowering::getValue(const Value *V) {
548 SDOperand &N = NodeMap[V];
549 if (N.Val) return N;
550
551 const Type *VTy = V->getType();
552 MVT::ValueType VT = TLI.getValueType(VTy);
553 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555 visit(CE->getOpcode(), *CE);
556 assert(N.Val && "visit didn't populate the ValueMap!");
557 return N;
558 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
559 return N = DAG.getGlobalAddress(GV, VT);
560 } else if (isa<ConstantPointerNull>(C)) {
561 return N = DAG.getConstant(0, TLI.getPointerTy());
562 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000563 if (!isa<PackedType>(VTy))
564 return N = DAG.getNode(ISD::UNDEF, VT);
565
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000566 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000567 const PackedType *PTy = cast<PackedType>(VTy);
568 unsigned NumElements = PTy->getNumElements();
569 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
570
571 std::vector<SDOperand> Ops;
572 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
573
574 // Create a VConstant node with generic Vector type.
575 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
576 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000577 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000578 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
579 return N = DAG.getConstantFP(CFP->getValue(), VT);
580 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
581 unsigned NumElements = PTy->getNumElements();
582 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000583
584 // Now that we know the number and type of the elements, push a
585 // Constant or ConstantFP node onto the ops list for each element of
586 // the packed constant.
587 std::vector<SDOperand> Ops;
588 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
589 if (MVT::isFloatingPoint(PVT)) {
590 for (unsigned i = 0; i != NumElements; ++i) {
591 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
592 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
593 }
594 } else {
595 for (unsigned i = 0; i != NumElements; ++i) {
596 const ConstantIntegral *El =
597 cast<ConstantIntegral>(CP->getOperand(i));
598 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
599 }
600 }
601 } else {
602 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
603 SDOperand Op;
604 if (MVT::isFloatingPoint(PVT))
605 Op = DAG.getConstantFP(0, PVT);
606 else
607 Op = DAG.getConstant(0, PVT);
608 Ops.assign(NumElements, Op);
609 }
610
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000611 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000612 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
613 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000614 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000615 } else {
616 // Canonicalize all constant ints to be unsigned.
617 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
618 }
619 }
620
621 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
622 std::map<const AllocaInst*, int>::iterator SI =
623 FuncInfo.StaticAllocaMap.find(AI);
624 if (SI != FuncInfo.StaticAllocaMap.end())
625 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
626 }
627
628 std::map<const Value*, unsigned>::const_iterator VMI =
629 FuncInfo.ValueMap.find(V);
630 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
631
632 unsigned InReg = VMI->second;
633
634 // If this type is not legal, make it so now.
635 if (VT == MVT::Vector) {
636 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
637 const PackedType *PTy = cast<PackedType>(VTy);
638 unsigned NumElements = PTy->getNumElements();
639 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
640 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
641 assert(TLI.isTypeLegal(TVT) &&
642 "FIXME: Cannot handle illegal vector types here yet!");
643 VT = TVT;
Chris Lattner313229c2006-03-24 22:49:42 +0000644 }
Chris Lattner8471b152006-03-16 19:57:50 +0000645
646 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
647
648 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
649 if (DestVT < VT) {
650 // Source must be expanded. This input value is actually coming from the
651 // register pair VMI->second and VMI->second+1.
652 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
653 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
654 } else {
655 if (DestVT > VT) { // Promotion case
656 if (MVT::isFloatingPoint(VT))
657 N = DAG.getNode(ISD::FP_ROUND, VT, N);
658 else
659 N = DAG.getNode(ISD::TRUNCATE, VT, N);
660 }
661 }
662
663 return N;
664}
665
666
Chris Lattner7a60d912005-01-07 07:47:53 +0000667void SelectionDAGLowering::visitRet(ReturnInst &I) {
668 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000669 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000670 return;
671 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000672 std::vector<SDOperand> NewValues;
673 NewValues.push_back(getRoot());
674 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
675 SDOperand RetOp = getValue(I.getOperand(i));
676
677 // If this is an integer return value, we need to promote it ourselves to
678 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
679 // than sign/zero.
680 if (MVT::isInteger(RetOp.getValueType()) &&
681 RetOp.getValueType() < MVT::i64) {
682 MVT::ValueType TmpVT;
683 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
684 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
685 else
686 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000687
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000688 if (I.getOperand(i)->getType()->isSigned())
689 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
690 else
691 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
692 }
693 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000694 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000695 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000696}
697
698void SelectionDAGLowering::visitBr(BranchInst &I) {
699 // Update machine-CFG edges.
700 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000701 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000702
703 // Figure out which block is immediately after the current one.
704 MachineBasicBlock *NextBlock = 0;
705 MachineFunction::iterator BBI = CurMBB;
706 if (++BBI != CurMBB->getParent()->end())
707 NextBlock = BBI;
708
709 if (I.isUnconditional()) {
710 // If this is not a fall-through branch, emit the branch.
711 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000712 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000713 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000714 } else {
715 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000716 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000717
718 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000719 if (Succ1MBB == NextBlock) {
720 // If the condition is false, fall through. This means we should branch
721 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000722 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000723 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000724 } else if (Succ0MBB == NextBlock) {
725 // If the condition is true, fall through. This means we should branch if
726 // the condition is false to Succ #1. Invert the condition first.
727 SDOperand True = DAG.getConstant(1, Cond.getValueType());
728 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000729 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000730 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000731 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000732 std::vector<SDOperand> Ops;
733 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000734 // If the false case is the current basic block, then this is a self
735 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
736 // adds an extra instruction in the loop. Instead, invert the
737 // condition and emit "Loop: ... br!cond Loop; br Out.
738 if (CurMBB == Succ1MBB) {
739 std::swap(Succ0MBB, Succ1MBB);
740 SDOperand True = DAG.getConstant(1, Cond.getValueType());
741 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
742 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000743 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
744 DAG.getBasicBlock(Succ0MBB));
745 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
746 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000747 }
748 }
749}
750
Nate Begemaned728c12006-03-27 01:32:24 +0000751/// visitSwitchCase - Emits the necessary code to represent a single node in
752/// the binary search tree resulting from lowering a switch instruction.
753void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
754 SDOperand SwitchOp = getValue(CB.SwitchV);
755 SDOperand CaseOp = getValue(CB.CaseC);
756 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
757
758 // Set NextBlock to be the MBB immediately after the current one, if any.
759 // This is used to avoid emitting unnecessary branches to the next block.
760 MachineBasicBlock *NextBlock = 0;
761 MachineFunction::iterator BBI = CurMBB;
762 if (++BBI != CurMBB->getParent()->end())
763 NextBlock = BBI;
764
765 // If the lhs block is the next block, invert the condition so that we can
766 // fall through to the lhs instead of the rhs block.
767 if (CB.LHSBB == NextBlock) {
768 std::swap(CB.LHSBB, CB.RHSBB);
769 SDOperand True = DAG.getConstant(1, Cond.getValueType());
770 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
771 }
772 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
773 DAG.getBasicBlock(CB.LHSBB));
774 if (CB.RHSBB == NextBlock)
775 DAG.setRoot(BrCond);
776 else
777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
778 DAG.getBasicBlock(CB.RHSBB)));
779 // Update successor info
780 CurMBB->addSuccessor(CB.LHSBB);
781 CurMBB->addSuccessor(CB.RHSBB);
782}
783
784void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
785 // Figure out which block is immediately after the current one.
786 MachineBasicBlock *NextBlock = 0;
787 MachineFunction::iterator BBI = CurMBB;
788 if (++BBI != CurMBB->getParent()->end())
789 NextBlock = BBI;
790
791 // If there is only the default destination, branch to it if it is not the
792 // next basic block. Otherwise, just fall through.
793 if (I.getNumOperands() == 2) {
794 // Update machine-CFG edges.
795 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
796 // If this is not a fall-through branch, emit the branch.
797 if (DefaultMBB != NextBlock)
798 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
799 DAG.getBasicBlock(DefaultMBB)));
800 return;
801 }
802
803 // If there are any non-default case statements, create a vector of Cases
804 // representing each one, and sort the vector so that we can efficiently
805 // create a binary search tree from them.
806 std::vector<Case> Cases;
807 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
808 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
809 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
810 }
811 std::sort(Cases.begin(), Cases.end(), CaseCmp());
812
813 // Get the Value to be switched on and default basic blocks, which will be
814 // inserted into CaseBlock records, representing basic blocks in the binary
815 // search tree.
816 Value *SV = I.getOperand(0);
817 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
818
819 // Get the current MachineFunction and LLVM basic block, for use in creating
820 // and inserting new MBBs during the creation of the binary search tree.
821 MachineFunction *CurMF = CurMBB->getParent();
822 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
823
824 // Push the initial CaseRec onto the worklist
825 std::vector<CaseRec> CaseVec;
826 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
827
828 while (!CaseVec.empty()) {
829 // Grab a record representing a case range to process off the worklist
830 CaseRec CR = CaseVec.back();
831 CaseVec.pop_back();
832
833 // Size is the number of Cases represented by this range. If Size is 1,
834 // then we are processing a leaf of the binary search tree. Otherwise,
835 // we need to pick a pivot, and push left and right ranges onto the
836 // worklist.
837 unsigned Size = CR.Range.second - CR.Range.first;
838
839 if (Size == 1) {
840 // Create a CaseBlock record representing a conditional branch to
841 // the Case's target mbb if the value being switched on SV is equal
842 // to C. Otherwise, branch to default.
843 Constant *C = CR.Range.first->first;
844 MachineBasicBlock *Target = CR.Range.first->second;
845 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
846 CR.CaseBB);
847 // If the MBB representing the leaf node is the current MBB, then just
848 // call visitSwitchCase to emit the code into the current block.
849 // Otherwise, push the CaseBlock onto the vector to be later processed
850 // by SDISel, and insert the node's MBB before the next MBB.
851 if (CR.CaseBB == CurMBB)
852 visitSwitchCase(CB);
853 else {
854 SwitchCases.push_back(CB);
855 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
856 }
857 } else {
858 // split case range at pivot
859 CaseItr Pivot = CR.Range.first + (Size / 2);
860 CaseRange LHSR(CR.Range.first, Pivot);
861 CaseRange RHSR(Pivot, CR.Range.second);
862 Constant *C = Pivot->first;
863 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
864 // We know that we branch to the LHS if the Value being switched on is
865 // less than the Pivot value, C. We use this to optimize our binary
866 // tree a bit, by recognizing that if SV is greater than or equal to the
867 // LHS's Case Value, and that Case Value is exactly one less than the
868 // Pivot's Value, then we can branch directly to the LHS's Target,
869 // rather than creating a leaf node for it.
870 if ((LHSR.second - LHSR.first) == 1 &&
871 LHSR.first->first == CR.GE &&
872 cast<ConstantIntegral>(C)->getRawValue() ==
873 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
874 LHSBB = LHSR.first->second;
875 } else {
876 LHSBB = new MachineBasicBlock(LLVMBB);
877 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
878 }
879 // Similar to the optimization above, if the Value being switched on is
880 // known to be less than the Constant CR.LT, and the current Case Value
881 // is CR.LT - 1, then we can branch directly to the target block for
882 // the current Case Value, rather than emitting a RHS leaf node for it.
883 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
884 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
885 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
886 RHSBB = RHSR.first->second;
887 } else {
888 RHSBB = new MachineBasicBlock(LLVMBB);
889 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
890 }
891 // Create a CaseBlock record representing a conditional branch to
892 // the LHS node if the value being switched on SV is less than C.
893 // Otherwise, branch to LHS.
894 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
895 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
896 if (CR.CaseBB == CurMBB)
897 visitSwitchCase(CB);
898 else {
899 SwitchCases.push_back(CB);
900 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
901 }
902 }
903 }
904}
905
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000906void SelectionDAGLowering::visitSub(User &I) {
907 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000908 if (I.getType()->isFloatingPoint()) {
909 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
910 if (CFP->isExactlyValue(-0.0)) {
911 SDOperand Op2 = getValue(I.getOperand(1));
912 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
913 return;
914 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000915 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000916 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000917}
918
Nate Begemanb2e089c2005-11-19 00:36:38 +0000919void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
920 unsigned VecOp) {
921 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000922 SDOperand Op1 = getValue(I.getOperand(0));
923 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000924
Chris Lattner19baba62005-11-19 18:40:42 +0000925 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000926 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
927 } else if (Ty->isFloatingPoint()) {
928 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
929 } else {
930 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000931 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
932 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
933 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000934 }
Nate Begeman127321b2005-11-18 07:42:56 +0000935}
Chris Lattner96c26752005-01-19 22:31:21 +0000936
Nate Begeman127321b2005-11-18 07:42:56 +0000937void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
938 SDOperand Op1 = getValue(I.getOperand(0));
939 SDOperand Op2 = getValue(I.getOperand(1));
940
941 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
942
Chris Lattner7a60d912005-01-07 07:47:53 +0000943 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
944}
945
946void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
947 ISD::CondCode UnsignedOpcode) {
948 SDOperand Op1 = getValue(I.getOperand(0));
949 SDOperand Op2 = getValue(I.getOperand(1));
950 ISD::CondCode Opcode = SignedOpcode;
951 if (I.getOperand(0)->getType()->isUnsigned())
952 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000953 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000954}
955
956void SelectionDAGLowering::visitSelect(User &I) {
957 SDOperand Cond = getValue(I.getOperand(0));
958 SDOperand TrueVal = getValue(I.getOperand(1));
959 SDOperand FalseVal = getValue(I.getOperand(2));
960 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
961 TrueVal, FalseVal));
962}
963
964void SelectionDAGLowering::visitCast(User &I) {
965 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000966 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +0000967 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000968
Chris Lattner2f4119a2006-03-22 20:09:35 +0000969 if (DestVT == MVT::Vector) {
970 // This is a cast to a vector from something else. This is always a bit
971 // convert. Get information about the input vector.
972 const PackedType *DestTy = cast<PackedType>(I.getType());
973 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
974 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
975 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
976 DAG.getValueType(EltVT)));
977 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000978 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000979 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000980 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000981 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000982 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000983 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000984 } else if (isInteger(SrcVT)) {
985 if (isInteger(DestVT)) { // Int -> Int cast
986 if (DestVT < SrcVT) // Truncating cast?
987 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000988 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000989 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000990 else
Chris Lattner4024c002006-03-15 22:19:46 +0000991 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +0000992 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000993 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000994 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000995 else
Chris Lattner4024c002006-03-15 22:19:46 +0000996 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000997 } else {
998 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000999 }
Chris Lattner4024c002006-03-15 22:19:46 +00001000 } else if (isFloatingPoint(SrcVT)) {
1001 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1002 if (DestVT < SrcVT) // Rounding cast?
1003 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001004 else
Chris Lattner4024c002006-03-15 22:19:46 +00001005 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001006 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001007 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001008 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001009 else
Chris Lattner4024c002006-03-15 22:19:46 +00001010 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001011 } else {
1012 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001013 }
1014 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001015 assert(SrcVT == MVT::Vector && "Unknown cast!");
1016 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1017 // This is a cast from a vector to something else. This is always a bit
1018 // convert. Get information about the input vector.
1019 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001020 }
1021}
1022
Chris Lattner32206f52006-03-18 01:44:44 +00001023void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001024 SDOperand InVec = getValue(I.getOperand(0));
1025 SDOperand InVal = getValue(I.getOperand(1));
1026 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1027 getValue(I.getOperand(2)));
1028
Chris Lattner29b23012006-03-19 01:17:20 +00001029 SDOperand Num = *(InVec.Val->op_end()-2);
1030 SDOperand Typ = *(InVec.Val->op_end()-1);
1031 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1032 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001033}
1034
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001035void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
1036 SDOperand InVec = getValue(I.getOperand(0));
1037 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1038 getValue(I.getOperand(1)));
1039 SDOperand Typ = *(InVec.Val->op_end()-1);
1040 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1041 TLI.getValueType(I.getType()), InVec, InIdx));
1042}
Chris Lattner32206f52006-03-18 01:44:44 +00001043
Chris Lattner7a60d912005-01-07 07:47:53 +00001044void SelectionDAGLowering::visitGetElementPtr(User &I) {
1045 SDOperand N = getValue(I.getOperand(0));
1046 const Type *Ty = I.getOperand(0)->getType();
1047 const Type *UIntPtrTy = TD.getIntPtrType();
1048
1049 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1050 OI != E; ++OI) {
1051 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001052 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001053 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1054 if (Field) {
1055 // N = N + Offset
1056 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1057 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001058 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001059 }
1060 Ty = StTy->getElementType(Field);
1061 } else {
1062 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001063
Chris Lattner43535a12005-11-09 04:45:33 +00001064 // If this is a constant subscript, handle it quickly.
1065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1066 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001067
Chris Lattner43535a12005-11-09 04:45:33 +00001068 uint64_t Offs;
1069 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1070 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1071 else
1072 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1073 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1074 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001075 }
Chris Lattner43535a12005-11-09 04:45:33 +00001076
1077 // N = N + Idx * ElementSize;
1078 uint64_t ElementSize = TD.getTypeSize(Ty);
1079 SDOperand IdxN = getValue(Idx);
1080
1081 // If the index is smaller or larger than intptr_t, truncate or extend
1082 // it.
1083 if (IdxN.getValueType() < N.getValueType()) {
1084 if (Idx->getType()->isSigned())
1085 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1086 else
1087 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1088 } else if (IdxN.getValueType() > N.getValueType())
1089 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1090
1091 // If this is a multiply by a power of two, turn it into a shl
1092 // immediately. This is a very common case.
1093 if (isPowerOf2_64(ElementSize)) {
1094 unsigned Amt = Log2_64(ElementSize);
1095 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001096 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001097 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1098 continue;
1099 }
1100
1101 SDOperand Scale = getIntPtrConstant(ElementSize);
1102 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1103 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001104 }
1105 }
1106 setValue(&I, N);
1107}
1108
1109void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1110 // If this is a fixed sized alloca in the entry block of the function,
1111 // allocate it statically on the stack.
1112 if (FuncInfo.StaticAllocaMap.count(&I))
1113 return; // getValue will auto-populate this.
1114
1115 const Type *Ty = I.getAllocatedType();
1116 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +00001117 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1118 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001119
1120 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001121 MVT::ValueType IntPtr = TLI.getPointerTy();
1122 if (IntPtr < AllocSize.getValueType())
1123 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1124 else if (IntPtr > AllocSize.getValueType())
1125 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001126
Chris Lattnereccb73d2005-01-22 23:04:37 +00001127 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001128 getIntPtrConstant(TySize));
1129
1130 // Handle alignment. If the requested alignment is less than or equal to the
1131 // stack alignment, ignore it and round the size of the allocation up to the
1132 // stack alignment size. If the size is greater than the stack alignment, we
1133 // note this in the DYNAMIC_STACKALLOC node.
1134 unsigned StackAlign =
1135 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1136 if (Align <= StackAlign) {
1137 Align = 0;
1138 // Add SA-1 to the size.
1139 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1140 getIntPtrConstant(StackAlign-1));
1141 // Mask out the low bits for alignment purposes.
1142 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1143 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1144 }
1145
Chris Lattner96c262e2005-05-14 07:29:57 +00001146 std::vector<MVT::ValueType> VTs;
1147 VTs.push_back(AllocSize.getValueType());
1148 VTs.push_back(MVT::Other);
1149 std::vector<SDOperand> Ops;
1150 Ops.push_back(getRoot());
1151 Ops.push_back(AllocSize);
1152 Ops.push_back(getIntPtrConstant(Align));
1153 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +00001154 DAG.setRoot(setValue(&I, DSA).getValue(1));
1155
1156 // Inform the Frame Information that we have just allocated a variable-sized
1157 // object.
1158 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1159}
1160
Chris Lattner7a60d912005-01-07 07:47:53 +00001161void SelectionDAGLowering::visitLoad(LoadInst &I) {
1162 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001163
Chris Lattner4d9651c2005-01-17 22:19:26 +00001164 SDOperand Root;
1165 if (I.isVolatile())
1166 Root = getRoot();
1167 else {
1168 // Do not serialize non-volatile loads against each other.
1169 Root = DAG.getRoot();
1170 }
Chris Lattner4024c002006-03-15 22:19:46 +00001171
1172 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1173 Root, I.isVolatile()));
1174}
1175
1176SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1177 SDOperand SrcValue, SDOperand Root,
1178 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001179 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001180 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001181 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001182 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001183 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001184 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001185 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001186
Chris Lattner4024c002006-03-15 22:19:46 +00001187 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001188 DAG.setRoot(L.getValue(1));
1189 else
1190 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001191
1192 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001193}
1194
1195
1196void SelectionDAGLowering::visitStore(StoreInst &I) {
1197 Value *SrcV = I.getOperand(0);
1198 SDOperand Src = getValue(SrcV);
1199 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001200 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001201 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001202}
1203
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001204/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1205/// access memory and has no other side effects at all.
1206static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1207#define GET_NO_MEMORY_INTRINSICS
1208#include "llvm/Intrinsics.gen"
1209#undef GET_NO_MEMORY_INTRINSICS
1210 return false;
1211}
1212
1213/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1214/// node.
1215void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1216 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001217 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001218
1219 // Build the operand list.
1220 std::vector<SDOperand> Ops;
1221 if (HasChain) // If this intrinsic has side-effects, chainify it.
1222 Ops.push_back(getRoot());
1223
1224 // Add the intrinsic ID as an integer operand.
1225 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1226
1227 // Add all operands of the call to the operand list.
1228 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1229 SDOperand Op = getValue(I.getOperand(i));
1230
1231 // If this is a vector type, force it to the right packed type.
1232 if (Op.getValueType() == MVT::Vector) {
1233 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1234 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1235
1236 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1237 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1238 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1239 }
1240
1241 assert(TLI.isTypeLegal(Op.getValueType()) &&
1242 "Intrinsic uses a non-legal type?");
1243 Ops.push_back(Op);
1244 }
1245
1246 std::vector<MVT::ValueType> VTs;
1247 if (I.getType() != Type::VoidTy) {
1248 MVT::ValueType VT = TLI.getValueType(I.getType());
1249 if (VT == MVT::Vector) {
1250 const PackedType *DestTy = cast<PackedType>(I.getType());
1251 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1252
1253 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1254 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1255 }
1256
1257 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1258 VTs.push_back(VT);
1259 }
1260 if (HasChain)
1261 VTs.push_back(MVT::Other);
1262
1263 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001264 SDOperand Result;
1265 if (!HasChain)
1266 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1267 else if (I.getType() != Type::VoidTy)
1268 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1269 else
1270 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1271
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001272 if (HasChain)
1273 DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1274 if (I.getType() != Type::VoidTy) {
1275 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1276 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1277 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1278 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1279 DAG.getValueType(EVT));
1280 }
1281 setValue(&I, Result);
1282 }
1283}
1284
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001285/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1286/// we want to emit this as a call to a named external function, return the name
1287/// otherwise lower it and return null.
1288const char *
1289SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1290 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001291 default:
1292 // By default, turn this into a target intrinsic node.
1293 visitTargetIntrinsic(I, Intrinsic);
1294 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001295 case Intrinsic::vastart: visitVAStart(I); return 0;
1296 case Intrinsic::vaend: visitVAEnd(I); return 0;
1297 case Intrinsic::vacopy: visitVACopy(I); return 0;
1298 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1299 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1300 case Intrinsic::setjmp:
1301 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1302 break;
1303 case Intrinsic::longjmp:
1304 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1305 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001306 case Intrinsic::memcpy_i32:
1307 case Intrinsic::memcpy_i64:
1308 visitMemIntrinsic(I, ISD::MEMCPY);
1309 return 0;
1310 case Intrinsic::memset_i32:
1311 case Intrinsic::memset_i64:
1312 visitMemIntrinsic(I, ISD::MEMSET);
1313 return 0;
1314 case Intrinsic::memmove_i32:
1315 case Intrinsic::memmove_i64:
1316 visitMemIntrinsic(I, ISD::MEMMOVE);
1317 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001318
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001319 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001320 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001321 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001322 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001323 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001324
Jim Laskey5995d012006-02-11 01:01:30 +00001325 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001326 Ops.push_back(getValue(SPI.getLineValue()));
1327 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001328
Jim Laskeya8bdac82006-03-23 18:06:46 +00001329 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001330 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001331 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1332
Jim Laskey5995d012006-02-11 01:01:30 +00001333 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1334 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1335
Jim Laskeya8bdac82006-03-23 18:06:46 +00001336 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001337 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001338
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001339 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001340 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001341 case Intrinsic::dbg_region_start: {
1342 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1343 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001344 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001345 std::vector<SDOperand> Ops;
1346
1347 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1348
1349 Ops.push_back(getRoot());
1350 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1351
1352 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1353 }
1354
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001355 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001356 }
1357 case Intrinsic::dbg_region_end: {
1358 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1359 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001360 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001361 std::vector<SDOperand> Ops;
1362
1363 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1364
1365 Ops.push_back(getRoot());
1366 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1367
1368 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1369 }
1370
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001371 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001372 }
1373 case Intrinsic::dbg_func_start: {
1374 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1375 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001376 if (DebugInfo && FSI.getSubprogram() &&
1377 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001378 std::vector<SDOperand> Ops;
1379
1380 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1381
1382 Ops.push_back(getRoot());
1383 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1384
1385 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1386 }
1387
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001388 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001389 }
1390 case Intrinsic::dbg_declare: {
1391 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1392 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001393 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001394 std::vector<SDOperand> Ops;
1395
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001396 SDOperand AddressOp = getValue(DI.getAddress());
1397 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001398 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1399 }
1400 }
1401
1402 return 0;
1403 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001404
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001405 case Intrinsic::isunordered_f32:
1406 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001407 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1408 getValue(I.getOperand(2)), ISD::SETUO));
1409 return 0;
1410
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001411 case Intrinsic::sqrt_f32:
1412 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001413 setValue(&I, DAG.getNode(ISD::FSQRT,
1414 getValue(I.getOperand(1)).getValueType(),
1415 getValue(I.getOperand(1))));
1416 return 0;
1417 case Intrinsic::pcmarker: {
1418 SDOperand Tmp = getValue(I.getOperand(1));
1419 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1420 return 0;
1421 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001422 case Intrinsic::readcyclecounter: {
1423 std::vector<MVT::ValueType> VTs;
1424 VTs.push_back(MVT::i64);
1425 VTs.push_back(MVT::Other);
1426 std::vector<SDOperand> Ops;
1427 Ops.push_back(getRoot());
1428 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1429 setValue(&I, Tmp);
1430 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001431 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001432 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001433 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001434 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001435 case Intrinsic::bswap_i64:
1436 setValue(&I, DAG.getNode(ISD::BSWAP,
1437 getValue(I.getOperand(1)).getValueType(),
1438 getValue(I.getOperand(1))));
1439 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001440 case Intrinsic::cttz_i8:
1441 case Intrinsic::cttz_i16:
1442 case Intrinsic::cttz_i32:
1443 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001444 setValue(&I, DAG.getNode(ISD::CTTZ,
1445 getValue(I.getOperand(1)).getValueType(),
1446 getValue(I.getOperand(1))));
1447 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001448 case Intrinsic::ctlz_i8:
1449 case Intrinsic::ctlz_i16:
1450 case Intrinsic::ctlz_i32:
1451 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001452 setValue(&I, DAG.getNode(ISD::CTLZ,
1453 getValue(I.getOperand(1)).getValueType(),
1454 getValue(I.getOperand(1))));
1455 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001456 case Intrinsic::ctpop_i8:
1457 case Intrinsic::ctpop_i16:
1458 case Intrinsic::ctpop_i32:
1459 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001460 setValue(&I, DAG.getNode(ISD::CTPOP,
1461 getValue(I.getOperand(1)).getValueType(),
1462 getValue(I.getOperand(1))));
1463 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001464 case Intrinsic::stacksave: {
1465 std::vector<MVT::ValueType> VTs;
1466 VTs.push_back(TLI.getPointerTy());
1467 VTs.push_back(MVT::Other);
1468 std::vector<SDOperand> Ops;
1469 Ops.push_back(getRoot());
1470 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1471 setValue(&I, Tmp);
1472 DAG.setRoot(Tmp.getValue(1));
1473 return 0;
1474 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001475 case Intrinsic::stackrestore: {
1476 SDOperand Tmp = getValue(I.getOperand(1));
1477 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001478 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001479 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001480 case Intrinsic::prefetch:
1481 // FIXME: Currently discarding prefetches.
1482 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001483 }
1484}
1485
1486
Chris Lattner7a60d912005-01-07 07:47:53 +00001487void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001488 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001489 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001490 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001491 if (unsigned IID = F->getIntrinsicID()) {
1492 RenameFn = visitIntrinsicCall(I, IID);
1493 if (!RenameFn)
1494 return;
1495 } else { // Not an LLVM intrinsic.
1496 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001497 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1498 if (I.getNumOperands() == 3 && // Basic sanity checks.
1499 I.getOperand(1)->getType()->isFloatingPoint() &&
1500 I.getType() == I.getOperand(1)->getType() &&
1501 I.getType() == I.getOperand(2)->getType()) {
1502 SDOperand LHS = getValue(I.getOperand(1));
1503 SDOperand RHS = getValue(I.getOperand(2));
1504 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1505 LHS, RHS));
1506 return;
1507 }
1508 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001509 if (I.getNumOperands() == 2 && // Basic sanity checks.
1510 I.getOperand(1)->getType()->isFloatingPoint() &&
1511 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001512 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001513 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1514 return;
1515 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001516 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001517 if (I.getNumOperands() == 2 && // Basic sanity checks.
1518 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001519 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001520 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001521 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1522 return;
1523 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001524 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001525 if (I.getNumOperands() == 2 && // Basic sanity checks.
1526 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001527 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001528 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001529 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1530 return;
1531 }
1532 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001533 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001534 } else if (isa<InlineAsm>(I.getOperand(0))) {
1535 visitInlineAsm(I);
1536 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001537 }
Misha Brukman835702a2005-04-21 22:36:52 +00001538
Chris Lattner18d2b342005-01-08 22:48:57 +00001539 SDOperand Callee;
1540 if (!RenameFn)
1541 Callee = getValue(I.getOperand(0));
1542 else
1543 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001544 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001545 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001546 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1547 Value *Arg = I.getOperand(i);
1548 SDOperand ArgNode = getValue(Arg);
1549 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1550 }
Misha Brukman835702a2005-04-21 22:36:52 +00001551
Nate Begemanf6565252005-03-26 01:29:23 +00001552 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1553 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001554
Chris Lattner1f45cd72005-01-08 19:26:18 +00001555 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001556 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001557 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001558 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001559 setValue(&I, Result.first);
1560 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001561}
1562
Chris Lattner6f87d182006-02-22 22:37:12 +00001563SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001564 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001565 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1566 Chain = Val.getValue(1);
1567 Flag = Val.getValue(2);
1568
1569 // If the result was expanded, copy from the top part.
1570 if (Regs.size() > 1) {
1571 assert(Regs.size() == 2 &&
1572 "Cannot expand to more than 2 elts yet!");
1573 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1574 Chain = Val.getValue(1);
1575 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001576 if (DAG.getTargetLoweringInfo().isLittleEndian())
1577 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1578 else
1579 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001580 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001581
Chris Lattner6f87d182006-02-22 22:37:12 +00001582 // Otherwise, if the return value was promoted, truncate it to the
1583 // appropriate type.
1584 if (RegVT == ValueVT)
1585 return Val;
1586
1587 if (MVT::isInteger(RegVT))
1588 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1589 else
1590 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1591}
1592
Chris Lattner571d9642006-02-23 19:21:04 +00001593/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1594/// specified value into the registers specified by this object. This uses
1595/// Chain/Flag as the input and updates them for the output Chain/Flag.
1596void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001597 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001598 if (Regs.size() == 1) {
1599 // If there is a single register and the types differ, this must be
1600 // a promotion.
1601 if (RegVT != ValueVT) {
1602 if (MVT::isInteger(RegVT))
1603 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1604 else
1605 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1606 }
1607 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1608 Flag = Chain.getValue(1);
1609 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001610 std::vector<unsigned> R(Regs);
1611 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1612 std::reverse(R.begin(), R.end());
1613
1614 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001615 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1616 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001617 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001618 Flag = Chain.getValue(1);
1619 }
1620 }
1621}
Chris Lattner6f87d182006-02-22 22:37:12 +00001622
Chris Lattner571d9642006-02-23 19:21:04 +00001623/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1624/// operand list. This adds the code marker and includes the number of
1625/// values added into it.
1626void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001627 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001628 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1629 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1630 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1631}
Chris Lattner6f87d182006-02-22 22:37:12 +00001632
1633/// isAllocatableRegister - If the specified register is safe to allocate,
1634/// i.e. it isn't a stack pointer or some other special register, return the
1635/// register class for the register. Otherwise, return null.
1636static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001637isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1638 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1639 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1640 E = MRI->regclass_end(); RCI != E; ++RCI) {
1641 const TargetRegisterClass *RC = *RCI;
1642 // If none of the the value types for this register class are valid, we
1643 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1644 bool isLegal = false;
1645 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1646 I != E; ++I) {
1647 if (TLI.isTypeLegal(*I)) {
1648 isLegal = true;
1649 break;
1650 }
1651 }
1652
1653 if (!isLegal) continue;
1654
Chris Lattner6f87d182006-02-22 22:37:12 +00001655 // NOTE: This isn't ideal. In particular, this might allocate the
1656 // frame pointer in functions that need it (due to them not being taken
1657 // out of allocation, because a variable sized allocation hasn't been seen
1658 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001659 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1660 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001661 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001662 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001663 }
1664 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001665}
1666
1667RegsForValue SelectionDAGLowering::
1668GetRegistersForValue(const std::string &ConstrCode,
1669 MVT::ValueType VT, bool isOutReg, bool isInReg,
1670 std::set<unsigned> &OutputRegs,
1671 std::set<unsigned> &InputRegs) {
1672 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1673 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1674 std::vector<unsigned> Regs;
1675
1676 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1677 MVT::ValueType RegVT;
1678 MVT::ValueType ValueVT = VT;
1679
1680 if (PhysReg.first) {
1681 if (VT == MVT::Other)
1682 ValueVT = *PhysReg.second->vt_begin();
1683 RegVT = VT;
1684
1685 // This is a explicit reference to a physical register.
1686 Regs.push_back(PhysReg.first);
1687
1688 // If this is an expanded reference, add the rest of the regs to Regs.
1689 if (NumRegs != 1) {
1690 RegVT = *PhysReg.second->vt_begin();
1691 TargetRegisterClass::iterator I = PhysReg.second->begin();
1692 TargetRegisterClass::iterator E = PhysReg.second->end();
1693 for (; *I != PhysReg.first; ++I)
1694 assert(I != E && "Didn't find reg!");
1695
1696 // Already added the first reg.
1697 --NumRegs; ++I;
1698 for (; NumRegs; --NumRegs, ++I) {
1699 assert(I != E && "Ran out of registers to allocate!");
1700 Regs.push_back(*I);
1701 }
1702 }
1703 return RegsForValue(Regs, RegVT, ValueVT);
1704 }
1705
1706 // This is a reference to a register class. Allocate NumRegs consecutive,
1707 // available, registers from the class.
1708 std::vector<unsigned> RegClassRegs =
1709 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1710
1711 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1712 MachineFunction &MF = *CurMBB->getParent();
1713 unsigned NumAllocated = 0;
1714 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1715 unsigned Reg = RegClassRegs[i];
1716 // See if this register is available.
1717 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1718 (isInReg && InputRegs.count(Reg))) { // Already used.
1719 // Make sure we find consecutive registers.
1720 NumAllocated = 0;
1721 continue;
1722 }
1723
1724 // Check to see if this register is allocatable (i.e. don't give out the
1725 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001726 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001727 if (!RC) {
1728 // Make sure we find consecutive registers.
1729 NumAllocated = 0;
1730 continue;
1731 }
1732
1733 // Okay, this register is good, we can use it.
1734 ++NumAllocated;
1735
1736 // If we allocated enough consecutive
1737 if (NumAllocated == NumRegs) {
1738 unsigned RegStart = (i-NumAllocated)+1;
1739 unsigned RegEnd = i+1;
1740 // Mark all of the allocated registers used.
1741 for (unsigned i = RegStart; i != RegEnd; ++i) {
1742 unsigned Reg = RegClassRegs[i];
1743 Regs.push_back(Reg);
1744 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1745 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1746 }
1747
1748 return RegsForValue(Regs, *RC->vt_begin(), VT);
1749 }
1750 }
1751
1752 // Otherwise, we couldn't allocate enough registers for this.
1753 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001754}
1755
Chris Lattner6f87d182006-02-22 22:37:12 +00001756
Chris Lattner476e67b2006-01-26 22:24:51 +00001757/// visitInlineAsm - Handle a call to an InlineAsm object.
1758///
1759void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1760 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1761
1762 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1763 MVT::Other);
1764
1765 // Note, we treat inline asms both with and without side-effects as the same.
1766 // If an inline asm doesn't have side effects and doesn't access memory, we
1767 // could not choose to not chain it.
1768 bool hasSideEffects = IA->hasSideEffects();
1769
Chris Lattner3a5ed552006-02-01 01:28:23 +00001770 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001771 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001772
1773 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1774 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1775 /// if it is a def of that register.
1776 std::vector<SDOperand> AsmNodeOperands;
1777 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1778 AsmNodeOperands.push_back(AsmStr);
1779
1780 SDOperand Chain = getRoot();
1781 SDOperand Flag;
1782
Chris Lattner1558fc62006-02-01 18:59:47 +00001783 // We fully assign registers here at isel time. This is not optimal, but
1784 // should work. For register classes that correspond to LLVM classes, we
1785 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1786 // over the constraints, collecting fixed registers that we know we can't use.
1787 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001788 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001789 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1790 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1791 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001792
Chris Lattner7ad77df2006-02-22 00:56:39 +00001793 MVT::ValueType OpVT;
1794
1795 // Compute the value type for each operand and add it to ConstraintVTs.
1796 switch (Constraints[i].Type) {
1797 case InlineAsm::isOutput:
1798 if (!Constraints[i].isIndirectOutput) {
1799 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1800 OpVT = TLI.getValueType(I.getType());
1801 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001802 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001803 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1804 OpNum++; // Consumes a call operand.
1805 }
1806 break;
1807 case InlineAsm::isInput:
1808 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1809 OpNum++; // Consumes a call operand.
1810 break;
1811 case InlineAsm::isClobber:
1812 OpVT = MVT::Other;
1813 break;
1814 }
1815
1816 ConstraintVTs.push_back(OpVT);
1817
Chris Lattner6f87d182006-02-22 22:37:12 +00001818 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1819 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001820
Chris Lattner6f87d182006-02-22 22:37:12 +00001821 // Build a list of regs that this operand uses. This always has a single
1822 // element for promoted/expanded operands.
1823 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1824 false, false,
1825 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001826
1827 switch (Constraints[i].Type) {
1828 case InlineAsm::isOutput:
1829 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001830 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001831 // If this is an early-clobber output, it cannot be assigned to the same
1832 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001833 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001834 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001835 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001836 case InlineAsm::isInput:
1837 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001838 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001839 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001840 case InlineAsm::isClobber:
1841 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001842 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1843 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001844 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001845 }
1846 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001847
Chris Lattner5c79f982006-02-21 23:12:12 +00001848 // Loop over all of the inputs, copying the operand values into the
1849 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001850 RegsForValue RetValRegs;
1851 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001852 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001853
Chris Lattner2e56e892006-01-31 02:03:41 +00001854 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001855 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1856 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001857
Chris Lattner3a5ed552006-02-01 01:28:23 +00001858 switch (Constraints[i].Type) {
1859 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001860 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1861 if (ConstraintCode.size() == 1) // not a physreg name.
1862 CTy = TLI.getConstraintType(ConstraintCode[0]);
1863
1864 if (CTy == TargetLowering::C_Memory) {
1865 // Memory output.
1866 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1867
1868 // Check that the operand (the address to store to) isn't a float.
1869 if (!MVT::isInteger(InOperandVal.getValueType()))
1870 assert(0 && "MATCH FAIL!");
1871
1872 if (!Constraints[i].isIndirectOutput)
1873 assert(0 && "MATCH FAIL!");
1874
1875 OpNum++; // Consumes a call operand.
1876
1877 // Extend/truncate to the right pointer type if needed.
1878 MVT::ValueType PtrType = TLI.getPointerTy();
1879 if (InOperandVal.getValueType() < PtrType)
1880 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1881 else if (InOperandVal.getValueType() > PtrType)
1882 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1883
1884 // Add information to the INLINEASM node to know about this output.
1885 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1886 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1887 AsmNodeOperands.push_back(InOperandVal);
1888 break;
1889 }
1890
1891 // Otherwise, this is a register output.
1892 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1893
Chris Lattner6f87d182006-02-22 22:37:12 +00001894 // If this is an early-clobber output, or if there is an input
1895 // constraint that matches this, we need to reserve the input register
1896 // so no other inputs allocate to it.
1897 bool UsesInputRegister = false;
1898 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1899 UsesInputRegister = true;
1900
1901 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001902 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001903 RegsForValue Regs =
1904 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1905 true, UsesInputRegister,
1906 OutputRegs, InputRegs);
1907 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001908
Chris Lattner3a5ed552006-02-01 01:28:23 +00001909 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001910 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001911 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001912 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001913 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001914 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001915 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1916 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001917 OpNum++; // Consumes a call operand.
1918 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001919
1920 // Add information to the INLINEASM node to know that this register is
1921 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001922 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001923 break;
1924 }
1925 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001926 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001927 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001928
Chris Lattner7f5880b2006-02-02 00:25:23 +00001929 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1930 // If this is required to match an output register we have already set,
1931 // just use its register.
1932 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001933
Chris Lattner571d9642006-02-23 19:21:04 +00001934 // Scan until we find the definition we already emitted of this operand.
1935 // When we find it, create a RegsForValue operand.
1936 unsigned CurOp = 2; // The first operand.
1937 for (; OperandNo; --OperandNo) {
1938 // Advance to the next operand.
1939 unsigned NumOps =
1940 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1941 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1942 "Skipped past definitions?");
1943 CurOp += (NumOps>>3)+1;
1944 }
1945
1946 unsigned NumOps =
1947 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1948 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1949 "Skipped past definitions?");
1950
1951 // Add NumOps>>3 registers to MatchedRegs.
1952 RegsForValue MatchedRegs;
1953 MatchedRegs.ValueVT = InOperandVal.getValueType();
1954 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1955 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1956 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1957 MatchedRegs.Regs.push_back(Reg);
1958 }
1959
1960 // Use the produced MatchedRegs object to
1961 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1962 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001963 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001964 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001965
1966 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1967 if (ConstraintCode.size() == 1) // not a physreg name.
1968 CTy = TLI.getConstraintType(ConstraintCode[0]);
1969
1970 if (CTy == TargetLowering::C_Other) {
1971 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1972 assert(0 && "MATCH FAIL!");
1973
1974 // Add information to the INLINEASM node to know about this input.
1975 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1976 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1977 AsmNodeOperands.push_back(InOperandVal);
1978 break;
1979 } else if (CTy == TargetLowering::C_Memory) {
1980 // Memory input.
1981
1982 // Check that the operand isn't a float.
1983 if (!MVT::isInteger(InOperandVal.getValueType()))
1984 assert(0 && "MATCH FAIL!");
1985
1986 // Extend/truncate to the right pointer type if needed.
1987 MVT::ValueType PtrType = TLI.getPointerTy();
1988 if (InOperandVal.getValueType() < PtrType)
1989 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1990 else if (InOperandVal.getValueType() > PtrType)
1991 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1992
1993 // Add information to the INLINEASM node to know about this input.
1994 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1995 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1996 AsmNodeOperands.push_back(InOperandVal);
1997 break;
1998 }
1999
2000 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2001
2002 // Copy the input into the appropriate registers.
2003 RegsForValue InRegs =
2004 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2005 false, true, OutputRegs, InputRegs);
2006 // FIXME: should be match fail.
2007 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2008
2009 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2010
2011 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002012 break;
2013 }
Chris Lattner571d9642006-02-23 19:21:04 +00002014 case InlineAsm::isClobber: {
2015 RegsForValue ClobberedRegs =
2016 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2017 OutputRegs, InputRegs);
2018 // Add the clobbered value to the operand list, so that the register
2019 // allocator is aware that the physreg got clobbered.
2020 if (!ClobberedRegs.Regs.empty())
2021 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002022 break;
2023 }
Chris Lattner571d9642006-02-23 19:21:04 +00002024 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002025 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002026
2027 // Finish up input operands.
2028 AsmNodeOperands[0] = Chain;
2029 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2030
2031 std::vector<MVT::ValueType> VTs;
2032 VTs.push_back(MVT::Other);
2033 VTs.push_back(MVT::Flag);
2034 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2035 Flag = Chain.getValue(1);
2036
Chris Lattner2e56e892006-01-31 02:03:41 +00002037 // If this asm returns a register value, copy the result from that register
2038 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002039 if (!RetValRegs.Regs.empty())
2040 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002041
Chris Lattner2e56e892006-01-31 02:03:41 +00002042 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2043
2044 // Process indirect outputs, first output all of the flagged copies out of
2045 // physregs.
2046 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002047 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002048 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002049 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2050 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002051 }
2052
2053 // Emit the non-flagged stores from the physregs.
2054 std::vector<SDOperand> OutChains;
2055 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2056 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2057 StoresToEmit[i].first,
2058 getValue(StoresToEmit[i].second),
2059 DAG.getSrcValue(StoresToEmit[i].second)));
2060 if (!OutChains.empty())
2061 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00002062 DAG.setRoot(Chain);
2063}
2064
2065
Chris Lattner7a60d912005-01-07 07:47:53 +00002066void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2067 SDOperand Src = getValue(I.getOperand(0));
2068
2069 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002070
2071 if (IntPtr < Src.getValueType())
2072 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2073 else if (IntPtr > Src.getValueType())
2074 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002075
2076 // Scale the source by the type size.
2077 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2078 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2079 Src, getIntPtrConstant(ElementSize));
2080
2081 std::vector<std::pair<SDOperand, const Type*> > Args;
2082 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002083
2084 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002085 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002086 DAG.getExternalSymbol("malloc", IntPtr),
2087 Args, DAG);
2088 setValue(&I, Result.first); // Pointers always fit in registers
2089 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002090}
2091
2092void SelectionDAGLowering::visitFree(FreeInst &I) {
2093 std::vector<std::pair<SDOperand, const Type*> > Args;
2094 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2095 TLI.getTargetData().getIntPtrType()));
2096 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002097 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002098 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002099 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2100 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002101}
2102
Chris Lattner13d7c252005-08-26 20:54:47 +00002103// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2104// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2105// instructions are special in various ways, which require special support to
2106// insert. The specified MachineInstr is created but not inserted into any
2107// basic blocks, and the scheduler passes ownership of it to this method.
2108MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2109 MachineBasicBlock *MBB) {
2110 std::cerr << "If a target marks an instruction with "
2111 "'usesCustomDAGSchedInserter', it must implement "
2112 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2113 abort();
2114 return 0;
2115}
2116
Chris Lattner58cfd792005-01-09 00:00:49 +00002117void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002118 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2119 getValue(I.getOperand(1)),
2120 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002121}
2122
2123void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002124 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2125 getValue(I.getOperand(0)),
2126 DAG.getSrcValue(I.getOperand(0)));
2127 setValue(&I, V);
2128 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002129}
2130
2131void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002132 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2133 getValue(I.getOperand(1)),
2134 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002135}
2136
2137void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002138 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2139 getValue(I.getOperand(1)),
2140 getValue(I.getOperand(2)),
2141 DAG.getSrcValue(I.getOperand(1)),
2142 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002143}
2144
Chris Lattner58cfd792005-01-09 00:00:49 +00002145// It is always conservatively correct for llvm.returnaddress and
2146// llvm.frameaddress to return 0.
2147std::pair<SDOperand, SDOperand>
2148TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2149 unsigned Depth, SelectionDAG &DAG) {
2150 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002151}
2152
Chris Lattner29dcc712005-05-14 05:50:48 +00002153SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002154 assert(0 && "LowerOperation not implemented for this target!");
2155 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002156 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002157}
2158
Nate Begeman595ec732006-01-28 03:14:31 +00002159SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2160 SelectionDAG &DAG) {
2161 assert(0 && "CustomPromoteOperation not implemented for this target!");
2162 abort();
2163 return SDOperand();
2164}
2165
Chris Lattner58cfd792005-01-09 00:00:49 +00002166void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2167 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2168 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002169 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002170 setValue(&I, Result.first);
2171 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002172}
2173
Evan Cheng6781b6e2006-02-15 21:59:04 +00002174/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002175/// operand.
2176static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002177 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002178 MVT::ValueType CurVT = VT;
2179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2180 uint64_t Val = C->getValue() & 255;
2181 unsigned Shift = 8;
2182 while (CurVT != MVT::i8) {
2183 Val = (Val << Shift) | Val;
2184 Shift <<= 1;
2185 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002186 }
2187 return DAG.getConstant(Val, VT);
2188 } else {
2189 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2190 unsigned Shift = 8;
2191 while (CurVT != MVT::i8) {
2192 Value =
2193 DAG.getNode(ISD::OR, VT,
2194 DAG.getNode(ISD::SHL, VT, Value,
2195 DAG.getConstant(Shift, MVT::i8)), Value);
2196 Shift <<= 1;
2197 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002198 }
2199
2200 return Value;
2201 }
2202}
2203
Evan Cheng6781b6e2006-02-15 21:59:04 +00002204/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2205/// used when a memcpy is turned into a memset when the source is a constant
2206/// string ptr.
2207static SDOperand getMemsetStringVal(MVT::ValueType VT,
2208 SelectionDAG &DAG, TargetLowering &TLI,
2209 std::string &Str, unsigned Offset) {
2210 MVT::ValueType CurVT = VT;
2211 uint64_t Val = 0;
2212 unsigned MSB = getSizeInBits(VT) / 8;
2213 if (TLI.isLittleEndian())
2214 Offset = Offset + MSB - 1;
2215 for (unsigned i = 0; i != MSB; ++i) {
2216 Val = (Val << 8) | Str[Offset];
2217 Offset += TLI.isLittleEndian() ? -1 : 1;
2218 }
2219 return DAG.getConstant(Val, VT);
2220}
2221
Evan Cheng81fcea82006-02-14 08:22:34 +00002222/// getMemBasePlusOffset - Returns base and offset node for the
2223static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2224 SelectionDAG &DAG, TargetLowering &TLI) {
2225 MVT::ValueType VT = Base.getValueType();
2226 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2227}
2228
Evan Chengdb2a7a72006-02-14 20:12:38 +00002229/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002230/// to replace the memset / memcpy is below the threshold. It also returns the
2231/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002232static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2233 unsigned Limit, uint64_t Size,
2234 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002235 MVT::ValueType VT;
2236
2237 if (TLI.allowsUnalignedMemoryAccesses()) {
2238 VT = MVT::i64;
2239 } else {
2240 switch (Align & 7) {
2241 case 0:
2242 VT = MVT::i64;
2243 break;
2244 case 4:
2245 VT = MVT::i32;
2246 break;
2247 case 2:
2248 VT = MVT::i16;
2249 break;
2250 default:
2251 VT = MVT::i8;
2252 break;
2253 }
2254 }
2255
Evan Chengd5026102006-02-14 09:11:59 +00002256 MVT::ValueType LVT = MVT::i64;
2257 while (!TLI.isTypeLegal(LVT))
2258 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2259 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002260
Evan Chengd5026102006-02-14 09:11:59 +00002261 if (VT > LVT)
2262 VT = LVT;
2263
Evan Cheng04514992006-02-14 23:05:54 +00002264 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002265 while (Size != 0) {
2266 unsigned VTSize = getSizeInBits(VT) / 8;
2267 while (VTSize > Size) {
2268 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002269 VTSize >>= 1;
2270 }
Evan Chengd5026102006-02-14 09:11:59 +00002271 assert(MVT::isInteger(VT));
2272
2273 if (++NumMemOps > Limit)
2274 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002275 MemOps.push_back(VT);
2276 Size -= VTSize;
2277 }
Evan Chengd5026102006-02-14 09:11:59 +00002278
2279 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002280}
2281
Chris Lattner875def92005-01-11 05:56:49 +00002282void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002283 SDOperand Op1 = getValue(I.getOperand(1));
2284 SDOperand Op2 = getValue(I.getOperand(2));
2285 SDOperand Op3 = getValue(I.getOperand(3));
2286 SDOperand Op4 = getValue(I.getOperand(4));
2287 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2288 if (Align == 0) Align = 1;
2289
2290 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2291 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002292
2293 // Expand memset / memcpy to a series of load / store ops
2294 // if the size operand falls below a certain threshold.
2295 std::vector<SDOperand> OutChains;
2296 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002297 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002298 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002299 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2300 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002301 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002302 unsigned Offset = 0;
2303 for (unsigned i = 0; i < NumMemOps; i++) {
2304 MVT::ValueType VT = MemOps[i];
2305 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002306 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002307 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2308 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002309 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2310 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002311 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002312 Offset += VTSize;
2313 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002314 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002315 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002316 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002317 case ISD::MEMCPY: {
2318 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2319 Size->getValue(), Align, TLI)) {
2320 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002321 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002322 GlobalAddressSDNode *G = NULL;
2323 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002324 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002325
2326 if (Op2.getOpcode() == ISD::GlobalAddress)
2327 G = cast<GlobalAddressSDNode>(Op2);
2328 else if (Op2.getOpcode() == ISD::ADD &&
2329 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2330 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2331 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002332 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002333 }
2334 if (G) {
2335 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002336 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002337 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002338 if (!Str.empty()) {
2339 CopyFromStr = true;
2340 SrcOff += SrcDelta;
2341 }
2342 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002343 }
2344
Evan Chenge2038bd2006-02-15 01:54:51 +00002345 for (unsigned i = 0; i < NumMemOps; i++) {
2346 MVT::ValueType VT = MemOps[i];
2347 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002348 SDOperand Value, Chain, Store;
2349
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002350 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002351 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2352 Chain = getRoot();
2353 Store =
2354 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2355 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2356 DAG.getSrcValue(I.getOperand(1), DstOff));
2357 } else {
2358 Value = DAG.getLoad(VT, getRoot(),
2359 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2360 DAG.getSrcValue(I.getOperand(2), SrcOff));
2361 Chain = Value.getValue(1);
2362 Store =
2363 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2364 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2365 DAG.getSrcValue(I.getOperand(1), DstOff));
2366 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002367 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002368 SrcOff += VTSize;
2369 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002370 }
2371 }
2372 break;
2373 }
2374 }
2375
2376 if (!OutChains.empty()) {
2377 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2378 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002379 }
2380 }
2381
Chris Lattner875def92005-01-11 05:56:49 +00002382 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002383 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002384 Ops.push_back(Op1);
2385 Ops.push_back(Op2);
2386 Ops.push_back(Op3);
2387 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002388 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002389}
2390
Chris Lattner875def92005-01-11 05:56:49 +00002391//===----------------------------------------------------------------------===//
2392// SelectionDAGISel code
2393//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002394
2395unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2396 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2397}
2398
Chris Lattnerc9950c12005-08-17 06:37:43 +00002399void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002400 // FIXME: we only modify the CFG to split critical edges. This
2401 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002402}
Chris Lattner7a60d912005-01-07 07:47:53 +00002403
Chris Lattner35397782005-12-05 07:10:48 +00002404
2405/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2406/// casting to the type of GEPI.
2407static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2408 Value *Ptr, Value *PtrOffset) {
2409 if (V) return V; // Already computed.
2410
2411 BasicBlock::iterator InsertPt;
2412 if (BB == GEPI->getParent()) {
2413 // If insert into the GEP's block, insert right after the GEP.
2414 InsertPt = GEPI;
2415 ++InsertPt;
2416 } else {
2417 // Otherwise, insert at the top of BB, after any PHI nodes
2418 InsertPt = BB->begin();
2419 while (isa<PHINode>(InsertPt)) ++InsertPt;
2420 }
2421
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002422 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2423 // BB so that there is only one value live across basic blocks (the cast
2424 // operand).
2425 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2426 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2427 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2428
Chris Lattner35397782005-12-05 07:10:48 +00002429 // Add the offset, cast it to the right type.
2430 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2431 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2432 return V = Ptr;
2433}
2434
2435
2436/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2437/// selection, we want to be a bit careful about some things. In particular, if
2438/// we have a GEP instruction that is used in a different block than it is
2439/// defined, the addressing expression of the GEP cannot be folded into loads or
2440/// stores that use it. In this case, decompose the GEP and move constant
2441/// indices into blocks that use it.
2442static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2443 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002444 // If this GEP is only used inside the block it is defined in, there is no
2445 // need to rewrite it.
2446 bool isUsedOutsideDefBB = false;
2447 BasicBlock *DefBB = GEPI->getParent();
2448 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2449 UI != E; ++UI) {
2450 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2451 isUsedOutsideDefBB = true;
2452 break;
2453 }
2454 }
2455 if (!isUsedOutsideDefBB) return;
2456
2457 // If this GEP has no non-zero constant indices, there is nothing we can do,
2458 // ignore it.
2459 bool hasConstantIndex = false;
2460 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2461 E = GEPI->op_end(); OI != E; ++OI) {
2462 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2463 if (CI->getRawValue()) {
2464 hasConstantIndex = true;
2465 break;
2466 }
2467 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002468 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2469 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002470
2471 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2472 // constant offset (which we now know is non-zero) and deal with it later.
2473 uint64_t ConstantOffset = 0;
2474 const Type *UIntPtrTy = TD.getIntPtrType();
2475 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2476 const Type *Ty = GEPI->getOperand(0)->getType();
2477
2478 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2479 E = GEPI->op_end(); OI != E; ++OI) {
2480 Value *Idx = *OI;
2481 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2482 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2483 if (Field)
2484 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2485 Ty = StTy->getElementType(Field);
2486 } else {
2487 Ty = cast<SequentialType>(Ty)->getElementType();
2488
2489 // Handle constant subscripts.
2490 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2491 if (CI->getRawValue() == 0) continue;
2492
2493 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2494 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2495 else
2496 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2497 continue;
2498 }
2499
2500 // Ptr = Ptr + Idx * ElementSize;
2501
2502 // Cast Idx to UIntPtrTy if needed.
2503 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2504
2505 uint64_t ElementSize = TD.getTypeSize(Ty);
2506 // Mask off bits that should not be set.
2507 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2508 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2509
2510 // Multiply by the element size and add to the base.
2511 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2512 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2513 }
2514 }
2515
2516 // Make sure that the offset fits in uintptr_t.
2517 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2518 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2519
2520 // Okay, we have now emitted all of the variable index parts to the BB that
2521 // the GEP is defined in. Loop over all of the using instructions, inserting
2522 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002523 // instruction to use the newly computed value, making GEPI dead. When the
2524 // user is a load or store instruction address, we emit the add into the user
2525 // block, otherwise we use a canonical version right next to the gep (these
2526 // won't be foldable as addresses, so we might as well share the computation).
2527
Chris Lattner35397782005-12-05 07:10:48 +00002528 std::map<BasicBlock*,Value*> InsertedExprs;
2529 while (!GEPI->use_empty()) {
2530 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002531
2532 // If this use is not foldable into the addressing mode, use a version
2533 // emitted in the GEP block.
2534 Value *NewVal;
2535 if (!isa<LoadInst>(User) &&
2536 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2537 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2538 Ptr, PtrOffset);
2539 } else {
2540 // Otherwise, insert the code in the User's block so it can be folded into
2541 // any users in that block.
2542 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002543 User->getParent(), GEPI,
2544 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002545 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002546 User->replaceUsesOfWith(GEPI, NewVal);
2547 }
Chris Lattner35397782005-12-05 07:10:48 +00002548
2549 // Finally, the GEP is dead, remove it.
2550 GEPI->eraseFromParent();
2551}
2552
Chris Lattner7a60d912005-01-07 07:47:53 +00002553bool SelectionDAGISel::runOnFunction(Function &Fn) {
2554 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2555 RegMap = MF.getSSARegMap();
2556 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2557
Chris Lattner35397782005-12-05 07:10:48 +00002558 // First, split all critical edges for PHI nodes with incoming values that are
2559 // constants, this way the load of the constant into a vreg will not be placed
2560 // into MBBs that are used some other way.
2561 //
2562 // In this pass we also look for GEP instructions that are used across basic
2563 // blocks and rewrites them to improve basic-block-at-a-time selection.
2564 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002565 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2566 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002567 BasicBlock::iterator BBI;
2568 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002569 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2570 if (isa<Constant>(PN->getIncomingValue(i)))
2571 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002572
2573 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2574 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2575 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002576 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002577
Chris Lattner7a60d912005-01-07 07:47:53 +00002578 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2579
2580 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2581 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002582
Chris Lattner7a60d912005-01-07 07:47:53 +00002583 return true;
2584}
2585
2586
Chris Lattner718b5c22005-01-13 17:59:43 +00002587SDOperand SelectionDAGISel::
2588CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002589 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002590 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002591 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002592 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002593
2594 // If this type is not legal, we must make sure to not create an invalid
2595 // register use.
2596 MVT::ValueType SrcVT = Op.getValueType();
2597 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2598 SelectionDAG &DAG = SDL.DAG;
2599 if (SrcVT == DestVT) {
2600 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002601 } else if (SrcVT == MVT::Vector) {
2602 // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2603
2604 // Figure out the right, legal destination reg to copy into.
2605 const PackedType *PTy = cast<PackedType>(V->getType());
2606 unsigned NumElts = PTy->getNumElements();
2607 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2608
2609 unsigned NumVectorRegs = 1;
2610
2611 // Divide the input until we get to a supported size. This will always
2612 // end with a scalar if the target doesn't support vectors.
2613 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2614 NumElts >>= 1;
2615 NumVectorRegs <<= 1;
2616 }
2617
2618 MVT::ValueType VT;
2619 if (NumElts == 1)
2620 VT = EltTy;
2621 else
2622 VT = getVectorType(EltTy, NumElts);
2623
2624 // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2625 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2626 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002627 } else if (SrcVT < DestVT) {
2628 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002629 if (MVT::isFloatingPoint(SrcVT))
2630 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2631 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002632 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002633 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2634 } else {
2635 // The src value is expanded into multiple registers.
2636 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2637 Op, DAG.getConstant(0, MVT::i32));
2638 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2639 Op, DAG.getConstant(1, MVT::i32));
2640 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2641 return DAG.getCopyToReg(Op, Reg+1, Hi);
2642 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002643}
2644
Chris Lattner16f64df2005-01-17 17:15:02 +00002645void SelectionDAGISel::
2646LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2647 std::vector<SDOperand> &UnorderedChains) {
2648 // If this is the entry block, emit arguments.
2649 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002650 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002651 SDOperand OldRoot = SDL.DAG.getRoot();
2652 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002653
Chris Lattner6871b232005-10-30 19:42:35 +00002654 unsigned a = 0;
2655 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2656 AI != E; ++AI, ++a)
2657 if (!AI->use_empty()) {
2658 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002659
Chris Lattner6871b232005-10-30 19:42:35 +00002660 // If this argument is live outside of the entry block, insert a copy from
2661 // whereever we got it to the vreg that other BB's will reference it as.
2662 if (FuncInfo.ValueMap.count(AI)) {
2663 SDOperand Copy =
2664 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2665 UnorderedChains.push_back(Copy);
2666 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002667 }
Chris Lattner6871b232005-10-30 19:42:35 +00002668
2669 // Next, if the function has live ins that need to be copied into vregs,
2670 // emit the copies now, into the top of the block.
2671 MachineFunction &MF = SDL.DAG.getMachineFunction();
2672 if (MF.livein_begin() != MF.livein_end()) {
2673 SSARegMap *RegMap = MF.getSSARegMap();
2674 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2675 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2676 E = MF.livein_end(); LI != E; ++LI)
2677 if (LI->second)
2678 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2679 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002680 }
Chris Lattner6871b232005-10-30 19:42:35 +00002681
2682 // Finally, if the target has anything special to do, allow it to do so.
2683 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002684}
2685
2686
Chris Lattner7a60d912005-01-07 07:47:53 +00002687void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2688 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00002689 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00002690 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002691
2692 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002693
Chris Lattner6871b232005-10-30 19:42:35 +00002694 // Lower any arguments needed in this block if this is the entry block.
2695 if (LLVMBB == &LLVMBB->getParent()->front())
2696 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002697
2698 BB = FuncInfo.MBBMap[LLVMBB];
2699 SDL.setCurrentBasicBlock(BB);
2700
2701 // Lower all of the non-terminator instructions.
2702 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2703 I != E; ++I)
2704 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00002705
Chris Lattner7a60d912005-01-07 07:47:53 +00002706 // Ensure that all instructions which are used outside of their defining
2707 // blocks are available as virtual registers.
2708 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002709 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002710 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002711 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002712 UnorderedChains.push_back(
2713 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002714 }
2715
2716 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2717 // ensure constants are generated when needed. Remember the virtual registers
2718 // that need to be added to the Machine PHI nodes as input. We cannot just
2719 // directly add them, because expansion might result in multiple MBB's for one
2720 // BB. As such, the start of the BB might correspond to a different MBB than
2721 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002722 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002723
2724 // Emit constants only once even if used by multiple PHI nodes.
2725 std::map<Constant*, unsigned> ConstantsOut;
2726
2727 // Check successor nodes PHI nodes that expect a constant to be available from
2728 // this block.
2729 TerminatorInst *TI = LLVMBB->getTerminator();
2730 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2731 BasicBlock *SuccBB = TI->getSuccessor(succ);
2732 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2733 PHINode *PN;
2734
2735 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2736 // nodes and Machine PHI nodes, but the incoming operands have not been
2737 // emitted yet.
2738 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002739 (PN = dyn_cast<PHINode>(I)); ++I)
2740 if (!PN->use_empty()) {
2741 unsigned Reg;
2742 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2743 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2744 unsigned &RegOut = ConstantsOut[C];
2745 if (RegOut == 0) {
2746 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002747 UnorderedChains.push_back(
2748 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002749 }
2750 Reg = RegOut;
2751 } else {
2752 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002753 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002754 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002755 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2756 "Didn't codegen value into a register!??");
2757 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002758 UnorderedChains.push_back(
2759 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002760 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002761 }
Misha Brukman835702a2005-04-21 22:36:52 +00002762
Chris Lattner8ea875f2005-01-07 21:34:19 +00002763 // Remember that this register needs to added to the machine PHI node as
2764 // the input for this MBB.
2765 unsigned NumElements =
2766 TLI.getNumElements(TLI.getValueType(PN->getType()));
2767 for (unsigned i = 0, e = NumElements; i != e; ++i)
2768 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002769 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002770 }
2771 ConstantsOut.clear();
2772
Chris Lattner718b5c22005-01-13 17:59:43 +00002773 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002774 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002775 SDOperand Root = SDL.getRoot();
2776 if (Root.getOpcode() != ISD::EntryToken) {
2777 unsigned i = 0, e = UnorderedChains.size();
2778 for (; i != e; ++i) {
2779 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2780 if (UnorderedChains[i].Val->getOperand(0) == Root)
2781 break; // Don't add the root if we already indirectly depend on it.
2782 }
2783
2784 if (i == e)
2785 UnorderedChains.push_back(Root);
2786 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002787 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2788 }
2789
Chris Lattner7a60d912005-01-07 07:47:53 +00002790 // Lower the terminator after the copies are emitted.
2791 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002792
Nate Begemaned728c12006-03-27 01:32:24 +00002793 // Copy over any CaseBlock records that may now exist due to SwitchInst
2794 // lowering.
2795 SwitchCases.clear();
2796 SwitchCases = SDL.SwitchCases;
2797
Chris Lattner4108bb02005-01-17 19:43:36 +00002798 // Make sure the root of the DAG is up-to-date.
2799 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002800}
2801
Nate Begemaned728c12006-03-27 01:32:24 +00002802void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002803 // Run the DAG combiner in pre-legalize mode.
2804 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002805
Chris Lattner7a60d912005-01-07 07:47:53 +00002806 DEBUG(std::cerr << "Lowered selection DAG:\n");
2807 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002808
Chris Lattner7a60d912005-01-07 07:47:53 +00002809 // Second step, hack on the DAG until it only uses operations and types that
2810 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002811 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00002812
Chris Lattner7a60d912005-01-07 07:47:53 +00002813 DEBUG(std::cerr << "Legalized selection DAG:\n");
2814 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002815
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002816 // Run the DAG combiner in post-legalize mode.
2817 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002818
Evan Cheng739a6a42006-01-21 02:32:06 +00002819 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002820
Chris Lattner5ca31d92005-03-30 01:10:47 +00002821 // Third, instruction select all of the operations to machine code, adding the
2822 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002823 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00002824
Chris Lattner7a60d912005-01-07 07:47:53 +00002825 DEBUG(std::cerr << "Selected machine code:\n");
2826 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002827}
Chris Lattner7a60d912005-01-07 07:47:53 +00002828
Nate Begemaned728c12006-03-27 01:32:24 +00002829void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2830 FunctionLoweringInfo &FuncInfo) {
2831 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2832 {
2833 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2834 CurDAG = &DAG;
2835
2836 // First step, lower LLVM code to some DAG. This DAG may use operations and
2837 // types that are not supported by the target.
2838 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2839
2840 // Second step, emit the lowered DAG as machine code.
2841 CodeGenAndEmitDAG(DAG);
2842 }
2843
Chris Lattner5ca31d92005-03-30 01:10:47 +00002844 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002845 // PHI nodes in successors.
Nate Begemaned728c12006-03-27 01:32:24 +00002846 if (SwitchCases.empty()) {
2847 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2848 MachineInstr *PHI = PHINodesToUpdate[i].first;
2849 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2850 "This is not a machine PHI node that we are updating!");
2851 PHI->addRegOperand(PHINodesToUpdate[i].second);
2852 PHI->addMachineBasicBlockOperand(BB);
2853 }
2854 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002855 }
Nate Begemaned728c12006-03-27 01:32:24 +00002856
2857 // If we generated any switch lowering information, build and codegen any
2858 // additional DAGs necessary.
2859 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2860 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2861 CurDAG = &SDAG;
2862 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2863 // Set the current basic block to the mbb we wish to insert the code into
2864 BB = SwitchCases[i].ThisBB;
2865 SDL.setCurrentBasicBlock(BB);
2866 // Emit the code
2867 SDL.visitSwitchCase(SwitchCases[i]);
2868 SDAG.setRoot(SDL.getRoot());
2869 CodeGenAndEmitDAG(SDAG);
2870 // Iterate over the phi nodes, if there is a phi node in a successor of this
2871 // block (for instance, the default block), then add a pair of operands to
2872 // the phi node for this block, as if we were coming from the original
2873 // BB before switch expansion.
2874 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2875 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2876 MachineBasicBlock *PHIBB = PHI->getParent();
2877 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2878 "This is not a machine PHI node that we are updating!");
2879 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2880 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2881 PHI->addMachineBasicBlockOperand(BB);
2882 }
2883 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002884 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002885}
Evan Cheng739a6a42006-01-21 02:32:06 +00002886
2887//===----------------------------------------------------------------------===//
2888/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2889/// target node in the graph.
2890void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2891 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002892 ScheduleDAG *SL = NULL;
2893
2894 switch (ISHeuristic) {
2895 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002896 case defaultScheduling:
2897 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2898 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2899 else /* TargetLowering::SchedulingForRegPressure */
2900 SL = createBURRListDAGScheduler(DAG, BB);
2901 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002902 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002903 SL = createBFS_DAGScheduler(DAG, BB);
2904 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002905 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002906 SL = createSimpleDAGScheduler(false, DAG, BB);
2907 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002908 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002909 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002910 break;
Evan Cheng31272342006-01-23 08:26:10 +00002911 case listSchedulingBURR:
2912 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002913 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002914 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002915 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002916 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002917 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002918 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002919 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002920}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002921
Chris Lattner543832d2006-03-08 04:25:59 +00002922HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2923 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002924}
2925
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002926/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2927/// by tblgen. Others should not call it.
2928void SelectionDAGISel::
2929SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2930 std::vector<SDOperand> InOps;
2931 std::swap(InOps, Ops);
2932
2933 Ops.push_back(InOps[0]); // input chain.
2934 Ops.push_back(InOps[1]); // input asm string.
2935
2936 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2937 unsigned i = 2, e = InOps.size();
2938 if (InOps[e-1].getValueType() == MVT::Flag)
2939 --e; // Don't process a flag operand if it is here.
2940
2941 while (i != e) {
2942 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2943 if ((Flags & 7) != 4 /*MEM*/) {
2944 // Just skip over this operand, copying the operands verbatim.
2945 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2946 i += (Flags >> 3) + 1;
2947 } else {
2948 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2949 // Otherwise, this is a memory operand. Ask the target to select it.
2950 std::vector<SDOperand> SelOps;
2951 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2952 std::cerr << "Could not match memory address. Inline asm failure!\n";
2953 exit(1);
2954 }
2955
2956 // Add this to the output node.
2957 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2958 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2959 i += 2;
2960 }
2961 }
2962
2963 // Add the flag input back if present.
2964 if (e != InOps.size())
2965 Ops.push_back(InOps.back());
2966}