blob: 7cf3f5cb0dcc68ef9264c31e9e8e2ae58b694ca9 [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Jim Laskey29e635d2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Misha Brukman835702a2005-04-21 22:36:52 +0000187
Chris Lattner49409cb2006-03-16 19:51:18 +0000188 unsigned CreateRegForValue(const Value *V);
189
Chris Lattner7a60d912005-01-07 07:47:53 +0000190 unsigned InitializeRegForValue(const Value *V) {
191 unsigned &R = ValueMap[V];
192 assert(R == 0 && "Already initialized this value register!");
193 return R = CreateRegForValue(V);
194 }
195 };
196}
197
198/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000199/// PHI nodes or outside of the basic block that defines it, or used by a
200/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000201static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
202 if (isa<PHINode>(I)) return true;
203 BasicBlock *BB = I->getParent();
204 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000205 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
206 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 return true;
208 return false;
209}
210
Chris Lattner6871b232005-10-30 19:42:35 +0000211/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000212/// entry block, return true. This includes arguments used by switches, since
213/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000214static bool isOnlyUsedInEntryBlock(Argument *A) {
215 BasicBlock *Entry = A->getParent()->begin();
216 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000217 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000218 return false; // Use not in entry block.
219 return true;
220}
221
Chris Lattner7a60d912005-01-07 07:47:53 +0000222FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000223 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
225
Chris Lattner6871b232005-10-30 19:42:35 +0000226 // Create a vreg for each argument register that is not dead and is used
227 // outside of the entry block for the function.
228 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
229 AI != E; ++AI)
230 if (!isOnlyUsedInEntryBlock(AI))
231 InitializeRegForValue(AI);
232
Chris Lattner7a60d912005-01-07 07:47:53 +0000233 // Initialize the mapping of values to registers. This is only set up for
234 // instruction values that are used outside of the block that defines
235 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000236 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
238 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
239 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
240 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000241 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000242 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000243 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000244 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000245
246 // If the alignment of the value is smaller than the size of the value,
247 // and if the size of the value is particularly small (<= 8 bytes),
248 // round up to the size of the value for potentially better performance.
249 //
250 // FIXME: This could be made better with a preferred alignment hook in
251 // TargetData. It serves primarily to 8-byte align doubles for X86.
252 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000253 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000254 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000255 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000256 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000257 }
258
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000259 for (; BB != EB; ++BB)
260 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
262 if (!isa<AllocaInst>(I) ||
263 !StaticAllocaMap.count(cast<AllocaInst>(I)))
264 InitializeRegForValue(I);
265
266 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
267 // also creates the initial PHI MachineInstrs, though none of the input
268 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000269 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000270 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
271 MBBMap[BB] = MBB;
272 MF.getBasicBlockList().push_back(MBB);
273
274 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
275 // appropriate.
276 PHINode *PN;
277 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000278 (PN = dyn_cast<PHINode>(I)); ++I)
279 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000280 MVT::ValueType VT = TLI.getValueType(PN->getType());
281 unsigned NumElements;
282 if (VT != MVT::Vector)
283 NumElements = TLI.getNumElements(VT);
284 else {
285 MVT::ValueType VT1,VT2;
286 NumElements =
287 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
288 VT1, VT2);
289 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000290 unsigned PHIReg = ValueMap[PN];
291 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
292 for (unsigned i = 0; i != NumElements; ++i)
293 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
294 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000295 }
296}
297
Chris Lattner49409cb2006-03-16 19:51:18 +0000298/// CreateRegForValue - Allocate the appropriate number of virtual registers of
299/// the correctly promoted or expanded types. Assign these registers
300/// consecutive vreg numbers and return the first assigned number.
301unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
302 MVT::ValueType VT = TLI.getValueType(V->getType());
303
304 // The number of multiples of registers that we need, to, e.g., split up
305 // a <2 x int64> -> 4 x i32 registers.
306 unsigned NumVectorRegs = 1;
307
308 // If this is a packed type, figure out what type it will decompose into
309 // and how many of the elements it will use.
310 if (VT == MVT::Vector) {
311 const PackedType *PTy = cast<PackedType>(V->getType());
312 unsigned NumElts = PTy->getNumElements();
313 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
314
315 // Divide the input until we get to a supported size. This will always
316 // end with a scalar if the target doesn't support vectors.
317 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
318 NumElts >>= 1;
319 NumVectorRegs <<= 1;
320 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000321 if (NumElts == 1)
322 VT = EltTy;
323 else
324 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000325 }
326
327 // The common case is that we will only create one register for this
328 // value. If we have that case, create and return the virtual register.
329 unsigned NV = TLI.getNumElements(VT);
330 if (NV == 1) {
331 // If we are promoting this value, pick the next largest supported type.
332 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
333 unsigned Reg = MakeReg(PromotedType);
334 // If this is a vector of supported or promoted types (e.g. 4 x i16),
335 // create all of the registers.
336 for (unsigned i = 1; i != NumVectorRegs; ++i)
337 MakeReg(PromotedType);
338 return Reg;
339 }
340
341 // If this value is represented with multiple target registers, make sure
342 // to create enough consecutive registers of the right (smaller) type.
343 unsigned NT = VT-1; // Find the type to use.
344 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
345 --NT;
346
347 unsigned R = MakeReg((MVT::ValueType)NT);
348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
349 MakeReg((MVT::ValueType)NT);
350 return R;
351}
Chris Lattner7a60d912005-01-07 07:47:53 +0000352
353//===----------------------------------------------------------------------===//
354/// SelectionDAGLowering - This is the common target-independent lowering
355/// implementation that is parameterized by a TargetLowering object.
356/// Also, targets can overload any lowering method.
357///
358namespace llvm {
359class SelectionDAGLowering {
360 MachineBasicBlock *CurMBB;
361
362 std::map<const Value*, SDOperand> NodeMap;
363
Chris Lattner4d9651c2005-01-17 22:19:26 +0000364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
365 /// them up and then emit token factor nodes when possible. This allows us to
366 /// get simple disambiguation between loads without worrying about alias
367 /// analysis.
368 std::vector<SDOperand> PendingLoads;
369
Nate Begemaned728c12006-03-27 01:32:24 +0000370 /// Case - A pair of values to record the Value for a switch case, and the
371 /// case's target basic block.
372 typedef std::pair<Constant*, MachineBasicBlock*> Case;
373 typedef std::vector<Case>::iterator CaseItr;
374 typedef std::pair<CaseItr, CaseItr> CaseRange;
375
376 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
377 /// of conditional branches.
378 struct CaseRec {
379 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
380 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
381
382 /// CaseBB - The MBB in which to emit the compare and branch
383 MachineBasicBlock *CaseBB;
384 /// LT, GE - If nonzero, we know the current case value must be less-than or
385 /// greater-than-or-equal-to these Constants.
386 Constant *LT;
387 Constant *GE;
388 /// Range - A pair of iterators representing the range of case values to be
389 /// processed at this point in the binary search tree.
390 CaseRange Range;
391 };
392
393 /// The comparison function for sorting Case values.
394 struct CaseCmp {
395 bool operator () (const Case& C1, const Case& C2) {
396 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
397 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
398
399 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
400 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
401 }
402 };
403
Chris Lattner7a60d912005-01-07 07:47:53 +0000404public:
405 // TLI - This is information that describes the available target features we
406 // need for lowering. This indicates when operations are unavailable,
407 // implemented with a libcall, etc.
408 TargetLowering &TLI;
409 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000410 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000411
Nate Begemaned728c12006-03-27 01:32:24 +0000412 /// SwitchCases - Vector of CaseBlock structures used to communicate
413 /// SwitchInst code generation information.
414 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000415 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000416
Chris Lattner7a60d912005-01-07 07:47:53 +0000417 /// FuncInfo - Information about the function as a whole.
418 ///
419 FunctionLoweringInfo &FuncInfo;
420
421 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000422 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000423 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000424 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000425 }
426
Chris Lattner4108bb02005-01-17 19:43:36 +0000427 /// getRoot - Return the current virtual root of the Selection DAG.
428 ///
429 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000430 if (PendingLoads.empty())
431 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000432
Chris Lattner4d9651c2005-01-17 22:19:26 +0000433 if (PendingLoads.size() == 1) {
434 SDOperand Root = PendingLoads[0];
435 DAG.setRoot(Root);
436 PendingLoads.clear();
437 return Root;
438 }
439
440 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000441 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
442 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000443 PendingLoads.clear();
444 DAG.setRoot(Root);
445 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000446 }
447
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 void visit(Instruction &I) { visit(I.getOpcode(), I); }
449
450 void visit(unsigned Opcode, User &I) {
451 switch (Opcode) {
452 default: assert(0 && "Unknown instruction type encountered!");
453 abort();
454 // Build the switch statement using the Instruction.def file.
455#define HANDLE_INST(NUM, OPCODE, CLASS) \
456 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
457#include "llvm/Instruction.def"
458 }
459 }
460
461 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
462
Chris Lattner4024c002006-03-15 22:19:46 +0000463 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000464 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000465 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000466
467 SDOperand getIntPtrConstant(uint64_t Val) {
468 return DAG.getConstant(Val, TLI.getPointerTy());
469 }
470
Chris Lattner8471b152006-03-16 19:57:50 +0000471 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000472
473 const SDOperand &setValue(const Value *V, SDOperand NewN) {
474 SDOperand &N = NodeMap[V];
475 assert(N.Val == 0 && "Already set a value for this node!");
476 return N = NewN;
477 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000478
Chris Lattner6f87d182006-02-22 22:37:12 +0000479 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
480 MVT::ValueType VT,
481 bool OutReg, bool InReg,
482 std::set<unsigned> &OutputRegs,
483 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000484
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 // Terminator instructions.
486 void visitRet(ReturnInst &I);
487 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000488 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 void visitUnreachable(UnreachableInst &I) { /* noop */ }
490
Nate Begemaned728c12006-03-27 01:32:24 +0000491 // Helper for visitSwitch
492 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000493 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000494
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000496 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
497 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
498
Nate Begemanb2e089c2005-11-19 00:36:38 +0000499 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000500 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000501 void visitAdd(User &I) {
502 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000503 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000504 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000505 void visitMul(User &I) {
506 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000507 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000508 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000509 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000510 visitBinary(I,
511 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
512 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 }
514 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000515 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000516 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000517 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000518 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
519 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
520 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000521 void visitShl(User &I) { visitShift(I, ISD::SHL); }
522 void visitShr(User &I) {
523 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000524 }
525
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000526 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
527 ISD::CondCode FPOpc);
528 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
529 ISD::SETOEQ); }
530 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
531 ISD::SETUNE); }
532 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
533 ISD::SETOLE); }
534 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
535 ISD::SETOGE); }
536 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
537 ISD::SETOLT); }
538 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
539 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000540
Chris Lattner67271862006-03-29 00:11:43 +0000541 void visitExtractElement(User &I);
542 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000543 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000544
Chris Lattner7a60d912005-01-07 07:47:53 +0000545 void visitGetElementPtr(User &I);
546 void visitCast(User &I);
547 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000548
549 void visitMalloc(MallocInst &I);
550 void visitFree(FreeInst &I);
551 void visitAlloca(AllocaInst &I);
552 void visitLoad(LoadInst &I);
553 void visitStore(StoreInst &I);
554 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
555 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000556 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000557 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000558 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000559
Chris Lattner7a60d912005-01-07 07:47:53 +0000560 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000561 void visitVAArg(VAArgInst &I);
562 void visitVAEnd(CallInst &I);
563 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000564 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000565
Chris Lattner875def92005-01-11 05:56:49 +0000566 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000567
568 void visitUserOp1(Instruction &I) {
569 assert(0 && "UserOp1 should not exist at instruction selection time!");
570 abort();
571 }
572 void visitUserOp2(Instruction &I) {
573 assert(0 && "UserOp2 should not exist at instruction selection time!");
574 abort();
575 }
576};
577} // end namespace llvm
578
Chris Lattner8471b152006-03-16 19:57:50 +0000579SDOperand SelectionDAGLowering::getValue(const Value *V) {
580 SDOperand &N = NodeMap[V];
581 if (N.Val) return N;
582
583 const Type *VTy = V->getType();
584 MVT::ValueType VT = TLI.getValueType(VTy);
585 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
587 visit(CE->getOpcode(), *CE);
588 assert(N.Val && "visit didn't populate the ValueMap!");
589 return N;
590 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
591 return N = DAG.getGlobalAddress(GV, VT);
592 } else if (isa<ConstantPointerNull>(C)) {
593 return N = DAG.getConstant(0, TLI.getPointerTy());
594 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000595 if (!isa<PackedType>(VTy))
596 return N = DAG.getNode(ISD::UNDEF, VT);
597
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000598 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000599 const PackedType *PTy = cast<PackedType>(VTy);
600 unsigned NumElements = PTy->getNumElements();
601 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
602
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000603 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000604 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
605
606 // Create a VConstant node with generic Vector type.
607 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
608 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000609 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
610 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000611 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
612 return N = DAG.getConstantFP(CFP->getValue(), VT);
613 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
614 unsigned NumElements = PTy->getNumElements();
615 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000616
617 // Now that we know the number and type of the elements, push a
618 // Constant or ConstantFP node onto the ops list for each element of
619 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000620 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000621 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000622 for (unsigned i = 0; i != NumElements; ++i)
623 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000624 } else {
625 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
626 SDOperand Op;
627 if (MVT::isFloatingPoint(PVT))
628 Op = DAG.getConstantFP(0, PVT);
629 else
630 Op = DAG.getConstant(0, PVT);
631 Ops.assign(NumElements, Op);
632 }
633
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000634 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000635 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
636 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000637 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000638 } else {
639 // Canonicalize all constant ints to be unsigned.
640 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
641 }
642 }
643
644 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
645 std::map<const AllocaInst*, int>::iterator SI =
646 FuncInfo.StaticAllocaMap.find(AI);
647 if (SI != FuncInfo.StaticAllocaMap.end())
648 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
649 }
650
651 std::map<const Value*, unsigned>::const_iterator VMI =
652 FuncInfo.ValueMap.find(V);
653 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
654
655 unsigned InReg = VMI->second;
656
657 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000658 if (VT != MVT::Vector) {
659 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000660
Chris Lattner5fe1f542006-03-31 02:06:56 +0000661 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
662 if (DestVT < VT) {
663 // Source must be expanded. This input value is actually coming from the
664 // register pair VMI->second and VMI->second+1.
665 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
666 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
667 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000668 if (MVT::isFloatingPoint(VT))
669 N = DAG.getNode(ISD::FP_ROUND, VT, N);
670 else
671 N = DAG.getNode(ISD::TRUNCATE, VT, N);
672 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000673 } else {
674 // Otherwise, if this is a vector, make it available as a generic vector
675 // here.
676 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000677 const PackedType *PTy = cast<PackedType>(VTy);
678 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000679 PTyLegalElementVT);
680
681 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000682 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000683 if (PTyElementVT == PTyLegalElementVT) {
684 // If the value types are legal, just VBUILD the CopyFromReg nodes.
685 for (unsigned i = 0; i != NE; ++i)
686 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
687 PTyElementVT));
688 } else if (PTyElementVT < PTyLegalElementVT) {
689 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
690 for (unsigned i = 0; i != NE; ++i) {
691 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
692 PTyElementVT);
693 if (MVT::isFloatingPoint(PTyElementVT))
694 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
695 else
696 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
697 Ops.push_back(Op);
698 }
699 } else {
700 // If the register was expanded, use BUILD_PAIR.
701 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
702 for (unsigned i = 0; i != NE/2; ++i) {
703 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
704 PTyElementVT);
705 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
706 PTyElementVT);
707 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
708 }
709 }
710
711 Ops.push_back(DAG.getConstant(NE, MVT::i32));
712 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000713 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000714
715 // Finally, use a VBIT_CONVERT to make this available as the appropriate
716 // vector type.
717 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
718 DAG.getConstant(PTy->getNumElements(),
719 MVT::i32),
720 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000721 }
722
723 return N;
724}
725
726
Chris Lattner7a60d912005-01-07 07:47:53 +0000727void SelectionDAGLowering::visitRet(ReturnInst &I) {
728 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000729 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000730 return;
731 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000732 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000733 NewValues.push_back(getRoot());
734 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
735 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000736 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000737
738 // If this is an integer return value, we need to promote it ourselves to
739 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
740 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000741 // FIXME: C calling convention requires the return type to be promoted to
742 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000743 if (MVT::isInteger(RetOp.getValueType()) &&
744 RetOp.getValueType() < MVT::i64) {
745 MVT::ValueType TmpVT;
746 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
747 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
748 else
749 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000750
Evan Chenga2e99532006-05-26 23:09:09 +0000751 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000752 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
753 else
754 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
755 }
756 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000757 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000758 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000759 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
760 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000761}
762
763void SelectionDAGLowering::visitBr(BranchInst &I) {
764 // Update machine-CFG edges.
765 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000766 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000767
768 // Figure out which block is immediately after the current one.
769 MachineBasicBlock *NextBlock = 0;
770 MachineFunction::iterator BBI = CurMBB;
771 if (++BBI != CurMBB->getParent()->end())
772 NextBlock = BBI;
773
774 if (I.isUnconditional()) {
775 // If this is not a fall-through branch, emit the branch.
776 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000778 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000779 } else {
780 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000781 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000782
783 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000784 if (Succ1MBB == NextBlock) {
785 // If the condition is false, fall through. This means we should branch
786 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000787 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000788 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000789 } else if (Succ0MBB == NextBlock) {
790 // If the condition is true, fall through. This means we should branch if
791 // the condition is false to Succ #1. Invert the condition first.
792 SDOperand True = DAG.getConstant(1, Cond.getValueType());
793 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000794 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000795 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000796 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000797 std::vector<SDOperand> Ops;
798 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000799 // If the false case is the current basic block, then this is a self
800 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
801 // adds an extra instruction in the loop. Instead, invert the
802 // condition and emit "Loop: ... br!cond Loop; br Out.
803 if (CurMBB == Succ1MBB) {
804 std::swap(Succ0MBB, Succ1MBB);
805 SDOperand True = DAG.getConstant(1, Cond.getValueType());
806 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
807 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000808 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
809 DAG.getBasicBlock(Succ0MBB));
810 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
811 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000812 }
813 }
814}
815
Nate Begemaned728c12006-03-27 01:32:24 +0000816/// visitSwitchCase - Emits the necessary code to represent a single node in
817/// the binary search tree resulting from lowering a switch instruction.
818void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
819 SDOperand SwitchOp = getValue(CB.SwitchV);
820 SDOperand CaseOp = getValue(CB.CaseC);
821 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
822
823 // Set NextBlock to be the MBB immediately after the current one, if any.
824 // This is used to avoid emitting unnecessary branches to the next block.
825 MachineBasicBlock *NextBlock = 0;
826 MachineFunction::iterator BBI = CurMBB;
827 if (++BBI != CurMBB->getParent()->end())
828 NextBlock = BBI;
829
830 // If the lhs block is the next block, invert the condition so that we can
831 // fall through to the lhs instead of the rhs block.
832 if (CB.LHSBB == NextBlock) {
833 std::swap(CB.LHSBB, CB.RHSBB);
834 SDOperand True = DAG.getConstant(1, Cond.getValueType());
835 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
836 }
837 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
838 DAG.getBasicBlock(CB.LHSBB));
839 if (CB.RHSBB == NextBlock)
840 DAG.setRoot(BrCond);
841 else
842 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
843 DAG.getBasicBlock(CB.RHSBB)));
844 // Update successor info
845 CurMBB->addSuccessor(CB.LHSBB);
846 CurMBB->addSuccessor(CB.RHSBB);
847}
848
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000849void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000850 // Emit the code for the jump table
851 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000852 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
853 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +0000854 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000855 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +0000856 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000857 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
858 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000859 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +0000860 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
861 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +0000862 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000863 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +0000864 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +0000865 // For Pic, the sequence is:
866 // BRIND(load(Jumptable + index) + RelocBase)
867 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +0000868 SDOperand Reloc;
869 if (TLI.usesGlobalOffsetTable())
870 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
871 else
872 Reloc = TAB;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000873 ADD = DAG.getNode(ISD::ADD, PTy,
Andrew Lenharth783a4a92006-09-24 19:45:58 +0000874 ((PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD), Reloc);
Nate Begeman78756502006-07-27 01:13:04 +0000875 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
876 } else {
877 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
878 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000879}
880
Nate Begemaned728c12006-03-27 01:32:24 +0000881void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
882 // Figure out which block is immediately after the current one.
883 MachineBasicBlock *NextBlock = 0;
884 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000885
Nate Begemaned728c12006-03-27 01:32:24 +0000886 if (++BBI != CurMBB->getParent()->end())
887 NextBlock = BBI;
888
889 // If there is only the default destination, branch to it if it is not the
890 // next basic block. Otherwise, just fall through.
891 if (I.getNumOperands() == 2) {
892 // Update machine-CFG edges.
893 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000894
Nate Begemaned728c12006-03-27 01:32:24 +0000895 // If this is not a fall-through branch, emit the branch.
896 if (DefaultMBB != NextBlock)
897 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
898 DAG.getBasicBlock(DefaultMBB)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000899
Chris Lattner32d92e02006-06-12 18:25:29 +0000900 CurMBB->addSuccessor(DefaultMBB);
Nate Begemaned728c12006-03-27 01:32:24 +0000901 return;
902 }
903
904 // If there are any non-default case statements, create a vector of Cases
905 // representing each one, and sort the vector so that we can efficiently
906 // create a binary search tree from them.
907 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000908
Nate Begemaned728c12006-03-27 01:32:24 +0000909 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
910 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
911 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
912 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000913
Nate Begemaned728c12006-03-27 01:32:24 +0000914 std::sort(Cases.begin(), Cases.end(), CaseCmp());
915
916 // Get the Value to be switched on and default basic blocks, which will be
917 // inserted into CaseBlock records, representing basic blocks in the binary
918 // search tree.
919 Value *SV = I.getOperand(0);
920 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000921
922 // Get the MachineFunction which holds the current MBB. This is used during
923 // emission of jump tables, and when inserting any additional MBBs necessary
924 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +0000925 MachineFunction *CurMF = CurMBB->getParent();
926 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000927
Nate Begemand7a19102006-05-08 16:51:36 +0000928 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
929 // target supports indirect branches, then emit a jump table rather than
930 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +0000931 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +0000932 Cases.size() > 5) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000933 uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
934 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
Nate Begemandf488392006-05-03 03:48:02 +0000935 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
936
Nate Begemand7a19102006-05-08 16:51:36 +0000937 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000938 // Create a new basic block to hold the code for loading the address
939 // of the jump table, and jumping to it. Update successor information;
940 // we will either branch to the default case for the switch, or the jump
941 // table.
942 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
943 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
944 CurMBB->addSuccessor(Default);
945 CurMBB->addSuccessor(JumpTableBB);
946
947 // Subtract the lowest switch case value from the value being switched on
948 // and conditional branch to default mbb if the result is greater than the
949 // difference between smallest and largest cases.
950 SDOperand SwitchOp = getValue(SV);
951 MVT::ValueType VT = SwitchOp.getValueType();
952 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
953 DAG.getConstant(First, VT));
954
955 // The SDNode we just created, which holds the value being switched on
956 // minus the the smallest case value, needs to be copied to a virtual
957 // register so it can be used as an index into the jump table in a
958 // subsequent basic block. This value may be smaller or larger than the
959 // target's pointer type, and therefore require extension or truncating.
960 if (VT > TLI.getPointerTy())
961 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
962 else
963 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000964
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000965 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
966 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
967
968 // Emit the range check for the jump table, and branch to the default
969 // block for the switch statement if the value being switched on exceeds
970 // the largest case in the switch.
971 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
972 DAG.getConstant(Last-First,VT), ISD::SETUGT);
973 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
974 DAG.getBasicBlock(Default)));
975
Nate Begemandf488392006-05-03 03:48:02 +0000976 // Build a vector of destination BBs, corresponding to each target
977 // of the jump table. If the value of the jump table slot corresponds to
978 // a case statement, push the case's BB onto the vector, otherwise, push
979 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000980 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +0000981 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000982
983 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Nate Begemandf488392006-05-03 03:48:02 +0000984 if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
985 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +0000986 ++ii;
987 } else {
988 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +0000989 }
Nate Begemandf488392006-05-03 03:48:02 +0000990
991 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +0000992 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
993 E = DestBBs.end(); I != E; ++I)
994 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +0000995
996 // Create a jump table index for this jump table, or return an existing
997 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000998 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
999
1000 // Set the jump table information so that we can codegen it as a second
1001 // MachineBasicBlock
1002 JT.Reg = JumpTableReg;
1003 JT.JTI = JTI;
1004 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001005 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001006 return;
1007 }
1008 }
Nate Begemaned728c12006-03-27 01:32:24 +00001009
1010 // Push the initial CaseRec onto the worklist
1011 std::vector<CaseRec> CaseVec;
1012 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1013
1014 while (!CaseVec.empty()) {
1015 // Grab a record representing a case range to process off the worklist
1016 CaseRec CR = CaseVec.back();
1017 CaseVec.pop_back();
1018
1019 // Size is the number of Cases represented by this range. If Size is 1,
1020 // then we are processing a leaf of the binary search tree. Otherwise,
1021 // we need to pick a pivot, and push left and right ranges onto the
1022 // worklist.
1023 unsigned Size = CR.Range.second - CR.Range.first;
1024
1025 if (Size == 1) {
1026 // Create a CaseBlock record representing a conditional branch to
1027 // the Case's target mbb if the value being switched on SV is equal
1028 // to C. Otherwise, branch to default.
1029 Constant *C = CR.Range.first->first;
1030 MachineBasicBlock *Target = CR.Range.first->second;
1031 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1032 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001033
Nate Begemaned728c12006-03-27 01:32:24 +00001034 // If the MBB representing the leaf node is the current MBB, then just
1035 // call visitSwitchCase to emit the code into the current block.
1036 // Otherwise, push the CaseBlock onto the vector to be later processed
1037 // by SDISel, and insert the node's MBB before the next MBB.
1038 if (CR.CaseBB == CurMBB)
1039 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001040 else
Nate Begemaned728c12006-03-27 01:32:24 +00001041 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001042 } else {
1043 // split case range at pivot
1044 CaseItr Pivot = CR.Range.first + (Size / 2);
1045 CaseRange LHSR(CR.Range.first, Pivot);
1046 CaseRange RHSR(Pivot, CR.Range.second);
1047 Constant *C = Pivot->first;
1048 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001049
Nate Begemaned728c12006-03-27 01:32:24 +00001050 // We know that we branch to the LHS if the Value being switched on is
1051 // less than the Pivot value, C. We use this to optimize our binary
1052 // tree a bit, by recognizing that if SV is greater than or equal to the
1053 // LHS's Case Value, and that Case Value is exactly one less than the
1054 // Pivot's Value, then we can branch directly to the LHS's Target,
1055 // rather than creating a leaf node for it.
1056 if ((LHSR.second - LHSR.first) == 1 &&
1057 LHSR.first->first == CR.GE &&
1058 cast<ConstantIntegral>(C)->getRawValue() ==
1059 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1060 LHSBB = LHSR.first->second;
1061 } else {
1062 LHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001063 CurMF->getBasicBlockList().insert(BBI, LHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001064 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1065 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001066
Nate Begemaned728c12006-03-27 01:32:24 +00001067 // Similar to the optimization above, if the Value being switched on is
1068 // known to be less than the Constant CR.LT, and the current Case Value
1069 // is CR.LT - 1, then we can branch directly to the target block for
1070 // the current Case Value, rather than emitting a RHS leaf node for it.
1071 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1072 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1073 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1074 RHSBB = RHSR.first->second;
1075 } else {
1076 RHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001077 CurMF->getBasicBlockList().insert(BBI, RHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001078 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1079 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001080
Nate Begemaned728c12006-03-27 01:32:24 +00001081 // Create a CaseBlock record representing a conditional branch to
1082 // the LHS node if the value being switched on SV is less than C.
1083 // Otherwise, branch to LHS.
1084 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1085 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001086
Nate Begemaned728c12006-03-27 01:32:24 +00001087 if (CR.CaseBB == CurMBB)
1088 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001089 else
Nate Begemaned728c12006-03-27 01:32:24 +00001090 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001091 }
1092 }
1093}
1094
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001095void SelectionDAGLowering::visitSub(User &I) {
1096 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001097 if (I.getType()->isFloatingPoint()) {
1098 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1099 if (CFP->isExactlyValue(-0.0)) {
1100 SDOperand Op2 = getValue(I.getOperand(1));
1101 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1102 return;
1103 }
Chris Lattner6f3b5772005-09-28 22:28:18 +00001104 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001105 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001106}
1107
Nate Begemanb2e089c2005-11-19 00:36:38 +00001108void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1109 unsigned VecOp) {
1110 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001111 SDOperand Op1 = getValue(I.getOperand(0));
1112 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001113
Chris Lattner19baba62005-11-19 18:40:42 +00001114 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001115 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1116 } else if (Ty->isFloatingPoint()) {
1117 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1118 } else {
1119 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +00001120 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1121 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1122 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001123 }
Nate Begeman127321b2005-11-18 07:42:56 +00001124}
Chris Lattner96c26752005-01-19 22:31:21 +00001125
Nate Begeman127321b2005-11-18 07:42:56 +00001126void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1127 SDOperand Op1 = getValue(I.getOperand(0));
1128 SDOperand Op2 = getValue(I.getOperand(1));
1129
1130 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1131
Chris Lattner7a60d912005-01-07 07:47:53 +00001132 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1133}
1134
1135void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001136 ISD::CondCode UnsignedOpcode,
1137 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001138 SDOperand Op1 = getValue(I.getOperand(0));
1139 SDOperand Op2 = getValue(I.getOperand(1));
1140 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001141 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001142 Opcode = FPOpcode;
1143 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001144 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001145 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001146}
1147
1148void SelectionDAGLowering::visitSelect(User &I) {
1149 SDOperand Cond = getValue(I.getOperand(0));
1150 SDOperand TrueVal = getValue(I.getOperand(1));
1151 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001152 if (!isa<PackedType>(I.getType())) {
1153 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1154 TrueVal, FalseVal));
1155 } else {
1156 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1157 *(TrueVal.Val->op_end()-2),
1158 *(TrueVal.Val->op_end()-1)));
1159 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001160}
1161
1162void SelectionDAGLowering::visitCast(User &I) {
1163 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001164 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001165 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001166
Chris Lattner2f4119a2006-03-22 20:09:35 +00001167 if (DestVT == MVT::Vector) {
1168 // This is a cast to a vector from something else. This is always a bit
1169 // convert. Get information about the input vector.
1170 const PackedType *DestTy = cast<PackedType>(I.getType());
1171 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1172 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1173 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1174 DAG.getValueType(EltVT)));
1175 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001176 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001177 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001178 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001179 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001180 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001181 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001182 } else if (isInteger(SrcVT)) {
1183 if (isInteger(DestVT)) { // Int -> Int cast
1184 if (DestVT < SrcVT) // Truncating cast?
1185 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001186 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001187 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001188 else
Chris Lattner4024c002006-03-15 22:19:46 +00001189 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001190 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001191 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001192 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001193 else
Chris Lattner4024c002006-03-15 22:19:46 +00001194 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001195 } else {
1196 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001197 }
Chris Lattner4024c002006-03-15 22:19:46 +00001198 } else if (isFloatingPoint(SrcVT)) {
1199 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1200 if (DestVT < SrcVT) // Rounding cast?
1201 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001202 else
Chris Lattner4024c002006-03-15 22:19:46 +00001203 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001204 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001205 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001206 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001207 else
Chris Lattner4024c002006-03-15 22:19:46 +00001208 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001209 } else {
1210 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001211 }
1212 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001213 assert(SrcVT == MVT::Vector && "Unknown cast!");
1214 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1215 // This is a cast from a vector to something else. This is always a bit
1216 // convert. Get information about the input vector.
1217 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001218 }
1219}
1220
Chris Lattner67271862006-03-29 00:11:43 +00001221void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001222 SDOperand InVec = getValue(I.getOperand(0));
1223 SDOperand InVal = getValue(I.getOperand(1));
1224 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1225 getValue(I.getOperand(2)));
1226
Chris Lattner29b23012006-03-19 01:17:20 +00001227 SDOperand Num = *(InVec.Val->op_end()-2);
1228 SDOperand Typ = *(InVec.Val->op_end()-1);
1229 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1230 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001231}
1232
Chris Lattner67271862006-03-29 00:11:43 +00001233void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001234 SDOperand InVec = getValue(I.getOperand(0));
1235 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1236 getValue(I.getOperand(1)));
1237 SDOperand Typ = *(InVec.Val->op_end()-1);
1238 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1239 TLI.getValueType(I.getType()), InVec, InIdx));
1240}
Chris Lattner32206f52006-03-18 01:44:44 +00001241
Chris Lattner098c01e2006-04-08 04:15:24 +00001242void SelectionDAGLowering::visitShuffleVector(User &I) {
1243 SDOperand V1 = getValue(I.getOperand(0));
1244 SDOperand V2 = getValue(I.getOperand(1));
1245 SDOperand Mask = getValue(I.getOperand(2));
1246
1247 SDOperand Num = *(V1.Val->op_end()-2);
1248 SDOperand Typ = *(V2.Val->op_end()-1);
1249 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1250 V1, V2, Mask, Num, Typ));
1251}
1252
1253
Chris Lattner7a60d912005-01-07 07:47:53 +00001254void SelectionDAGLowering::visitGetElementPtr(User &I) {
1255 SDOperand N = getValue(I.getOperand(0));
1256 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001257
1258 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1259 OI != E; ++OI) {
1260 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001261 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001262 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1263 if (Field) {
1264 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001265 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001266 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001267 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001268 }
1269 Ty = StTy->getElementType(Field);
1270 } else {
1271 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001272
Chris Lattner43535a12005-11-09 04:45:33 +00001273 // If this is a constant subscript, handle it quickly.
1274 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1275 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001276
Chris Lattner43535a12005-11-09 04:45:33 +00001277 uint64_t Offs;
1278 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
Owen Anderson20a631f2006-05-03 01:29:57 +00001279 Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001280 else
Owen Anderson20a631f2006-05-03 01:29:57 +00001281 Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001282 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1283 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001284 }
Chris Lattner43535a12005-11-09 04:45:33 +00001285
1286 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001287 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001288 SDOperand IdxN = getValue(Idx);
1289
1290 // If the index is smaller or larger than intptr_t, truncate or extend
1291 // it.
1292 if (IdxN.getValueType() < N.getValueType()) {
1293 if (Idx->getType()->isSigned())
1294 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1295 else
1296 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1297 } else if (IdxN.getValueType() > N.getValueType())
1298 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1299
1300 // If this is a multiply by a power of two, turn it into a shl
1301 // immediately. This is a very common case.
1302 if (isPowerOf2_64(ElementSize)) {
1303 unsigned Amt = Log2_64(ElementSize);
1304 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001305 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001306 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1307 continue;
1308 }
1309
1310 SDOperand Scale = getIntPtrConstant(ElementSize);
1311 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1312 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001313 }
1314 }
1315 setValue(&I, N);
1316}
1317
1318void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1319 // If this is a fixed sized alloca in the entry block of the function,
1320 // allocate it statically on the stack.
1321 if (FuncInfo.StaticAllocaMap.count(&I))
1322 return; // getValue will auto-populate this.
1323
1324 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001325 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1326 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001327 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001328
1329 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001330 MVT::ValueType IntPtr = TLI.getPointerTy();
1331 if (IntPtr < AllocSize.getValueType())
1332 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1333 else if (IntPtr > AllocSize.getValueType())
1334 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001335
Chris Lattnereccb73d2005-01-22 23:04:37 +00001336 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001337 getIntPtrConstant(TySize));
1338
1339 // Handle alignment. If the requested alignment is less than or equal to the
1340 // stack alignment, ignore it and round the size of the allocation up to the
1341 // stack alignment size. If the size is greater than the stack alignment, we
1342 // note this in the DYNAMIC_STACKALLOC node.
1343 unsigned StackAlign =
1344 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1345 if (Align <= StackAlign) {
1346 Align = 0;
1347 // Add SA-1 to the size.
1348 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1349 getIntPtrConstant(StackAlign-1));
1350 // Mask out the low bits for alignment purposes.
1351 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1352 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1353 }
1354
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001355 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001356 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1357 MVT::Other);
1358 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001359 DAG.setRoot(setValue(&I, DSA).getValue(1));
1360
1361 // Inform the Frame Information that we have just allocated a variable-sized
1362 // object.
1363 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1364}
1365
Chris Lattner7a60d912005-01-07 07:47:53 +00001366void SelectionDAGLowering::visitLoad(LoadInst &I) {
1367 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001368
Chris Lattner4d9651c2005-01-17 22:19:26 +00001369 SDOperand Root;
1370 if (I.isVolatile())
1371 Root = getRoot();
1372 else {
1373 // Do not serialize non-volatile loads against each other.
1374 Root = DAG.getRoot();
1375 }
Chris Lattner4024c002006-03-15 22:19:46 +00001376
Evan Chenge71fe34d2006-10-09 20:57:25 +00001377 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001378 Root, I.isVolatile()));
1379}
1380
1381SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001382 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001383 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001384 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001385 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001386 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001387 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1388 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001389 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001390 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001391 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001392
Chris Lattner4024c002006-03-15 22:19:46 +00001393 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001394 DAG.setRoot(L.getValue(1));
1395 else
1396 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001397
1398 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001399}
1400
1401
1402void SelectionDAGLowering::visitStore(StoreInst &I) {
1403 Value *SrcV = I.getOperand(0);
1404 SDOperand Src = getValue(SrcV);
1405 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001406 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1407 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001408}
1409
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001410/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1411/// access memory and has no other side effects at all.
1412static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1413#define GET_NO_MEMORY_INTRINSICS
1414#include "llvm/Intrinsics.gen"
1415#undef GET_NO_MEMORY_INTRINSICS
1416 return false;
1417}
1418
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001419// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1420// have any side-effects or if it only reads memory.
1421static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1422#define GET_SIDE_EFFECT_INFO
1423#include "llvm/Intrinsics.gen"
1424#undef GET_SIDE_EFFECT_INFO
1425 return false;
1426}
1427
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001428/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1429/// node.
1430void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1431 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001432 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001433 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001434
1435 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001436 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001437 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1438 if (OnlyLoad) {
1439 // We don't need to serialize loads against other loads.
1440 Ops.push_back(DAG.getRoot());
1441 } else {
1442 Ops.push_back(getRoot());
1443 }
1444 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001445
1446 // Add the intrinsic ID as an integer operand.
1447 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1448
1449 // Add all operands of the call to the operand list.
1450 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1451 SDOperand Op = getValue(I.getOperand(i));
1452
1453 // If this is a vector type, force it to the right packed type.
1454 if (Op.getValueType() == MVT::Vector) {
1455 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1456 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1457
1458 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1459 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1460 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1461 }
1462
1463 assert(TLI.isTypeLegal(Op.getValueType()) &&
1464 "Intrinsic uses a non-legal type?");
1465 Ops.push_back(Op);
1466 }
1467
1468 std::vector<MVT::ValueType> VTs;
1469 if (I.getType() != Type::VoidTy) {
1470 MVT::ValueType VT = TLI.getValueType(I.getType());
1471 if (VT == MVT::Vector) {
1472 const PackedType *DestTy = cast<PackedType>(I.getType());
1473 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1474
1475 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1476 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1477 }
1478
1479 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1480 VTs.push_back(VT);
1481 }
1482 if (HasChain)
1483 VTs.push_back(MVT::Other);
1484
Chris Lattnerbd887772006-08-14 23:53:35 +00001485 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1486
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001487 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001488 SDOperand Result;
1489 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001490 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1491 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001492 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001493 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1494 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001495 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001496 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1497 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001498
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001499 if (HasChain) {
1500 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1501 if (OnlyLoad)
1502 PendingLoads.push_back(Chain);
1503 else
1504 DAG.setRoot(Chain);
1505 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001506 if (I.getType() != Type::VoidTy) {
1507 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1508 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1509 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1510 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1511 DAG.getValueType(EVT));
1512 }
1513 setValue(&I, Result);
1514 }
1515}
1516
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001517/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1518/// we want to emit this as a call to a named external function, return the name
1519/// otherwise lower it and return null.
1520const char *
1521SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1522 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001523 default:
1524 // By default, turn this into a target intrinsic node.
1525 visitTargetIntrinsic(I, Intrinsic);
1526 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001527 case Intrinsic::vastart: visitVAStart(I); return 0;
1528 case Intrinsic::vaend: visitVAEnd(I); return 0;
1529 case Intrinsic::vacopy: visitVACopy(I); return 0;
1530 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1531 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1532 case Intrinsic::setjmp:
1533 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1534 break;
1535 case Intrinsic::longjmp:
1536 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1537 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001538 case Intrinsic::memcpy_i32:
1539 case Intrinsic::memcpy_i64:
1540 visitMemIntrinsic(I, ISD::MEMCPY);
1541 return 0;
1542 case Intrinsic::memset_i32:
1543 case Intrinsic::memset_i64:
1544 visitMemIntrinsic(I, ISD::MEMSET);
1545 return 0;
1546 case Intrinsic::memmove_i32:
1547 case Intrinsic::memmove_i64:
1548 visitMemIntrinsic(I, ISD::MEMMOVE);
1549 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001550
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001551 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001552 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001553 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001554 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001555 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001556
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001557 Ops[0] = getRoot();
1558 Ops[1] = getValue(SPI.getLineValue());
1559 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001560
Jim Laskeya8bdac82006-03-23 18:06:46 +00001561 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001562 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001563 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1564
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001565 Ops[3] = DAG.getString(CompileUnit->getFileName());
1566 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001567
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001568 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001569 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001570
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001571 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001572 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001573 case Intrinsic::dbg_region_start: {
1574 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1575 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001576 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001577 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001578 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1579 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001580 }
1581
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001582 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001583 }
1584 case Intrinsic::dbg_region_end: {
1585 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1586 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001587 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001588 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001589 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1590 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001591 }
1592
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001593 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001594 }
1595 case Intrinsic::dbg_func_start: {
1596 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1597 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001598 if (DebugInfo && FSI.getSubprogram() &&
1599 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001600 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001601 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1602 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001603 }
1604
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001605 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001606 }
1607 case Intrinsic::dbg_declare: {
1608 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1609 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001610 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001611 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001612 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001613 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001614 }
1615
1616 return 0;
1617 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001618
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001619 case Intrinsic::isunordered_f32:
1620 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001621 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1622 getValue(I.getOperand(2)), ISD::SETUO));
1623 return 0;
1624
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001625 case Intrinsic::sqrt_f32:
1626 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001627 setValue(&I, DAG.getNode(ISD::FSQRT,
1628 getValue(I.getOperand(1)).getValueType(),
1629 getValue(I.getOperand(1))));
1630 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001631 case Intrinsic::powi_f32:
1632 case Intrinsic::powi_f64:
1633 setValue(&I, DAG.getNode(ISD::FPOWI,
1634 getValue(I.getOperand(1)).getValueType(),
1635 getValue(I.getOperand(1)),
1636 getValue(I.getOperand(2))));
1637 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001638 case Intrinsic::pcmarker: {
1639 SDOperand Tmp = getValue(I.getOperand(1));
1640 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1641 return 0;
1642 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001643 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001644 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001645 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1646 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1647 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001648 setValue(&I, Tmp);
1649 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001650 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001651 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001652 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001653 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001654 case Intrinsic::bswap_i64:
1655 setValue(&I, DAG.getNode(ISD::BSWAP,
1656 getValue(I.getOperand(1)).getValueType(),
1657 getValue(I.getOperand(1))));
1658 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001659 case Intrinsic::cttz_i8:
1660 case Intrinsic::cttz_i16:
1661 case Intrinsic::cttz_i32:
1662 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001663 setValue(&I, DAG.getNode(ISD::CTTZ,
1664 getValue(I.getOperand(1)).getValueType(),
1665 getValue(I.getOperand(1))));
1666 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001667 case Intrinsic::ctlz_i8:
1668 case Intrinsic::ctlz_i16:
1669 case Intrinsic::ctlz_i32:
1670 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001671 setValue(&I, DAG.getNode(ISD::CTLZ,
1672 getValue(I.getOperand(1)).getValueType(),
1673 getValue(I.getOperand(1))));
1674 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001675 case Intrinsic::ctpop_i8:
1676 case Intrinsic::ctpop_i16:
1677 case Intrinsic::ctpop_i32:
1678 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001679 setValue(&I, DAG.getNode(ISD::CTPOP,
1680 getValue(I.getOperand(1)).getValueType(),
1681 getValue(I.getOperand(1))));
1682 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001683 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001684 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001685 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1686 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001687 setValue(&I, Tmp);
1688 DAG.setRoot(Tmp.getValue(1));
1689 return 0;
1690 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001691 case Intrinsic::stackrestore: {
1692 SDOperand Tmp = getValue(I.getOperand(1));
1693 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001694 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001695 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001696 case Intrinsic::prefetch:
1697 // FIXME: Currently discarding prefetches.
1698 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001699 }
1700}
1701
1702
Chris Lattner7a60d912005-01-07 07:47:53 +00001703void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001704 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001705 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001706 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001707 if (unsigned IID = F->getIntrinsicID()) {
1708 RenameFn = visitIntrinsicCall(I, IID);
1709 if (!RenameFn)
1710 return;
1711 } else { // Not an LLVM intrinsic.
1712 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001713 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1714 if (I.getNumOperands() == 3 && // Basic sanity checks.
1715 I.getOperand(1)->getType()->isFloatingPoint() &&
1716 I.getType() == I.getOperand(1)->getType() &&
1717 I.getType() == I.getOperand(2)->getType()) {
1718 SDOperand LHS = getValue(I.getOperand(1));
1719 SDOperand RHS = getValue(I.getOperand(2));
1720 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1721 LHS, RHS));
1722 return;
1723 }
1724 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001725 if (I.getNumOperands() == 2 && // Basic sanity checks.
1726 I.getOperand(1)->getType()->isFloatingPoint() &&
1727 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001728 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001729 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1730 return;
1731 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001732 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001733 if (I.getNumOperands() == 2 && // Basic sanity checks.
1734 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001735 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001736 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001737 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1738 return;
1739 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001740 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001741 if (I.getNumOperands() == 2 && // Basic sanity checks.
1742 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001743 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001744 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001745 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1746 return;
1747 }
1748 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001749 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001750 } else if (isa<InlineAsm>(I.getOperand(0))) {
1751 visitInlineAsm(I);
1752 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001753 }
Misha Brukman835702a2005-04-21 22:36:52 +00001754
Chris Lattner18d2b342005-01-08 22:48:57 +00001755 SDOperand Callee;
1756 if (!RenameFn)
1757 Callee = getValue(I.getOperand(0));
1758 else
1759 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001760 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001761 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001762 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1763 Value *Arg = I.getOperand(i);
1764 SDOperand ArgNode = getValue(Arg);
1765 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1766 }
Misha Brukman835702a2005-04-21 22:36:52 +00001767
Nate Begemanf6565252005-03-26 01:29:23 +00001768 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1769 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001770
Chris Lattner1f45cd72005-01-08 19:26:18 +00001771 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001772 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001773 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001774 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001775 setValue(&I, Result.first);
1776 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001777}
1778
Chris Lattner6f87d182006-02-22 22:37:12 +00001779SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001780 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001781 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1782 Chain = Val.getValue(1);
1783 Flag = Val.getValue(2);
1784
1785 // If the result was expanded, copy from the top part.
1786 if (Regs.size() > 1) {
1787 assert(Regs.size() == 2 &&
1788 "Cannot expand to more than 2 elts yet!");
1789 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00001790 Chain = Hi.getValue(1);
1791 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001792 if (DAG.getTargetLoweringInfo().isLittleEndian())
1793 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1794 else
1795 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001796 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001797
Chris Lattner705948d2006-06-08 18:22:48 +00001798 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00001799 // appropriate type.
1800 if (RegVT == ValueVT)
1801 return Val;
1802
Chris Lattner705948d2006-06-08 18:22:48 +00001803 if (MVT::isInteger(RegVT)) {
1804 if (ValueVT < RegVT)
1805 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1806 else
1807 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1808 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001809 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00001810 }
Chris Lattner6f87d182006-02-22 22:37:12 +00001811}
1812
Chris Lattner571d9642006-02-23 19:21:04 +00001813/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1814/// specified value into the registers specified by this object. This uses
1815/// Chain/Flag as the input and updates them for the output Chain/Flag.
1816void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00001817 SDOperand &Chain, SDOperand &Flag,
1818 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001819 if (Regs.size() == 1) {
1820 // If there is a single register and the types differ, this must be
1821 // a promotion.
1822 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00001823 if (MVT::isInteger(RegVT)) {
1824 if (RegVT < ValueVT)
1825 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1826 else
1827 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1828 } else
Chris Lattner571d9642006-02-23 19:21:04 +00001829 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1830 }
1831 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1832 Flag = Chain.getValue(1);
1833 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001834 std::vector<unsigned> R(Regs);
1835 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1836 std::reverse(R.begin(), R.end());
1837
1838 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001839 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00001840 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001841 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001842 Flag = Chain.getValue(1);
1843 }
1844 }
1845}
Chris Lattner6f87d182006-02-22 22:37:12 +00001846
Chris Lattner571d9642006-02-23 19:21:04 +00001847/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1848/// operand list. This adds the code marker and includes the number of
1849/// values added into it.
1850void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001851 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001852 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1853 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1854 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1855}
Chris Lattner6f87d182006-02-22 22:37:12 +00001856
1857/// isAllocatableRegister - If the specified register is safe to allocate,
1858/// i.e. it isn't a stack pointer or some other special register, return the
1859/// register class for the register. Otherwise, return null.
1860static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001861isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1862 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001863 MVT::ValueType FoundVT = MVT::Other;
1864 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001865 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1866 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001867 MVT::ValueType ThisVT = MVT::Other;
1868
Chris Lattnerb1124f32006-02-22 23:09:03 +00001869 const TargetRegisterClass *RC = *RCI;
1870 // If none of the the value types for this register class are valid, we
1871 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001872 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1873 I != E; ++I) {
1874 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001875 // If we have already found this register in a different register class,
1876 // choose the one with the largest VT specified. For example, on
1877 // PowerPC, we favor f64 register classes over f32.
1878 if (FoundVT == MVT::Other ||
1879 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1880 ThisVT = *I;
1881 break;
1882 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001883 }
1884 }
1885
Chris Lattnerbec582f2006-04-02 00:24:45 +00001886 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001887
Chris Lattner6f87d182006-02-22 22:37:12 +00001888 // NOTE: This isn't ideal. In particular, this might allocate the
1889 // frame pointer in functions that need it (due to them not being taken
1890 // out of allocation, because a variable sized allocation hasn't been seen
1891 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001892 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1893 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001894 if (*I == Reg) {
1895 // We found a matching register class. Keep looking at others in case
1896 // we find one with larger registers that this physreg is also in.
1897 FoundRC = RC;
1898 FoundVT = ThisVT;
1899 break;
1900 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001901 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001902 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001903}
1904
1905RegsForValue SelectionDAGLowering::
1906GetRegistersForValue(const std::string &ConstrCode,
1907 MVT::ValueType VT, bool isOutReg, bool isInReg,
1908 std::set<unsigned> &OutputRegs,
1909 std::set<unsigned> &InputRegs) {
1910 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1911 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1912 std::vector<unsigned> Regs;
1913
1914 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1915 MVT::ValueType RegVT;
1916 MVT::ValueType ValueVT = VT;
1917
1918 if (PhysReg.first) {
1919 if (VT == MVT::Other)
1920 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00001921
1922 // Get the actual register value type. This is important, because the user
1923 // may have asked for (e.g.) the AX register in i32 type. We need to
1924 // remember that AX is actually i16 to get the right extension.
1925 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00001926
1927 // This is a explicit reference to a physical register.
1928 Regs.push_back(PhysReg.first);
1929
1930 // If this is an expanded reference, add the rest of the regs to Regs.
1931 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001932 TargetRegisterClass::iterator I = PhysReg.second->begin();
1933 TargetRegisterClass::iterator E = PhysReg.second->end();
1934 for (; *I != PhysReg.first; ++I)
1935 assert(I != E && "Didn't find reg!");
1936
1937 // Already added the first reg.
1938 --NumRegs; ++I;
1939 for (; NumRegs; --NumRegs, ++I) {
1940 assert(I != E && "Ran out of registers to allocate!");
1941 Regs.push_back(*I);
1942 }
1943 }
1944 return RegsForValue(Regs, RegVT, ValueVT);
1945 }
1946
1947 // This is a reference to a register class. Allocate NumRegs consecutive,
1948 // available, registers from the class.
1949 std::vector<unsigned> RegClassRegs =
1950 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1951
1952 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1953 MachineFunction &MF = *CurMBB->getParent();
1954 unsigned NumAllocated = 0;
1955 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1956 unsigned Reg = RegClassRegs[i];
1957 // See if this register is available.
1958 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1959 (isInReg && InputRegs.count(Reg))) { // Already used.
1960 // Make sure we find consecutive registers.
1961 NumAllocated = 0;
1962 continue;
1963 }
1964
1965 // Check to see if this register is allocatable (i.e. don't give out the
1966 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001967 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001968 if (!RC) {
1969 // Make sure we find consecutive registers.
1970 NumAllocated = 0;
1971 continue;
1972 }
1973
1974 // Okay, this register is good, we can use it.
1975 ++NumAllocated;
1976
1977 // If we allocated enough consecutive
1978 if (NumAllocated == NumRegs) {
1979 unsigned RegStart = (i-NumAllocated)+1;
1980 unsigned RegEnd = i+1;
1981 // Mark all of the allocated registers used.
1982 for (unsigned i = RegStart; i != RegEnd; ++i) {
1983 unsigned Reg = RegClassRegs[i];
1984 Regs.push_back(Reg);
1985 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1986 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1987 }
1988
1989 return RegsForValue(Regs, *RC->vt_begin(), VT);
1990 }
1991 }
1992
1993 // Otherwise, we couldn't allocate enough registers for this.
1994 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001995}
1996
Chris Lattner6f87d182006-02-22 22:37:12 +00001997
Chris Lattner476e67b2006-01-26 22:24:51 +00001998/// visitInlineAsm - Handle a call to an InlineAsm object.
1999///
2000void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2001 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2002
2003 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2004 MVT::Other);
2005
2006 // Note, we treat inline asms both with and without side-effects as the same.
2007 // If an inline asm doesn't have side effects and doesn't access memory, we
2008 // could not choose to not chain it.
2009 bool hasSideEffects = IA->hasSideEffects();
2010
Chris Lattner3a5ed552006-02-01 01:28:23 +00002011 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002012 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002013
2014 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2015 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2016 /// if it is a def of that register.
2017 std::vector<SDOperand> AsmNodeOperands;
2018 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2019 AsmNodeOperands.push_back(AsmStr);
2020
2021 SDOperand Chain = getRoot();
2022 SDOperand Flag;
2023
Chris Lattner1558fc62006-02-01 18:59:47 +00002024 // We fully assign registers here at isel time. This is not optimal, but
2025 // should work. For register classes that correspond to LLVM classes, we
2026 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2027 // over the constraints, collecting fixed registers that we know we can't use.
2028 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002029 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002030 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2031 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2032 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002033
Chris Lattner7ad77df2006-02-22 00:56:39 +00002034 MVT::ValueType OpVT;
2035
2036 // Compute the value type for each operand and add it to ConstraintVTs.
2037 switch (Constraints[i].Type) {
2038 case InlineAsm::isOutput:
2039 if (!Constraints[i].isIndirectOutput) {
2040 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2041 OpVT = TLI.getValueType(I.getType());
2042 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002043 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002044 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2045 OpNum++; // Consumes a call operand.
2046 }
2047 break;
2048 case InlineAsm::isInput:
2049 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2050 OpNum++; // Consumes a call operand.
2051 break;
2052 case InlineAsm::isClobber:
2053 OpVT = MVT::Other;
2054 break;
2055 }
2056
2057 ConstraintVTs.push_back(OpVT);
2058
Chris Lattner6f87d182006-02-22 22:37:12 +00002059 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2060 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002061
Chris Lattner6f87d182006-02-22 22:37:12 +00002062 // Build a list of regs that this operand uses. This always has a single
2063 // element for promoted/expanded operands.
2064 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2065 false, false,
2066 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002067
2068 switch (Constraints[i].Type) {
2069 case InlineAsm::isOutput:
2070 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002071 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002072 // If this is an early-clobber output, it cannot be assigned to the same
2073 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002074 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002075 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002076 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002077 case InlineAsm::isInput:
2078 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002079 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002080 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002081 case InlineAsm::isClobber:
2082 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002083 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2084 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002085 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002086 }
2087 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002088
Chris Lattner5c79f982006-02-21 23:12:12 +00002089 // Loop over all of the inputs, copying the operand values into the
2090 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002091 RegsForValue RetValRegs;
2092 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002093 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002094
Chris Lattner2e56e892006-01-31 02:03:41 +00002095 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002096 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2097 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002098
Chris Lattner3a5ed552006-02-01 01:28:23 +00002099 switch (Constraints[i].Type) {
2100 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002101 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2102 if (ConstraintCode.size() == 1) // not a physreg name.
2103 CTy = TLI.getConstraintType(ConstraintCode[0]);
2104
2105 if (CTy == TargetLowering::C_Memory) {
2106 // Memory output.
2107 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2108
2109 // Check that the operand (the address to store to) isn't a float.
2110 if (!MVT::isInteger(InOperandVal.getValueType()))
2111 assert(0 && "MATCH FAIL!");
2112
2113 if (!Constraints[i].isIndirectOutput)
2114 assert(0 && "MATCH FAIL!");
2115
2116 OpNum++; // Consumes a call operand.
2117
2118 // Extend/truncate to the right pointer type if needed.
2119 MVT::ValueType PtrType = TLI.getPointerTy();
2120 if (InOperandVal.getValueType() < PtrType)
2121 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2122 else if (InOperandVal.getValueType() > PtrType)
2123 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2124
2125 // Add information to the INLINEASM node to know about this output.
2126 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2127 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2128 AsmNodeOperands.push_back(InOperandVal);
2129 break;
2130 }
2131
2132 // Otherwise, this is a register output.
2133 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2134
Chris Lattner6f87d182006-02-22 22:37:12 +00002135 // If this is an early-clobber output, or if there is an input
2136 // constraint that matches this, we need to reserve the input register
2137 // so no other inputs allocate to it.
2138 bool UsesInputRegister = false;
2139 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2140 UsesInputRegister = true;
2141
2142 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002143 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002144 RegsForValue Regs =
2145 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2146 true, UsesInputRegister,
2147 OutputRegs, InputRegs);
2148 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002149
Chris Lattner3a5ed552006-02-01 01:28:23 +00002150 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002151 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002152 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002153 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002154 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002155 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002156 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2157 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002158 OpNum++; // Consumes a call operand.
2159 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002160
2161 // Add information to the INLINEASM node to know that this register is
2162 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002163 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002164 break;
2165 }
2166 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002167 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002168 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002169
Chris Lattner7f5880b2006-02-02 00:25:23 +00002170 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2171 // If this is required to match an output register we have already set,
2172 // just use its register.
2173 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002174
Chris Lattner571d9642006-02-23 19:21:04 +00002175 // Scan until we find the definition we already emitted of this operand.
2176 // When we find it, create a RegsForValue operand.
2177 unsigned CurOp = 2; // The first operand.
2178 for (; OperandNo; --OperandNo) {
2179 // Advance to the next operand.
2180 unsigned NumOps =
2181 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002182 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2183 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002184 "Skipped past definitions?");
2185 CurOp += (NumOps>>3)+1;
2186 }
2187
2188 unsigned NumOps =
2189 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2190 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2191 "Skipped past definitions?");
2192
2193 // Add NumOps>>3 registers to MatchedRegs.
2194 RegsForValue MatchedRegs;
2195 MatchedRegs.ValueVT = InOperandVal.getValueType();
2196 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2197 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2198 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2199 MatchedRegs.Regs.push_back(Reg);
2200 }
2201
2202 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002203 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2204 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002205 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002206 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002207 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002208
2209 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2210 if (ConstraintCode.size() == 1) // not a physreg name.
2211 CTy = TLI.getConstraintType(ConstraintCode[0]);
2212
2213 if (CTy == TargetLowering::C_Other) {
2214 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2215 assert(0 && "MATCH FAIL!");
2216
2217 // Add information to the INLINEASM node to know about this input.
2218 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2219 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2220 AsmNodeOperands.push_back(InOperandVal);
2221 break;
2222 } else if (CTy == TargetLowering::C_Memory) {
2223 // Memory input.
2224
2225 // Check that the operand isn't a float.
2226 if (!MVT::isInteger(InOperandVal.getValueType()))
2227 assert(0 && "MATCH FAIL!");
2228
2229 // Extend/truncate to the right pointer type if needed.
2230 MVT::ValueType PtrType = TLI.getPointerTy();
2231 if (InOperandVal.getValueType() < PtrType)
2232 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2233 else if (InOperandVal.getValueType() > PtrType)
2234 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2235
2236 // Add information to the INLINEASM node to know about this input.
2237 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2238 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2239 AsmNodeOperands.push_back(InOperandVal);
2240 break;
2241 }
2242
2243 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2244
2245 // Copy the input into the appropriate registers.
2246 RegsForValue InRegs =
2247 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2248 false, true, OutputRegs, InputRegs);
2249 // FIXME: should be match fail.
2250 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2251
Evan Chengef9e07d2006-06-15 08:11:54 +00002252 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002253
2254 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002255 break;
2256 }
Chris Lattner571d9642006-02-23 19:21:04 +00002257 case InlineAsm::isClobber: {
2258 RegsForValue ClobberedRegs =
2259 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2260 OutputRegs, InputRegs);
2261 // Add the clobbered value to the operand list, so that the register
2262 // allocator is aware that the physreg got clobbered.
2263 if (!ClobberedRegs.Regs.empty())
2264 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002265 break;
2266 }
Chris Lattner571d9642006-02-23 19:21:04 +00002267 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002268 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002269
2270 // Finish up input operands.
2271 AsmNodeOperands[0] = Chain;
2272 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2273
Chris Lattnerbd887772006-08-14 23:53:35 +00002274 Chain = DAG.getNode(ISD::INLINEASM,
2275 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002276 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002277 Flag = Chain.getValue(1);
2278
Chris Lattner2e56e892006-01-31 02:03:41 +00002279 // If this asm returns a register value, copy the result from that register
2280 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002281 if (!RetValRegs.Regs.empty())
2282 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002283
Chris Lattner2e56e892006-01-31 02:03:41 +00002284 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2285
2286 // Process indirect outputs, first output all of the flagged copies out of
2287 // physregs.
2288 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002289 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002290 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002291 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2292 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002293 }
2294
2295 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002296 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002297 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002298 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002299 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002300 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002301 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002302 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2303 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002304 DAG.setRoot(Chain);
2305}
2306
2307
Chris Lattner7a60d912005-01-07 07:47:53 +00002308void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2309 SDOperand Src = getValue(I.getOperand(0));
2310
2311 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002312
2313 if (IntPtr < Src.getValueType())
2314 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2315 else if (IntPtr > Src.getValueType())
2316 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002317
2318 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002319 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002320 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2321 Src, getIntPtrConstant(ElementSize));
2322
2323 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002324 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002325
2326 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002327 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002328 DAG.getExternalSymbol("malloc", IntPtr),
2329 Args, DAG);
2330 setValue(&I, Result.first); // Pointers always fit in registers
2331 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002332}
2333
2334void SelectionDAGLowering::visitFree(FreeInst &I) {
2335 std::vector<std::pair<SDOperand, const Type*> > Args;
2336 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002337 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002338 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002339 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002340 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002341 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2342 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002343}
2344
Chris Lattner13d7c252005-08-26 20:54:47 +00002345// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2346// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2347// instructions are special in various ways, which require special support to
2348// insert. The specified MachineInstr is created but not inserted into any
2349// basic blocks, and the scheduler passes ownership of it to this method.
2350MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2351 MachineBasicBlock *MBB) {
2352 std::cerr << "If a target marks an instruction with "
2353 "'usesCustomDAGSchedInserter', it must implement "
2354 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2355 abort();
2356 return 0;
2357}
2358
Chris Lattner58cfd792005-01-09 00:00:49 +00002359void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002360 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2361 getValue(I.getOperand(1)),
2362 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002363}
2364
2365void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002366 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2367 getValue(I.getOperand(0)),
2368 DAG.getSrcValue(I.getOperand(0)));
2369 setValue(&I, V);
2370 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002371}
2372
2373void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002374 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2375 getValue(I.getOperand(1)),
2376 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002377}
2378
2379void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002380 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2381 getValue(I.getOperand(1)),
2382 getValue(I.getOperand(2)),
2383 DAG.getSrcValue(I.getOperand(1)),
2384 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002385}
2386
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002387/// TargetLowering::LowerArguments - This is the default LowerArguments
2388/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002389/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2390/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002391std::vector<SDOperand>
2392TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2393 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2394 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002395 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002396 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2397 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2398
2399 // Add one result value for each formal argument.
2400 std::vector<MVT::ValueType> RetVals;
2401 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2402 MVT::ValueType VT = getValueType(I->getType());
2403
2404 switch (getTypeAction(VT)) {
2405 default: assert(0 && "Unknown type action!");
2406 case Legal:
2407 RetVals.push_back(VT);
2408 break;
2409 case Promote:
2410 RetVals.push_back(getTypeToTransformTo(VT));
2411 break;
2412 case Expand:
2413 if (VT != MVT::Vector) {
2414 // If this is a large integer, it needs to be broken up into small
2415 // integers. Figure out what the destination type is and how many small
2416 // integers it turns into.
2417 MVT::ValueType NVT = getTypeToTransformTo(VT);
2418 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2419 for (unsigned i = 0; i != NumVals; ++i)
2420 RetVals.push_back(NVT);
2421 } else {
2422 // Otherwise, this is a vector type. We only support legal vectors
2423 // right now.
2424 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2425 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002426
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002427 // Figure out if there is a Packed type corresponding to this Vector
2428 // type. If so, convert to the packed type.
2429 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2430 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2431 RetVals.push_back(TVT);
2432 } else {
2433 assert(0 && "Don't support illegal by-val vector arguments yet!");
2434 }
2435 }
2436 break;
2437 }
2438 }
Evan Cheng9618df12006-04-25 23:03:35 +00002439
Chris Lattner3d826992006-05-16 06:45:34 +00002440 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002441
2442 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002443 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2444 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002445 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002446
2447 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002448
2449 // Set up the return result vector.
2450 Ops.clear();
2451 unsigned i = 0;
2452 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2453 MVT::ValueType VT = getValueType(I->getType());
2454
2455 switch (getTypeAction(VT)) {
2456 default: assert(0 && "Unknown type action!");
2457 case Legal:
2458 Ops.push_back(SDOperand(Result, i++));
2459 break;
2460 case Promote: {
2461 SDOperand Op(Result, i++);
2462 if (MVT::isInteger(VT)) {
2463 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2464 : ISD::AssertZext;
2465 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2466 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2467 } else {
2468 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2469 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2470 }
2471 Ops.push_back(Op);
2472 break;
2473 }
2474 case Expand:
2475 if (VT != MVT::Vector) {
2476 // If this is a large integer, it needs to be reassembled from small
2477 // integers. Figure out what the source elt type is and how many small
2478 // integers it is.
2479 MVT::ValueType NVT = getTypeToTransformTo(VT);
2480 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2481 if (NumVals == 2) {
2482 SDOperand Lo = SDOperand(Result, i++);
2483 SDOperand Hi = SDOperand(Result, i++);
2484
2485 if (!isLittleEndian())
2486 std::swap(Lo, Hi);
2487
2488 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2489 } else {
2490 // Value scalarized into many values. Unimp for now.
2491 assert(0 && "Cannot expand i64 -> i16 yet!");
2492 }
2493 } else {
2494 // Otherwise, this is a vector type. We only support legal vectors
2495 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002496 const PackedType *PTy = cast<PackedType>(I->getType());
2497 unsigned NumElems = PTy->getNumElements();
2498 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002499
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002500 // Figure out if there is a Packed type corresponding to this Vector
2501 // type. If so, convert to the packed type.
2502 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002503 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002504 SDOperand N = SDOperand(Result, i++);
2505 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002506 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2507 DAG.getConstant(NumElems, MVT::i32),
2508 DAG.getValueType(getValueType(EltTy)));
2509 Ops.push_back(N);
2510 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002511 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002512 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002513 }
2514 }
2515 break;
2516 }
2517 }
2518 return Ops;
2519}
2520
Chris Lattneraaa23d92006-05-16 22:53:20 +00002521
2522/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2523/// implementation, which just inserts an ISD::CALL node, which is later custom
2524/// lowered by the target to something concrete. FIXME: When all targets are
2525/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2526std::pair<SDOperand, SDOperand>
2527TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2528 unsigned CallingConv, bool isTailCall,
2529 SDOperand Callee,
2530 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002531 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002532 Ops.push_back(Chain); // Op#0 - Chain
2533 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2534 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2535 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2536 Ops.push_back(Callee);
2537
2538 // Handle all of the outgoing arguments.
2539 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2540 MVT::ValueType VT = getValueType(Args[i].second);
2541 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002542 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002543 switch (getTypeAction(VT)) {
2544 default: assert(0 && "Unknown type action!");
2545 case Legal:
2546 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002547 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002548 break;
2549 case Promote:
2550 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002551 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002552 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2553 } else {
2554 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2555 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2556 }
2557 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002558 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002559 break;
2560 case Expand:
2561 if (VT != MVT::Vector) {
2562 // If this is a large integer, it needs to be broken down into small
2563 // integers. Figure out what the source elt type is and how many small
2564 // integers it is.
2565 MVT::ValueType NVT = getTypeToTransformTo(VT);
2566 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2567 if (NumVals == 2) {
2568 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2569 DAG.getConstant(0, getPointerTy()));
2570 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2571 DAG.getConstant(1, getPointerTy()));
2572 if (!isLittleEndian())
2573 std::swap(Lo, Hi);
2574
2575 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002576 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002577 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002578 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002579 } else {
2580 // Value scalarized into many values. Unimp for now.
2581 assert(0 && "Cannot expand i64 -> i16 yet!");
2582 }
2583 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002584 // Otherwise, this is a vector type. We only support legal vectors
2585 // right now.
2586 const PackedType *PTy = cast<PackedType>(Args[i].second);
2587 unsigned NumElems = PTy->getNumElements();
2588 const Type *EltTy = PTy->getElementType();
2589
2590 // Figure out if there is a Packed type corresponding to this Vector
2591 // type. If so, convert to the packed type.
2592 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002593 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2594 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2595 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2596 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002597 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002598 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002599 assert(0 && "Don't support illegal by-val vector call args yet!");
2600 abort();
2601 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002602 }
2603 break;
2604 }
2605 }
2606
2607 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002608 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002609
2610 if (RetTy != Type::VoidTy) {
2611 MVT::ValueType VT = getValueType(RetTy);
2612 switch (getTypeAction(VT)) {
2613 default: assert(0 && "Unknown type action!");
2614 case Legal:
2615 RetTys.push_back(VT);
2616 break;
2617 case Promote:
2618 RetTys.push_back(getTypeToTransformTo(VT));
2619 break;
2620 case Expand:
2621 if (VT != MVT::Vector) {
2622 // If this is a large integer, it needs to be reassembled from small
2623 // integers. Figure out what the source elt type is and how many small
2624 // integers it is.
2625 MVT::ValueType NVT = getTypeToTransformTo(VT);
2626 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2627 for (unsigned i = 0; i != NumVals; ++i)
2628 RetTys.push_back(NVT);
2629 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002630 // Otherwise, this is a vector type. We only support legal vectors
2631 // right now.
2632 const PackedType *PTy = cast<PackedType>(RetTy);
2633 unsigned NumElems = PTy->getNumElements();
2634 const Type *EltTy = PTy->getElementType();
2635
2636 // Figure out if there is a Packed type corresponding to this Vector
2637 // type. If so, convert to the packed type.
2638 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2639 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2640 RetTys.push_back(TVT);
2641 } else {
2642 assert(0 && "Don't support illegal by-val vector call results yet!");
2643 abort();
2644 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002645 }
2646 }
2647 }
2648
2649 RetTys.push_back(MVT::Other); // Always has a chain.
2650
2651 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002652 SDOperand Res = DAG.getNode(ISD::CALL,
2653 DAG.getVTList(&RetTys[0], RetTys.size()),
2654 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002655
2656 // This returns a pair of operands. The first element is the
2657 // return value for the function (if RetTy is not VoidTy). The second
2658 // element is the outgoing token chain.
2659 SDOperand ResVal;
2660 if (RetTys.size() != 1) {
2661 MVT::ValueType VT = getValueType(RetTy);
2662 if (RetTys.size() == 2) {
2663 ResVal = Res;
2664
2665 // If this value was promoted, truncate it down.
2666 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002667 if (VT == MVT::Vector) {
2668 // Insert a VBITCONVERT to convert from the packed result type to the
2669 // MVT::Vector type.
2670 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2671 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2672
2673 // Figure out if there is a Packed type corresponding to this Vector
2674 // type. If so, convert to the packed type.
2675 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2676 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002677 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2678 // "N x PTyElementVT" MVT::Vector type.
2679 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002680 DAG.getConstant(NumElems, MVT::i32),
2681 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002682 } else {
2683 abort();
2684 }
2685 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002686 unsigned AssertOp = RetTy->isSigned() ?
2687 ISD::AssertSext : ISD::AssertZext;
2688 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2689 DAG.getValueType(VT));
2690 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2691 } else {
2692 assert(MVT::isFloatingPoint(VT));
2693 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2694 }
2695 }
2696 } else if (RetTys.size() == 3) {
2697 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2698 Res.getValue(0), Res.getValue(1));
2699
2700 } else {
2701 assert(0 && "Case not handled yet!");
2702 }
2703 }
2704
2705 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2706}
2707
2708
2709
Chris Lattner58cfd792005-01-09 00:00:49 +00002710// It is always conservatively correct for llvm.returnaddress and
2711// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002712//
2713// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2714// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002715std::pair<SDOperand, SDOperand>
2716TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2717 unsigned Depth, SelectionDAG &DAG) {
2718 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002719}
2720
Chris Lattner29dcc712005-05-14 05:50:48 +00002721SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002722 assert(0 && "LowerOperation not implemented for this target!");
2723 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002724 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002725}
2726
Nate Begeman595ec732006-01-28 03:14:31 +00002727SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2728 SelectionDAG &DAG) {
2729 assert(0 && "CustomPromoteOperation not implemented for this target!");
2730 abort();
2731 return SDOperand();
2732}
2733
Chris Lattner58cfd792005-01-09 00:00:49 +00002734void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2735 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2736 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002737 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002738 setValue(&I, Result.first);
2739 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002740}
2741
Evan Cheng6781b6e2006-02-15 21:59:04 +00002742/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002743/// operand.
2744static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002745 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002746 MVT::ValueType CurVT = VT;
2747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2748 uint64_t Val = C->getValue() & 255;
2749 unsigned Shift = 8;
2750 while (CurVT != MVT::i8) {
2751 Val = (Val << Shift) | Val;
2752 Shift <<= 1;
2753 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002754 }
2755 return DAG.getConstant(Val, VT);
2756 } else {
2757 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2758 unsigned Shift = 8;
2759 while (CurVT != MVT::i8) {
2760 Value =
2761 DAG.getNode(ISD::OR, VT,
2762 DAG.getNode(ISD::SHL, VT, Value,
2763 DAG.getConstant(Shift, MVT::i8)), Value);
2764 Shift <<= 1;
2765 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002766 }
2767
2768 return Value;
2769 }
2770}
2771
Evan Cheng6781b6e2006-02-15 21:59:04 +00002772/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2773/// used when a memcpy is turned into a memset when the source is a constant
2774/// string ptr.
2775static SDOperand getMemsetStringVal(MVT::ValueType VT,
2776 SelectionDAG &DAG, TargetLowering &TLI,
2777 std::string &Str, unsigned Offset) {
2778 MVT::ValueType CurVT = VT;
2779 uint64_t Val = 0;
2780 unsigned MSB = getSizeInBits(VT) / 8;
2781 if (TLI.isLittleEndian())
2782 Offset = Offset + MSB - 1;
2783 for (unsigned i = 0; i != MSB; ++i) {
2784 Val = (Val << 8) | Str[Offset];
2785 Offset += TLI.isLittleEndian() ? -1 : 1;
2786 }
2787 return DAG.getConstant(Val, VT);
2788}
2789
Evan Cheng81fcea82006-02-14 08:22:34 +00002790/// getMemBasePlusOffset - Returns base and offset node for the
2791static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2792 SelectionDAG &DAG, TargetLowering &TLI) {
2793 MVT::ValueType VT = Base.getValueType();
2794 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2795}
2796
Evan Chengdb2a7a72006-02-14 20:12:38 +00002797/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002798/// to replace the memset / memcpy is below the threshold. It also returns the
2799/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002800static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2801 unsigned Limit, uint64_t Size,
2802 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002803 MVT::ValueType VT;
2804
2805 if (TLI.allowsUnalignedMemoryAccesses()) {
2806 VT = MVT::i64;
2807 } else {
2808 switch (Align & 7) {
2809 case 0:
2810 VT = MVT::i64;
2811 break;
2812 case 4:
2813 VT = MVT::i32;
2814 break;
2815 case 2:
2816 VT = MVT::i16;
2817 break;
2818 default:
2819 VT = MVT::i8;
2820 break;
2821 }
2822 }
2823
Evan Chengd5026102006-02-14 09:11:59 +00002824 MVT::ValueType LVT = MVT::i64;
2825 while (!TLI.isTypeLegal(LVT))
2826 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2827 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002828
Evan Chengd5026102006-02-14 09:11:59 +00002829 if (VT > LVT)
2830 VT = LVT;
2831
Evan Cheng04514992006-02-14 23:05:54 +00002832 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002833 while (Size != 0) {
2834 unsigned VTSize = getSizeInBits(VT) / 8;
2835 while (VTSize > Size) {
2836 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002837 VTSize >>= 1;
2838 }
Evan Chengd5026102006-02-14 09:11:59 +00002839 assert(MVT::isInteger(VT));
2840
2841 if (++NumMemOps > Limit)
2842 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002843 MemOps.push_back(VT);
2844 Size -= VTSize;
2845 }
Evan Chengd5026102006-02-14 09:11:59 +00002846
2847 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002848}
2849
Chris Lattner875def92005-01-11 05:56:49 +00002850void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002851 SDOperand Op1 = getValue(I.getOperand(1));
2852 SDOperand Op2 = getValue(I.getOperand(2));
2853 SDOperand Op3 = getValue(I.getOperand(3));
2854 SDOperand Op4 = getValue(I.getOperand(4));
2855 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2856 if (Align == 0) Align = 1;
2857
2858 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2859 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002860
2861 // Expand memset / memcpy to a series of load / store ops
2862 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002863 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00002864 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002865 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002866 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002867 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2868 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002869 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002870 unsigned Offset = 0;
2871 for (unsigned i = 0; i < NumMemOps; i++) {
2872 MVT::ValueType VT = MemOps[i];
2873 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002874 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00002875 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002876 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002877 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00002878 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002879 Offset += VTSize;
2880 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002881 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002882 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002883 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002884 case ISD::MEMCPY: {
2885 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2886 Size->getValue(), Align, TLI)) {
2887 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002888 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002889 GlobalAddressSDNode *G = NULL;
2890 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002891 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002892
2893 if (Op2.getOpcode() == ISD::GlobalAddress)
2894 G = cast<GlobalAddressSDNode>(Op2);
2895 else if (Op2.getOpcode() == ISD::ADD &&
2896 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2897 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2898 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002899 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002900 }
2901 if (G) {
2902 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002903 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002904 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002905 if (!Str.empty()) {
2906 CopyFromStr = true;
2907 SrcOff += SrcDelta;
2908 }
2909 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002910 }
2911
Evan Chenge2038bd2006-02-15 01:54:51 +00002912 for (unsigned i = 0; i < NumMemOps; i++) {
2913 MVT::ValueType VT = MemOps[i];
2914 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002915 SDOperand Value, Chain, Store;
2916
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002917 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002918 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2919 Chain = getRoot();
2920 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002921 DAG.getStore(Chain, Value,
2922 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002923 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002924 } else {
2925 Value = DAG.getLoad(VT, getRoot(),
2926 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00002927 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002928 Chain = Value.getValue(1);
2929 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002930 DAG.getStore(Chain, Value,
2931 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002932 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002933 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002934 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002935 SrcOff += VTSize;
2936 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002937 }
2938 }
2939 break;
2940 }
2941 }
2942
2943 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002944 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
2945 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00002946 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002947 }
2948 }
2949
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002950 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00002951}
2952
Chris Lattner875def92005-01-11 05:56:49 +00002953//===----------------------------------------------------------------------===//
2954// SelectionDAGISel code
2955//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002956
2957unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2958 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2959}
2960
Chris Lattnerc9950c12005-08-17 06:37:43 +00002961void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002962 // FIXME: we only modify the CFG to split critical edges. This
2963 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00002964 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00002965}
Chris Lattner7a60d912005-01-07 07:47:53 +00002966
Chris Lattner35397782005-12-05 07:10:48 +00002967
Chris Lattner3e3f2c62006-05-05 21:17:49 +00002968/// OptimizeNoopCopyExpression - We have determined that the specified cast
2969/// instruction is a noop copy (e.g. it's casting from one pointer type to
2970/// another, int->uint, or int->sbyte on PPC.
2971///
2972/// Return true if any changes are made.
2973static bool OptimizeNoopCopyExpression(CastInst *CI) {
2974 BasicBlock *DefBB = CI->getParent();
2975
2976 /// InsertedCasts - Only insert a cast in each block once.
2977 std::map<BasicBlock*, CastInst*> InsertedCasts;
2978
2979 bool MadeChange = false;
2980 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2981 UI != E; ) {
2982 Use &TheUse = UI.getUse();
2983 Instruction *User = cast<Instruction>(*UI);
2984
2985 // Figure out which BB this cast is used in. For PHI's this is the
2986 // appropriate predecessor block.
2987 BasicBlock *UserBB = User->getParent();
2988 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2989 unsigned OpVal = UI.getOperandNo()/2;
2990 UserBB = PN->getIncomingBlock(OpVal);
2991 }
2992
2993 // Preincrement use iterator so we don't invalidate it.
2994 ++UI;
2995
2996 // If this user is in the same block as the cast, don't change the cast.
2997 if (UserBB == DefBB) continue;
2998
2999 // If we have already inserted a cast into this block, use it.
3000 CastInst *&InsertedCast = InsertedCasts[UserBB];
3001
3002 if (!InsertedCast) {
3003 BasicBlock::iterator InsertPt = UserBB->begin();
3004 while (isa<PHINode>(InsertPt)) ++InsertPt;
3005
3006 InsertedCast =
3007 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3008 MadeChange = true;
3009 }
3010
3011 // Replace a use of the cast with a use of the new casat.
3012 TheUse = InsertedCast;
3013 }
3014
3015 // If we removed all uses, nuke the cast.
3016 if (CI->use_empty())
3017 CI->eraseFromParent();
3018
3019 return MadeChange;
3020}
3021
Chris Lattner35397782005-12-05 07:10:48 +00003022/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3023/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003024static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3025 Instruction *GEPI, Value *Ptr,
3026 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003027 if (V) return V; // Already computed.
3028
3029 BasicBlock::iterator InsertPt;
3030 if (BB == GEPI->getParent()) {
3031 // If insert into the GEP's block, insert right after the GEP.
3032 InsertPt = GEPI;
3033 ++InsertPt;
3034 } else {
3035 // Otherwise, insert at the top of BB, after any PHI nodes
3036 InsertPt = BB->begin();
3037 while (isa<PHINode>(InsertPt)) ++InsertPt;
3038 }
3039
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003040 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3041 // BB so that there is only one value live across basic blocks (the cast
3042 // operand).
3043 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3044 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3045 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3046
Chris Lattner35397782005-12-05 07:10:48 +00003047 // Add the offset, cast it to the right type.
3048 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003049 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003050}
3051
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003052/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3053/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3054/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3055/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3056/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3057/// the constant add into a load or store instruction. Additionally, if a user
3058/// is a pointer-pointer cast, we look through it to find its users.
3059static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3060 Constant *PtrOffset, BasicBlock *DefBB,
3061 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003062 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003063 while (!RepPtr->use_empty()) {
3064 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003065
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003066 // If the user is a Pointer-Pointer cast, recurse.
3067 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3068 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003069
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003070 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3071 // could invalidate an iterator.
3072 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3073 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003074 }
3075
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003076 // If this is a load of the pointer, or a store through the pointer, emit
3077 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003078 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003079 if (isa<LoadInst>(User) ||
3080 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3081 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3082 User->getParent(), GEPI,
3083 Ptr, PtrOffset);
3084 } else {
3085 // If this use is not foldable into the addressing mode, use a version
3086 // emitted in the GEP block.
3087 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3088 Ptr, PtrOffset);
3089 }
3090
Chris Lattner21cd9902006-05-06 09:10:37 +00003091 if (GEPI->getType() != RepPtr->getType()) {
3092 BasicBlock::iterator IP = NewVal;
3093 ++IP;
3094 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3095 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003096 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003097 }
3098}
Chris Lattner35397782005-12-05 07:10:48 +00003099
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003100
Chris Lattner35397782005-12-05 07:10:48 +00003101/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3102/// selection, we want to be a bit careful about some things. In particular, if
3103/// we have a GEP instruction that is used in a different block than it is
3104/// defined, the addressing expression of the GEP cannot be folded into loads or
3105/// stores that use it. In this case, decompose the GEP and move constant
3106/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003107static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003108 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003109 // If this GEP is only used inside the block it is defined in, there is no
3110 // need to rewrite it.
3111 bool isUsedOutsideDefBB = false;
3112 BasicBlock *DefBB = GEPI->getParent();
3113 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3114 UI != E; ++UI) {
3115 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3116 isUsedOutsideDefBB = true;
3117 break;
3118 }
3119 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003120 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003121
3122 // If this GEP has no non-zero constant indices, there is nothing we can do,
3123 // ignore it.
3124 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003125 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003126 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3127 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003128 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Chris Lattner35397782005-12-05 07:10:48 +00003129 if (CI->getRawValue()) {
3130 hasConstantIndex = true;
3131 break;
3132 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003133 } else {
3134 hasVariableIndex = true;
3135 }
Chris Lattner35397782005-12-05 07:10:48 +00003136 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003137
3138 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3139 if (!hasConstantIndex && !hasVariableIndex) {
3140 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3141 GEPI->getName(), GEPI);
3142 GEPI->replaceAllUsesWith(NC);
3143 GEPI->eraseFromParent();
3144 return true;
3145 }
3146
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003147 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003148 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3149 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003150
3151 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3152 // constant offset (which we now know is non-zero) and deal with it later.
3153 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003154 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003155 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3156 const Type *Ty = GEPI->getOperand(0)->getType();
3157
3158 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3159 E = GEPI->op_end(); OI != E; ++OI) {
3160 Value *Idx = *OI;
3161 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3162 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
3163 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003164 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003165 Ty = StTy->getElementType(Field);
3166 } else {
3167 Ty = cast<SequentialType>(Ty)->getElementType();
3168
3169 // Handle constant subscripts.
3170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3171 if (CI->getRawValue() == 0) continue;
3172
3173 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
Owen Anderson20a631f2006-05-03 01:29:57 +00003174 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
Chris Lattner35397782005-12-05 07:10:48 +00003175 else
Owen Anderson20a631f2006-05-03 01:29:57 +00003176 ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
Chris Lattner35397782005-12-05 07:10:48 +00003177 continue;
3178 }
3179
3180 // Ptr = Ptr + Idx * ElementSize;
3181
3182 // Cast Idx to UIntPtrTy if needed.
3183 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3184
Owen Anderson20a631f2006-05-03 01:29:57 +00003185 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003186 // Mask off bits that should not be set.
3187 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3188 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
3189
3190 // Multiply by the element size and add to the base.
3191 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3192 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3193 }
3194 }
3195
3196 // Make sure that the offset fits in uintptr_t.
3197 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3198 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
3199
3200 // Okay, we have now emitted all of the variable index parts to the BB that
3201 // the GEP is defined in. Loop over all of the using instructions, inserting
3202 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003203 // instruction to use the newly computed value, making GEPI dead. When the
3204 // user is a load or store instruction address, we emit the add into the user
3205 // block, otherwise we use a canonical version right next to the gep (these
3206 // won't be foldable as addresses, so we might as well share the computation).
3207
Chris Lattner21cd9902006-05-06 09:10:37 +00003208 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003209 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003210
3211 // Finally, the GEP is dead, remove it.
3212 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003213
3214 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003215}
3216
Chris Lattnera9caf952006-09-28 06:17:10 +00003217/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3218/// constant operands, and if any of the edges feeding the PHI node are
3219/// critical, split them so that the assignments of a constant to a register
3220/// will not be executed on a path that isn't relevant.
3221void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003222 // The most common case is that this is a PHI node with two incoming
3223 // successors handle this case efficiently, because it is simple.
3224 PHINode *PN = cast<PHINode>(BB->begin());
3225 if (PN->getNumIncomingValues() == 2) {
3226 // If neither edge is critical, we never need to split.
3227 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3228 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3229 return;
3230
3231 BasicBlock::iterator BBI = BB->begin();
3232 while ((PN = dyn_cast<PHINode>(BBI++))) {
3233 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3234 if (isa<Constant>(PN->getIncomingValue(i)))
3235 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3236 }
3237 return;
3238 }
3239
3240 // Otherwise, things are a bit trickier.
3241
3242 // BE SMART HERE.
3243
Chris Lattnera9caf952006-09-28 06:17:10 +00003244 BasicBlock::iterator BBI = BB->begin();
3245 while ((PN = dyn_cast<PHINode>(BBI++))) {
3246 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3247 if (isa<Constant>(PN->getIncomingValue(i)))
3248 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3249 }
3250}
3251
3252
Chris Lattner7a60d912005-01-07 07:47:53 +00003253bool SelectionDAGISel::runOnFunction(Function &Fn) {
3254 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3255 RegMap = MF.getSSARegMap();
3256 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3257
Chris Lattner35397782005-12-05 07:10:48 +00003258 // First, split all critical edges for PHI nodes with incoming values that are
3259 // constants, this way the load of the constant into a vreg will not be placed
3260 // into MBBs that are used some other way.
3261 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003262 // In this pass we also look for GEP and cast instructions that are used
3263 // across basic blocks and rewrite them to improve basic-block-at-a-time
3264 // selection.
3265 //
Chris Lattner35397782005-12-05 07:10:48 +00003266 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003267 bool MadeChange = true;
3268 while (MadeChange) {
3269 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003270 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003271 // If this block has any PHI nodes with constant operands, and if any of the
3272 // edges feeding the PHI node are critical, split them.
3273 if (isa<PHINode>(BB->begin()))
3274 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003275
Chris Lattnera9caf952006-09-28 06:17:10 +00003276 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003277 Instruction *I = BBI++;
3278 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003279 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003280 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003281 // If the source of the cast is a constant, then this should have
3282 // already been constant folded. The only reason NOT to constant fold
3283 // it is if something (e.g. LSR) was careful to place the constant
3284 // evaluation in a block other than then one that uses it (e.g. to hoist
3285 // the address of globals out of a loop). If this is the case, we don't
3286 // want to forward-subst the cast.
3287 if (isa<Constant>(CI->getOperand(0)))
3288 continue;
3289
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003290 // If this is a noop copy, sink it into user blocks to reduce the number
3291 // of virtual registers that must be created and coallesced.
3292 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3293 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3294
3295 // This is an fp<->int conversion?
3296 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3297 continue;
3298
3299 // If this is an extension, it will be a zero or sign extension, which
3300 // isn't a noop.
3301 if (SrcVT < DstVT) continue;
3302
3303 // If these values will be promoted, find out what they will be promoted
3304 // to. This helps us consider truncates on PPC as noop copies when they
3305 // are.
3306 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3307 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3308 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3309 DstVT = TLI.getTypeToTransformTo(DstVT);
3310
3311 // If, after promotion, these are the same types, this is a noop copy.
3312 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003313 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003314 }
3315 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003316 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003317 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003318
Chris Lattner7a60d912005-01-07 07:47:53 +00003319 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3320
3321 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3322 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003323
Chris Lattner7a60d912005-01-07 07:47:53 +00003324 return true;
3325}
3326
3327
Chris Lattner718b5c22005-01-13 17:59:43 +00003328SDOperand SelectionDAGISel::
3329CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00003330 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003331 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003332 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003333 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003334
3335 // If this type is not legal, we must make sure to not create an invalid
3336 // register use.
3337 MVT::ValueType SrcVT = Op.getValueType();
3338 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3339 SelectionDAG &DAG = SDL.DAG;
3340 if (SrcVT == DestVT) {
3341 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003342 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003343 // Handle copies from generic vectors to registers.
3344 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3345 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3346 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003347
Chris Lattner5fe1f542006-03-31 02:06:56 +00003348 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3349 // MVT::Vector type.
3350 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3351 DAG.getConstant(NE, MVT::i32),
3352 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003353
Chris Lattner5fe1f542006-03-31 02:06:56 +00003354 // Loop over all of the elements of the resultant vector,
3355 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3356 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003357 SmallVector<SDOperand, 8> OutChains;
Chris Lattner5fe1f542006-03-31 02:06:56 +00003358 SDOperand Root = SDL.getRoot();
3359 for (unsigned i = 0; i != NE; ++i) {
3360 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003361 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003362 if (PTyElementVT == PTyLegalElementVT) {
3363 // Elements are legal.
3364 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3365 } else if (PTyLegalElementVT > PTyElementVT) {
3366 // Elements are promoted.
3367 if (MVT::isFloatingPoint(PTyLegalElementVT))
3368 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3369 else
3370 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3371 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3372 } else {
3373 // Elements are expanded.
3374 // The src value is expanded into multiple registers.
3375 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003376 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003377 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003378 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003379 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3380 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3381 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003382 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003383 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3384 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003385 } else if (SrcVT < DestVT) {
3386 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003387 if (MVT::isFloatingPoint(SrcVT))
3388 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3389 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003390 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003391 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3392 } else {
3393 // The src value is expanded into multiple registers.
3394 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003395 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003396 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003397 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003398 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3399 return DAG.getCopyToReg(Op, Reg+1, Hi);
3400 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003401}
3402
Chris Lattner16f64df2005-01-17 17:15:02 +00003403void SelectionDAGISel::
3404LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3405 std::vector<SDOperand> &UnorderedChains) {
3406 // If this is the entry block, emit arguments.
3407 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003408 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003409 SDOperand OldRoot = SDL.DAG.getRoot();
3410 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003411
Chris Lattner6871b232005-10-30 19:42:35 +00003412 unsigned a = 0;
3413 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3414 AI != E; ++AI, ++a)
3415 if (!AI->use_empty()) {
3416 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003417
Chris Lattner6871b232005-10-30 19:42:35 +00003418 // If this argument is live outside of the entry block, insert a copy from
3419 // whereever we got it to the vreg that other BB's will reference it as.
3420 if (FuncInfo.ValueMap.count(AI)) {
3421 SDOperand Copy =
3422 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3423 UnorderedChains.push_back(Copy);
3424 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003425 }
Chris Lattner6871b232005-10-30 19:42:35 +00003426
Chris Lattner6871b232005-10-30 19:42:35 +00003427 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003428 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003429 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003430}
3431
Chris Lattner7a60d912005-01-07 07:47:53 +00003432void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3433 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003434 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003435 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003436
3437 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003438
Chris Lattner6871b232005-10-30 19:42:35 +00003439 // Lower any arguments needed in this block if this is the entry block.
3440 if (LLVMBB == &LLVMBB->getParent()->front())
3441 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003442
3443 BB = FuncInfo.MBBMap[LLVMBB];
3444 SDL.setCurrentBasicBlock(BB);
3445
3446 // Lower all of the non-terminator instructions.
3447 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3448 I != E; ++I)
3449 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003450
Chris Lattner7a60d912005-01-07 07:47:53 +00003451 // Ensure that all instructions which are used outside of their defining
3452 // blocks are available as virtual registers.
3453 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003454 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003455 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003456 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003457 UnorderedChains.push_back(
3458 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003459 }
3460
3461 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3462 // ensure constants are generated when needed. Remember the virtual registers
3463 // that need to be added to the Machine PHI nodes as input. We cannot just
3464 // directly add them, because expansion might result in multiple MBB's for one
3465 // BB. As such, the start of the BB might correspond to a different MBB than
3466 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003467 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003468
3469 // Emit constants only once even if used by multiple PHI nodes.
3470 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003471
Chris Lattner7a60d912005-01-07 07:47:53 +00003472 // Check successor nodes PHI nodes that expect a constant to be available from
3473 // this block.
3474 TerminatorInst *TI = LLVMBB->getTerminator();
3475 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3476 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003477 if (!isa<PHINode>(SuccBB->begin())) continue;
3478
Chris Lattner7a60d912005-01-07 07:47:53 +00003479 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3480 PHINode *PN;
3481
3482 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3483 // nodes and Machine PHI nodes, but the incoming operands have not been
3484 // emitted yet.
3485 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003486 (PN = dyn_cast<PHINode>(I)); ++I)
3487 if (!PN->use_empty()) {
3488 unsigned Reg;
3489 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3490 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3491 unsigned &RegOut = ConstantsOut[C];
3492 if (RegOut == 0) {
3493 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003494 UnorderedChains.push_back(
3495 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003496 }
3497 Reg = RegOut;
3498 } else {
3499 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003500 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003501 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003502 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3503 "Didn't codegen value into a register!??");
3504 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003505 UnorderedChains.push_back(
3506 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003507 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003508 }
Misha Brukman835702a2005-04-21 22:36:52 +00003509
Chris Lattner8ea875f2005-01-07 21:34:19 +00003510 // Remember that this register needs to added to the machine PHI node as
3511 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003512 MVT::ValueType VT = TLI.getValueType(PN->getType());
3513 unsigned NumElements;
3514 if (VT != MVT::Vector)
3515 NumElements = TLI.getNumElements(VT);
3516 else {
3517 MVT::ValueType VT1,VT2;
3518 NumElements =
3519 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3520 VT1, VT2);
3521 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003522 for (unsigned i = 0, e = NumElements; i != e; ++i)
3523 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003524 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003525 }
3526 ConstantsOut.clear();
3527
Chris Lattner718b5c22005-01-13 17:59:43 +00003528 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003529 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003530 SDOperand Root = SDL.getRoot();
3531 if (Root.getOpcode() != ISD::EntryToken) {
3532 unsigned i = 0, e = UnorderedChains.size();
3533 for (; i != e; ++i) {
3534 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3535 if (UnorderedChains[i].Val->getOperand(0) == Root)
3536 break; // Don't add the root if we already indirectly depend on it.
3537 }
3538
3539 if (i == e)
3540 UnorderedChains.push_back(Root);
3541 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003542 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3543 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003544 }
3545
Chris Lattner7a60d912005-01-07 07:47:53 +00003546 // Lower the terminator after the copies are emitted.
3547 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003548
Nate Begemaned728c12006-03-27 01:32:24 +00003549 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003550 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003551 SwitchCases.clear();
3552 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003553 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003554
Chris Lattner4108bb02005-01-17 19:43:36 +00003555 // Make sure the root of the DAG is up-to-date.
3556 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003557}
3558
Nate Begemaned728c12006-03-27 01:32:24 +00003559void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003560 // Get alias analysis for load/store combining.
3561 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3562
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003563 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003564 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003565
Chris Lattner7a60d912005-01-07 07:47:53 +00003566 DEBUG(std::cerr << "Lowered selection DAG:\n");
3567 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003568
Chris Lattner7a60d912005-01-07 07:47:53 +00003569 // Second step, hack on the DAG until it only uses operations and types that
3570 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003571 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003572
Chris Lattner7a60d912005-01-07 07:47:53 +00003573 DEBUG(std::cerr << "Legalized selection DAG:\n");
3574 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003575
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003576 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003577 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003578
Evan Cheng739a6a42006-01-21 02:32:06 +00003579 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003580
Chris Lattner5ca31d92005-03-30 01:10:47 +00003581 // Third, instruction select all of the operations to machine code, adding the
3582 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003583 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003584
Chris Lattner7a60d912005-01-07 07:47:53 +00003585 DEBUG(std::cerr << "Selected machine code:\n");
3586 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003587}
Chris Lattner7a60d912005-01-07 07:47:53 +00003588
Nate Begemaned728c12006-03-27 01:32:24 +00003589void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3590 FunctionLoweringInfo &FuncInfo) {
3591 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3592 {
3593 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3594 CurDAG = &DAG;
3595
3596 // First step, lower LLVM code to some DAG. This DAG may use operations and
3597 // types that are not supported by the target.
3598 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3599
3600 // Second step, emit the lowered DAG as machine code.
3601 CodeGenAndEmitDAG(DAG);
3602 }
3603
Chris Lattner5ca31d92005-03-30 01:10:47 +00003604 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003605 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003606 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003607 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3608 MachineInstr *PHI = PHINodesToUpdate[i].first;
3609 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3610 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003611 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003612 PHI->addMachineBasicBlockOperand(BB);
3613 }
3614 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003615 }
Nate Begemaned728c12006-03-27 01:32:24 +00003616
Nate Begeman866b4b42006-04-23 06:26:20 +00003617 // If the JumpTable record is filled in, then we need to emit a jump table.
3618 // Updating the PHI nodes is tricky in this case, since we need to determine
3619 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003620 if (JT.Reg) {
3621 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3622 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3623 CurDAG = &SDAG;
3624 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003625 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003626 // Set the current basic block to the mbb we wish to insert the code into
3627 BB = JT.MBB;
3628 SDL.setCurrentBasicBlock(BB);
3629 // Emit the code
3630 SDL.visitJumpTable(JT);
3631 SDAG.setRoot(SDL.getRoot());
3632 CodeGenAndEmitDAG(SDAG);
3633 // Update PHI Nodes
3634 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3635 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3636 MachineBasicBlock *PHIBB = PHI->getParent();
3637 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3638 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003639 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003640 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003641 PHI->addMachineBasicBlockOperand(RangeBB);
3642 }
3643 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003644 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003645 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003646 }
3647 }
3648 return;
3649 }
3650
Nate Begemaned728c12006-03-27 01:32:24 +00003651 // If we generated any switch lowering information, build and codegen any
3652 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003653 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003654 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3655 CurDAG = &SDAG;
3656 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003657
Nate Begemaned728c12006-03-27 01:32:24 +00003658 // Set the current basic block to the mbb we wish to insert the code into
3659 BB = SwitchCases[i].ThisBB;
3660 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003661
Nate Begemaned728c12006-03-27 01:32:24 +00003662 // Emit the code
3663 SDL.visitSwitchCase(SwitchCases[i]);
3664 SDAG.setRoot(SDL.getRoot());
3665 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003666
3667 // Handle any PHI nodes in successors of this chunk, as if we were coming
3668 // from the original BB before switch expansion. Note that PHI nodes can
3669 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3670 // handle them the right number of times.
3671 while ((BB = SwitchCases[i].LHSBB)) { // Handle LHS and RHS.
3672 for (MachineBasicBlock::iterator Phi = BB->begin();
3673 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3674 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3675 for (unsigned pn = 0; ; ++pn) {
3676 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3677 if (PHINodesToUpdate[pn].first == Phi) {
3678 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3679 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3680 break;
3681 }
3682 }
Nate Begemaned728c12006-03-27 01:32:24 +00003683 }
Chris Lattner707339a52006-09-07 01:59:34 +00003684
3685 // Don't process RHS if same block as LHS.
3686 if (BB == SwitchCases[i].RHSBB)
3687 SwitchCases[i].RHSBB = 0;
3688
3689 // If we haven't handled the RHS, do so now. Otherwise, we're done.
3690 SwitchCases[i].LHSBB = SwitchCases[i].RHSBB;
3691 SwitchCases[i].RHSBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003692 }
Chris Lattner707339a52006-09-07 01:59:34 +00003693 assert(SwitchCases[i].LHSBB == 0 && SwitchCases[i].RHSBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003694 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003695}
Evan Cheng739a6a42006-01-21 02:32:06 +00003696
Jim Laskey95eda5b2006-08-01 14:21:23 +00003697
Evan Cheng739a6a42006-01-21 02:32:06 +00003698//===----------------------------------------------------------------------===//
3699/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3700/// target node in the graph.
3701void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3702 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003703
Jim Laskey29e635d2006-08-02 12:30:23 +00003704 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003705
3706 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003707 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003708 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003709 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003710
Jim Laskey03593f72006-08-01 18:29:48 +00003711 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003712 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003713 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003714}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003715
Chris Lattner47639db2006-03-06 00:22:00 +00003716
Jim Laskey03593f72006-08-01 18:29:48 +00003717HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3718 return new HazardRecognizer();
3719}
3720
Chris Lattner6df34962006-10-11 03:58:02 +00003721//===----------------------------------------------------------------------===//
3722// Helper functions used by the generated instruction selector.
3723//===----------------------------------------------------------------------===//
3724// Calls to these methods are generated by tblgen.
3725
3726/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3727/// the dag combiner simplified the 255, we still want to match. RHS is the
3728/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3729/// specified in the .td file (e.g. 255).
3730bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3731 int64_t DesiredMaskS) {
3732 uint64_t ActualMask = RHS->getValue();
3733 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3734
3735 // If the actual mask exactly matches, success!
3736 if (ActualMask == DesiredMask)
3737 return true;
3738
3739 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3740 if (ActualMask & ~DesiredMask)
3741 return false;
3742
3743 // Otherwise, the DAG Combiner may have proven that the value coming in is
3744 // either already zero or is not demanded. Check for known zero input bits.
3745 uint64_t NeededMask = DesiredMask & ~ActualMask;
3746 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3747 return true;
3748
3749 // TODO: check to see if missing bits are just not demanded.
3750
3751 // Otherwise, this pattern doesn't match.
3752 return false;
3753}
3754
3755/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3756/// the dag combiner simplified the 255, we still want to match. RHS is the
3757/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3758/// specified in the .td file (e.g. 255).
3759bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3760 int64_t DesiredMaskS) {
3761 uint64_t ActualMask = RHS->getValue();
3762 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3763
3764 // If the actual mask exactly matches, success!
3765 if (ActualMask == DesiredMask)
3766 return true;
3767
3768 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3769 if (ActualMask & ~DesiredMask)
3770 return false;
3771
3772 // Otherwise, the DAG Combiner may have proven that the value coming in is
3773 // either already zero or is not demanded. Check for known zero input bits.
3774 uint64_t NeededMask = DesiredMask & ~ActualMask;
3775
3776 uint64_t KnownZero, KnownOne;
3777 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
3778
3779 // If all the missing bits in the or are already known to be set, match!
3780 if ((NeededMask & KnownOne) == NeededMask)
3781 return true;
3782
3783 // TODO: check to see if missing bits are just not demanded.
3784
3785 // Otherwise, this pattern doesn't match.
3786 return false;
3787}
3788
Jim Laskey03593f72006-08-01 18:29:48 +00003789
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003790/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3791/// by tblgen. Others should not call it.
3792void SelectionDAGISel::
3793SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3794 std::vector<SDOperand> InOps;
3795 std::swap(InOps, Ops);
3796
3797 Ops.push_back(InOps[0]); // input chain.
3798 Ops.push_back(InOps[1]); // input asm string.
3799
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003800 unsigned i = 2, e = InOps.size();
3801 if (InOps[e-1].getValueType() == MVT::Flag)
3802 --e; // Don't process a flag operand if it is here.
3803
3804 while (i != e) {
3805 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3806 if ((Flags & 7) != 4 /*MEM*/) {
3807 // Just skip over this operand, copying the operands verbatim.
3808 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3809 i += (Flags >> 3) + 1;
3810 } else {
3811 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3812 // Otherwise, this is a memory operand. Ask the target to select it.
3813 std::vector<SDOperand> SelOps;
3814 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3815 std::cerr << "Could not match memory address. Inline asm failure!\n";
3816 exit(1);
3817 }
3818
3819 // Add this to the output node.
3820 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3821 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3822 i += 2;
3823 }
3824 }
3825
3826 // Add the flag input back if present.
3827 if (e != InOps.size())
3828 Ops.push_back(InOps.back());
3829}