blob: f953a74d9d21415ad669d2fd3f6449d04e4fe251 [file] [log] [blame]
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "SelectionDAGBuild.h"
16#include "llvm/ADT/BitVector.h"
Dan Gohman5b229802008-09-04 20:49:27 +000017#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Constants.h"
Dan Gohman98ca4f22009-08-05 01:29:28 +000020#include "llvm/Constants.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000021#include "llvm/CallingConv.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/InlineAsm.h"
26#include "llvm/Instructions.h"
27#include "llvm/Intrinsics.h"
28#include "llvm/IntrinsicInst.h"
Devang Patel53bb5c92009-11-10 23:06:00 +000029#include "llvm/LLVMContext.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000030#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000031#include "llvm/CodeGen/FastISel.h"
32#include "llvm/CodeGen/GCStrategy.h"
33#include "llvm/CodeGen/GCMetadata.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
37#include "llvm/CodeGen/MachineJumpTableInfo.h"
38#include "llvm/CodeGen/MachineModuleInfo.h"
39#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000040#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000041#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000042#include "llvm/CodeGen/DwarfWriter.h"
43#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000044#include "llvm/Target/TargetRegisterInfo.h"
45#include "llvm/Target/TargetData.h"
46#include "llvm/Target/TargetFrameInfo.h"
47#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000048#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000049#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000050#include "llvm/Target/TargetOptions.h"
51#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000052#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000056#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000057#include <algorithm>
58using namespace llvm;
59
Dale Johannesen601d3c02008-09-05 01:48:15 +000060/// LimitFloatPrecision - Generate low-precision inline sequences for
61/// some float libcalls (6, 8 or 12 bits).
62static unsigned LimitFloatPrecision;
63
64static cl::opt<unsigned, true>
65LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
69 cl::init(0));
70
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000071/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000072/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000073/// the linearized index of the start of the member.
74///
75static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
76 const unsigned *Indices,
77 const unsigned *IndicesEnd,
78 unsigned CurIndex = 0) {
79 // Base case: We're done.
80 if (Indices && Indices == IndicesEnd)
81 return CurIndex;
82
83 // Given a struct type, recursively traverse the elements.
84 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
85 for (StructType::element_iterator EB = STy->element_begin(),
86 EI = EB,
87 EE = STy->element_end();
88 EI != EE; ++EI) {
89 if (Indices && *Indices == unsigned(EI - EB))
90 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
91 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
92 }
Dan Gohman2c91d102009-01-06 22:53:52 +000093 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000094 }
95 // Given an array type, recursively traverse the elements.
96 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
97 const Type *EltTy = ATy->getElementType();
98 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
99 if (Indices && *Indices == i)
100 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
101 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
102 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000103 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000104 }
105 // We haven't found the type we're looking for, so keep searching.
106 return CurIndex + 1;
107}
108
109/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
Owen Andersone50ed302009-08-10 22:56:29 +0000110/// EVTs that represent all the individual underlying
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000111/// non-aggregate types that comprise it.
112///
113/// If Offsets is non-null, it points to a vector to be filled in
114/// with the in-memory offsets of each of the individual values.
115///
116static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
Owen Andersone50ed302009-08-10 22:56:29 +0000117 SmallVectorImpl<EVT> &ValueVTs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000118 SmallVectorImpl<uint64_t> *Offsets = 0,
119 uint64_t StartingOffset = 0) {
120 // Given a struct type, recursively traverse the elements.
121 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
122 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
123 for (StructType::element_iterator EB = STy->element_begin(),
124 EI = EB,
125 EE = STy->element_end();
126 EI != EE; ++EI)
127 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
128 StartingOffset + SL->getElementOffset(EI - EB));
129 return;
130 }
131 // Given an array type, recursively traverse the elements.
132 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
133 const Type *EltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000134 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000135 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
136 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
137 StartingOffset + i * EltSize);
138 return;
139 }
Dan Gohman5e5558b2009-04-23 22:50:03 +0000140 // Interpret void as zero return values.
Owen Anderson1d0be152009-08-13 21:58:54 +0000141 if (Ty == Type::getVoidTy(Ty->getContext()))
Dan Gohman5e5558b2009-04-23 22:50:03 +0000142 return;
Owen Andersone50ed302009-08-10 22:56:29 +0000143 // Base case: we can get an EVT for this LLVM IR type.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000144 ValueVTs.push_back(TLI.getValueType(Ty));
145 if (Offsets)
146 Offsets->push_back(StartingOffset);
147}
148
Dan Gohman2a7c6712008-09-03 23:18:39 +0000149namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000150 /// RegsForValue - This struct represents the registers (physical or virtual)
151 /// that a particular set of values is assigned, and the type information about
152 /// the value. The most common situation is to represent one value at a time,
153 /// but struct or array values are handled element-wise as multiple values.
154 /// The splitting of aggregates is performed recursively, so that we never
155 /// have aggregate-typed registers. The values at this point do not necessarily
156 /// have legal types, so each value may require one or more registers of some
157 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000158 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000159 struct VISIBILITY_HIDDEN RegsForValue {
160 /// TLI - The TargetLowering object.
161 ///
162 const TargetLowering *TLI;
163
164 /// ValueVTs - The value types of the values, which may not be legal, and
165 /// may need be promoted or synthesized from one or more registers.
166 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000167 SmallVector<EVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000168
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000169 /// RegVTs - The value types of the registers. This is the same size as
170 /// ValueVTs and it records, for each value, what the type of the assigned
171 /// register or registers are. (Individual values are never synthesized
172 /// from more than one type of register.)
173 ///
174 /// With virtual registers, the contents of RegVTs is redundant with TLI's
175 /// getRegisterType member function, however when with physical registers
176 /// it is necessary to have a separate record of the types.
177 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000178 SmallVector<EVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000179
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000180 /// Regs - This list holds the registers assigned to the values.
181 /// Each legal or promoted value requires one register, and each
182 /// expanded value requires multiple registers.
183 ///
184 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000185
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000186 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000187
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000188 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000189 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000190 EVT regvt, EVT valuevt)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000191 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000193 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000194 const SmallVector<EVT, 4> &regvts,
195 const SmallVector<EVT, 4> &valuevts)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000196 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Owen Anderson23b9b192009-08-12 00:36:31 +0000197 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000198 unsigned Reg, const Type *Ty) : TLI(&tli) {
199 ComputeValueVTs(tli, Ty, ValueVTs);
200
201 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000202 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000203 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
204 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000205 for (unsigned i = 0; i != NumRegs; ++i)
206 Regs.push_back(Reg + i);
207 RegVTs.push_back(RegisterVT);
208 Reg += NumRegs;
209 }
210 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000212 /// append - Add the specified values to this one.
213 void append(const RegsForValue &RHS) {
214 TLI = RHS.TLI;
215 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
216 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
217 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
218 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000219
220
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000222 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000223 /// Chain/Flag as the input and updates them for the output Chain/Flag.
224 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000225 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000226 SDValue &Chain, SDValue *Flag) const;
227
228 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 /// Chain/Flag as the input and updates them for the output Chain/Flag.
231 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000232 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000233 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000234
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000235 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000236 /// operand list. This adds the code marker, matching input operand index
237 /// (if applicable), and includes the number of values added into it.
238 void AddInlineAsmOperands(unsigned Code,
239 bool HasMatching, unsigned MatchingIdx,
240 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000241 };
242}
243
244/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000245/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000246/// switch or atomic instruction, which may expand to multiple basic blocks.
247static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
248 if (isa<PHINode>(I)) return true;
249 BasicBlock *BB = I->getParent();
250 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Dan Gohman8e5c0da2009-04-09 02:33:36 +0000251 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000252 return true;
253 return false;
254}
255
256/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
257/// entry block, return true. This includes arguments used by switches, since
258/// the switch may expand into multiple basic blocks.
259static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
260 // With FastISel active, we may be splitting blocks, so force creation
261 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000262 // Don't force virtual registers for byval arguments though, because
263 // fast-isel can't handle those in all cases.
264 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000265 return A->use_empty();
266
267 BasicBlock *Entry = A->getParent()->begin();
268 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
269 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
270 return false; // Use not in entry block.
271 return true;
272}
273
274FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
275 : TLI(tli) {
276}
277
278void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000279 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000280 bool EnableFastISel) {
281 Fn = &fn;
282 MF = &mf;
283 RegInfo = &MF->getRegInfo();
284
285 // Create a vreg for each argument register that is not dead and is used
286 // outside of the entry block for the function.
287 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
288 AI != E; ++AI)
289 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
290 InitializeRegForValue(AI);
291
292 // Initialize the mapping of values to registers. This is only set up for
293 // instruction values that are used outside of the block that defines
294 // them.
295 Function::iterator BB = Fn->begin(), EB = Fn->end();
296 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
297 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
298 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
299 const Type *Ty = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000300 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000301 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000302 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
303 AI->getAlignment());
304
305 TySize *= CUI->getZExtValue(); // Get total allocated size.
306 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
307 StaticAllocaMap[AI] =
David Greene3f2bf852009-11-12 20:49:22 +0000308 MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000309 }
310
311 for (; BB != EB; ++BB)
312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
313 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
314 if (!isa<AllocaInst>(I) ||
315 !StaticAllocaMap.count(cast<AllocaInst>(I)))
316 InitializeRegForValue(I);
317
318 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
319 // also creates the initial PHI MachineInstrs, though none of the input
320 // operands are populated.
321 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
322 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
323 MBBMap[BB] = MBB;
324 MF->push_back(MBB);
325
Dan Gohman8c2b5252009-10-30 01:27:03 +0000326 // Transfer the address-taken flag. This is necessary because there could
327 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
328 // the first one should be marked.
329 if (BB->hasAddressTaken())
330 MBB->setHasAddressTaken();
331
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000332 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
333 // appropriate.
334 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000335 DebugLoc DL;
336 for (BasicBlock::iterator
337 I = BB->begin(), E = BB->end(); I != E; ++I) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000338
339 PN = dyn_cast<PHINode>(I);
340 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000341
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000342 unsigned PHIReg = ValueMap[PN];
343 assert(PHIReg && "PHI node does not have an assigned virtual register!");
344
Owen Andersone50ed302009-08-10 22:56:29 +0000345 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000346 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
347 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +0000348 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +0000349 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000350 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000351 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000352 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000353 PHIReg += NumRegisters;
354 }
355 }
356 }
357}
358
Owen Andersone50ed302009-08-10 22:56:29 +0000359unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000360 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
361}
362
363/// CreateRegForValue - Allocate the appropriate number of virtual registers of
364/// the correctly promoted or expanded types. Assign these registers
365/// consecutive vreg numbers and return the first assigned number.
366///
367/// In the case that the given value has struct or array type, this function
368/// will assign registers for each member or element.
369///
370unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Owen Andersone50ed302009-08-10 22:56:29 +0000371 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000372 ComputeValueVTs(TLI, V->getType(), ValueVTs);
373
374 unsigned FirstReg = 0;
375 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000376 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000377 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000378
Owen Anderson23b9b192009-08-12 00:36:31 +0000379 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000380 for (unsigned i = 0; i != NumRegs; ++i) {
381 unsigned R = MakeReg(RegisterVT);
382 if (!FirstReg) FirstReg = R;
383 }
384 }
385 return FirstReg;
386}
387
388/// getCopyFromParts - Create a value that contains the specified legal parts
389/// combined into the value they represent. If the parts combine to a type
390/// larger then ValueVT then AssertOp can be used to specify whether the extra
391/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
392/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000393static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
394 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000395 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000396 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000397 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000399 SDValue Val = Parts[0];
400
401 if (NumParts > 1) {
402 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000403 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000404 unsigned PartBits = PartVT.getSizeInBits();
405 unsigned ValueBits = ValueVT.getSizeInBits();
406
407 // Assemble the power of 2 part.
408 unsigned RoundParts = NumParts & (NumParts - 1) ?
409 1 << Log2_32(NumParts) : NumParts;
410 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000411 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000412 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000413 SDValue Lo, Hi;
414
Owen Anderson23b9b192009-08-12 00:36:31 +0000415 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000417 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000418 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
419 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000420 PartVT, HalfVT);
421 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000422 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
423 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000424 }
425 if (TLI.isBigEndian())
426 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000427 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000428
429 if (RoundParts < NumParts) {
430 // Assemble the trailing non-power-of-2 part.
431 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000432 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000433 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000434 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000435
436 // Combine the round and odd parts.
437 Lo = Val;
438 if (TLI.isBigEndian())
439 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000440 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000441 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
442 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000444 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000445 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
446 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000447 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000448 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000449 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000450 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000451 unsigned NumIntermediates;
452 unsigned NumRegs =
Owen Anderson23b9b192009-08-12 00:36:31 +0000453 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
454 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000455 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
456 NumParts = NumRegs; // Silence a compiler warning.
457 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
458 assert(RegisterVT == Parts[0].getValueType() &&
459 "Part type doesn't match part!");
460
461 // Assemble the parts into intermediate operands.
462 SmallVector<SDValue, 8> Ops(NumIntermediates);
463 if (NumIntermediates == NumParts) {
464 // If the register was not expanded, truncate or copy the value,
465 // as appropriate.
466 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000467 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000468 PartVT, IntermediateVT);
469 } else if (NumParts > 0) {
470 // If the intermediate type was expanded, build the intermediate operands
471 // from the parts.
472 assert(NumParts % NumIntermediates == 0 &&
473 "Must expand into a divisible number of parts!");
474 unsigned Factor = NumParts / NumIntermediates;
475 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000476 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000477 PartVT, IntermediateVT);
478 }
479
480 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
481 // operands.
482 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000483 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000484 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000485 } else if (PartVT.isFloatingPoint()) {
486 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000487 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000488 "Unexpected split");
489 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000490 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
491 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000492 if (TLI.isBigEndian())
493 std::swap(Lo, Hi);
494 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
495 } else {
496 // FP split into integer parts (soft fp)
497 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
498 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000499 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Eli Friedman2ac8b322009-05-20 06:02:09 +0000500 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000501 }
502 }
503
504 // There is now one part, held in Val. Correct it to match ValueVT.
505 PartVT = Val.getValueType();
506
507 if (PartVT == ValueVT)
508 return Val;
509
510 if (PartVT.isVector()) {
511 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000512 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000513 }
514
515 if (ValueVT.isVector()) {
516 assert(ValueVT.getVectorElementType() == PartVT &&
517 ValueVT.getVectorNumElements() == 1 &&
518 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000519 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000520 }
521
522 if (PartVT.isInteger() &&
523 ValueVT.isInteger()) {
524 if (ValueVT.bitsLT(PartVT)) {
525 // For a truncate, see if we have any information to
526 // indicate whether the truncated bits will always be
527 // zero or sign-extension.
528 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000529 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000530 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000531 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000532 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000533 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000534 }
535 }
536
537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
538 if (ValueVT.bitsLT(Val.getValueType()))
539 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000540 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000541 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000542 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000543 }
544
545 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000546 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000547
Torok Edwinc23197a2009-07-14 16:55:14 +0000548 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000549 return SDValue();
550}
551
552/// getCopyToParts - Create a series of nodes that contain the specified value
553/// split into legal parts. If the parts contain more bits than Val, then, for
554/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000555static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Owen Andersone50ed302009-08-10 22:56:29 +0000556 SDValue *Parts, unsigned NumParts, EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000557 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000559 EVT PtrVT = TLI.getPointerTy();
560 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000561 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000562 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000563 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
564
565 if (!NumParts)
566 return;
567
568 if (!ValueVT.isVector()) {
569 if (PartVT == ValueVT) {
570 assert(NumParts == 1 && "No-op copy with multiple parts!");
571 Parts[0] = Val;
572 return;
573 }
574
575 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
576 // If the parts cover more bits than the value has, promote the value.
577 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
578 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000579 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000580 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000581 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000582 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000583 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000584 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000585 }
586 } else if (PartBits == ValueVT.getSizeInBits()) {
587 // Different types of the same size.
588 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000589 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000590 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
591 // If the parts cover less bits than value has, truncate the value.
592 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000593 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000594 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000595 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000596 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000597 }
598 }
599
600 // The value may have changed - recompute ValueVT.
601 ValueVT = Val.getValueType();
602 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
603 "Failed to tile the value with PartVT!");
604
605 if (NumParts == 1) {
606 assert(PartVT == ValueVT && "Type conversion failed!");
607 Parts[0] = Val;
608 return;
609 }
610
611 // Expand the value into multiple parts.
612 if (NumParts & (NumParts - 1)) {
613 // The number of parts is not a power of 2. Split off and copy the tail.
614 assert(PartVT.isInteger() && ValueVT.isInteger() &&
615 "Do not know what to expand to!");
616 unsigned RoundParts = 1 << Log2_32(NumParts);
617 unsigned RoundBits = RoundParts * PartBits;
618 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000619 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000620 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000621 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000622 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000623 if (TLI.isBigEndian())
624 // The odd parts were reversed by getCopyToParts - unreverse them.
625 std::reverse(Parts + RoundParts, Parts + NumParts);
626 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000627 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000628 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000629 }
630
631 // The number of parts is a power of 2. Repeatedly bisect the value using
632 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000633 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson23b9b192009-08-12 00:36:31 +0000634 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000635 Val);
636 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
637 for (unsigned i = 0; i < NumParts; i += StepSize) {
638 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000639 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000640 SDValue &Part0 = Parts[i];
641 SDValue &Part1 = Parts[i+StepSize/2];
642
Scott Michelfdc40a02009-02-17 22:15:04 +0000643 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000644 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000645 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000646 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000647 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000648 DAG.getConstant(0, PtrVT));
649
650 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000651 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000652 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000653 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000654 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 }
656 }
657 }
658
659 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000660 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000661
662 return;
663 }
664
665 // Vector ValueVT.
666 if (NumParts == 1) {
667 if (PartVT != ValueVT) {
668 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000669 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000670 } else {
671 assert(ValueVT.getVectorElementType() == PartVT &&
672 ValueVT.getVectorNumElements() == 1 &&
673 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000674 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000675 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000676 DAG.getConstant(0, PtrVT));
677 }
678 }
679
680 Parts[0] = Val;
681 return;
682 }
683
684 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000685 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000686 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000687 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
688 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000689 unsigned NumElements = ValueVT.getVectorNumElements();
690
691 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692 NumParts = NumRegs; // Silence a compiler warning.
693 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
694
695 // Split the vector into intermediate operands.
696 SmallVector<SDValue, 8> Ops(NumIntermediates);
697 for (unsigned i = 0; i != NumIntermediates; ++i)
698 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000699 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000700 IntermediateVT, Val,
701 DAG.getConstant(i * (NumElements / NumIntermediates),
702 PtrVT));
703 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000704 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000705 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000706 DAG.getConstant(i, PtrVT));
707
708 // Split the intermediate operands into legal parts.
709 if (NumParts == NumIntermediates) {
710 // If the register was not expanded, promote or copy the value,
711 // as appropriate.
712 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000713 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000714 } else if (NumParts > 0) {
715 // If the intermediate type was expanded, split each the value into
716 // legal parts.
717 assert(NumParts % NumIntermediates == 0 &&
718 "Must expand into a divisible number of parts!");
719 unsigned Factor = NumParts / NumIntermediates;
720 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000721 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000722 }
723}
724
725
726void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
727 AA = &aa;
728 GFI = gfi;
729 TD = DAG.getTarget().getTargetData();
730}
731
732/// clear - Clear out the curret SelectionDAG and the associated
733/// state and prepare this SelectionDAGLowering object to be used
734/// for a new block. This doesn't clear out information about
735/// additional blocks that are needed to complete switch lowering
736/// or PHI node updating; that information is cleared out as it is
737/// consumed.
738void SelectionDAGLowering::clear() {
739 NodeMap.clear();
740 PendingLoads.clear();
741 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000742 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000743 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000744 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000745 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000746}
747
748/// getRoot - Return the current virtual root of the Selection DAG,
749/// flushing any PendingLoad items. This must be done before emitting
750/// a store or any other node that may need to be ordered after any
751/// prior load instructions.
752///
753SDValue SelectionDAGLowering::getRoot() {
754 if (PendingLoads.empty())
755 return DAG.getRoot();
756
757 if (PendingLoads.size() == 1) {
758 SDValue Root = PendingLoads[0];
759 DAG.setRoot(Root);
760 PendingLoads.clear();
761 return Root;
762 }
763
764 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000765 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000766 &PendingLoads[0], PendingLoads.size());
767 PendingLoads.clear();
768 DAG.setRoot(Root);
769 return Root;
770}
771
772/// getControlRoot - Similar to getRoot, but instead of flushing all the
773/// PendingLoad items, flush all the PendingExports items. It is necessary
774/// to do this before emitting a terminator instruction.
775///
776SDValue SelectionDAGLowering::getControlRoot() {
777 SDValue Root = DAG.getRoot();
778
779 if (PendingExports.empty())
780 return Root;
781
782 // Turn all of the CopyToReg chains into one factored node.
783 if (Root.getOpcode() != ISD::EntryToken) {
784 unsigned i = 0, e = PendingExports.size();
785 for (; i != e; ++i) {
786 assert(PendingExports[i].getNode()->getNumOperands() > 1);
787 if (PendingExports[i].getNode()->getOperand(0) == Root)
788 break; // Don't add the root if we already indirectly depend on it.
789 }
790
791 if (i == e)
792 PendingExports.push_back(Root);
793 }
794
Owen Anderson825b72b2009-08-11 20:47:22 +0000795 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000796 &PendingExports[0],
797 PendingExports.size());
798 PendingExports.clear();
799 DAG.setRoot(Root);
800 return Root;
801}
802
803void SelectionDAGLowering::visit(Instruction &I) {
804 visit(I.getOpcode(), I);
805}
806
807void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
808 // Note: this doesn't use InstVisitor, because it has to work with
809 // ConstantExpr's in addition to instructions.
810 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000811 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000812 // Build the switch statement using the Instruction.def file.
813#define HANDLE_INST(NUM, OPCODE, CLASS) \
814 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
815#include "llvm/Instruction.def"
816 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000817}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000818
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000819SDValue SelectionDAGLowering::getValue(const Value *V) {
820 SDValue &N = NodeMap[V];
821 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000822
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000823 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000824 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000825
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000826 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000827 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000828
829 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
830 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000831
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000832 if (isa<ConstantPointerNull>(C))
833 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000834
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000835 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000836 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000837
Nate Begeman9008ca62009-04-27 18:41:29 +0000838 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000839 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000840
841 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
842 visit(CE->getOpcode(), *CE);
843 SDValue N1 = NodeMap[V];
844 assert(N1.getNode() && "visit didn't populate the ValueMap!");
845 return N1;
846 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000847
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000848 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
849 SmallVector<SDValue, 4> Constants;
850 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
851 OI != OE; ++OI) {
852 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000853 // If the operand is an empty aggregate, there are no values.
854 if (!Val) continue;
855 // Add each leaf value from the operand to the Constants list
856 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000857 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
858 Constants.push_back(SDValue(Val, i));
859 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000860 return DAG.getMergeValues(&Constants[0], Constants.size(),
861 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000862 }
863
864 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
865 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
866 "Unknown struct or array constant!");
867
Owen Andersone50ed302009-08-10 22:56:29 +0000868 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000869 ComputeValueVTs(TLI, C->getType(), ValueVTs);
870 unsigned NumElts = ValueVTs.size();
871 if (NumElts == 0)
872 return SDValue(); // empty struct
873 SmallVector<SDValue, 4> Constants(NumElts);
874 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000875 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000876 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000877 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000878 else if (EltVT.isFloatingPoint())
879 Constants[i] = DAG.getConstantFP(0, EltVT);
880 else
881 Constants[i] = DAG.getConstant(0, EltVT);
882 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000883 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000884 }
885
Dan Gohman8c2b5252009-10-30 01:27:03 +0000886 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +0000887 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +0000888
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000889 const VectorType *VecTy = cast<VectorType>(V->getType());
890 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000891
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000892 // Now that we know the number and type of the elements, get that number of
893 // elements into the Ops array based on what kind of constant it is.
894 SmallVector<SDValue, 16> Ops;
895 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
896 for (unsigned i = 0; i != NumElements; ++i)
897 Ops.push_back(getValue(CP->getOperand(i)));
898 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000899 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000900 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000901
902 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000903 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000904 Op = DAG.getConstantFP(0, EltVT);
905 else
906 Op = DAG.getConstant(0, EltVT);
907 Ops.assign(NumElements, Op);
908 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000909
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000911 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
912 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000913 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 // If this is a static alloca, generate it as the frameindex instead of
916 // computation.
917 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
918 DenseMap<const AllocaInst*, int>::iterator SI =
919 FuncInfo.StaticAllocaMap.find(AI);
920 if (SI != FuncInfo.StaticAllocaMap.end())
921 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
922 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000923
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000924 unsigned InReg = FuncInfo.ValueMap[V];
925 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000926
Owen Anderson23b9b192009-08-12 00:36:31 +0000927 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000929 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000930}
931
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000932/// Get the EVTs and ArgFlags collections that represent the return type
933/// of the given function. This does not require a DAG or a return value, and
934/// is suitable for use before any DAGs for the function are constructed.
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000935static void getReturnInfo(const Type* ReturnType,
936 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000937 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000938 TargetLowering &TLI,
939 SmallVectorImpl<uint64_t> *Offsets = 0) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000940 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000941 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000942 unsigned NumValues = ValueVTs.size();
943 if ( NumValues == 0 ) return;
944
945 for (unsigned j = 0, f = NumValues; j != f; ++j) {
946 EVT VT = ValueVTs[j];
947 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000948
949 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000950 ExtendKind = ISD::SIGN_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000951 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000952 ExtendKind = ISD::ZERO_EXTEND;
953
954 // FIXME: C calling convention requires the return type to be promoted to
955 // at least 32-bit. But this is not necessary for non-C calling
956 // conventions. The frontend should mark functions whose return values
957 // require promoting with signext or zeroext attributes.
958 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000959 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000960 if (VT.bitsLT(MinVT))
961 VT = MinVT;
962 }
963
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000964 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
965 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000966 // 'inreg' on function refers to return value
967 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000968 if (attr & Attribute::InReg)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000969 Flags.setInReg();
970
971 // Propagate extension type if any
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000972 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000973 Flags.setSExt();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000974 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000975 Flags.setZExt();
976
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000977 for (unsigned i = 0; i < NumParts; ++i) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000978 OutVTs.push_back(PartVT);
979 OutFlags.push_back(Flags);
980 }
981 }
982}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000983
984void SelectionDAGLowering::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000985 SDValue Chain = getControlRoot();
986 SmallVector<ISD::OutputArg, 8> Outs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000987 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
988
989 if (!FLI.CanLowerReturn) {
990 unsigned DemoteReg = FLI.DemoteRegister;
991 const Function *F = I.getParent()->getParent();
992
993 // Emit a store of the return value through the virtual register.
994 // Leave Outs empty so that LowerReturn won't try to load return
995 // registers the usual way.
996 SmallVector<EVT, 1> PtrValueVTs;
997 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
998 PtrValueVTs);
999
1000 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1001 SDValue RetOp = getValue(I.getOperand(0));
1002
Owen Andersone50ed302009-08-10 22:56:29 +00001003 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001004 SmallVector<uint64_t, 4> Offsets;
1005 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001006 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001007
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001008 SmallVector<SDValue, 4> Chains(NumValues);
1009 EVT PtrVT = PtrValueVTs[0];
1010 for (unsigned i = 0; i != NumValues; ++i)
1011 Chains[i] = DAG.getStore(Chain, getCurDebugLoc(),
1012 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1013 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
1014 DAG.getConstant(Offsets[i], PtrVT)),
1015 NULL, Offsets[i], false, 0);
1016 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1017 MVT::Other, &Chains[0], NumValues);
1018 }
1019 else {
1020 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1021 SmallVector<EVT, 4> ValueVTs;
1022 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1023 unsigned NumValues = ValueVTs.size();
1024 if (NumValues == 0) continue;
1025
1026 SDValue RetOp = getValue(I.getOperand(i));
1027 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1028 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001029
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001030 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001031
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001032 const Function *F = I.getParent()->getParent();
1033 if (F->paramHasAttr(0, Attribute::SExt))
1034 ExtendKind = ISD::SIGN_EXTEND;
1035 else if (F->paramHasAttr(0, Attribute::ZExt))
1036 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001037
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001038 // FIXME: C calling convention requires the return type to be promoted to
1039 // at least 32-bit. But this is not necessary for non-C calling
1040 // conventions. The frontend should mark functions whose return values
1041 // require promoting with signext or zeroext attributes.
1042 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1043 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
1044 if (VT.bitsLT(MinVT))
1045 VT = MinVT;
1046 }
1047
1048 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1049 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1050 SmallVector<SDValue, 4> Parts(NumParts);
1051 getCopyToParts(DAG, getCurDebugLoc(),
1052 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1053 &Parts[0], NumParts, PartVT, ExtendKind);
1054
1055 // 'inreg' on function refers to return value
1056 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1057 if (F->paramHasAttr(0, Attribute::InReg))
1058 Flags.setInReg();
1059
1060 // Propagate extension type if any
1061 if (F->paramHasAttr(0, Attribute::SExt))
1062 Flags.setSExt();
1063 else if (F->paramHasAttr(0, Attribute::ZExt))
1064 Flags.setZExt();
1065
1066 for (unsigned i = 0; i < NumParts; ++i)
1067 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +00001068 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001069 }
1070 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001071
1072 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001073 CallingConv::ID CallConv =
1074 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001075 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1076 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001077
1078 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001079 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001080 "LowerReturn didn't return a valid chain!");
1081
1082 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001083 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001084}
1085
Dan Gohmanad62f532009-04-23 23:13:24 +00001086/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1087/// created for it, emit nodes to copy the value into the virtual
1088/// registers.
1089void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1090 if (!V->use_empty()) {
1091 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1092 if (VMI != FuncInfo.ValueMap.end())
1093 CopyValueToVirtualRegister(V, VMI->second);
1094 }
1095}
1096
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001097/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1098/// the current basic block, add it to ValueMap now so that we'll get a
1099/// CopyTo/FromReg.
1100void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1101 // No need to export constants.
1102 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001103
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001104 // Already exported?
1105 if (FuncInfo.isExportedInst(V)) return;
1106
1107 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1108 CopyValueToVirtualRegister(V, Reg);
1109}
1110
1111bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1112 const BasicBlock *FromBB) {
1113 // The operands of the setcc have to be in this block. We don't know
1114 // how to export them from some other block.
1115 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1116 // Can export from current BB.
1117 if (VI->getParent() == FromBB)
1118 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001119
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001120 // Is already exported, noop.
1121 return FuncInfo.isExportedInst(V);
1122 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001123
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001124 // If this is an argument, we can export it if the BB is the entry block or
1125 // if it is already exported.
1126 if (isa<Argument>(V)) {
1127 if (FromBB == &FromBB->getParent()->getEntryBlock())
1128 return true;
1129
1130 // Otherwise, can only export this if it is already exported.
1131 return FuncInfo.isExportedInst(V);
1132 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001133
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001134 // Otherwise, constants can always be exported.
1135 return true;
1136}
1137
1138static bool InBlock(const Value *V, const BasicBlock *BB) {
1139 if (const Instruction *I = dyn_cast<Instruction>(V))
1140 return I->getParent() == BB;
1141 return true;
1142}
1143
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001144/// getFCmpCondCode - Return the ISD condition code corresponding to
1145/// the given LLVM IR floating-point condition code. This includes
1146/// consideration of global floating-point math flags.
1147///
1148static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1149 ISD::CondCode FPC, FOC;
1150 switch (Pred) {
1151 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1152 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1153 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1154 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1155 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1156 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1157 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1158 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1159 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1160 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1161 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1162 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1163 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1164 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1165 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1166 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1167 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001168 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001169 FOC = FPC = ISD::SETFALSE;
1170 break;
1171 }
1172 if (FiniteOnlyFPMath())
1173 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001174 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001175 return FPC;
1176}
1177
1178/// getICmpCondCode - Return the ISD condition code corresponding to
1179/// the given LLVM IR integer condition code.
1180///
1181static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1182 switch (Pred) {
1183 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1184 case ICmpInst::ICMP_NE: return ISD::SETNE;
1185 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1186 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1187 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1188 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1189 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1190 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1191 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1192 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1193 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001194 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001195 return ISD::SETNE;
1196 }
1197}
1198
Dan Gohmanc2277342008-10-17 21:16:08 +00001199/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1200/// This function emits a branch and is used at the leaves of an OR or an
1201/// AND operator tree.
1202///
1203void
1204SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1205 MachineBasicBlock *TBB,
1206 MachineBasicBlock *FBB,
1207 MachineBasicBlock *CurBB) {
1208 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001209
Dan Gohmanc2277342008-10-17 21:16:08 +00001210 // If the leaf of the tree is a comparison, merge the condition into
1211 // the caseblock.
1212 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1213 // The operands of the cmp have to be in this block. We don't know
1214 // how to export them from some other block. If this is the first block
1215 // of the sequence, no exporting is needed.
1216 if (CurBB == CurMBB ||
1217 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1218 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001219 ISD::CondCode Condition;
1220 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001221 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001222 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001223 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001224 } else {
1225 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001226 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001227 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001228
1229 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001230 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1231 SwitchCases.push_back(CB);
1232 return;
1233 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001234 }
1235
1236 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001237 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001238 NULL, TBB, FBB, CurBB);
1239 SwitchCases.push_back(CB);
1240}
1241
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001242/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001243void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1244 MachineBasicBlock *TBB,
1245 MachineBasicBlock *FBB,
1246 MachineBasicBlock *CurBB,
1247 unsigned Opc) {
1248 // If this node is not part of the or/and tree, emit it as a branch.
1249 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001250 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001251 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1252 BOp->getParent() != CurBB->getBasicBlock() ||
1253 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1254 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1255 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001256 return;
1257 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001258
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001259 // Create TmpBB after CurBB.
1260 MachineFunction::iterator BBI = CurBB;
1261 MachineFunction &MF = DAG.getMachineFunction();
1262 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1263 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001264
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001265 if (Opc == Instruction::Or) {
1266 // Codegen X | Y as:
1267 // jmp_if_X TBB
1268 // jmp TmpBB
1269 // TmpBB:
1270 // jmp_if_Y TBB
1271 // jmp FBB
1272 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001273
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001274 // Emit the LHS condition.
1275 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001276
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001277 // Emit the RHS condition into TmpBB.
1278 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1279 } else {
1280 assert(Opc == Instruction::And && "Unknown merge op!");
1281 // Codegen X & Y as:
1282 // jmp_if_X TmpBB
1283 // jmp FBB
1284 // TmpBB:
1285 // jmp_if_Y TBB
1286 // jmp FBB
1287 //
1288 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001289
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001290 // Emit the LHS condition.
1291 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001292
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001293 // Emit the RHS condition into TmpBB.
1294 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1295 }
1296}
1297
1298/// If the set of cases should be emitted as a series of branches, return true.
1299/// If we should emit this as a bunch of and/or'd together conditions, return
1300/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001301bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001302SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1303 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001305 // If this is two comparisons of the same values or'd or and'd together, they
1306 // will get folded into a single comparison, so don't emit two blocks.
1307 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1308 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1309 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1310 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1311 return false;
1312 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001313
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001314 return true;
1315}
1316
1317void SelectionDAGLowering::visitBr(BranchInst &I) {
1318 // Update machine-CFG edges.
1319 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1320
1321 // Figure out which block is immediately after the current one.
1322 MachineBasicBlock *NextBlock = 0;
1323 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001324 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 NextBlock = BBI;
1326
1327 if (I.isUnconditional()) {
1328 // Update machine-CFG edges.
1329 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001330
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001331 // If this is not a fall-through branch, emit the branch.
1332 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001333 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001334 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001335 DAG.getBasicBlock(Succ0MBB)));
1336 return;
1337 }
1338
1339 // If this condition is one of the special cases we handle, do special stuff
1340 // now.
1341 Value *CondVal = I.getCondition();
1342 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1343
1344 // If this is a series of conditions that are or'd or and'd together, emit
1345 // this as a sequence of branches instead of setcc's with and/or operations.
1346 // For example, instead of something like:
1347 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001348 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001349 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001350 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001351 // or C, F
1352 // jnz foo
1353 // Emit:
1354 // cmp A, B
1355 // je foo
1356 // cmp D, E
1357 // jle foo
1358 //
1359 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001360 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001361 (BOp->getOpcode() == Instruction::And ||
1362 BOp->getOpcode() == Instruction::Or)) {
1363 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1364 // If the compares in later blocks need to use values not currently
1365 // exported from this block, export them now. This block should always
1366 // be the first entry.
1367 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001368
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001369 // Allow some cases to be rejected.
1370 if (ShouldEmitAsBranches(SwitchCases)) {
1371 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1372 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1373 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1374 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001376 // Emit the branch for this block.
1377 visitSwitchCase(SwitchCases[0]);
1378 SwitchCases.erase(SwitchCases.begin());
1379 return;
1380 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001381
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001382 // Okay, we decided not to do this, remove any inserted MBB's and clear
1383 // SwitchCases.
1384 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001385 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001386
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387 SwitchCases.clear();
1388 }
1389 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001390
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001392 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001393 NULL, Succ0MBB, Succ1MBB, CurMBB);
1394 // Use visitSwitchCase to actually insert the fast branch sequence for this
1395 // cond branch.
1396 visitSwitchCase(CB);
1397}
1398
1399/// visitSwitchCase - Emits the necessary code to represent a single node in
1400/// the binary search tree resulting from lowering a switch instruction.
1401void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1402 SDValue Cond;
1403 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001404 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001405
1406 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407 if (CB.CmpMHS == NULL) {
1408 // Fold "(X == true)" to X and "(X == false)" to !X to
1409 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001410 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001411 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001412 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001413 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001414 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001415 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001416 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001417 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001418 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001419 } else {
1420 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1421
Anton Korobeynikov23218582008-12-23 22:25:27 +00001422 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1423 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001424
1425 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001426 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001427
1428 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001429 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001430 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001432 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001433 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001434 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001435 DAG.getConstant(High-Low, VT), ISD::SETULE);
1436 }
1437 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001439 // Update successor info
1440 CurMBB->addSuccessor(CB.TrueBB);
1441 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001443 // Set NextBlock to be the MBB immediately after the current one, if any.
1444 // This is used to avoid emitting unnecessary branches to the next block.
1445 MachineBasicBlock *NextBlock = 0;
1446 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001447 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001448 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001449
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001450 // If the lhs block is the next block, invert the condition so that we can
1451 // fall through to the lhs instead of the rhs block.
1452 if (CB.TrueBB == NextBlock) {
1453 std::swap(CB.TrueBB, CB.FalseBB);
1454 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001455 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001456 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001457 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001458 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001459 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001460
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461 // If the branch was constant folded, fix up the CFG.
1462 if (BrCond.getOpcode() == ISD::BR) {
1463 CurMBB->removeSuccessor(CB.FalseBB);
1464 DAG.setRoot(BrCond);
1465 } else {
1466 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001467 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001468 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001469
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001470 if (CB.FalseBB == NextBlock)
1471 DAG.setRoot(BrCond);
1472 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001473 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001474 DAG.getBasicBlock(CB.FalseBB)));
1475 }
1476}
1477
1478/// visitJumpTable - Emit JumpTable node in the current MBB
1479void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1480 // Emit the code for the jump table
1481 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001482 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001483 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1484 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001485 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001486 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001487 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001488 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489}
1490
1491/// visitJumpTableHeader - This function emits necessary code to produce index
1492/// in the JumpTable from switch case.
1493void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1494 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001495 // Subtract the lowest switch case value from the value being switched on and
1496 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001497 // difference between smallest and largest cases.
1498 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001499 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001500 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001501 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001502
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001503 // The SDNode we just created, which holds the value being switched on minus
1504 // the the smallest case value, needs to be copied to a virtual register so it
1505 // can be used as an index into the jump table in a subsequent basic block.
1506 // This value may be smaller or larger than the target's pointer type, and
1507 // therefore require extension or truncating.
Duncan Sands3a66a682009-10-13 21:04:12 +00001508 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001509
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001510 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001511 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1512 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 JT.Reg = JumpTableReg;
1514
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001515 // Emit the range check for the jump table, and branch to the default block
1516 // for the switch statement if the value being switched on exceeds the largest
1517 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001518 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1519 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001520 DAG.getConstant(JTH.Last-JTH.First,VT),
1521 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001522
1523 // Set NextBlock to be the MBB immediately after the current one, if any.
1524 // This is used to avoid emitting unnecessary branches to the next block.
1525 MachineBasicBlock *NextBlock = 0;
1526 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001527 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001528 NextBlock = BBI;
1529
Dale Johannesen66978ee2009-01-31 02:22:37 +00001530 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001531 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001532 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001533
1534 if (JT.MBB == NextBlock)
1535 DAG.setRoot(BrCond);
1536 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001537 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001538 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001539}
1540
1541/// visitBitTestHeader - This function emits necessary code to produce value
1542/// suitable for "bit tests"
1543void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1544 // Subtract the minimum value
1545 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001546 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001547 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001548 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001549
1550 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001551 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1552 TLI.getSetCCResultType(SUB.getValueType()),
1553 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001554 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001555
Duncan Sands3a66a682009-10-13 21:04:12 +00001556 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001557
Duncan Sands92abc622009-01-31 15:50:11 +00001558 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001559 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1560 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001561
1562 // Set NextBlock to be the MBB immediately after the current one, if any.
1563 // This is used to avoid emitting unnecessary branches to the next block.
1564 MachineBasicBlock *NextBlock = 0;
1565 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001566 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001567 NextBlock = BBI;
1568
1569 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1570
1571 CurMBB->addSuccessor(B.Default);
1572 CurMBB->addSuccessor(MBB);
1573
Dale Johannesen66978ee2009-01-31 02:22:37 +00001574 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001575 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001576 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001577
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001578 if (MBB == NextBlock)
1579 DAG.setRoot(BrRange);
1580 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001581 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001583}
1584
1585/// visitBitTestCase - this function produces one "bit test"
1586void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1587 unsigned Reg,
1588 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001589 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001590 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001591 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001592 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001593 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001594 DAG.getConstant(1, TLI.getPointerTy()),
1595 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001596
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001597 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001598 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001599 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001600 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001601 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1602 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001603 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001604 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001605
1606 CurMBB->addSuccessor(B.TargetBB);
1607 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001608
Dale Johannesen66978ee2009-01-31 02:22:37 +00001609 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001610 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001611 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612
1613 // Set NextBlock to be the MBB immediately after the current one, if any.
1614 // This is used to avoid emitting unnecessary branches to the next block.
1615 MachineBasicBlock *NextBlock = 0;
1616 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001617 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618 NextBlock = BBI;
1619
1620 if (NextMBB == NextBlock)
1621 DAG.setRoot(BrAnd);
1622 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001623 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001625}
1626
1627void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1628 // Retrieve successors.
1629 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1630 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1631
Gabor Greifb67e6b32009-01-15 11:10:44 +00001632 const Value *Callee(I.getCalledValue());
1633 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001634 visitInlineAsm(&I);
1635 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001636 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637
1638 // If the value of the invoke is used outside of its defining block, make it
1639 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001640 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001641
1642 // Update successor info
1643 CurMBB->addSuccessor(Return);
1644 CurMBB->addSuccessor(LandingPad);
1645
1646 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001647 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001648 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001649 DAG.getBasicBlock(Return)));
1650}
1651
1652void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1653}
1654
1655/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1656/// small case ranges).
1657bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1658 CaseRecVector& WorkList,
1659 Value* SV,
1660 MachineBasicBlock* Default) {
1661 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001662
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001663 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001664 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001665 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001666 return false;
1667
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001668 // Get the MachineFunction which holds the current MBB. This is used when
1669 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001670 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001671
1672 // Figure out which block is immediately after the current one.
1673 MachineBasicBlock *NextBlock = 0;
1674 MachineFunction::iterator BBI = CR.CaseBB;
1675
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001676 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001677 NextBlock = BBI;
1678
1679 // TODO: If any two of the cases has the same destination, and if one value
1680 // is the same as the other, but has one bit unset that the other has set,
1681 // use bit manipulation to do two compares at once. For example:
1682 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001683
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001684 // Rearrange the case blocks so that the last one falls through if possible.
1685 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1686 // The last case block won't fall through into 'NextBlock' if we emit the
1687 // branches in this order. See if rearranging a case value would help.
1688 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1689 if (I->BB == NextBlock) {
1690 std::swap(*I, BackCase);
1691 break;
1692 }
1693 }
1694 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696 // Create a CaseBlock record representing a conditional branch to
1697 // the Case's target mbb if the value being switched on SV is equal
1698 // to C.
1699 MachineBasicBlock *CurBlock = CR.CaseBB;
1700 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1701 MachineBasicBlock *FallThrough;
1702 if (I != E-1) {
1703 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1704 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001705
1706 // Put SV in a virtual register to make it available from the new blocks.
1707 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001708 } else {
1709 // If the last case doesn't match, go to the default block.
1710 FallThrough = Default;
1711 }
1712
1713 Value *RHS, *LHS, *MHS;
1714 ISD::CondCode CC;
1715 if (I->High == I->Low) {
1716 // This is just small small case range :) containing exactly 1 case
1717 CC = ISD::SETEQ;
1718 LHS = SV; RHS = I->High; MHS = NULL;
1719 } else {
1720 CC = ISD::SETLE;
1721 LHS = I->Low; MHS = SV; RHS = I->High;
1722 }
1723 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001725 // If emitting the first comparison, just call visitSwitchCase to emit the
1726 // code into the current block. Otherwise, push the CaseBlock onto the
1727 // vector to be later processed by SDISel, and insert the node's MBB
1728 // before the next MBB.
1729 if (CurBlock == CurMBB)
1730 visitSwitchCase(CB);
1731 else
1732 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001733
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001734 CurBlock = FallThrough;
1735 }
1736
1737 return true;
1738}
1739
1740static inline bool areJTsAllowed(const TargetLowering &TLI) {
1741 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001742 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1743 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001744}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001745
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001746static APInt ComputeRange(const APInt &First, const APInt &Last) {
1747 APInt LastExt(Last), FirstExt(First);
1748 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1749 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1750 return (LastExt - FirstExt + 1ULL);
1751}
1752
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001753/// handleJTSwitchCase - Emit jumptable for current switch case range
1754bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1755 CaseRecVector& WorkList,
1756 Value* SV,
1757 MachineBasicBlock* Default) {
1758 Case& FrontCase = *CR.Range.first;
1759 Case& BackCase = *(CR.Range.second-1);
1760
Chris Lattnere880efe2009-11-07 07:50:34 +00001761 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1762 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001763
Chris Lattnere880efe2009-11-07 07:50:34 +00001764 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001765 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1766 I!=E; ++I)
1767 TSize += I->size();
1768
Chris Lattnere880efe2009-11-07 07:50:34 +00001769 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001770 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001771
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001772 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001773 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001774 if (Density < 0.4)
1775 return false;
1776
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001777 DEBUG(errs() << "Lowering jump table\n"
1778 << "First entry: " << First << ". Last entry: " << Last << '\n'
1779 << "Range: " << Range
1780 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001781
1782 // Get the MachineFunction which holds the current MBB. This is used when
1783 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001784 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001785
1786 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001787 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001788 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001789
1790 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1791
1792 // Create a new basic block to hold the code for loading the address
1793 // of the jump table, and jumping to it. Update successor information;
1794 // we will either branch to the default case for the switch, or the jump
1795 // table.
1796 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1797 CurMF->insert(BBI, JumpTableBB);
1798 CR.CaseBB->addSuccessor(Default);
1799 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001800
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001801 // Build a vector of destination BBs, corresponding to each target
1802 // of the jump table. If the value of the jump table slot corresponds to
1803 // a case statement, push the case's BB onto the vector, otherwise, push
1804 // the default BB.
1805 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001806 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001807 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001808 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1809 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1810
1811 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001812 DestBBs.push_back(I->BB);
1813 if (TEI==High)
1814 ++I;
1815 } else {
1816 DestBBs.push_back(Default);
1817 }
1818 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001819
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001820 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001821 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1822 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001823 E = DestBBs.end(); I != E; ++I) {
1824 if (!SuccsHandled[(*I)->getNumber()]) {
1825 SuccsHandled[(*I)->getNumber()] = true;
1826 JumpTableBB->addSuccessor(*I);
1827 }
1828 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001829
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001830 // Create a jump table index for this jump table, or return an existing
1831 // one.
1832 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001833
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001834 // Set the jump table information so that we can codegen it as a second
1835 // MachineBasicBlock
1836 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1837 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1838 if (CR.CaseBB == CurMBB)
1839 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001840
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001841 JTCases.push_back(JumpTableBlock(JTH, JT));
1842
1843 return true;
1844}
1845
1846/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1847/// 2 subtrees.
1848bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1849 CaseRecVector& WorkList,
1850 Value* SV,
1851 MachineBasicBlock* Default) {
1852 // Get the MachineFunction which holds the current MBB. This is used when
1853 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001854 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001855
1856 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001857 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001858 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001859
1860 Case& FrontCase = *CR.Range.first;
1861 Case& BackCase = *(CR.Range.second-1);
1862 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1863
1864 // Size is the number of Cases represented by this range.
1865 unsigned Size = CR.Range.second - CR.Range.first;
1866
Chris Lattnere880efe2009-11-07 07:50:34 +00001867 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1868 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001869 double FMetric = 0;
1870 CaseItr Pivot = CR.Range.first + Size/2;
1871
1872 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1873 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001874 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001875 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1876 I!=E; ++I)
1877 TSize += I->size();
1878
Chris Lattnere880efe2009-11-07 07:50:34 +00001879 APInt LSize = FrontCase.size();
1880 APInt RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001881 DEBUG(errs() << "Selecting best pivot: \n"
1882 << "First: " << First << ", Last: " << Last <<'\n'
1883 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001884 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1885 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001886 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1887 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001888 APInt Range = ComputeRange(LEnd, RBegin);
1889 assert((Range - 2ULL).isNonNegative() &&
1890 "Invalid case distance");
Chris Lattnere880efe2009-11-07 07:50:34 +00001891 double LDensity = (double)LSize.roundToDouble() /
1892 (LEnd - First + 1ULL).roundToDouble();
1893 double RDensity = (double)RSize.roundToDouble() /
1894 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001895 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001896 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001897 DEBUG(errs() <<"=>Step\n"
1898 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1899 << "LDensity: " << LDensity
1900 << ", RDensity: " << RDensity << '\n'
1901 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001902 if (FMetric < Metric) {
1903 Pivot = J;
1904 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001905 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001906 }
1907
1908 LSize += J->size();
1909 RSize -= J->size();
1910 }
1911 if (areJTsAllowed(TLI)) {
1912 // If our case is dense we *really* should handle it earlier!
1913 assert((FMetric > 0) && "Should handle dense range earlier!");
1914 } else {
1915 Pivot = CR.Range.first + Size/2;
1916 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001918 CaseRange LHSR(CR.Range.first, Pivot);
1919 CaseRange RHSR(Pivot, CR.Range.second);
1920 Constant *C = Pivot->Low;
1921 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001923 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001924 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001925 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001926 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001927 // Pivot's Value, then we can branch directly to the LHS's Target,
1928 // rather than creating a leaf node for it.
1929 if ((LHSR.second - LHSR.first) == 1 &&
1930 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001931 cast<ConstantInt>(C)->getValue() ==
1932 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933 TrueBB = LHSR.first->BB;
1934 } else {
1935 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1936 CurMF->insert(BBI, TrueBB);
1937 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001938
1939 // Put SV in a virtual register to make it available from the new blocks.
1940 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001941 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001943 // Similar to the optimization above, if the Value being switched on is
1944 // known to be less than the Constant CR.LT, and the current Case Value
1945 // is CR.LT - 1, then we can branch directly to the target block for
1946 // the current Case Value, rather than emitting a RHS leaf node for it.
1947 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1949 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001950 FalseBB = RHSR.first->BB;
1951 } else {
1952 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1953 CurMF->insert(BBI, FalseBB);
1954 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001955
1956 // Put SV in a virtual register to make it available from the new blocks.
1957 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 }
1959
1960 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001961 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962 // Otherwise, branch to LHS.
1963 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1964
1965 if (CR.CaseBB == CurMBB)
1966 visitSwitchCase(CB);
1967 else
1968 SwitchCases.push_back(CB);
1969
1970 return true;
1971}
1972
1973/// handleBitTestsSwitchCase - if current case range has few destination and
1974/// range span less, than machine word bitwidth, encode case range into series
1975/// of masks and emit bit tests with these masks.
1976bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1977 CaseRecVector& WorkList,
1978 Value* SV,
1979 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001980 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001981 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001982
1983 Case& FrontCase = *CR.Range.first;
1984 Case& BackCase = *(CR.Range.second-1);
1985
1986 // Get the MachineFunction which holds the current MBB. This is used when
1987 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001988 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001989
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001990 // If target does not have legal shift left, do not emit bit tests at all.
1991 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1992 return false;
1993
Anton Korobeynikov23218582008-12-23 22:25:27 +00001994 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001995 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1996 I!=E; ++I) {
1997 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001998 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001999 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002000
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002001 // Count unique destinations
2002 SmallSet<MachineBasicBlock*, 4> Dests;
2003 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2004 Dests.insert(I->BB);
2005 if (Dests.size() > 3)
2006 // Don't bother the code below, if there are too much unique destinations
2007 return false;
2008 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002009 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
2010 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002011
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002012 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002013 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2014 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002015 APInt cmpRange = maxValue - minValue;
2016
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002017 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
2018 << "Low bound: " << minValue << '\n'
2019 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002020
2021 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002022 (!(Dests.size() == 1 && numCmps >= 3) &&
2023 !(Dests.size() == 2 && numCmps >= 5) &&
2024 !(Dests.size() >= 3 && numCmps >= 6)))
2025 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002026
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002027 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00002028 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2029
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002030 // Optimize the case where all the case values fit in a
2031 // word without having to subtract minValue. In this case,
2032 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002033 if (minValue.isNonNegative() &&
2034 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
2035 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002036 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002037 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002038 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002040 CaseBitsVector CasesBits;
2041 unsigned i, count = 0;
2042
2043 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2044 MachineBasicBlock* Dest = I->BB;
2045 for (i = 0; i < count; ++i)
2046 if (Dest == CasesBits[i].BB)
2047 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002049 if (i == count) {
2050 assert((count < 3) && "Too much destinations to test!");
2051 CasesBits.push_back(CaseBits(0, Dest, 0));
2052 count++;
2053 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002054
2055 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2056 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2057
2058 uint64_t lo = (lowValue - lowBound).getZExtValue();
2059 uint64_t hi = (highValue - lowBound).getZExtValue();
2060
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002061 for (uint64_t j = lo; j <= hi; j++) {
2062 CasesBits[i].Mask |= 1ULL << j;
2063 CasesBits[i].Bits++;
2064 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002065
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002066 }
2067 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002068
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002069 BitTestInfo BTC;
2070
2071 // Figure out which block is immediately after the current one.
2072 MachineFunction::iterator BBI = CR.CaseBB;
2073 ++BBI;
2074
2075 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2076
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002077 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002078 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002079 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2080 << ", Bits: " << CasesBits[i].Bits
2081 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002082
2083 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2084 CurMF->insert(BBI, CaseBB);
2085 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2086 CaseBB,
2087 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002088
2089 // Put SV in a virtual register to make it available from the new blocks.
2090 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002091 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002092
2093 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002094 -1U, (CR.CaseBB == CurMBB),
2095 CR.CaseBB, Default, BTC);
2096
2097 if (CR.CaseBB == CurMBB)
2098 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100 BitTestCases.push_back(BTB);
2101
2102 return true;
2103}
2104
2105
2106/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002107size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002108 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002109 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002110
2111 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002112 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002113 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2114 Cases.push_back(Case(SI.getSuccessorValue(i),
2115 SI.getSuccessorValue(i),
2116 SMBB));
2117 }
2118 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2119
2120 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002121 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002122 // Must recompute end() each iteration because it may be
2123 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002124 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2125 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2126 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002127 MachineBasicBlock* nextBB = J->BB;
2128 MachineBasicBlock* currentBB = I->BB;
2129
2130 // If the two neighboring cases go to the same destination, merge them
2131 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002132 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002133 I->High = J->High;
2134 J = Cases.erase(J);
2135 } else {
2136 I = J++;
2137 }
2138 }
2139
2140 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2141 if (I->Low != I->High)
2142 // A range counts double, since it requires two compares.
2143 ++numCmps;
2144 }
2145
2146 return numCmps;
2147}
2148
Anton Korobeynikov23218582008-12-23 22:25:27 +00002149void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002150 // Figure out which block is immediately after the current one.
2151 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002152
2153 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2154
2155 // If there is only the default destination, branch to it if it is not the
2156 // next basic block. Otherwise, just fall through.
2157 if (SI.getNumOperands() == 2) {
2158 // Update machine-CFG edges.
2159
2160 // If this is not a fall-through branch, emit the branch.
2161 CurMBB->addSuccessor(Default);
2162 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002163 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002164 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002166 return;
2167 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002168
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002169 // If there are any non-default case statements, create a vector of Cases
2170 // representing each one, and sort the vector so that we can efficiently
2171 // create a binary search tree from them.
2172 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002173 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002174 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2175 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002176 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002177
2178 // Get the Value to be switched on and default basic blocks, which will be
2179 // inserted into CaseBlock records, representing basic blocks in the binary
2180 // search tree.
2181 Value *SV = SI.getOperand(0);
2182
2183 // Push the initial CaseRec onto the worklist
2184 CaseRecVector WorkList;
2185 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2186
2187 while (!WorkList.empty()) {
2188 // Grab a record representing a case range to process off the worklist
2189 CaseRec CR = WorkList.back();
2190 WorkList.pop_back();
2191
2192 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2193 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002194
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002195 // If the range has few cases (two or less) emit a series of specific
2196 // tests.
2197 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2198 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002199
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002200 // If the switch has more than 5 blocks, and at least 40% dense, and the
2201 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002202 // lowering the switch to a binary tree of conditional branches.
2203 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2204 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002205
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002206 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2207 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2208 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2209 }
2210}
2211
Chris Lattnerab21db72009-10-28 00:19:10 +00002212void SelectionDAGLowering::visitIndirectBr(IndirectBrInst &I) {
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002213 // Update machine-CFG edges.
2214 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2215 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2216
Dan Gohman64825152009-10-27 21:56:26 +00002217 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2218 MVT::Other, getControlRoot(),
2219 getValue(I.getAddress())));
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002220}
2221
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002222
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002223void SelectionDAGLowering::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002224 // -0.0 - X --> fneg
2225 const Type *Ty = I.getType();
2226 if (isa<VectorType>(Ty)) {
2227 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2228 const VectorType *DestTy = cast<VectorType>(I.getType());
2229 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002230 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002231 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002232 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002233 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002234 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002235 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002236 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002237 return;
2238 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002239 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002240 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002241 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002242 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002243 SDValue Op2 = getValue(I.getOperand(1));
2244 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2245 Op2.getValueType(), Op2));
2246 return;
2247 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002248
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002249 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002250}
2251
2252void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2253 SDValue Op1 = getValue(I.getOperand(0));
2254 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002255
Scott Michelfdc40a02009-02-17 22:15:04 +00002256 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002257 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002258}
2259
2260void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2261 SDValue Op1 = getValue(I.getOperand(0));
2262 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002263 if (!isa<VectorType>(I.getType()) &&
2264 Op2.getValueType() != TLI.getShiftAmountTy()) {
2265 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002266 EVT PTy = TLI.getPointerTy();
2267 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002268 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002269 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2270 TLI.getShiftAmountTy(), Op2);
2271 // If the operand is larger than the shift count type but the shift
2272 // count type has enough bits to represent any shift value, truncate
2273 // it now. This is a common case and it exposes the truncate to
2274 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002275 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002276 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2277 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2278 TLI.getShiftAmountTy(), Op2);
2279 // Otherwise we'll need to temporarily settle for some other
2280 // convenient type; type legalization will make adjustments as
2281 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002282 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002283 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002284 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002285 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002286 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002287 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002288 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002289
Scott Michelfdc40a02009-02-17 22:15:04 +00002290 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002291 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002292}
2293
2294void SelectionDAGLowering::visitICmp(User &I) {
2295 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2296 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2297 predicate = IC->getPredicate();
2298 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2299 predicate = ICmpInst::Predicate(IC->getPredicate());
2300 SDValue Op1 = getValue(I.getOperand(0));
2301 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002302 ISD::CondCode Opcode = getICmpCondCode(predicate);
Chris Lattner9800e842009-07-07 22:41:32 +00002303
Owen Andersone50ed302009-08-10 22:56:29 +00002304 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002305 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306}
2307
2308void SelectionDAGLowering::visitFCmp(User &I) {
2309 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2310 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2311 predicate = FC->getPredicate();
2312 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2313 predicate = FCmpInst::Predicate(FC->getPredicate());
2314 SDValue Op1 = getValue(I.getOperand(0));
2315 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002316 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002317 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002318 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002319}
2320
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002321void SelectionDAGLowering::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002322 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002323 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2324 unsigned NumValues = ValueVTs.size();
2325 if (NumValues != 0) {
2326 SmallVector<SDValue, 4> Values(NumValues);
2327 SDValue Cond = getValue(I.getOperand(0));
2328 SDValue TrueVal = getValue(I.getOperand(1));
2329 SDValue FalseVal = getValue(I.getOperand(2));
2330
2331 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002332 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002333 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002334 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2335 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2336
Scott Michelfdc40a02009-02-17 22:15:04 +00002337 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002338 DAG.getVTList(&ValueVTs[0], NumValues),
2339 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002340 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002341}
2342
2343
2344void SelectionDAGLowering::visitTrunc(User &I) {
2345 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2346 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002347 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002348 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002349}
2350
2351void SelectionDAGLowering::visitZExt(User &I) {
2352 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2353 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2354 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002355 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002356 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002357}
2358
2359void SelectionDAGLowering::visitSExt(User &I) {
2360 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2361 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2362 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002363 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002364 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002365}
2366
2367void SelectionDAGLowering::visitFPTrunc(User &I) {
2368 // FPTrunc is never a no-op cast, no need to check
2369 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002370 EVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002371 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002372 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002373}
2374
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002375void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002376 // FPTrunc is never a no-op cast, no need to check
2377 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002378 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002379 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002380}
2381
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002382void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002383 // FPToUI is never a no-op cast, no need to check
2384 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002385 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002386 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002387}
2388
2389void SelectionDAGLowering::visitFPToSI(User &I) {
2390 // FPToSI is never a no-op cast, no need to check
2391 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002392 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002393 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002394}
2395
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002396void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002397 // UIToFP is never a no-op cast, no need to check
2398 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002399 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002400 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002401}
2402
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002403void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002404 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002405 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002406 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002407 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002408}
2409
2410void SelectionDAGLowering::visitPtrToInt(User &I) {
2411 // What to do depends on the size of the integer and the size of the pointer.
2412 // We can either truncate, zero extend, or no-op, accordingly.
2413 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002414 EVT SrcVT = N.getValueType();
2415 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002416 SDValue Result = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002417 setValue(&I, Result);
2418}
2419
2420void SelectionDAGLowering::visitIntToPtr(User &I) {
2421 // What to do depends on the size of the integer and the size of the pointer.
2422 // We can either truncate, zero extend, or no-op, accordingly.
2423 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002424 EVT SrcVT = N.getValueType();
2425 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002426 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002427}
2428
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002429void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002430 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002431 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002432
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002433 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002434 // is either a BIT_CONVERT or a no-op.
2435 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002436 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002437 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002438 else
2439 setValue(&I, N); // noop cast.
2440}
2441
2442void SelectionDAGLowering::visitInsertElement(User &I) {
2443 SDValue InVec = getValue(I.getOperand(0));
2444 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002445 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002446 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002447 getValue(I.getOperand(2)));
2448
Scott Michelfdc40a02009-02-17 22:15:04 +00002449 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002450 TLI.getValueType(I.getType()),
2451 InVec, InVal, InIdx));
2452}
2453
2454void SelectionDAGLowering::visitExtractElement(User &I) {
2455 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002456 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002457 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002458 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002460 TLI.getValueType(I.getType()), InVec, InIdx));
2461}
2462
Mon P Wangaeb06d22008-11-10 04:46:22 +00002463
2464// Utility for visitShuffleVector - Returns true if the mask is mask starting
2465// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002466static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2467 unsigned MaskNumElts = Mask.size();
2468 for (unsigned i = 0; i != MaskNumElts; ++i)
2469 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002470 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002471 return true;
2472}
2473
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002474void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002475 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002476 SDValue Src1 = getValue(I.getOperand(0));
2477 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002478
Nate Begeman9008ca62009-04-27 18:41:29 +00002479 // Convert the ConstantVector mask operand into an array of ints, with -1
2480 // representing undef values.
2481 SmallVector<Constant*, 8> MaskElts;
Owen Anderson001dbfe2009-07-16 18:04:31 +00002482 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2483 MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002484 unsigned MaskNumElts = MaskElts.size();
2485 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002486 if (isa<UndefValue>(MaskElts[i]))
2487 Mask.push_back(-1);
2488 else
2489 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2490 }
2491
Owen Andersone50ed302009-08-10 22:56:29 +00002492 EVT VT = TLI.getValueType(I.getType());
2493 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002494 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002495
Mon P Wangc7849c22008-11-16 05:06:27 +00002496 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002497 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2498 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002499 return;
2500 }
2501
2502 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002503 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2504 // Mask is longer than the source vectors and is a multiple of the source
2505 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002506 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002507 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2508 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002509 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002510 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002511 return;
2512 }
2513
Mon P Wangc7849c22008-11-16 05:06:27 +00002514 // Pad both vectors with undefs to make them the same length as the mask.
2515 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002516 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2517 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002518 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002519
Nate Begeman9008ca62009-04-27 18:41:29 +00002520 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2521 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002522 MOps1[0] = Src1;
2523 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002524
2525 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2526 getCurDebugLoc(), VT,
2527 &MOps1[0], NumConcat);
2528 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2529 getCurDebugLoc(), VT,
2530 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002531
Mon P Wangaeb06d22008-11-10 04:46:22 +00002532 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002533 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002534 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002535 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002536 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002537 MappedOps.push_back(Idx);
2538 else
2539 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002540 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002541 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2542 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002543 return;
2544 }
2545
Mon P Wangc7849c22008-11-16 05:06:27 +00002546 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002547 // Analyze the access pattern of the vector to see if we can extract
2548 // two subvectors and do the shuffle. The analysis is done by calculating
2549 // the range of elements the mask access on both vectors.
2550 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2551 int MaxRange[2] = {-1, -1};
2552
Nate Begeman5a5ca152009-04-29 05:20:52 +00002553 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002554 int Idx = Mask[i];
2555 int Input = 0;
2556 if (Idx < 0)
2557 continue;
2558
Nate Begeman5a5ca152009-04-29 05:20:52 +00002559 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002560 Input = 1;
2561 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002562 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002563 if (Idx > MaxRange[Input])
2564 MaxRange[Input] = Idx;
2565 if (Idx < MinRange[Input])
2566 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002567 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002568
Mon P Wangc7849c22008-11-16 05:06:27 +00002569 // Check if the access is smaller than the vector size and can we find
2570 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002571 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002572 int StartIdx[2]; // StartIdx to extract from
2573 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002574 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002575 RangeUse[Input] = 0; // Unused
2576 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002577 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002579 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002580 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002581 RangeUse[Input] = 1; // Extract from beginning of the vector
2582 StartIdx[Input] = 0;
2583 } else {
2584 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002585 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002586 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002587 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002588 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002589 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002590 }
2591
Bill Wendling636e2582009-08-21 18:16:06 +00002592 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002593 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002594 return;
2595 }
2596 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2597 // Extract appropriate subvector and generate a vector shuffle
2598 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002599 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002600 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002601 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002602 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002603 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002604 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002605 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002606 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002607 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002608 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002609 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002610 int Idx = Mask[i];
2611 if (Idx < 0)
2612 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002613 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002614 MappedOps.push_back(Idx - StartIdx[0]);
2615 else
2616 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002617 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002618 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2619 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002620 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002621 }
2622 }
2623
Mon P Wangc7849c22008-11-16 05:06:27 +00002624 // We can't use either concat vectors or extract subvectors so fall back to
2625 // replacing the shuffle with extract and build vector.
2626 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002627 EVT EltVT = VT.getVectorElementType();
2628 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002629 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002630 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002631 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002632 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002633 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002634 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002635 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002636 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002637 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002638 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002639 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002640 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002641 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002642 }
2643 }
Evan Chenga87008d2009-02-25 22:49:59 +00002644 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2645 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002646}
2647
2648void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2649 const Value *Op0 = I.getOperand(0);
2650 const Value *Op1 = I.getOperand(1);
2651 const Type *AggTy = I.getType();
2652 const Type *ValTy = Op1->getType();
2653 bool IntoUndef = isa<UndefValue>(Op0);
2654 bool FromUndef = isa<UndefValue>(Op1);
2655
2656 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2657 I.idx_begin(), I.idx_end());
2658
Owen Andersone50ed302009-08-10 22:56:29 +00002659 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002660 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002661 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002662 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2663
2664 unsigned NumAggValues = AggValueVTs.size();
2665 unsigned NumValValues = ValValueVTs.size();
2666 SmallVector<SDValue, 4> Values(NumAggValues);
2667
2668 SDValue Agg = getValue(Op0);
2669 SDValue Val = getValue(Op1);
2670 unsigned i = 0;
2671 // Copy the beginning value(s) from the original aggregate.
2672 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002673 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002674 SDValue(Agg.getNode(), Agg.getResNo() + i);
2675 // Copy values from the inserted value(s).
2676 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002677 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002678 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2679 // Copy remaining value(s) from the original aggregate.
2680 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002681 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002682 SDValue(Agg.getNode(), Agg.getResNo() + i);
2683
Scott Michelfdc40a02009-02-17 22:15:04 +00002684 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002685 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2686 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687}
2688
2689void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2690 const Value *Op0 = I.getOperand(0);
2691 const Type *AggTy = Op0->getType();
2692 const Type *ValTy = I.getType();
2693 bool OutOfUndef = isa<UndefValue>(Op0);
2694
2695 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2696 I.idx_begin(), I.idx_end());
2697
Owen Andersone50ed302009-08-10 22:56:29 +00002698 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002699 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2700
2701 unsigned NumValValues = ValValueVTs.size();
2702 SmallVector<SDValue, 4> Values(NumValValues);
2703
2704 SDValue Agg = getValue(Op0);
2705 // Copy out the selected value(s).
2706 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2707 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002708 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002709 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002710 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002711
Scott Michelfdc40a02009-02-17 22:15:04 +00002712 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002713 DAG.getVTList(&ValValueVTs[0], NumValValues),
2714 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002715}
2716
2717
2718void SelectionDAGLowering::visitGetElementPtr(User &I) {
2719 SDValue N = getValue(I.getOperand(0));
2720 const Type *Ty = I.getOperand(0)->getType();
2721
2722 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2723 OI != E; ++OI) {
2724 Value *Idx = *OI;
2725 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2726 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2727 if (Field) {
2728 // N = N + Offset
2729 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002730 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002731 DAG.getIntPtrConstant(Offset));
2732 }
2733 Ty = StTy->getElementType(Field);
2734 } else {
2735 Ty = cast<SequentialType>(Ty)->getElementType();
2736
2737 // If this is a constant subscript, handle it quickly.
2738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2739 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002740 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002741 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002742 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002743 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002744 unsigned PtrBits = PTy.getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002745 if (PtrBits < 64) {
2746 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2747 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002748 DAG.getConstant(Offs, MVT::i64));
Evan Cheng65b52df2009-02-09 21:01:06 +00002749 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002750 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002751 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002752 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002753 continue;
2754 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002755
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002756 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002757 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2758 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002759 SDValue IdxN = getValue(Idx);
2760
2761 // If the index is smaller or larger than intptr_t, truncate or extend
2762 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002763 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002764
2765 // If this is a multiply by a power of two, turn it into a shl
2766 // immediately. This is a very common case.
2767 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002768 if (ElementSize.isPowerOf2()) {
2769 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002770 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002771 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002772 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002773 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002774 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002775 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002776 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002777 }
2778 }
2779
Scott Michelfdc40a02009-02-17 22:15:04 +00002780 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002781 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782 }
2783 }
2784 setValue(&I, N);
2785}
2786
2787void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2788 // If this is a fixed sized alloca in the entry block of the function,
2789 // allocate it statically on the stack.
2790 if (FuncInfo.StaticAllocaMap.count(&I))
2791 return; // getValue will auto-populate this.
2792
2793 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002794 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002795 unsigned Align =
2796 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2797 I.getAlignment());
2798
2799 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002800
2801 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2802 AllocSize,
2803 DAG.getConstant(TySize, AllocSize.getValueType()));
2804
2805
2806
Owen Andersone50ed302009-08-10 22:56:29 +00002807 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002808 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002809
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002810 // Handle alignment. If the requested alignment is less than or equal to
2811 // the stack alignment, ignore it. If the size is greater than or equal to
2812 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2813 unsigned StackAlign =
2814 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2815 if (Align <= StackAlign)
2816 Align = 0;
2817
2818 // Round the size of the allocation up to the stack alignment size
2819 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002820 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002821 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002822 DAG.getIntPtrConstant(StackAlign-1));
2823 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002824 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002825 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002826 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2827
2828 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002829 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002830 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002831 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002832 setValue(&I, DSA);
2833 DAG.setRoot(DSA.getValue(1));
2834
2835 // Inform the Frame Information that we have just allocated a variable-sized
2836 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002837 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002838}
2839
2840void SelectionDAGLowering::visitLoad(LoadInst &I) {
2841 const Value *SV = I.getOperand(0);
2842 SDValue Ptr = getValue(SV);
2843
2844 const Type *Ty = I.getType();
2845 bool isVolatile = I.isVolatile();
2846 unsigned Alignment = I.getAlignment();
2847
Owen Andersone50ed302009-08-10 22:56:29 +00002848 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002849 SmallVector<uint64_t, 4> Offsets;
2850 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2851 unsigned NumValues = ValueVTs.size();
2852 if (NumValues == 0)
2853 return;
2854
2855 SDValue Root;
2856 bool ConstantMemory = false;
2857 if (I.isVolatile())
2858 // Serialize volatile loads with other side effects.
2859 Root = getRoot();
2860 else if (AA->pointsToConstantMemory(SV)) {
2861 // Do not serialize (non-volatile) loads of constant memory with anything.
2862 Root = DAG.getEntryNode();
2863 ConstantMemory = true;
2864 } else {
2865 // Do not serialize non-volatile loads against each other.
2866 Root = DAG.getRoot();
2867 }
2868
2869 SmallVector<SDValue, 4> Values(NumValues);
2870 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002871 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002872 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002873 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Nate Begemane6798372009-09-15 00:13:12 +00002874 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2875 PtrVT, Ptr,
2876 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002877 SV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002878 Values[i] = L;
2879 Chains[i] = L.getValue(1);
2880 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002881
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002882 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002883 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002884 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002885 &Chains[0], NumValues);
2886 if (isVolatile)
2887 DAG.setRoot(Chain);
2888 else
2889 PendingLoads.push_back(Chain);
2890 }
2891
Scott Michelfdc40a02009-02-17 22:15:04 +00002892 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002893 DAG.getVTList(&ValueVTs[0], NumValues),
2894 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002895}
2896
2897
2898void SelectionDAGLowering::visitStore(StoreInst &I) {
2899 Value *SrcV = I.getOperand(0);
2900 Value *PtrV = I.getOperand(1);
2901
Owen Andersone50ed302009-08-10 22:56:29 +00002902 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002903 SmallVector<uint64_t, 4> Offsets;
2904 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2905 unsigned NumValues = ValueVTs.size();
2906 if (NumValues == 0)
2907 return;
2908
2909 // Get the lowered operands. Note that we do this after
2910 // checking if NumResults is zero, because with zero results
2911 // the operands won't have values in the map.
2912 SDValue Src = getValue(SrcV);
2913 SDValue Ptr = getValue(PtrV);
2914
2915 SDValue Root = getRoot();
2916 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002917 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002918 bool isVolatile = I.isVolatile();
2919 unsigned Alignment = I.getAlignment();
2920 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002921 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002922 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002923 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002924 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002925 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002926 PtrV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002927
Scott Michelfdc40a02009-02-17 22:15:04 +00002928 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002929 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002930}
2931
2932/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2933/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002934void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002935 unsigned Intrinsic) {
2936 bool HasChain = !I.doesNotAccessMemory();
2937 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2938
2939 // Build the operand list.
2940 SmallVector<SDValue, 8> Ops;
2941 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2942 if (OnlyLoad) {
2943 // We don't need to serialize loads against other loads.
2944 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002945 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002946 Ops.push_back(getRoot());
2947 }
2948 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002949
2950 // Info is set by getTgtMemInstrinsic
2951 TargetLowering::IntrinsicInfo Info;
2952 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2953
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002954 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002955 if (!IsTgtIntrinsic)
2956 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002957
2958 // Add all operands of the call to the operand list.
2959 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2960 SDValue Op = getValue(I.getOperand(i));
2961 assert(TLI.isTypeLegal(Op.getValueType()) &&
2962 "Intrinsic uses a non-legal type?");
2963 Ops.push_back(Op);
2964 }
2965
Owen Andersone50ed302009-08-10 22:56:29 +00002966 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002967 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2968#ifndef NDEBUG
2969 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2970 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2971 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002972 }
Bob Wilson8d919552009-07-31 22:41:21 +00002973#endif // NDEBUG
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002974 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002975 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002976
Bob Wilson8d919552009-07-31 22:41:21 +00002977 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002978
2979 // Create the node.
2980 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002981 if (IsTgtIntrinsic) {
2982 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002983 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002984 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002985 Info.memVT, Info.ptrVal, Info.offset,
2986 Info.align, Info.vol,
2987 Info.readMem, Info.writeMem);
2988 }
2989 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002990 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002991 VTs, &Ops[0], Ops.size());
Owen Anderson1d0be152009-08-13 21:58:54 +00002992 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002993 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002994 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002995 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002996 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002997 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002998
2999 if (HasChain) {
3000 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3001 if (OnlyLoad)
3002 PendingLoads.push_back(Chain);
3003 else
3004 DAG.setRoot(Chain);
3005 }
Owen Anderson1d0be152009-08-13 21:58:54 +00003006 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003007 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00003008 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003009 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003010 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003011 setValue(&I, Result);
3012 }
3013}
3014
3015/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3016static GlobalVariable *ExtractTypeInfo(Value *V) {
3017 V = V->stripPointerCasts();
3018 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3019 assert ((GV || isa<ConstantPointerNull>(V)) &&
3020 "TypeInfo must be a global variable or NULL");
3021 return GV;
3022}
3023
3024namespace llvm {
3025
3026/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3027/// call, and add them to the specified machine basic block.
3028void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3029 MachineBasicBlock *MBB) {
3030 // Inform the MachineModuleInfo of the personality for this landing pad.
3031 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3032 assert(CE->getOpcode() == Instruction::BitCast &&
3033 isa<Function>(CE->getOperand(0)) &&
3034 "Personality should be a function");
3035 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3036
3037 // Gather all the type infos for this landing pad and pass them along to
3038 // MachineModuleInfo.
3039 std::vector<GlobalVariable *> TyInfo;
3040 unsigned N = I.getNumOperands();
3041
3042 for (unsigned i = N - 1; i > 2; --i) {
3043 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3044 unsigned FilterLength = CI->getZExtValue();
3045 unsigned FirstCatch = i + FilterLength + !FilterLength;
3046 assert (FirstCatch <= N && "Invalid filter length");
3047
3048 if (FirstCatch < N) {
3049 TyInfo.reserve(N - FirstCatch);
3050 for (unsigned j = FirstCatch; j < N; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addCatchTypeInfo(MBB, TyInfo);
3053 TyInfo.clear();
3054 }
3055
3056 if (!FilterLength) {
3057 // Cleanup.
3058 MMI->addCleanup(MBB);
3059 } else {
3060 // Filter.
3061 TyInfo.reserve(FilterLength - 1);
3062 for (unsigned j = i + 1; j < FirstCatch; ++j)
3063 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3064 MMI->addFilterTypeInfo(MBB, TyInfo);
3065 TyInfo.clear();
3066 }
3067
3068 N = i;
3069 }
3070 }
3071
3072 if (N > 3) {
3073 TyInfo.reserve(N - 3);
3074 for (unsigned j = 3; j < N; ++j)
3075 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3076 MMI->addCatchTypeInfo(MBB, TyInfo);
3077 }
3078}
3079
3080}
3081
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003082/// GetSignificand - Get the significand and build it into a floating-point
3083/// number with exponent of 1:
3084///
3085/// Op = (Op & 0x007fffff) | 0x3f800000;
3086///
3087/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003088static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003089GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003090 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3091 DAG.getConstant(0x007fffff, MVT::i32));
3092 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3093 DAG.getConstant(0x3f800000, MVT::i32));
3094 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003095}
3096
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003097/// GetExponent - Get the exponent:
3098///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003099/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003100///
3101/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003102static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003103GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3104 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003105 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3106 DAG.getConstant(0x7f800000, MVT::i32));
3107 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003108 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003109 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3110 DAG.getConstant(127, MVT::i32));
3111 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003112}
3113
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003114/// getF32Constant - Get 32-bit floating point constant.
3115static SDValue
3116getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003117 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003118}
3119
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003120/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003121/// visitIntrinsicCall: I is a call instruction
3122/// Op is the associated NodeType for I
3123const char *
3124SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003125 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003126 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003127 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003128 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003129 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003130 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003131 getValue(I.getOperand(2)),
3132 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003133 setValue(&I, L);
3134 DAG.setRoot(L.getValue(1));
3135 return 0;
3136}
3137
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003138// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003139const char *
3140SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003141 SDValue Op1 = getValue(I.getOperand(1));
3142 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003143
Owen Anderson825b72b2009-08-11 20:47:22 +00003144 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Dan Gohmanfc166572009-04-09 23:54:40 +00003145 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003146
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003147 setValue(&I, Result);
3148 return 0;
3149}
Bill Wendling74c37652008-12-09 22:08:41 +00003150
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003151/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3152/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003153void
3154SelectionDAGLowering::visitExp(CallInst &I) {
3155 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003156 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003157
Owen Anderson825b72b2009-08-11 20:47:22 +00003158 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003159 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3160 SDValue Op = getValue(I.getOperand(1));
3161
3162 // Put the exponent in the right bit position for later addition to the
3163 // final result:
3164 //
3165 // #define LOG2OFe 1.4426950f
3166 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003167 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003168 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003169 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003170
3171 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003172 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3173 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003174
3175 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003176 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003177 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003178
3179 if (LimitFloatPrecision <= 6) {
3180 // For floating-point precision of 6:
3181 //
3182 // TwoToFractionalPartOfX =
3183 // 0.997535578f +
3184 // (0.735607626f + 0.252464424f * x) * x;
3185 //
3186 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003187 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003188 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003189 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003190 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003191 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3192 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003193 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003194 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003195
3196 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003197 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003198 TwoToFracPartOfX, IntegerPartOfX);
3199
Owen Anderson825b72b2009-08-11 20:47:22 +00003200 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003201 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3202 // For floating-point precision of 12:
3203 //
3204 // TwoToFractionalPartOfX =
3205 // 0.999892986f +
3206 // (0.696457318f +
3207 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3208 //
3209 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003210 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003211 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003212 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003213 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003214 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3215 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003216 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003217 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3218 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003219 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003220 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003221
3222 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003223 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003224 TwoToFracPartOfX, IntegerPartOfX);
3225
Owen Anderson825b72b2009-08-11 20:47:22 +00003226 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003227 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3228 // For floating-point precision of 18:
3229 //
3230 // TwoToFractionalPartOfX =
3231 // 0.999999982f +
3232 // (0.693148872f +
3233 // (0.240227044f +
3234 // (0.554906021e-1f +
3235 // (0.961591928e-2f +
3236 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3237 //
3238 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003239 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003240 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003241 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003242 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003243 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3244 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003245 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003246 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3247 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003248 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003249 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3250 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003251 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003252 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3253 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003254 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003255 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3256 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003257 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003258 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003259 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003260
3261 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003262 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003263 TwoToFracPartOfX, IntegerPartOfX);
3264
Owen Anderson825b72b2009-08-11 20:47:22 +00003265 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003266 }
3267 } else {
3268 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003269 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003270 getValue(I.getOperand(1)).getValueType(),
3271 getValue(I.getOperand(1)));
3272 }
3273
Dale Johannesen59e577f2008-09-05 18:38:42 +00003274 setValue(&I, result);
3275}
3276
Bill Wendling39150252008-09-09 20:39:27 +00003277/// visitLog - Lower a log intrinsic. Handles the special sequences for
3278/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003279void
3280SelectionDAGLowering::visitLog(CallInst &I) {
3281 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003282 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003283
Owen Anderson825b72b2009-08-11 20:47:22 +00003284 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003285 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3286 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003287 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003288
3289 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003290 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003291 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003292 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003293
3294 // Get the significand and build it into a floating-point number with
3295 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003296 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003297
3298 if (LimitFloatPrecision <= 6) {
3299 // For floating-point precision of 6:
3300 //
3301 // LogofMantissa =
3302 // -1.1609546f +
3303 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003304 //
Bill Wendling39150252008-09-09 20:39:27 +00003305 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003306 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003307 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003308 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003309 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003310 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3311 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003312 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003313
Scott Michelfdc40a02009-02-17 22:15:04 +00003314 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003315 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003316 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3317 // For floating-point precision of 12:
3318 //
3319 // LogOfMantissa =
3320 // -1.7417939f +
3321 // (2.8212026f +
3322 // (-1.4699568f +
3323 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3324 //
3325 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003326 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003328 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003329 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3331 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003332 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003333 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3334 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003335 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003336 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3337 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003338 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003339
Scott Michelfdc40a02009-02-17 22:15:04 +00003340 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003341 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003342 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3343 // For floating-point precision of 18:
3344 //
3345 // LogOfMantissa =
3346 // -2.1072184f +
3347 // (4.2372794f +
3348 // (-3.7029485f +
3349 // (2.2781945f +
3350 // (-0.87823314f +
3351 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3352 //
3353 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003354 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003355 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003356 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003357 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003358 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3359 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003360 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003361 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3362 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003363 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003364 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3365 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003366 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003367 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3368 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003369 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003370 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3371 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003372 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003373
Scott Michelfdc40a02009-02-17 22:15:04 +00003374 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003375 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003376 }
3377 } else {
3378 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003379 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003380 getValue(I.getOperand(1)).getValueType(),
3381 getValue(I.getOperand(1)));
3382 }
3383
Dale Johannesen59e577f2008-09-05 18:38:42 +00003384 setValue(&I, result);
3385}
3386
Bill Wendling3eb59402008-09-09 00:28:24 +00003387/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3388/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003389void
3390SelectionDAGLowering::visitLog2(CallInst &I) {
3391 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003392 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003393
Owen Anderson825b72b2009-08-11 20:47:22 +00003394 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003395 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3396 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003397 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003398
Bill Wendling39150252008-09-09 20:39:27 +00003399 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003400 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003401
3402 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003403 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003404 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003405
Bill Wendling3eb59402008-09-09 00:28:24 +00003406 // Different possible minimax approximations of significand in
3407 // floating-point for various degrees of accuracy over [1,2].
3408 if (LimitFloatPrecision <= 6) {
3409 // For floating-point precision of 6:
3410 //
3411 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3412 //
3413 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003414 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003415 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003416 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003417 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3419 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003420 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003421
Scott Michelfdc40a02009-02-17 22:15:04 +00003422 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003423 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003424 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3425 // For floating-point precision of 12:
3426 //
3427 // Log2ofMantissa =
3428 // -2.51285454f +
3429 // (4.07009056f +
3430 // (-2.12067489f +
3431 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003432 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003433 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003434 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003435 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003436 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003437 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003438 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3439 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003440 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003441 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3442 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003443 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003444 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3445 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003446 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003447
Scott Michelfdc40a02009-02-17 22:15:04 +00003448 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003449 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003450 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3451 // For floating-point precision of 18:
3452 //
3453 // Log2ofMantissa =
3454 // -3.0400495f +
3455 // (6.1129976f +
3456 // (-5.3420409f +
3457 // (3.2865683f +
3458 // (-1.2669343f +
3459 // (0.27515199f -
3460 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3461 //
3462 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003463 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003465 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003466 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3468 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003469 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003470 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3471 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003472 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003473 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3474 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003475 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003476 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3477 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003478 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003479 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3480 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003481 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003482
Scott Michelfdc40a02009-02-17 22:15:04 +00003483 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003484 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003485 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003486 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003487 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003488 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003489 getValue(I.getOperand(1)).getValueType(),
3490 getValue(I.getOperand(1)));
3491 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003492
Dale Johannesen59e577f2008-09-05 18:38:42 +00003493 setValue(&I, result);
3494}
3495
Bill Wendling3eb59402008-09-09 00:28:24 +00003496/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3497/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003498void
3499SelectionDAGLowering::visitLog10(CallInst &I) {
3500 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003501 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003502
Owen Anderson825b72b2009-08-11 20:47:22 +00003503 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003504 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3505 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003506 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003507
Bill Wendling39150252008-09-09 20:39:27 +00003508 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003509 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003510 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003512
3513 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003514 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003515 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003516
3517 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003518 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003519 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003520 // Log10ofMantissa =
3521 // -0.50419619f +
3522 // (0.60948995f - 0.10380950f * x) * x;
3523 //
3524 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003525 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003526 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003527 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003528 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003529 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3530 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003531 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003532
Scott Michelfdc40a02009-02-17 22:15:04 +00003533 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003534 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003535 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3536 // For floating-point precision of 12:
3537 //
3538 // Log10ofMantissa =
3539 // -0.64831180f +
3540 // (0.91751397f +
3541 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3542 //
3543 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003544 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003545 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003546 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003547 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003548 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3549 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003550 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003551 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3552 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003553 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003554
Scott Michelfdc40a02009-02-17 22:15:04 +00003555 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003556 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003557 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003558 // For floating-point precision of 18:
3559 //
3560 // Log10ofMantissa =
3561 // -0.84299375f +
3562 // (1.5327582f +
3563 // (-1.0688956f +
3564 // (0.49102474f +
3565 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3566 //
3567 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003568 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003569 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003570 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003571 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003572 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3573 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003574 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003575 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3576 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003577 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003578 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3579 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003580 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003581 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3582 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003583 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003584
Scott Michelfdc40a02009-02-17 22:15:04 +00003585 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003586 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003587 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003588 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003589 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003590 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003591 getValue(I.getOperand(1)).getValueType(),
3592 getValue(I.getOperand(1)));
3593 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003594
Dale Johannesen59e577f2008-09-05 18:38:42 +00003595 setValue(&I, result);
3596}
3597
Bill Wendlinge10c8142008-09-09 22:39:21 +00003598/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3599/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003600void
3601SelectionDAGLowering::visitExp2(CallInst &I) {
3602 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003603 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003604
Owen Anderson825b72b2009-08-11 20:47:22 +00003605 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003606 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3607 SDValue Op = getValue(I.getOperand(1));
3608
Owen Anderson825b72b2009-08-11 20:47:22 +00003609 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003610
3611 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003612 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3613 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614
3615 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003616 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003617 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003618
3619 if (LimitFloatPrecision <= 6) {
3620 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003621 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003622 // TwoToFractionalPartOfX =
3623 // 0.997535578f +
3624 // (0.735607626f + 0.252464424f * x) * x;
3625 //
3626 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003627 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003628 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003629 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003630 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003631 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3632 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003633 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003634 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003635 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003636 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003637
Scott Michelfdc40a02009-02-17 22:15:04 +00003638 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003639 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003640 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3641 // For floating-point precision of 12:
3642 //
3643 // TwoToFractionalPartOfX =
3644 // 0.999892986f +
3645 // (0.696457318f +
3646 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3647 //
3648 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003650 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003651 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003653 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3654 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003655 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003656 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3657 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003658 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003659 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003660 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003661 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003662
Scott Michelfdc40a02009-02-17 22:15:04 +00003663 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003664 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003665 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3666 // For floating-point precision of 18:
3667 //
3668 // TwoToFractionalPartOfX =
3669 // 0.999999982f +
3670 // (0.693148872f +
3671 // (0.240227044f +
3672 // (0.554906021e-1f +
3673 // (0.961591928e-2f +
3674 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3675 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003676 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003677 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003678 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003679 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003680 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3681 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003682 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003683 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3684 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003685 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003686 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3687 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003688 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003689 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3690 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003691 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003692 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3693 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003694 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003695 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003696 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003697 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003698
Scott Michelfdc40a02009-02-17 22:15:04 +00003699 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003700 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003701 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003702 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003703 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003704 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003705 getValue(I.getOperand(1)).getValueType(),
3706 getValue(I.getOperand(1)));
3707 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003708
Dale Johannesen601d3c02008-09-05 01:48:15 +00003709 setValue(&I, result);
3710}
3711
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003712/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3713/// limited-precision mode with x == 10.0f.
3714void
3715SelectionDAGLowering::visitPow(CallInst &I) {
3716 SDValue result;
3717 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003718 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003719 bool IsExp10 = false;
3720
Owen Anderson825b72b2009-08-11 20:47:22 +00003721 if (getValue(Val).getValueType() == MVT::f32 &&
3722 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003723 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3724 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3725 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3726 APFloat Ten(10.0f);
3727 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3728 }
3729 }
3730 }
3731
3732 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3733 SDValue Op = getValue(I.getOperand(2));
3734
3735 // Put the exponent in the right bit position for later addition to the
3736 // final result:
3737 //
3738 // #define LOG2OF10 3.3219281f
3739 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003740 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003741 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003742 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003743
3744 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003745 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3746 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003747
3748 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003749 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003750 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003751
3752 if (LimitFloatPrecision <= 6) {
3753 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003754 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003755 // twoToFractionalPartOfX =
3756 // 0.997535578f +
3757 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003758 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003759 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003760 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003761 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003762 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003763 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003764 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3765 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003766 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003767 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003768 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003769 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003770
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003772 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003773 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3774 // For floating-point precision of 12:
3775 //
3776 // TwoToFractionalPartOfX =
3777 // 0.999892986f +
3778 // (0.696457318f +
3779 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3780 //
3781 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003782 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003783 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003784 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003785 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003786 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3787 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003788 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003789 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3790 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003791 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003792 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003793 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003794 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003795
Scott Michelfdc40a02009-02-17 22:15:04 +00003796 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003797 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003798 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3799 // For floating-point precision of 18:
3800 //
3801 // TwoToFractionalPartOfX =
3802 // 0.999999982f +
3803 // (0.693148872f +
3804 // (0.240227044f +
3805 // (0.554906021e-1f +
3806 // (0.961591928e-2f +
3807 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3808 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003810 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003811 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003812 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003813 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3814 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003815 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003816 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3817 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003818 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003819 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3820 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003821 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003822 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3823 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003824 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003825 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3826 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003827 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003828 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003829 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003830 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003831
Scott Michelfdc40a02009-02-17 22:15:04 +00003832 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003833 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003834 }
3835 } else {
3836 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003837 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003838 getValue(I.getOperand(1)).getValueType(),
3839 getValue(I.getOperand(1)),
3840 getValue(I.getOperand(2)));
3841 }
3842
3843 setValue(&I, result);
3844}
3845
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003846/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3847/// we want to emit this as a call to a named external function, return the name
3848/// otherwise lower it and return null.
3849const char *
3850SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003851 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003852 switch (Intrinsic) {
3853 default:
3854 // By default, turn this into a target intrinsic node.
3855 visitTargetIntrinsic(I, Intrinsic);
3856 return 0;
3857 case Intrinsic::vastart: visitVAStart(I); return 0;
3858 case Intrinsic::vaend: visitVAEnd(I); return 0;
3859 case Intrinsic::vacopy: visitVACopy(I); return 0;
3860 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003861 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003862 getValue(I.getOperand(1))));
3863 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003864 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003865 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003866 getValue(I.getOperand(1))));
3867 return 0;
3868 case Intrinsic::setjmp:
3869 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3870 break;
3871 case Intrinsic::longjmp:
3872 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3873 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003874 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003875 SDValue Op1 = getValue(I.getOperand(1));
3876 SDValue Op2 = getValue(I.getOperand(2));
3877 SDValue Op3 = getValue(I.getOperand(3));
3878 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003879 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003880 I.getOperand(1), 0, I.getOperand(2), 0));
3881 return 0;
3882 }
Chris Lattner824b9582008-11-21 16:42:48 +00003883 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003884 SDValue Op1 = getValue(I.getOperand(1));
3885 SDValue Op2 = getValue(I.getOperand(2));
3886 SDValue Op3 = getValue(I.getOperand(3));
3887 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003888 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003889 I.getOperand(1), 0));
3890 return 0;
3891 }
Chris Lattner824b9582008-11-21 16:42:48 +00003892 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003893 SDValue Op1 = getValue(I.getOperand(1));
3894 SDValue Op2 = getValue(I.getOperand(2));
3895 SDValue Op3 = getValue(I.getOperand(3));
3896 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3897
3898 // If the source and destination are known to not be aliases, we can
3899 // lower memmove as memcpy.
3900 uint64_t Size = -1ULL;
3901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003902 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3904 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003905 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003906 I.getOperand(1), 0, I.getOperand(2), 0));
3907 return 0;
3908 }
3909
Dale Johannesena04b7572009-02-03 23:04:43 +00003910 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003911 I.getOperand(1), 0, I.getOperand(2), 0));
3912 return 0;
3913 }
Devang Patel70d75ca2009-11-12 19:02:56 +00003914 case Intrinsic::dbg_stoppoint:
3915 case Intrinsic::dbg_region_start:
3916 case Intrinsic::dbg_region_end:
3917 case Intrinsic::dbg_func_start:
3918 // FIXME - Remove this instructions once the dust settles.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003919 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003920 case Intrinsic::dbg_declare: {
Devang Patel7e1e31f2009-07-02 22:43:26 +00003921 if (OptLevel != CodeGenOpt::None)
3922 // FIXME: Variable debug info is not supported here.
3923 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003924 DwarfWriter *DW = DAG.getDwarfWriter();
3925 if (!DW)
3926 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003927 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3928 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3929 return 0;
3930
Devang Patelac1ceb32009-10-09 22:42:28 +00003931 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003932 Value *Address = DI.getAddress();
3933 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3934 Address = BCI->getOperand(0);
3935 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3936 // Don't handle byval struct arguments or VLAs, for example.
3937 if (!AI)
3938 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003939 DenseMap<const AllocaInst*, int>::iterator SI =
3940 FuncInfo.StaticAllocaMap.find(AI);
3941 if (SI == FuncInfo.StaticAllocaMap.end())
3942 return 0; // VLAs.
3943 int FI = SI->second;
Devang Patel70d75ca2009-11-12 19:02:56 +00003944
Devang Patelac1ceb32009-10-09 22:42:28 +00003945 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Devang Patel53bb5c92009-11-10 23:06:00 +00003946 if (MMI) {
3947 MetadataContext &TheMetadata =
3948 DI.getParent()->getContext().getMetadata();
3949 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
3950 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
3951 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3952 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003953 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003954 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003955 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003956 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003957 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003958 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003959 SDValue Ops[1];
3960 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003961 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003962 setValue(&I, Op);
3963 DAG.setRoot(Op.getValue(1));
3964 return 0;
3965 }
3966
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003967 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003968 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003969
Chris Lattner3a5815f2009-09-17 23:54:54 +00003970 if (CurMBB->isLandingPad())
3971 AddCatchInfo(I, MMI, CurMBB);
3972 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003973#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00003974 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003975#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00003976 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3977 unsigned Reg = TLI.getExceptionSelectorRegister();
3978 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003979 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003980
Chris Lattner3a5815f2009-09-17 23:54:54 +00003981 // Insert the EHSELECTION instruction.
3982 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3983 SDValue Ops[2];
3984 Ops[0] = getValue(I.getOperand(1));
3985 Ops[1] = getRoot();
3986 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3987
3988 DAG.setRoot(Op.getValue(1));
3989
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003990 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003991 return 0;
3992 }
3993
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003994 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003995 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003996
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003997 if (MMI) {
3998 // Find the type id for the given typeinfo.
3999 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4000
4001 unsigned TypeID = MMI->getTypeIDFor(GV);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004002 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004003 } else {
4004 // Return something different to eh_selector.
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004005 setValue(&I, DAG.getConstant(1, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004006 }
4007
4008 return 0;
4009 }
4010
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004011 case Intrinsic::eh_return_i32:
4012 case Intrinsic::eh_return_i64:
4013 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004014 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004015 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004016 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004017 getControlRoot(),
4018 getValue(I.getOperand(1)),
4019 getValue(I.getOperand(2))));
4020 } else {
4021 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4022 }
4023
4024 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004025 case Intrinsic::eh_unwind_init:
4026 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4027 MMI->setCallsUnwindInit(true);
4028 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004029
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004030 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004031
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004032 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00004033 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00004034 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4035 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004036
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004037 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004038 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004039 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004040 TLI.getPointerTy()),
4041 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004042 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004043 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004044 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004045 TLI.getPointerTy(),
4046 DAG.getConstant(0,
4047 TLI.getPointerTy())),
4048 Offset));
4049 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004050 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004051 case Intrinsic::convertff:
4052 case Intrinsic::convertfsi:
4053 case Intrinsic::convertfui:
4054 case Intrinsic::convertsif:
4055 case Intrinsic::convertuif:
4056 case Intrinsic::convertss:
4057 case Intrinsic::convertsu:
4058 case Intrinsic::convertus:
4059 case Intrinsic::convertuu: {
4060 ISD::CvtCode Code = ISD::CVT_INVALID;
4061 switch (Intrinsic) {
4062 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4063 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4064 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4065 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4066 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4067 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4068 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4069 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4070 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4071 }
Owen Andersone50ed302009-08-10 22:56:29 +00004072 EVT DestVT = TLI.getValueType(I.getType());
Mon P Wang77cdf302008-11-10 20:54:11 +00004073 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004074 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004075 DAG.getValueType(DestVT),
4076 DAG.getValueType(getValue(Op1).getValueType()),
4077 getValue(I.getOperand(2)),
4078 getValue(I.getOperand(3)),
4079 Code));
4080 return 0;
4081 }
4082
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004083 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004084 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004085 getValue(I.getOperand(1)).getValueType(),
4086 getValue(I.getOperand(1))));
4087 return 0;
4088 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004089 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004090 getValue(I.getOperand(1)).getValueType(),
4091 getValue(I.getOperand(1)),
4092 getValue(I.getOperand(2))));
4093 return 0;
4094 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004095 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004096 getValue(I.getOperand(1)).getValueType(),
4097 getValue(I.getOperand(1))));
4098 return 0;
4099 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004100 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004101 getValue(I.getOperand(1)).getValueType(),
4102 getValue(I.getOperand(1))));
4103 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004104 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004105 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004106 return 0;
4107 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004108 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004109 return 0;
4110 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004111 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004112 return 0;
4113 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004114 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004115 return 0;
4116 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004117 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004118 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004119 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004120 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004121 return 0;
4122 case Intrinsic::pcmarker: {
4123 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004124 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004125 return 0;
4126 }
4127 case Intrinsic::readcyclecounter: {
4128 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004129 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004130 DAG.getVTList(MVT::i64, MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004131 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004132 setValue(&I, Tmp);
4133 DAG.setRoot(Tmp.getValue(1));
4134 return 0;
4135 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004136 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004137 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004138 getValue(I.getOperand(1)).getValueType(),
4139 getValue(I.getOperand(1))));
4140 return 0;
4141 case Intrinsic::cttz: {
4142 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004143 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004144 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004145 setValue(&I, result);
4146 return 0;
4147 }
4148 case Intrinsic::ctlz: {
4149 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004150 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004151 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004152 setValue(&I, result);
4153 return 0;
4154 }
4155 case Intrinsic::ctpop: {
4156 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004157 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004158 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004159 setValue(&I, result);
4160 return 0;
4161 }
4162 case Intrinsic::stacksave: {
4163 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004164 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004165 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004166 setValue(&I, Tmp);
4167 DAG.setRoot(Tmp.getValue(1));
4168 return 0;
4169 }
4170 case Intrinsic::stackrestore: {
4171 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004172 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004173 return 0;
4174 }
Bill Wendling57344502008-11-18 11:01:33 +00004175 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004176 // Emit code into the DAG to store the stack guard onto the stack.
4177 MachineFunction &MF = DAG.getMachineFunction();
4178 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004179 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004180
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004181 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4182 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004183
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004184 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004185 MFI->setStackProtectorIndex(FI);
4186
4187 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4188
4189 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004190 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Evan Chengff89dcb2009-10-18 18:16:27 +00004191 PseudoSourceValue::getFixedStack(FI),
4192 0, true);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004193 setValue(&I, Result);
4194 DAG.setRoot(Result);
4195 return 0;
4196 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004197 case Intrinsic::objectsize: {
4198 // If we don't know by now, we're never going to know.
4199 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4200
4201 assert(CI && "Non-constant type in __builtin_object_size?");
4202
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004203 SDValue Arg = getValue(I.getOperand(0));
4204 EVT Ty = Arg.getValueType();
4205
Eric Christopher7b5e6172009-10-27 00:52:25 +00004206 if (CI->getZExtValue() < 2)
Mike Stump70e5e682009-11-09 22:28:21 +00004207 setValue(&I, DAG.getConstant(-1ULL, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004208 else
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004209 setValue(&I, DAG.getConstant(0, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004210 return 0;
4211 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004212 case Intrinsic::var_annotation:
4213 // Discard annotate attributes
4214 return 0;
4215
4216 case Intrinsic::init_trampoline: {
4217 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4218
4219 SDValue Ops[6];
4220 Ops[0] = getRoot();
4221 Ops[1] = getValue(I.getOperand(1));
4222 Ops[2] = getValue(I.getOperand(2));
4223 Ops[3] = getValue(I.getOperand(3));
4224 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4225 Ops[5] = DAG.getSrcValue(F);
4226
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004227 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004228 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004229 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004230
4231 setValue(&I, Tmp);
4232 DAG.setRoot(Tmp.getValue(1));
4233 return 0;
4234 }
4235
4236 case Intrinsic::gcroot:
4237 if (GFI) {
4238 Value *Alloca = I.getOperand(1);
4239 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004240
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004241 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4242 GFI->addStackRoot(FI->getIndex(), TypeMap);
4243 }
4244 return 0;
4245
4246 case Intrinsic::gcread:
4247 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004248 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004249 return 0;
4250
4251 case Intrinsic::flt_rounds: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004252 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004253 return 0;
4254 }
4255
4256 case Intrinsic::trap: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004257 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004258 return 0;
4259 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004260
Bill Wendlingef375462008-11-21 02:38:44 +00004261 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004262 return implVisitAluOverflow(I, ISD::UADDO);
4263 case Intrinsic::sadd_with_overflow:
4264 return implVisitAluOverflow(I, ISD::SADDO);
4265 case Intrinsic::usub_with_overflow:
4266 return implVisitAluOverflow(I, ISD::USUBO);
4267 case Intrinsic::ssub_with_overflow:
4268 return implVisitAluOverflow(I, ISD::SSUBO);
4269 case Intrinsic::umul_with_overflow:
4270 return implVisitAluOverflow(I, ISD::UMULO);
4271 case Intrinsic::smul_with_overflow:
4272 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004273
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004274 case Intrinsic::prefetch: {
4275 SDValue Ops[4];
4276 Ops[0] = getRoot();
4277 Ops[1] = getValue(I.getOperand(1));
4278 Ops[2] = getValue(I.getOperand(2));
4279 Ops[3] = getValue(I.getOperand(3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004280 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004281 return 0;
4282 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004284 case Intrinsic::memory_barrier: {
4285 SDValue Ops[6];
4286 Ops[0] = getRoot();
4287 for (int x = 1; x < 6; ++x)
4288 Ops[x] = getValue(I.getOperand(x));
4289
Owen Anderson825b72b2009-08-11 20:47:22 +00004290 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004291 return 0;
4292 }
4293 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004294 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004295 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004296 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004297 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4298 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004299 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004300 getValue(I.getOperand(2)),
4301 getValue(I.getOperand(3)),
4302 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004303 setValue(&I, L);
4304 DAG.setRoot(L.getValue(1));
4305 return 0;
4306 }
4307 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004308 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004309 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004310 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004311 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004312 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004313 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004314 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004315 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004316 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004317 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004318 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004319 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004320 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004321 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004322 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004323 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004324 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004325 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004326 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004327 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004328 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004329
4330 case Intrinsic::invariant_start:
4331 case Intrinsic::lifetime_start:
4332 // Discard region information.
4333 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4334 return 0;
4335 case Intrinsic::invariant_end:
4336 case Intrinsic::lifetime_end:
4337 // Discard region information.
4338 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004339 }
4340}
4341
Dan Gohman98ca4f22009-08-05 01:29:28 +00004342/// Test if the given instruction is in a position to be optimized
4343/// with a tail-call. This roughly means that it's in a block with
4344/// a return and there's nothing that needs to be scheduled
4345/// between it and the return.
4346///
4347/// This function only tests target-independent requirements.
4348/// For target-dependent requirements, a target should override
4349/// TargetLowering::IsEligibleForTailCallOptimization.
4350///
4351static bool
Dan Gohman01205a82009-11-13 18:49:38 +00004352isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004353 const TargetLowering &TLI) {
4354 const BasicBlock *ExitBB = I->getParent();
4355 const TerminatorInst *Term = ExitBB->getTerminator();
4356 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4357 const Function *F = ExitBB->getParent();
4358
4359 // The block must end in a return statement or an unreachable.
4360 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4361
4362 // If I will have a chain, make sure no other instruction that will have a
4363 // chain interposes between I and the return.
4364 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4365 !I->isSafeToSpeculativelyExecute())
4366 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4367 --BBI) {
4368 if (&*BBI == I)
4369 break;
4370 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4371 !BBI->isSafeToSpeculativelyExecute())
4372 return false;
4373 }
4374
4375 // If the block ends with a void return or unreachable, it doesn't matter
4376 // what the call's return type is.
4377 if (!Ret || Ret->getNumOperands() == 0) return true;
4378
Dan Gohmaned9bab32009-11-14 02:06:30 +00004379 // If the return value is undef, it doesn't matter what the call's
4380 // return type is.
4381 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4382
Dan Gohman98ca4f22009-08-05 01:29:28 +00004383 // Conservatively require the attributes of the call to match those of
Dan Gohman01205a82009-11-13 18:49:38 +00004384 // the return. Ignore noalias because it doesn't affect the call sequence.
4385 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4386 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
Dan Gohman98ca4f22009-08-05 01:29:28 +00004387 return false;
4388
4389 // Otherwise, make sure the unmodified return value of I is the return value.
4390 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4391 U = dyn_cast<Instruction>(U->getOperand(0))) {
4392 if (!U)
4393 return false;
4394 if (!U->hasOneUse())
4395 return false;
4396 if (U == I)
4397 break;
4398 // Check for a truly no-op truncate.
4399 if (isa<TruncInst>(U) &&
4400 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4401 continue;
4402 // Check for a truly no-op bitcast.
4403 if (isa<BitCastInst>(U) &&
4404 (U->getOperand(0)->getType() == U->getType() ||
4405 (isa<PointerType>(U->getOperand(0)->getType()) &&
4406 isa<PointerType>(U->getType()))))
4407 continue;
4408 // Otherwise it's not a true no-op.
4409 return false;
4410 }
4411
4412 return true;
4413}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004414
4415void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004416 bool isTailCall,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004417 MachineBasicBlock *LandingPad) {
4418 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4419 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004420 const Type *RetTy = FTy->getReturnType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004421 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4422 unsigned BeginLabel = 0, EndLabel = 0;
4423
4424 TargetLowering::ArgListTy Args;
4425 TargetLowering::ArgListEntry Entry;
4426 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004427
4428 // Check whether the function can return without sret-demotion.
4429 SmallVector<EVT, 4> OutVTs;
4430 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4431 SmallVector<uint64_t, 4> Offsets;
4432 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4433 OutVTs, OutsFlags, TLI, &Offsets);
4434
4435
4436 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4437 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4438
4439 SDValue DemoteStackSlot;
4440
4441 if (!CanLowerReturn) {
4442 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4443 FTy->getReturnType());
4444 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4445 FTy->getReturnType());
4446 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00004447 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004448 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4449
4450 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4451 Entry.Node = DemoteStackSlot;
4452 Entry.Ty = StackSlotPtrType;
4453 Entry.isSExt = false;
4454 Entry.isZExt = false;
4455 Entry.isInReg = false;
4456 Entry.isSRet = true;
4457 Entry.isNest = false;
4458 Entry.isByVal = false;
4459 Entry.Alignment = Align;
4460 Args.push_back(Entry);
4461 RetTy = Type::getVoidTy(FTy->getContext());
4462 }
4463
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004464 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004465 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004466 SDValue ArgNode = getValue(*i);
4467 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4468
4469 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004470 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4471 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4472 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4473 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4474 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4475 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004476 Entry.Alignment = CS.getParamAlignment(attrInd);
4477 Args.push_back(Entry);
4478 }
4479
4480 if (LandingPad && MMI) {
4481 // Insert a label before the invoke call to mark the try range. This can be
4482 // used to detect deletion of the invoke via the MachineModuleInfo.
4483 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004484
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004485 // Both PendingLoads and PendingExports must be flushed here;
4486 // this call might not return.
4487 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004488 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4489 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004490 }
4491
Dan Gohman98ca4f22009-08-05 01:29:28 +00004492 // Check if target-independent constraints permit a tail call here.
4493 // Target-dependent constraints are checked within TLI.LowerCallTo.
4494 if (isTailCall &&
4495 !isInTailCallPosition(CS.getInstruction(),
4496 CS.getAttributes().getRetAttributes(),
4497 TLI))
4498 isTailCall = false;
4499
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004500 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004501 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004502 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004503 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004504 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004505 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004506 isTailCall,
4507 !CS.getInstruction()->use_empty(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004508 Callee, Args, DAG, getCurDebugLoc());
Dan Gohman98ca4f22009-08-05 01:29:28 +00004509 assert((isTailCall || Result.second.getNode()) &&
4510 "Non-null chain expected with non-tail call!");
4511 assert((Result.second.getNode() || !Result.first.getNode()) &&
4512 "Null value expected with tail call!");
4513 if (Result.first.getNode())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004514 setValue(CS.getInstruction(), Result.first);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004515 else if (!CanLowerReturn && Result.second.getNode()) {
4516 // The instruction result is the result of loading from the
4517 // hidden sret parameter.
4518 SmallVector<EVT, 1> PVTs;
4519 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4520
4521 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4522 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4523 EVT PtrVT = PVTs[0];
4524 unsigned NumValues = OutVTs.size();
4525 SmallVector<SDValue, 4> Values(NumValues);
4526 SmallVector<SDValue, 4> Chains(NumValues);
4527
4528 for (unsigned i = 0; i < NumValues; ++i) {
4529 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4530 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot,
4531 DAG.getConstant(Offsets[i], PtrVT)),
4532 NULL, Offsets[i], false, 1);
4533 Values[i] = L;
4534 Chains[i] = L.getValue(1);
4535 }
4536 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4537 MVT::Other, &Chains[0], NumValues);
4538 PendingLoads.push_back(Chain);
4539
4540 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES,
4541 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues),
4542 &Values[0], NumValues));
4543 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00004544 // As a special case, a null chain means that a tail call has
4545 // been emitted and the DAG root is already updated.
4546 if (Result.second.getNode())
4547 DAG.setRoot(Result.second);
4548 else
4549 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004550
4551 if (LandingPad && MMI) {
4552 // Insert a label at the end of the invoke call to mark the try range. This
4553 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4554 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004555 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4556 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004557
4558 // Inform MachineModuleInfo of range.
4559 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4560 }
4561}
4562
4563
4564void SelectionDAGLowering::visitCall(CallInst &I) {
4565 const char *RenameFn = 0;
4566 if (Function *F = I.getCalledFunction()) {
4567 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004568 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4569 if (II) {
4570 if (unsigned IID = II->getIntrinsicID(F)) {
4571 RenameFn = visitIntrinsicCall(I, IID);
4572 if (!RenameFn)
4573 return;
4574 }
4575 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004576 if (unsigned IID = F->getIntrinsicID()) {
4577 RenameFn = visitIntrinsicCall(I, IID);
4578 if (!RenameFn)
4579 return;
4580 }
4581 }
4582
4583 // Check for well-known libc/libm calls. If the function is internal, it
4584 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004585 if (!F->hasLocalLinkage() && F->hasName()) {
4586 StringRef Name = F->getName();
4587 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004588 if (I.getNumOperands() == 3 && // Basic sanity checks.
4589 I.getOperand(1)->getType()->isFloatingPoint() &&
4590 I.getType() == I.getOperand(1)->getType() &&
4591 I.getType() == I.getOperand(2)->getType()) {
4592 SDValue LHS = getValue(I.getOperand(1));
4593 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004594 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004595 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004596 return;
4597 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004598 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004599 if (I.getNumOperands() == 2 && // Basic sanity checks.
4600 I.getOperand(1)->getType()->isFloatingPoint() &&
4601 I.getType() == I.getOperand(1)->getType()) {
4602 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004603 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004604 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004605 return;
4606 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004607 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004608 if (I.getNumOperands() == 2 && // Basic sanity checks.
4609 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004610 I.getType() == I.getOperand(1)->getType() &&
4611 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004612 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004613 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004614 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004615 return;
4616 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004617 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004618 if (I.getNumOperands() == 2 && // Basic sanity checks.
4619 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004620 I.getType() == I.getOperand(1)->getType() &&
4621 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004622 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004623 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004624 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625 return;
4626 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004627 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4628 if (I.getNumOperands() == 2 && // Basic sanity checks.
4629 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004630 I.getType() == I.getOperand(1)->getType() &&
4631 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004632 SDValue Tmp = getValue(I.getOperand(1));
4633 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4634 Tmp.getValueType(), Tmp));
4635 return;
4636 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004637 }
4638 }
4639 } else if (isa<InlineAsm>(I.getOperand(0))) {
4640 visitInlineAsm(&I);
4641 return;
4642 }
4643
4644 SDValue Callee;
4645 if (!RenameFn)
4646 Callee = getValue(I.getOperand(0));
4647 else
Bill Wendling056292f2008-09-16 21:48:12 +00004648 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004649
Dan Gohman98ca4f22009-08-05 01:29:28 +00004650 // Check if we can potentially perform a tail call. More detailed
4651 // checking is be done within LowerCallTo, after more information
4652 // about the call is known.
4653 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4654
4655 LowerCallTo(&I, Callee, isTailCall);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004656}
4657
4658
4659/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004660/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004661/// Chain/Flag as the input and updates them for the output Chain/Flag.
4662/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004663SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004664 SDValue &Chain,
4665 SDValue *Flag) const {
4666 // Assemble the legal parts into the final values.
4667 SmallVector<SDValue, 4> Values(ValueVTs.size());
4668 SmallVector<SDValue, 8> Parts;
4669 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4670 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004671 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004672 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004673 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004674
4675 Parts.resize(NumRegs);
4676 for (unsigned i = 0; i != NumRegs; ++i) {
4677 SDValue P;
4678 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004679 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004680 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004681 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004682 *Flag = P.getValue(2);
4683 }
4684 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004686 // If the source register was virtual and if we know something about it,
4687 // add an assert node.
4688 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4689 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4690 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4691 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4692 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4693 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004694
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695 unsigned RegSize = RegisterVT.getSizeInBits();
4696 unsigned NumSignBits = LOI.NumSignBits;
4697 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699 // FIXME: We capture more information than the dag can represent. For
4700 // now, just use the tightest assertzext/assertsext possible.
4701 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004702 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004703 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004704 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004705 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004706 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004707 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004708 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004709 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004710 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004711 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004712 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004713 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004714 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004715 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004716 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004717 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004718 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004719
Owen Anderson825b72b2009-08-11 20:47:22 +00004720 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004721 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004722 RegisterVT, P, DAG.getValueType(FromVT));
4723
4724 }
4725 }
4726 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004727
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004728 Parts[i] = P;
4729 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004730
Scott Michelfdc40a02009-02-17 22:15:04 +00004731 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004732 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 Part += NumRegs;
4734 Parts.clear();
4735 }
4736
Dale Johannesen66978ee2009-01-31 02:22:37 +00004737 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004738 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4739 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004740}
4741
4742/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004743/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744/// Chain/Flag as the input and updates them for the output Chain/Flag.
4745/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004746void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004747 SDValue &Chain, SDValue *Flag) const {
4748 // Get the list of the values's legal parts.
4749 unsigned NumRegs = Regs.size();
4750 SmallVector<SDValue, 8> Parts(NumRegs);
4751 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004752 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004753 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004754 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004755
Dale Johannesen66978ee2009-01-31 02:22:37 +00004756 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004757 &Parts[Part], NumParts, RegisterVT);
4758 Part += NumParts;
4759 }
4760
4761 // Copy the parts into the registers.
4762 SmallVector<SDValue, 8> Chains(NumRegs);
4763 for (unsigned i = 0; i != NumRegs; ++i) {
4764 SDValue Part;
4765 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004766 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004767 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004768 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004769 *Flag = Part.getValue(1);
4770 }
4771 Chains[i] = Part.getValue(0);
4772 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004773
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004774 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004775 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 // flagged to it. That is the CopyToReg nodes and the user are considered
4777 // a single scheduling unit. If we create a TokenFactor and return it as
4778 // chain, then the TokenFactor is both a predecessor (operand) of the
4779 // user as well as a successor (the TF operands are flagged to the user).
4780 // c1, f1 = CopyToReg
4781 // c2, f2 = CopyToReg
4782 // c3 = TokenFactor c1, c2
4783 // ...
4784 // = op c3, ..., f2
4785 Chain = Chains[NumRegs-1];
4786 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004787 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004788}
4789
4790/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004791/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004792/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004793void RegsForValue::AddInlineAsmOperands(unsigned Code,
4794 bool HasMatching,unsigned MatchingIdx,
4795 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004796 std::vector<SDValue> &Ops) const {
Owen Andersone50ed302009-08-10 22:56:29 +00004797 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004798 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4799 unsigned Flag = Code | (Regs.size() << 3);
4800 if (HasMatching)
4801 Flag |= 0x80000000 | (MatchingIdx << 16);
4802 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004803 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004804 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004805 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004806 for (unsigned i = 0; i != NumRegs; ++i) {
4807 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004808 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004809 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004810 }
4811}
4812
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004813/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004814/// i.e. it isn't a stack pointer or some other special register, return the
4815/// register class for the register. Otherwise, return null.
4816static const TargetRegisterClass *
4817isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4818 const TargetLowering &TLI,
4819 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004820 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004821 const TargetRegisterClass *FoundRC = 0;
4822 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4823 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004824 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004825
4826 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004827 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004828 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4829 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4830 I != E; ++I) {
4831 if (TLI.isTypeLegal(*I)) {
4832 // If we have already found this register in a different register class,
4833 // choose the one with the largest VT specified. For example, on
4834 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004835 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836 ThisVT = *I;
4837 break;
4838 }
4839 }
4840 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004841
Owen Anderson825b72b2009-08-11 20:47:22 +00004842 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004844 // NOTE: This isn't ideal. In particular, this might allocate the
4845 // frame pointer in functions that need it (due to them not being taken
4846 // out of allocation, because a variable sized allocation hasn't been seen
4847 // yet). This is a slight code pessimization, but should still work.
4848 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4849 E = RC->allocation_order_end(MF); I != E; ++I)
4850 if (*I == Reg) {
4851 // We found a matching register class. Keep looking at others in case
4852 // we find one with larger registers that this physreg is also in.
4853 FoundRC = RC;
4854 FoundVT = ThisVT;
4855 break;
4856 }
4857 }
4858 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004859}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004860
4861
4862namespace llvm {
4863/// AsmOperandInfo - This contains information for each constraint that we are
4864/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004865class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004866 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004867public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004868 /// CallOperand - If this is the result output operand or a clobber
4869 /// this is null, otherwise it is the incoming operand to the CallInst.
4870 /// This gets modified as the asm is processed.
4871 SDValue CallOperand;
4872
4873 /// AssignedRegs - If this is a register or register class operand, this
4874 /// contains the set of register corresponding to the operand.
4875 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004876
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4878 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4879 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004880
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004881 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4882 /// busy in OutputRegs/InputRegs.
4883 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004884 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885 std::set<unsigned> &InputRegs,
4886 const TargetRegisterInfo &TRI) const {
4887 if (isOutReg) {
4888 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4889 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4890 }
4891 if (isInReg) {
4892 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4893 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4894 }
4895 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004896
Owen Andersone50ed302009-08-10 22:56:29 +00004897 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004898 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004899 /// MVT::Other.
Owen Anderson1d0be152009-08-13 21:58:54 +00004900 EVT getCallOperandValEVT(LLVMContext &Context,
4901 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004902 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004903 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004904
Chris Lattner81249c92008-10-17 17:05:25 +00004905 if (isa<BasicBlock>(CallOperandVal))
4906 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004907
Chris Lattner81249c92008-10-17 17:05:25 +00004908 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004909
Chris Lattner81249c92008-10-17 17:05:25 +00004910 // If this is an indirect operand, the operand is a pointer to the
4911 // accessed type.
4912 if (isIndirect)
4913 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004914
Chris Lattner81249c92008-10-17 17:05:25 +00004915 // If OpTy is not a single value, it may be a struct/union that we
4916 // can tile with integers.
4917 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4918 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4919 switch (BitSize) {
4920 default: break;
4921 case 1:
4922 case 8:
4923 case 16:
4924 case 32:
4925 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004926 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004927 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004928 break;
4929 }
4930 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004931
Chris Lattner81249c92008-10-17 17:05:25 +00004932 return TLI.getValueType(OpTy, true);
4933 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004934
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004935private:
4936 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4937 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004938 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004939 const TargetRegisterInfo &TRI) {
4940 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4941 Regs.insert(Reg);
4942 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4943 for (; *Aliases; ++Aliases)
4944 Regs.insert(*Aliases);
4945 }
4946};
4947} // end llvm namespace.
4948
4949
4950/// GetRegistersForValue - Assign registers (virtual or physical) for the
4951/// specified operand. We prefer to assign virtual registers, to allow the
4952/// register allocator handle the assignment process. However, if the asm uses
4953/// features that we can't model on machineinstrs, we have SDISel do the
4954/// allocation. This produces generally horrible, but correct, code.
4955///
4956/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004957/// Input and OutputRegs are the set of already allocated physical registers.
4958///
4959void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004960GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004961 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004962 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00004963 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00004964
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004965 // Compute whether this value requires an input register, an output register,
4966 // or both.
4967 bool isOutReg = false;
4968 bool isInReg = false;
4969 switch (OpInfo.Type) {
4970 case InlineAsm::isOutput:
4971 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004972
4973 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004974 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004975 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004976 break;
4977 case InlineAsm::isInput:
4978 isInReg = true;
4979 isOutReg = false;
4980 break;
4981 case InlineAsm::isClobber:
4982 isOutReg = true;
4983 isInReg = true;
4984 break;
4985 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
4987
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004988 MachineFunction &MF = DAG.getMachineFunction();
4989 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991 // If this is a constraint for a single physreg, or a constraint for a
4992 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004993 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004994 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4995 OpInfo.ConstraintVT);
4996
4997 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00004998 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00004999 // If this is a FP input in an integer register (or visa versa) insert a bit
5000 // cast of the input value. More generally, handle any case where the input
5001 // value disagrees with the register class we plan to stick this in.
5002 if (OpInfo.Type == InlineAsm::isInput &&
5003 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005004 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005005 // types are identical size, use a bitcast to convert (e.g. two differing
5006 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005007 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005008 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005009 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005010 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005011 OpInfo.ConstraintVT = RegVT;
5012 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5013 // If the input is a FP value and we want it in FP registers, do a
5014 // bitcast to the corresponding integer type. This turns an f64 value
5015 // into i64, which can be passed with two i32 values on a 32-bit
5016 // machine.
Owen Anderson23b9b192009-08-12 00:36:31 +00005017 RegVT = EVT::getIntegerVT(Context,
5018 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005019 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005020 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005021 OpInfo.ConstraintVT = RegVT;
5022 }
5023 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005024
Owen Anderson23b9b192009-08-12 00:36:31 +00005025 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005026 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005027
Owen Andersone50ed302009-08-10 22:56:29 +00005028 EVT RegVT;
5029 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005030
5031 // If this is a constraint for a specific physical register, like {r17},
5032 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005033 if (unsigned AssignedReg = PhysReg.first) {
5034 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005035 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005036 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005038 // Get the actual register value type. This is important, because the user
5039 // may have asked for (e.g.) the AX register in i32 type. We need to
5040 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005041 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005043 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005044 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045
5046 // If this is an expanded reference, add the rest of the regs to Regs.
5047 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005048 TargetRegisterClass::iterator I = RC->begin();
5049 for (; *I != AssignedReg; ++I)
5050 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005051
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005052 // Already added the first reg.
5053 --NumRegs; ++I;
5054 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005055 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005056 Regs.push_back(*I);
5057 }
5058 }
5059 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5060 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5061 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5062 return;
5063 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005064
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005065 // Otherwise, if this was a reference to an LLVM register class, create vregs
5066 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005067 if (const TargetRegisterClass *RC = PhysReg.second) {
5068 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005069 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005070 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005071
Evan Chengfb112882009-03-23 08:01:15 +00005072 // Create the appropriate number of virtual registers.
5073 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5074 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005075 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005076
Evan Chengfb112882009-03-23 08:01:15 +00005077 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5078 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005079 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005080
5081 // This is a reference to a register class that doesn't directly correspond
5082 // to an LLVM register class. Allocate NumRegs consecutive, available,
5083 // registers from the class.
5084 std::vector<unsigned> RegClassRegs
5085 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5086 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005087
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005088 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5089 unsigned NumAllocated = 0;
5090 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5091 unsigned Reg = RegClassRegs[i];
5092 // See if this register is available.
5093 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5094 (isInReg && InputRegs.count(Reg))) { // Already used.
5095 // Make sure we find consecutive registers.
5096 NumAllocated = 0;
5097 continue;
5098 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005100 // Check to see if this register is allocatable (i.e. don't give out the
5101 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005102 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5103 if (!RC) { // Couldn't allocate this register.
5104 // Reset NumAllocated to make sure we return consecutive registers.
5105 NumAllocated = 0;
5106 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005108
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005109 // Okay, this register is good, we can use it.
5110 ++NumAllocated;
5111
5112 // If we allocated enough consecutive registers, succeed.
5113 if (NumAllocated == NumRegs) {
5114 unsigned RegStart = (i-NumAllocated)+1;
5115 unsigned RegEnd = i+1;
5116 // Mark all of the allocated registers used.
5117 for (unsigned i = RegStart; i != RegEnd; ++i)
5118 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005119
5120 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121 OpInfo.ConstraintVT);
5122 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5123 return;
5124 }
5125 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005126
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005127 // Otherwise, we couldn't allocate enough registers for this.
5128}
5129
Evan Chengda43bcf2008-09-24 00:05:32 +00005130/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5131/// processed uses a memory 'm' constraint.
5132static bool
5133hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005134 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005135 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5136 InlineAsm::ConstraintInfo &CI = CInfos[i];
5137 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5138 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5139 if (CType == TargetLowering::C_Memory)
5140 return true;
5141 }
Chris Lattner6c147292009-04-30 00:48:50 +00005142
5143 // Indirect operand accesses access memory.
5144 if (CI.isIndirect)
5145 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005146 }
5147
5148 return false;
5149}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005150
5151/// visitInlineAsm - Handle a call to an InlineAsm object.
5152///
5153void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5154 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5155
5156 /// ConstraintOperands - Information about all of the constraints.
5157 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005158
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005159 std::set<unsigned> OutputRegs, InputRegs;
5160
5161 // Do a prepass over the constraints, canonicalizing them, and building up the
5162 // ConstraintOperands list.
5163 std::vector<InlineAsm::ConstraintInfo>
5164 ConstraintInfos = IA->ParseConstraints();
5165
Evan Chengda43bcf2008-09-24 00:05:32 +00005166 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005167
5168 SDValue Chain, Flag;
5169
5170 // We won't need to flush pending loads if this asm doesn't touch
5171 // memory and is nonvolatile.
5172 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005173 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005174 else
5175 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005176
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005177 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5178 unsigned ResNo = 0; // ResNo - The result number of the next output.
5179 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5180 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5181 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005182
Owen Anderson825b72b2009-08-11 20:47:22 +00005183 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005184
5185 // Compute the value type for each operand.
5186 switch (OpInfo.Type) {
5187 case InlineAsm::isOutput:
5188 // Indirect outputs just consume an argument.
5189 if (OpInfo.isIndirect) {
5190 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5191 break;
5192 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005193
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005194 // The return value of the call is this value. As such, there is no
5195 // corresponding argument.
Owen Anderson1d0be152009-08-13 21:58:54 +00005196 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5197 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005198 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5199 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5200 } else {
5201 assert(ResNo == 0 && "Asm only has one result!");
5202 OpVT = TLI.getValueType(CS.getType());
5203 }
5204 ++ResNo;
5205 break;
5206 case InlineAsm::isInput:
5207 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5208 break;
5209 case InlineAsm::isClobber:
5210 // Nothing to do.
5211 break;
5212 }
5213
5214 // If this is an input or an indirect output, process the call argument.
5215 // BasicBlocks are labels, currently appearing only in asm's.
5216 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005217 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005218 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5219
Chris Lattner81249c92008-10-17 17:05:25 +00005220 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005221 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005222 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005223 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005224 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005225
Owen Anderson1d0be152009-08-13 21:58:54 +00005226 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005227 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005229 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005230 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005231
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005232 // Second pass over the constraints: compute which constraint option to use
5233 // and assign registers to constraints that want a specific physreg.
5234 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5235 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005236
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005237 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005238 // matching input. If their types mismatch, e.g. one is an integer, the
5239 // other is floating point, or their sizes are different, flag it as an
5240 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005241 if (OpInfo.hasMatchingInput()) {
5242 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5243 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005244 if ((OpInfo.ConstraintVT.isInteger() !=
5245 Input.ConstraintVT.isInteger()) ||
5246 (OpInfo.ConstraintVT.getSizeInBits() !=
5247 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005248 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005249 " with a matching output constraint of incompatible"
5250 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005251 }
5252 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005253 }
5254 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005255
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005256 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005257 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005258
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 // If this is a memory input, and if the operand is not indirect, do what we
5260 // need to to provide an address for the memory input.
5261 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5262 !OpInfo.isIndirect) {
5263 assert(OpInfo.Type == InlineAsm::isInput &&
5264 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005265
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005266 // Memory operands really want the address of the value. If we don't have
5267 // an indirect input, put it in the constpool if we can, otherwise spill
5268 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005269
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005270 // If the operand is a float, integer, or vector constant, spill to a
5271 // constant pool entry to get its address.
5272 Value *OpVal = OpInfo.CallOperandVal;
5273 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5274 isa<ConstantVector>(OpVal)) {
5275 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5276 TLI.getPointerTy());
5277 } else {
5278 // Otherwise, create a stack slot and emit a store to it before the
5279 // asm.
5280 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005281 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005282 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5283 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005284 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005285 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005286 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005287 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005288 OpInfo.CallOperand = StackSlot;
5289 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005291 // There is no longer a Value* corresponding to this operand.
5292 OpInfo.CallOperandVal = 0;
5293 // It is now an indirect operand.
5294 OpInfo.isIndirect = true;
5295 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005296
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005297 // If this constraint is for a specific register, allocate it before
5298 // anything else.
5299 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005300 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005301 }
5302 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005303
5304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005305 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005306 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005307 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5308 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005309
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005310 // C_Register operands have already been allocated, Other/Memory don't need
5311 // to be.
5312 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005313 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005314 }
5315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005316 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5317 std::vector<SDValue> AsmNodeOperands;
5318 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5319 AsmNodeOperands.push_back(
Owen Anderson825b72b2009-08-11 20:47:22 +00005320 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005321
5322
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 // Loop over all of the inputs, copying the operand values into the
5324 // appropriate registers and processing the output regs.
5325 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005326
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5328 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005329
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005330 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5331 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5332
5333 switch (OpInfo.Type) {
5334 case InlineAsm::isOutput: {
5335 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5336 OpInfo.ConstraintType != TargetLowering::C_Register) {
5337 // Memory output, or 'other' output (e.g. 'X' constraint).
5338 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5339
5340 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005341 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5342 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005343 TLI.getPointerTy()));
5344 AsmNodeOperands.push_back(OpInfo.CallOperand);
5345 break;
5346 }
5347
5348 // Otherwise, this is a register or register class output.
5349
5350 // Copy the output from the appropriate register. Find a register that
5351 // we can use.
5352 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005353 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005354 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005355 }
5356
5357 // If this is an indirect operand, store through the pointer after the
5358 // asm.
5359 if (OpInfo.isIndirect) {
5360 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5361 OpInfo.CallOperandVal));
5362 } else {
5363 // This is the result value of the call.
Owen Anderson1d0be152009-08-13 21:58:54 +00005364 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5365 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005366 // Concatenate this output onto the outputs list.
5367 RetValRegs.append(OpInfo.AssignedRegs);
5368 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005369
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 // Add information to the INLINEASM node to know that this register is
5371 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005372 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5373 6 /* EARLYCLOBBER REGDEF */ :
5374 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005375 false,
5376 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005377 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005378 break;
5379 }
5380 case InlineAsm::isInput: {
5381 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005382
Chris Lattner6bdcda32008-10-17 16:47:46 +00005383 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005384 // If this is required to match an output register we have already set,
5385 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005386 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005387
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005388 // Scan until we find the definition we already emitted of this operand.
5389 // When we find it, create a RegsForValue operand.
5390 unsigned CurOp = 2; // The first operand.
5391 for (; OperandNo; --OperandNo) {
5392 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005393 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005394 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005395 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5396 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5397 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005398 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005399 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005400 }
5401
Evan Cheng697cbbf2009-03-20 18:03:34 +00005402 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005403 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005404 if ((OpFlag & 7) == 2 /*REGDEF*/
5405 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5406 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005407 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005408 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005409 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005410 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005411 RegsForValue MatchedRegs;
5412 MatchedRegs.TLI = &TLI;
5413 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005414 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005415 MatchedRegs.RegVTs.push_back(RegVT);
5416 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005417 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005418 i != e; ++i)
5419 MatchedRegs.Regs.
5420 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005421
5422 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005423 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5424 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005425 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5426 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005427 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005428 break;
5429 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005430 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5431 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5432 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005433 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005434 // See InlineAsm.h isUseOperandTiedToDef.
5435 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005436 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437 TLI.getPointerTy()));
5438 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5439 break;
5440 }
5441 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005443 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005444 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005446
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 std::vector<SDValue> Ops;
5448 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005449 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005450 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005451 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005452 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005454
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005455 // Add information to the INLINEASM node to know about this input.
5456 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005457 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005458 TLI.getPointerTy()));
5459 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5460 break;
5461 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5462 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5463 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5464 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005465
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005466 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005467 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5468 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005469 TLI.getPointerTy()));
5470 AsmNodeOperands.push_back(InOperandVal);
5471 break;
5472 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005473
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005474 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5475 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5476 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005477 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005478 "Don't know how to handle indirect register inputs yet!");
5479
5480 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005481 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005482 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005483 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005484 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005485
Dale Johannesen66978ee2009-01-31 02:22:37 +00005486 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5487 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005488
Evan Cheng697cbbf2009-03-20 18:03:34 +00005489 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005490 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 break;
5492 }
5493 case InlineAsm::isClobber: {
5494 // Add the clobbered value to the operand list, so that the register
5495 // allocator is aware that the physreg got clobbered.
5496 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005497 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005498 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005499 break;
5500 }
5501 }
5502 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005503
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005504 // Finish up input operands.
5505 AsmNodeOperands[0] = Chain;
5506 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005507
Dale Johannesen66978ee2009-01-31 02:22:37 +00005508 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005509 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005510 &AsmNodeOperands[0], AsmNodeOperands.size());
5511 Flag = Chain.getValue(1);
5512
5513 // If this asm returns a register value, copy the result from that register
5514 // and set it as the value of the call.
5515 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005516 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005517 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005518
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005519 // FIXME: Why don't we do this for inline asms with MRVs?
5520 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005521 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005522
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005523 // If any of the results of the inline asm is a vector, it may have the
5524 // wrong width/num elts. This can happen for register classes that can
5525 // contain multiple different value types. The preg or vreg allocated may
5526 // not have the same VT as was expected. Convert it to the right type
5527 // with bit_convert.
5528 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005529 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005530 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005531
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005532 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005533 ResultType.isInteger() && Val.getValueType().isInteger()) {
5534 // If a result value was tied to an input value, the computed result may
5535 // have a wider width than the expected result. Extract the relevant
5536 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005537 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005538 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005539
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005540 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005541 }
Dan Gohman95915732008-10-18 01:03:45 +00005542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005544 // Don't need to use this as a chain in this case.
5545 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5546 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005547 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005548
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005549 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005550
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005551 // Process indirect outputs, first output all of the flagged copies out of
5552 // physregs.
5553 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5554 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5555 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005556 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5557 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005559
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005560 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005561
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005562 // Emit the non-flagged stores from the physregs.
5563 SmallVector<SDValue, 8> OutChains;
5564 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005565 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005566 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005567 getValue(StoresToEmit[i].second),
5568 StoresToEmit[i].second, 0));
5569 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005570 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005571 &OutChains[0], OutChains.size());
5572 DAG.setRoot(Chain);
5573}
5574
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005575void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005576 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005577 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005578 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005579 DAG.getSrcValue(I.getOperand(1))));
5580}
5581
5582void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005583 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5584 getRoot(), getValue(I.getOperand(0)),
5585 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005586 setValue(&I, V);
5587 DAG.setRoot(V.getValue(1));
5588}
5589
5590void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005591 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005592 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005593 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005594 DAG.getSrcValue(I.getOperand(1))));
5595}
5596
5597void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005598 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005599 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005600 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005601 getValue(I.getOperand(2)),
5602 DAG.getSrcValue(I.getOperand(1)),
5603 DAG.getSrcValue(I.getOperand(2))));
5604}
5605
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005606/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005607/// implementation, which just calls LowerCall.
5608/// FIXME: When all targets are
5609/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005610std::pair<SDValue, SDValue>
5611TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5612 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005613 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005614 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005615 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005616 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005617 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00005618
Dan Gohman1937e2f2008-09-16 01:42:28 +00005619 assert((!isTailCall || PerformTailCallOpt) &&
5620 "isTailCall set when tail-call optimizations are disabled!");
5621
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005622 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005623 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005624 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005625 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005626 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5627 for (unsigned Value = 0, NumValues = ValueVTs.size();
5628 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005629 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005630 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005631 SDValue Op = SDValue(Args[i].Node.getNode(),
5632 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005633 ISD::ArgFlagsTy Flags;
5634 unsigned OriginalAlignment =
5635 getTargetData()->getABITypeAlignment(ArgTy);
5636
5637 if (Args[i].isZExt)
5638 Flags.setZExt();
5639 if (Args[i].isSExt)
5640 Flags.setSExt();
5641 if (Args[i].isInReg)
5642 Flags.setInReg();
5643 if (Args[i].isSRet)
5644 Flags.setSRet();
5645 if (Args[i].isByVal) {
5646 Flags.setByVal();
5647 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5648 const Type *ElementTy = Ty->getElementType();
5649 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005650 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005651 // For ByVal, alignment should come from FE. BE will guess if this
5652 // info is not there but there are cases it cannot get right.
5653 if (Args[i].Alignment)
5654 FrameAlign = Args[i].Alignment;
5655 Flags.setByValAlign(FrameAlign);
5656 Flags.setByValSize(FrameSize);
5657 }
5658 if (Args[i].isNest)
5659 Flags.setNest();
5660 Flags.setOrigAlign(OriginalAlignment);
5661
Owen Anderson23b9b192009-08-12 00:36:31 +00005662 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5663 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005664 SmallVector<SDValue, 4> Parts(NumParts);
5665 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5666
5667 if (Args[i].isSExt)
5668 ExtendKind = ISD::SIGN_EXTEND;
5669 else if (Args[i].isZExt)
5670 ExtendKind = ISD::ZERO_EXTEND;
5671
Dale Johannesen66978ee2009-01-31 02:22:37 +00005672 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005673
Dan Gohman98ca4f22009-08-05 01:29:28 +00005674 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005675 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005676 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5677 if (NumParts > 1 && j == 0)
5678 MyFlags.Flags.setSplit();
5679 else if (j != 0)
5680 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005681
Dan Gohman98ca4f22009-08-05 01:29:28 +00005682 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005683 }
5684 }
5685 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005686
Dan Gohman98ca4f22009-08-05 01:29:28 +00005687 // Handle the incoming return values from the call.
5688 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005689 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005690 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005691 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005692 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005693 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5694 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005695 for (unsigned i = 0; i != NumRegs; ++i) {
5696 ISD::InputArg MyFlags;
5697 MyFlags.VT = RegisterVT;
5698 MyFlags.Used = isReturnValueUsed;
5699 if (RetSExt)
5700 MyFlags.Flags.setSExt();
5701 if (RetZExt)
5702 MyFlags.Flags.setZExt();
5703 if (isInreg)
5704 MyFlags.Flags.setInReg();
5705 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005706 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005707 }
5708
Dan Gohman98ca4f22009-08-05 01:29:28 +00005709 // Check if target-dependent constraints permit a tail call here.
5710 // Target-independent constraints should be checked by the caller.
5711 if (isTailCall &&
5712 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5713 isTailCall = false;
5714
5715 SmallVector<SDValue, 4> InVals;
5716 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5717 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005718
5719 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005720 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005721 "LowerCall didn't return a valid chain!");
5722 assert((!isTailCall || InVals.empty()) &&
5723 "LowerCall emitted a return value for a tail call!");
5724 assert((isTailCall || InVals.size() == Ins.size()) &&
5725 "LowerCall didn't emit the correct number of values!");
5726 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5727 assert(InVals[i].getNode() &&
5728 "LowerCall emitted a null value!");
5729 assert(Ins[i].VT == InVals[i].getValueType() &&
5730 "LowerCall emitted a value with the wrong type!");
5731 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005732
5733 // For a tail call, the return value is merely live-out and there aren't
5734 // any nodes in the DAG representing it. Return a special value to
5735 // indicate that a tail call has been emitted and no more Instructions
5736 // should be processed in the current block.
5737 if (isTailCall) {
5738 DAG.setRoot(Chain);
5739 return std::make_pair(SDValue(), SDValue());
5740 }
5741
5742 // Collect the legal value parts into potentially illegal values
5743 // that correspond to the original function's return values.
5744 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5745 if (RetSExt)
5746 AssertOp = ISD::AssertSext;
5747 else if (RetZExt)
5748 AssertOp = ISD::AssertZext;
5749 SmallVector<SDValue, 4> ReturnValues;
5750 unsigned CurReg = 0;
5751 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005752 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005753 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5754 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005755
5756 SDValue ReturnValue =
5757 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5758 AssertOp);
5759 ReturnValues.push_back(ReturnValue);
5760 CurReg += NumRegs;
5761 }
5762
5763 // For a function returning void, there is no return value. We can't create
5764 // such a node, so we just return a null return value in that case. In
5765 // that case, nothing will actualy look at the value.
5766 if (ReturnValues.empty())
5767 return std::make_pair(SDValue(), Chain);
5768
5769 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5770 DAG.getVTList(&RetTys[0], RetTys.size()),
5771 &ReturnValues[0], ReturnValues.size());
5772
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005773 return std::make_pair(Res, Chain);
5774}
5775
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005776void TargetLowering::LowerOperationWrapper(SDNode *N,
5777 SmallVectorImpl<SDValue> &Results,
5778 SelectionDAG &DAG) {
5779 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005780 if (Res.getNode())
5781 Results.push_back(Res);
5782}
5783
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005784SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005785 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005786 return SDValue();
5787}
5788
5789
5790void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5791 SDValue Op = getValue(V);
5792 assert((Op.getOpcode() != ISD::CopyFromReg ||
5793 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5794 "Copy from a reg to the same reg!");
5795 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5796
Owen Anderson23b9b192009-08-12 00:36:31 +00005797 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005798 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005799 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005800 PendingExports.push_back(Chain);
5801}
5802
5803#include "llvm/CodeGen/SelectionDAGISel.h"
5804
Dan Gohman8c2b5252009-10-30 01:27:03 +00005805void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005806 // If this is the entry block, emit arguments.
5807 Function &F = *LLVMBB->getParent();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005808 SelectionDAG &DAG = SDL->DAG;
5809 SDValue OldRoot = DAG.getRoot();
5810 DebugLoc dl = SDL->getCurDebugLoc();
5811 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005812 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005813
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005814 // Check whether the function can return without sret-demotion.
5815 SmallVector<EVT, 4> OutVTs;
5816 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005817 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5818 OutVTs, OutsFlags, TLI);
5819 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5820
5821 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5822 OutVTs, OutsFlags, DAG);
5823 if (!FLI.CanLowerReturn) {
5824 // Put in an sret pointer parameter before all the other parameters.
5825 SmallVector<EVT, 1> ValueVTs;
5826 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5827
5828 // NOTE: Assuming that a pointer will never break down to more than one VT
5829 // or one register.
5830 ISD::ArgFlagsTy Flags;
5831 Flags.setSRet();
5832 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5833 ISD::InputArg RetArg(Flags, RegisterVT, true);
5834 Ins.push_back(RetArg);
5835 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005836
Dan Gohman98ca4f22009-08-05 01:29:28 +00005837 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005838 unsigned Idx = 1;
5839 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5840 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005841 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005842 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5843 bool isArgValueUsed = !I->use_empty();
5844 for (unsigned Value = 0, NumValues = ValueVTs.size();
5845 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005846 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005847 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005848 ISD::ArgFlagsTy Flags;
5849 unsigned OriginalAlignment =
5850 TD->getABITypeAlignment(ArgTy);
5851
5852 if (F.paramHasAttr(Idx, Attribute::ZExt))
5853 Flags.setZExt();
5854 if (F.paramHasAttr(Idx, Attribute::SExt))
5855 Flags.setSExt();
5856 if (F.paramHasAttr(Idx, Attribute::InReg))
5857 Flags.setInReg();
5858 if (F.paramHasAttr(Idx, Attribute::StructRet))
5859 Flags.setSRet();
5860 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5861 Flags.setByVal();
5862 const PointerType *Ty = cast<PointerType>(I->getType());
5863 const Type *ElementTy = Ty->getElementType();
5864 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5865 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5866 // For ByVal, alignment should be passed from FE. BE will guess if
5867 // this info is not there but there are cases it cannot get right.
5868 if (F.getParamAlignment(Idx))
5869 FrameAlign = F.getParamAlignment(Idx);
5870 Flags.setByValAlign(FrameAlign);
5871 Flags.setByValSize(FrameSize);
5872 }
5873 if (F.paramHasAttr(Idx, Attribute::Nest))
5874 Flags.setNest();
5875 Flags.setOrigAlign(OriginalAlignment);
5876
Owen Anderson23b9b192009-08-12 00:36:31 +00005877 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5878 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005879 for (unsigned i = 0; i != NumRegs; ++i) {
5880 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5881 if (NumRegs > 1 && i == 0)
5882 MyFlags.Flags.setSplit();
5883 // if it isn't first piece, alignment must be 1
5884 else if (i > 0)
5885 MyFlags.Flags.setOrigAlign(1);
5886 Ins.push_back(MyFlags);
5887 }
5888 }
5889 }
5890
5891 // Call the target to set up the argument values.
5892 SmallVector<SDValue, 8> InVals;
5893 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5894 F.isVarArg(), Ins,
5895 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005896
5897 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005898 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005899 "LowerFormalArguments didn't return a valid chain!");
5900 assert(InVals.size() == Ins.size() &&
5901 "LowerFormalArguments didn't emit the correct number of values!");
5902 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5903 assert(InVals[i].getNode() &&
5904 "LowerFormalArguments emitted a null value!");
5905 assert(Ins[i].VT == InVals[i].getValueType() &&
5906 "LowerFormalArguments emitted a value with the wrong type!");
5907 });
5908
5909 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005910 DAG.setRoot(NewRoot);
5911
5912 // Set up the argument values.
5913 unsigned i = 0;
5914 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005915 if (!FLI.CanLowerReturn) {
5916 // Create a virtual register for the sret pointer, and put in a copy
5917 // from the sret argument into it.
5918 SmallVector<EVT, 1> ValueVTs;
5919 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5920 EVT VT = ValueVTs[0];
5921 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5922 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5923 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
5924 VT, AssertOp);
5925
5926 MachineFunction& MF = SDL->DAG.getMachineFunction();
5927 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5928 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5929 FLI.DemoteRegister = SRetReg;
5930 NewRoot = SDL->DAG.getCopyToReg(NewRoot, SDL->getCurDebugLoc(), SRetReg, ArgValue);
5931 DAG.setRoot(NewRoot);
5932
5933 // i indexes lowered arguments. Bump it past the hidden sret argument.
5934 // Idx indexes LLVM arguments. Don't touch it.
5935 ++i;
5936 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00005937 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5938 ++I, ++Idx) {
5939 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00005940 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005941 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005942 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005943 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005944 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005945 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5946 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005947
5948 if (!I->use_empty()) {
5949 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5950 if (F.paramHasAttr(Idx, Attribute::SExt))
5951 AssertOp = ISD::AssertSext;
5952 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5953 AssertOp = ISD::AssertZext;
5954
5955 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5956 PartVT, VT, AssertOp));
5957 }
5958 i += NumParts;
5959 }
5960 if (!I->use_empty()) {
5961 SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5962 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005963 // If this argument is live outside of the entry block, insert a copy from
5964 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005965 SDL->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005966 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005967 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00005968 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005969
5970 // Finally, if the target has anything special to do, allow it to do so.
5971 // FIXME: this should insert code into the DAG!
5972 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5973}
5974
5975/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5976/// ensure constants are generated when needed. Remember the virtual registers
5977/// that need to be added to the Machine PHI nodes as input. We cannot just
5978/// directly add them, because expansion might result in multiple MBB's for one
5979/// BB. As such, the start of the BB might correspond to a different MBB than
5980/// the end.
5981///
5982void
5983SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5984 TerminatorInst *TI = LLVMBB->getTerminator();
5985
5986 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5987
5988 // Check successor nodes' PHI nodes that expect a constant to be available
5989 // from this block.
5990 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5991 BasicBlock *SuccBB = TI->getSuccessor(succ);
5992 if (!isa<PHINode>(SuccBB->begin())) continue;
5993 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005994
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005995 // If this terminator has multiple identical successors (common for
5996 // switches), only handle each succ once.
5997 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005998
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005999 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6000 PHINode *PN;
6001
6002 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6003 // nodes and Machine PHI nodes, but the incoming operands have not been
6004 // emitted yet.
6005 for (BasicBlock::iterator I = SuccBB->begin();
6006 (PN = dyn_cast<PHINode>(I)); ++I) {
6007 // Ignore dead phi's.
6008 if (PN->use_empty()) continue;
6009
6010 unsigned Reg;
6011 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6012
6013 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6014 unsigned &RegOut = SDL->ConstantsOut[C];
6015 if (RegOut == 0) {
6016 RegOut = FuncInfo->CreateRegForValue(C);
6017 SDL->CopyValueToVirtualRegister(C, RegOut);
6018 }
6019 Reg = RegOut;
6020 } else {
6021 Reg = FuncInfo->ValueMap[PHIOp];
6022 if (Reg == 0) {
6023 assert(isa<AllocaInst>(PHIOp) &&
6024 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6025 "Didn't codegen value into a register!??");
6026 Reg = FuncInfo->CreateRegForValue(PHIOp);
6027 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
6028 }
6029 }
6030
6031 // Remember that this register needs to added to the machine PHI node as
6032 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006033 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006034 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6035 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006036 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006037 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006038 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6039 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6040 Reg += NumRegisters;
6041 }
6042 }
6043 }
6044 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006045}
6046
Dan Gohman3df24e62008-09-03 23:12:08 +00006047/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6048/// supports legal types, and it emits MachineInstrs directly instead of
6049/// creating SelectionDAG nodes.
6050///
6051bool
6052SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6053 FastISel *F) {
6054 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006055
Dan Gohman3df24e62008-09-03 23:12:08 +00006056 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6057 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6058
6059 // Check successor nodes' PHI nodes that expect a constant to be available
6060 // from this block.
6061 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6062 BasicBlock *SuccBB = TI->getSuccessor(succ);
6063 if (!isa<PHINode>(SuccBB->begin())) continue;
6064 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006065
Dan Gohman3df24e62008-09-03 23:12:08 +00006066 // If this terminator has multiple identical successors (common for
6067 // switches), only handle each succ once.
6068 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006069
Dan Gohman3df24e62008-09-03 23:12:08 +00006070 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6071 PHINode *PN;
6072
6073 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6074 // nodes and Machine PHI nodes, but the incoming operands have not been
6075 // emitted yet.
6076 for (BasicBlock::iterator I = SuccBB->begin();
6077 (PN = dyn_cast<PHINode>(I)); ++I) {
6078 // Ignore dead phi's.
6079 if (PN->use_empty()) continue;
6080
6081 // Only handle legal types. Two interesting things to note here. First,
6082 // by bailing out early, we may leave behind some dead instructions,
6083 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6084 // own moves. Second, this check is necessary becuase FastISel doesn't
6085 // use CreateRegForValue to create registers, so it always creates
6086 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006087 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006088 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6089 // Promote MVT::i1.
6090 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006091 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006092 else {
6093 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6094 return false;
6095 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006096 }
6097
6098 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6099
6100 unsigned Reg = F->getRegForValue(PHIOp);
6101 if (Reg == 0) {
6102 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6103 return false;
6104 }
6105 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6106 }
6107 }
6108
6109 return true;
6110}