blob: f74d6aefd36c3b8db2887ed631b2f663e62ca60c [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] =
308 MF->getFrameInfo()->CreateStackObject(TySize, Align);
309 }
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) {
338 if (CallInst *CI = dyn_cast<CallInst>(I)) {
339 if (Function *F = CI->getCalledFunction()) {
340 switch (F->getIntrinsicID()) {
341 default: break;
342 case Intrinsic::dbg_stoppoint: {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000343 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000344 if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default))
345 DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000346 break;
347 }
348 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000349 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000350 if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default))
351 DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000352 break;
353 }
354 }
355 }
356 }
357
358 PN = dyn_cast<PHINode>(I);
359 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000360
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 unsigned PHIReg = ValueMap[PN];
362 assert(PHIReg && "PHI node does not have an assigned virtual register!");
363
Owen Andersone50ed302009-08-10 22:56:29 +0000364 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000365 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
366 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +0000367 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +0000368 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000369 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000370 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000371 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000372 PHIReg += NumRegisters;
373 }
374 }
375 }
376}
377
Owen Andersone50ed302009-08-10 22:56:29 +0000378unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000379 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
380}
381
382/// CreateRegForValue - Allocate the appropriate number of virtual registers of
383/// the correctly promoted or expanded types. Assign these registers
384/// consecutive vreg numbers and return the first assigned number.
385///
386/// In the case that the given value has struct or array type, this function
387/// will assign registers for each member or element.
388///
389unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Owen Andersone50ed302009-08-10 22:56:29 +0000390 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000391 ComputeValueVTs(TLI, V->getType(), ValueVTs);
392
393 unsigned FirstReg = 0;
394 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000395 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000396 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000397
Owen Anderson23b9b192009-08-12 00:36:31 +0000398 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000399 for (unsigned i = 0; i != NumRegs; ++i) {
400 unsigned R = MakeReg(RegisterVT);
401 if (!FirstReg) FirstReg = R;
402 }
403 }
404 return FirstReg;
405}
406
407/// getCopyFromParts - Create a value that contains the specified legal parts
408/// combined into the value they represent. If the parts combine to a type
409/// larger then ValueVT then AssertOp can be used to specify whether the extra
410/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
411/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000412static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
413 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000414 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000415 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000416 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000418 SDValue Val = Parts[0];
419
420 if (NumParts > 1) {
421 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000422 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000423 unsigned PartBits = PartVT.getSizeInBits();
424 unsigned ValueBits = ValueVT.getSizeInBits();
425
426 // Assemble the power of 2 part.
427 unsigned RoundParts = NumParts & (NumParts - 1) ?
428 1 << Log2_32(NumParts) : NumParts;
429 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000430 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000431 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000432 SDValue Lo, Hi;
433
Owen Anderson23b9b192009-08-12 00:36:31 +0000434 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000435
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000436 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000437 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
438 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000439 PartVT, HalfVT);
440 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000441 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
442 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 }
444 if (TLI.isBigEndian())
445 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000446 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000447
448 if (RoundParts < NumParts) {
449 // Assemble the trailing non-power-of-2 part.
450 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000451 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000452 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000453 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000454
455 // Combine the round and odd parts.
456 Lo = Val;
457 if (TLI.isBigEndian())
458 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000459 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000460 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
461 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000462 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000463 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000464 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
465 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000466 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000467 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000468 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000469 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000470 unsigned NumIntermediates;
471 unsigned NumRegs =
Owen Anderson23b9b192009-08-12 00:36:31 +0000472 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
473 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000474 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
475 NumParts = NumRegs; // Silence a compiler warning.
476 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
477 assert(RegisterVT == Parts[0].getValueType() &&
478 "Part type doesn't match part!");
479
480 // Assemble the parts into intermediate operands.
481 SmallVector<SDValue, 8> Ops(NumIntermediates);
482 if (NumIntermediates == NumParts) {
483 // If the register was not expanded, truncate or copy the value,
484 // as appropriate.
485 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000486 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000487 PartVT, IntermediateVT);
488 } else if (NumParts > 0) {
489 // If the intermediate type was expanded, build the intermediate operands
490 // from the parts.
491 assert(NumParts % NumIntermediates == 0 &&
492 "Must expand into a divisible number of parts!");
493 unsigned Factor = NumParts / NumIntermediates;
494 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000495 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000496 PartVT, IntermediateVT);
497 }
498
499 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
500 // operands.
501 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000502 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000503 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000504 } else if (PartVT.isFloatingPoint()) {
505 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000506 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000507 "Unexpected split");
508 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000509 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
510 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000511 if (TLI.isBigEndian())
512 std::swap(Lo, Hi);
513 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
514 } else {
515 // FP split into integer parts (soft fp)
516 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
517 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000518 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Eli Friedman2ac8b322009-05-20 06:02:09 +0000519 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000520 }
521 }
522
523 // There is now one part, held in Val. Correct it to match ValueVT.
524 PartVT = Val.getValueType();
525
526 if (PartVT == ValueVT)
527 return Val;
528
529 if (PartVT.isVector()) {
530 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000531 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000532 }
533
534 if (ValueVT.isVector()) {
535 assert(ValueVT.getVectorElementType() == PartVT &&
536 ValueVT.getVectorNumElements() == 1 &&
537 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000538 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539 }
540
541 if (PartVT.isInteger() &&
542 ValueVT.isInteger()) {
543 if (ValueVT.bitsLT(PartVT)) {
544 // For a truncate, see if we have any information to
545 // indicate whether the truncated bits will always be
546 // zero or sign-extension.
547 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000548 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000549 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000550 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000551 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000552 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000553 }
554 }
555
556 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
557 if (ValueVT.bitsLT(Val.getValueType()))
558 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000559 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000560 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000561 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000562 }
563
564 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000565 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000566
Torok Edwinc23197a2009-07-14 16:55:14 +0000567 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000568 return SDValue();
569}
570
571/// getCopyToParts - Create a series of nodes that contain the specified value
572/// split into legal parts. If the parts contain more bits than Val, then, for
573/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000574static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Owen Andersone50ed302009-08-10 22:56:29 +0000575 SDValue *Parts, unsigned NumParts, EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000576 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000578 EVT PtrVT = TLI.getPointerTy();
579 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000580 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000581 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000582 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
583
584 if (!NumParts)
585 return;
586
587 if (!ValueVT.isVector()) {
588 if (PartVT == ValueVT) {
589 assert(NumParts == 1 && "No-op copy with multiple parts!");
590 Parts[0] = Val;
591 return;
592 }
593
594 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
595 // If the parts cover more bits than the value has, promote the value.
596 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
597 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000598 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000599 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000600 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000601 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000602 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000603 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000604 }
605 } else if (PartBits == ValueVT.getSizeInBits()) {
606 // Different types of the same size.
607 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000608 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000609 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
610 // If the parts cover less bits than value has, truncate the value.
611 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000612 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000613 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000614 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000615 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 }
617 }
618
619 // The value may have changed - recompute ValueVT.
620 ValueVT = Val.getValueType();
621 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
622 "Failed to tile the value with PartVT!");
623
624 if (NumParts == 1) {
625 assert(PartVT == ValueVT && "Type conversion failed!");
626 Parts[0] = Val;
627 return;
628 }
629
630 // Expand the value into multiple parts.
631 if (NumParts & (NumParts - 1)) {
632 // The number of parts is not a power of 2. Split off and copy the tail.
633 assert(PartVT.isInteger() && ValueVT.isInteger() &&
634 "Do not know what to expand to!");
635 unsigned RoundParts = 1 << Log2_32(NumParts);
636 unsigned RoundBits = RoundParts * PartBits;
637 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000638 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000639 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000640 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000641 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000642 if (TLI.isBigEndian())
643 // The odd parts were reversed by getCopyToParts - unreverse them.
644 std::reverse(Parts + RoundParts, Parts + NumParts);
645 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000646 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000647 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000648 }
649
650 // The number of parts is a power of 2. Repeatedly bisect the value using
651 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000652 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson23b9b192009-08-12 00:36:31 +0000653 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000654 Val);
655 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
656 for (unsigned i = 0; i < NumParts; i += StepSize) {
657 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000658 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000659 SDValue &Part0 = Parts[i];
660 SDValue &Part1 = Parts[i+StepSize/2];
661
Scott Michelfdc40a02009-02-17 22:15:04 +0000662 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000663 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000664 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000665 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000666 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000667 DAG.getConstant(0, PtrVT));
668
669 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000670 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000671 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000672 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000673 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000674 }
675 }
676 }
677
678 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000679 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000680
681 return;
682 }
683
684 // Vector ValueVT.
685 if (NumParts == 1) {
686 if (PartVT != ValueVT) {
687 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000688 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000689 } else {
690 assert(ValueVT.getVectorElementType() == PartVT &&
691 ValueVT.getVectorNumElements() == 1 &&
692 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000693 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000694 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000695 DAG.getConstant(0, PtrVT));
696 }
697 }
698
699 Parts[0] = Val;
700 return;
701 }
702
703 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000704 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000705 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000706 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
707 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000708 unsigned NumElements = ValueVT.getVectorNumElements();
709
710 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
711 NumParts = NumRegs; // Silence a compiler warning.
712 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
713
714 // Split the vector into intermediate operands.
715 SmallVector<SDValue, 8> Ops(NumIntermediates);
716 for (unsigned i = 0; i != NumIntermediates; ++i)
717 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000718 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000719 IntermediateVT, Val,
720 DAG.getConstant(i * (NumElements / NumIntermediates),
721 PtrVT));
722 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000723 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000724 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000725 DAG.getConstant(i, PtrVT));
726
727 // Split the intermediate operands into legal parts.
728 if (NumParts == NumIntermediates) {
729 // If the register was not expanded, promote or copy the value,
730 // as appropriate.
731 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000732 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000733 } else if (NumParts > 0) {
734 // If the intermediate type was expanded, split each the value into
735 // legal parts.
736 assert(NumParts % NumIntermediates == 0 &&
737 "Must expand into a divisible number of parts!");
738 unsigned Factor = NumParts / NumIntermediates;
739 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000740 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000741 }
742}
743
744
745void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
746 AA = &aa;
747 GFI = gfi;
748 TD = DAG.getTarget().getTargetData();
749}
750
751/// clear - Clear out the curret SelectionDAG and the associated
752/// state and prepare this SelectionDAGLowering object to be used
753/// for a new block. This doesn't clear out information about
754/// additional blocks that are needed to complete switch lowering
755/// or PHI node updating; that information is cleared out as it is
756/// consumed.
757void SelectionDAGLowering::clear() {
758 NodeMap.clear();
759 PendingLoads.clear();
760 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000761 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000762 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000763 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000764 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000765}
766
767/// getRoot - Return the current virtual root of the Selection DAG,
768/// flushing any PendingLoad items. This must be done before emitting
769/// a store or any other node that may need to be ordered after any
770/// prior load instructions.
771///
772SDValue SelectionDAGLowering::getRoot() {
773 if (PendingLoads.empty())
774 return DAG.getRoot();
775
776 if (PendingLoads.size() == 1) {
777 SDValue Root = PendingLoads[0];
778 DAG.setRoot(Root);
779 PendingLoads.clear();
780 return Root;
781 }
782
783 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000784 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000785 &PendingLoads[0], PendingLoads.size());
786 PendingLoads.clear();
787 DAG.setRoot(Root);
788 return Root;
789}
790
791/// getControlRoot - Similar to getRoot, but instead of flushing all the
792/// PendingLoad items, flush all the PendingExports items. It is necessary
793/// to do this before emitting a terminator instruction.
794///
795SDValue SelectionDAGLowering::getControlRoot() {
796 SDValue Root = DAG.getRoot();
797
798 if (PendingExports.empty())
799 return Root;
800
801 // Turn all of the CopyToReg chains into one factored node.
802 if (Root.getOpcode() != ISD::EntryToken) {
803 unsigned i = 0, e = PendingExports.size();
804 for (; i != e; ++i) {
805 assert(PendingExports[i].getNode()->getNumOperands() > 1);
806 if (PendingExports[i].getNode()->getOperand(0) == Root)
807 break; // Don't add the root if we already indirectly depend on it.
808 }
809
810 if (i == e)
811 PendingExports.push_back(Root);
812 }
813
Owen Anderson825b72b2009-08-11 20:47:22 +0000814 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000815 &PendingExports[0],
816 PendingExports.size());
817 PendingExports.clear();
818 DAG.setRoot(Root);
819 return Root;
820}
821
822void SelectionDAGLowering::visit(Instruction &I) {
823 visit(I.getOpcode(), I);
824}
825
826void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
827 // Note: this doesn't use InstVisitor, because it has to work with
828 // ConstantExpr's in addition to instructions.
829 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000830 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000831 // Build the switch statement using the Instruction.def file.
832#define HANDLE_INST(NUM, OPCODE, CLASS) \
833 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
834#include "llvm/Instruction.def"
835 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000836}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000837
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000838SDValue SelectionDAGLowering::getValue(const Value *V) {
839 SDValue &N = NodeMap[V];
840 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000841
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000842 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000843 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000844
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000845 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000846 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000847
848 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
849 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000850
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000851 if (isa<ConstantPointerNull>(C))
852 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000854 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000855 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000856
Nate Begeman9008ca62009-04-27 18:41:29 +0000857 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000858 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000859
860 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
861 visit(CE->getOpcode(), *CE);
862 SDValue N1 = NodeMap[V];
863 assert(N1.getNode() && "visit didn't populate the ValueMap!");
864 return N1;
865 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000866
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000867 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
868 SmallVector<SDValue, 4> Constants;
869 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
870 OI != OE; ++OI) {
871 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000872 // If the operand is an empty aggregate, there are no values.
873 if (!Val) continue;
874 // Add each leaf value from the operand to the Constants list
875 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000876 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
877 Constants.push_back(SDValue(Val, i));
878 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000879 return DAG.getMergeValues(&Constants[0], Constants.size(),
880 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000881 }
882
883 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
884 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
885 "Unknown struct or array constant!");
886
Owen Andersone50ed302009-08-10 22:56:29 +0000887 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000888 ComputeValueVTs(TLI, C->getType(), ValueVTs);
889 unsigned NumElts = ValueVTs.size();
890 if (NumElts == 0)
891 return SDValue(); // empty struct
892 SmallVector<SDValue, 4> Constants(NumElts);
893 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000894 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000895 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000896 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000897 else if (EltVT.isFloatingPoint())
898 Constants[i] = DAG.getConstantFP(0, EltVT);
899 else
900 Constants[i] = DAG.getConstant(0, EltVT);
901 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000902 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000903 }
904
Dan Gohman8c2b5252009-10-30 01:27:03 +0000905 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
906 return DAG.getBlockAddress(BA, getCurDebugLoc());
907
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000908 const VectorType *VecTy = cast<VectorType>(V->getType());
909 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000911 // Now that we know the number and type of the elements, get that number of
912 // elements into the Ops array based on what kind of constant it is.
913 SmallVector<SDValue, 16> Ops;
914 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
915 for (unsigned i = 0; i != NumElements; ++i)
916 Ops.push_back(getValue(CP->getOperand(i)));
917 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000918 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000919 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000920
921 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000922 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000923 Op = DAG.getConstantFP(0, EltVT);
924 else
925 Op = DAG.getConstant(0, EltVT);
926 Ops.assign(NumElements, Op);
927 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000929 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000930 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
931 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000932 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 // If this is a static alloca, generate it as the frameindex instead of
935 // computation.
936 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
937 DenseMap<const AllocaInst*, int>::iterator SI =
938 FuncInfo.StaticAllocaMap.find(AI);
939 if (SI != FuncInfo.StaticAllocaMap.end())
940 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
941 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000943 unsigned InReg = FuncInfo.ValueMap[V];
944 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945
Owen Anderson23b9b192009-08-12 00:36:31 +0000946 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000947 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000948 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000949}
950
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000951/// Get the EVTs and ArgFlags collections that represent the return type
952/// of the given function. This does not require a DAG or a return value, and
953/// is suitable for use before any DAGs for the function are constructed.
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000954static void getReturnInfo(const Type* ReturnType,
955 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000956 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000957 TargetLowering &TLI,
958 SmallVectorImpl<uint64_t> *Offsets = 0) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000959 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000960 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000961 unsigned NumValues = ValueVTs.size();
962 if ( NumValues == 0 ) return;
963
964 for (unsigned j = 0, f = NumValues; j != f; ++j) {
965 EVT VT = ValueVTs[j];
966 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000967
968 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000969 ExtendKind = ISD::SIGN_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000970 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000971 ExtendKind = ISD::ZERO_EXTEND;
972
973 // FIXME: C calling convention requires the return type to be promoted to
974 // at least 32-bit. But this is not necessary for non-C calling
975 // conventions. The frontend should mark functions whose return values
976 // require promoting with signext or zeroext attributes.
977 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000978 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000979 if (VT.bitsLT(MinVT))
980 VT = MinVT;
981 }
982
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000983 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
984 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000985 // 'inreg' on function refers to return value
986 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000987 if (attr & Attribute::InReg)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000988 Flags.setInReg();
989
990 // Propagate extension type if any
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000991 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000992 Flags.setSExt();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000993 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000994 Flags.setZExt();
995
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000996 for (unsigned i = 0; i < NumParts; ++i) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000997 OutVTs.push_back(PartVT);
998 OutFlags.push_back(Flags);
999 }
1000 }
1001}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001002
1003void SelectionDAGLowering::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00001004 SDValue Chain = getControlRoot();
1005 SmallVector<ISD::OutputArg, 8> Outs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001006 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
1007
1008 if (!FLI.CanLowerReturn) {
1009 unsigned DemoteReg = FLI.DemoteRegister;
1010 const Function *F = I.getParent()->getParent();
1011
1012 // Emit a store of the return value through the virtual register.
1013 // Leave Outs empty so that LowerReturn won't try to load return
1014 // registers the usual way.
1015 SmallVector<EVT, 1> PtrValueVTs;
1016 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1017 PtrValueVTs);
1018
1019 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1020 SDValue RetOp = getValue(I.getOperand(0));
1021
Owen Andersone50ed302009-08-10 22:56:29 +00001022 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001023 SmallVector<uint64_t, 4> Offsets;
1024 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001025 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001026
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001027 SmallVector<SDValue, 4> Chains(NumValues);
1028 EVT PtrVT = PtrValueVTs[0];
1029 for (unsigned i = 0; i != NumValues; ++i)
1030 Chains[i] = DAG.getStore(Chain, getCurDebugLoc(),
1031 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1032 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
1033 DAG.getConstant(Offsets[i], PtrVT)),
1034 NULL, Offsets[i], false, 0);
1035 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1036 MVT::Other, &Chains[0], NumValues);
1037 }
1038 else {
1039 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1040 SmallVector<EVT, 4> ValueVTs;
1041 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1042 unsigned NumValues = ValueVTs.size();
1043 if (NumValues == 0) continue;
1044
1045 SDValue RetOp = getValue(I.getOperand(i));
1046 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1047 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001048
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001049 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001050
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001051 const Function *F = I.getParent()->getParent();
1052 if (F->paramHasAttr(0, Attribute::SExt))
1053 ExtendKind = ISD::SIGN_EXTEND;
1054 else if (F->paramHasAttr(0, Attribute::ZExt))
1055 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001056
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001057 // FIXME: C calling convention requires the return type to be promoted to
1058 // at least 32-bit. But this is not necessary for non-C calling
1059 // conventions. The frontend should mark functions whose return values
1060 // require promoting with signext or zeroext attributes.
1061 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1062 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
1063 if (VT.bitsLT(MinVT))
1064 VT = MinVT;
1065 }
1066
1067 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1068 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1069 SmallVector<SDValue, 4> Parts(NumParts);
1070 getCopyToParts(DAG, getCurDebugLoc(),
1071 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1072 &Parts[0], NumParts, PartVT, ExtendKind);
1073
1074 // 'inreg' on function refers to return value
1075 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1076 if (F->paramHasAttr(0, Attribute::InReg))
1077 Flags.setInReg();
1078
1079 // Propagate extension type if any
1080 if (F->paramHasAttr(0, Attribute::SExt))
1081 Flags.setSExt();
1082 else if (F->paramHasAttr(0, Attribute::ZExt))
1083 Flags.setZExt();
1084
1085 for (unsigned i = 0; i < NumParts; ++i)
1086 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +00001087 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001088 }
1089 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001090
1091 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001092 CallingConv::ID CallConv =
1093 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001094 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1095 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001096
1097 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001098 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001099 "LowerReturn didn't return a valid chain!");
1100
1101 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001102 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001103}
1104
Dan Gohmanad62f532009-04-23 23:13:24 +00001105/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1106/// created for it, emit nodes to copy the value into the virtual
1107/// registers.
1108void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1109 if (!V->use_empty()) {
1110 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1111 if (VMI != FuncInfo.ValueMap.end())
1112 CopyValueToVirtualRegister(V, VMI->second);
1113 }
1114}
1115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001116/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1117/// the current basic block, add it to ValueMap now so that we'll get a
1118/// CopyTo/FromReg.
1119void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1120 // No need to export constants.
1121 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001123 // Already exported?
1124 if (FuncInfo.isExportedInst(V)) return;
1125
1126 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1127 CopyValueToVirtualRegister(V, Reg);
1128}
1129
1130bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1131 const BasicBlock *FromBB) {
1132 // The operands of the setcc have to be in this block. We don't know
1133 // how to export them from some other block.
1134 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1135 // Can export from current BB.
1136 if (VI->getParent() == FromBB)
1137 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001138
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001139 // Is already exported, noop.
1140 return FuncInfo.isExportedInst(V);
1141 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001143 // If this is an argument, we can export it if the BB is the entry block or
1144 // if it is already exported.
1145 if (isa<Argument>(V)) {
1146 if (FromBB == &FromBB->getParent()->getEntryBlock())
1147 return true;
1148
1149 // Otherwise, can only export this if it is already exported.
1150 return FuncInfo.isExportedInst(V);
1151 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001152
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001153 // Otherwise, constants can always be exported.
1154 return true;
1155}
1156
1157static bool InBlock(const Value *V, const BasicBlock *BB) {
1158 if (const Instruction *I = dyn_cast<Instruction>(V))
1159 return I->getParent() == BB;
1160 return true;
1161}
1162
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001163/// getFCmpCondCode - Return the ISD condition code corresponding to
1164/// the given LLVM IR floating-point condition code. This includes
1165/// consideration of global floating-point math flags.
1166///
1167static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1168 ISD::CondCode FPC, FOC;
1169 switch (Pred) {
1170 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1171 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1172 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1173 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1174 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1175 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1176 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1177 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1178 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1179 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1180 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1181 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1182 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1183 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1184 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1185 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1186 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001187 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001188 FOC = FPC = ISD::SETFALSE;
1189 break;
1190 }
1191 if (FiniteOnlyFPMath())
1192 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001193 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001194 return FPC;
1195}
1196
1197/// getICmpCondCode - Return the ISD condition code corresponding to
1198/// the given LLVM IR integer condition code.
1199///
1200static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1201 switch (Pred) {
1202 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1203 case ICmpInst::ICMP_NE: return ISD::SETNE;
1204 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1205 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1206 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1207 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1208 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1209 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1210 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1211 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1212 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001213 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001214 return ISD::SETNE;
1215 }
1216}
1217
Dan Gohmanc2277342008-10-17 21:16:08 +00001218/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1219/// This function emits a branch and is used at the leaves of an OR or an
1220/// AND operator tree.
1221///
1222void
1223SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1224 MachineBasicBlock *TBB,
1225 MachineBasicBlock *FBB,
1226 MachineBasicBlock *CurBB) {
1227 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001228
Dan Gohmanc2277342008-10-17 21:16:08 +00001229 // If the leaf of the tree is a comparison, merge the condition into
1230 // the caseblock.
1231 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1232 // The operands of the cmp have to be in this block. We don't know
1233 // how to export them from some other block. If this is the first block
1234 // of the sequence, no exporting is needed.
1235 if (CurBB == CurMBB ||
1236 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1237 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001238 ISD::CondCode Condition;
1239 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001240 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001241 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001242 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001243 } else {
1244 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001245 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001246 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001247
1248 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001249 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1250 SwitchCases.push_back(CB);
1251 return;
1252 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001253 }
1254
1255 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001256 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001257 NULL, TBB, FBB, CurBB);
1258 SwitchCases.push_back(CB);
1259}
1260
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001261/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001262void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1263 MachineBasicBlock *TBB,
1264 MachineBasicBlock *FBB,
1265 MachineBasicBlock *CurBB,
1266 unsigned Opc) {
1267 // If this node is not part of the or/and tree, emit it as a branch.
1268 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001269 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001270 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1271 BOp->getParent() != CurBB->getBasicBlock() ||
1272 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1273 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1274 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001275 return;
1276 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001277
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001278 // Create TmpBB after CurBB.
1279 MachineFunction::iterator BBI = CurBB;
1280 MachineFunction &MF = DAG.getMachineFunction();
1281 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1282 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 if (Opc == Instruction::Or) {
1285 // Codegen X | Y as:
1286 // jmp_if_X TBB
1287 // jmp TmpBB
1288 // TmpBB:
1289 // jmp_if_Y TBB
1290 // jmp FBB
1291 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001292
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001293 // Emit the LHS condition.
1294 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001295
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001296 // Emit the RHS condition into TmpBB.
1297 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1298 } else {
1299 assert(Opc == Instruction::And && "Unknown merge op!");
1300 // Codegen X & Y as:
1301 // jmp_if_X TmpBB
1302 // jmp FBB
1303 // TmpBB:
1304 // jmp_if_Y TBB
1305 // jmp FBB
1306 //
1307 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 // Emit the LHS condition.
1310 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001311
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001312 // Emit the RHS condition into TmpBB.
1313 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1314 }
1315}
1316
1317/// If the set of cases should be emitted as a series of branches, return true.
1318/// If we should emit this as a bunch of and/or'd together conditions, return
1319/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001320bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001321SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1322 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001323
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001324 // If this is two comparisons of the same values or'd or and'd together, they
1325 // will get folded into a single comparison, so don't emit two blocks.
1326 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1327 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1328 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1329 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1330 return false;
1331 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001332
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001333 return true;
1334}
1335
1336void SelectionDAGLowering::visitBr(BranchInst &I) {
1337 // Update machine-CFG edges.
1338 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1339
1340 // Figure out which block is immediately after the current one.
1341 MachineBasicBlock *NextBlock = 0;
1342 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001343 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001344 NextBlock = BBI;
1345
1346 if (I.isUnconditional()) {
1347 // Update machine-CFG edges.
1348 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001349
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001350 // If this is not a fall-through branch, emit the branch.
1351 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001352 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001353 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001354 DAG.getBasicBlock(Succ0MBB)));
1355 return;
1356 }
1357
1358 // If this condition is one of the special cases we handle, do special stuff
1359 // now.
1360 Value *CondVal = I.getCondition();
1361 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1362
1363 // If this is a series of conditions that are or'd or and'd together, emit
1364 // this as a sequence of branches instead of setcc's with and/or operations.
1365 // For example, instead of something like:
1366 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001367 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001368 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001369 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001370 // or C, F
1371 // jnz foo
1372 // Emit:
1373 // cmp A, B
1374 // je foo
1375 // cmp D, E
1376 // jle foo
1377 //
1378 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001379 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001380 (BOp->getOpcode() == Instruction::And ||
1381 BOp->getOpcode() == Instruction::Or)) {
1382 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1383 // If the compares in later blocks need to use values not currently
1384 // exported from this block, export them now. This block should always
1385 // be the first entry.
1386 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001387
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001388 // Allow some cases to be rejected.
1389 if (ShouldEmitAsBranches(SwitchCases)) {
1390 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1391 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1392 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1393 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001394
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001395 // Emit the branch for this block.
1396 visitSwitchCase(SwitchCases[0]);
1397 SwitchCases.erase(SwitchCases.begin());
1398 return;
1399 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001400
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001401 // Okay, we decided not to do this, remove any inserted MBB's and clear
1402 // SwitchCases.
1403 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001404 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001405
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406 SwitchCases.clear();
1407 }
1408 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001409
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001410 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001411 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001412 NULL, Succ0MBB, Succ1MBB, CurMBB);
1413 // Use visitSwitchCase to actually insert the fast branch sequence for this
1414 // cond branch.
1415 visitSwitchCase(CB);
1416}
1417
1418/// visitSwitchCase - Emits the necessary code to represent a single node in
1419/// the binary search tree resulting from lowering a switch instruction.
1420void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1421 SDValue Cond;
1422 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001423 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001424
1425 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001426 if (CB.CmpMHS == NULL) {
1427 // Fold "(X == true)" to X and "(X == false)" to !X to
1428 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001429 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001430 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001432 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001433 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001434 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001435 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001436 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001437 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001438 } else {
1439 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1440
Anton Korobeynikov23218582008-12-23 22:25:27 +00001441 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1442 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001443
1444 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001445 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001446
1447 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001448 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001449 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001450 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001451 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001452 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001453 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001454 DAG.getConstant(High-Low, VT), ISD::SETULE);
1455 }
1456 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001457
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001458 // Update successor info
1459 CurMBB->addSuccessor(CB.TrueBB);
1460 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001461
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001462 // Set NextBlock to be the MBB immediately after the current one, if any.
1463 // This is used to avoid emitting unnecessary branches to the next block.
1464 MachineBasicBlock *NextBlock = 0;
1465 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001466 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001468
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001469 // If the lhs block is the next block, invert the condition so that we can
1470 // fall through to the lhs instead of the rhs block.
1471 if (CB.TrueBB == NextBlock) {
1472 std::swap(CB.TrueBB, CB.FalseBB);
1473 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001474 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001475 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001476 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001477 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001478 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001479
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001480 // If the branch was constant folded, fix up the CFG.
1481 if (BrCond.getOpcode() == ISD::BR) {
1482 CurMBB->removeSuccessor(CB.FalseBB);
1483 DAG.setRoot(BrCond);
1484 } else {
1485 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001486 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001487 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001488
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489 if (CB.FalseBB == NextBlock)
1490 DAG.setRoot(BrCond);
1491 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001492 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001493 DAG.getBasicBlock(CB.FalseBB)));
1494 }
1495}
1496
1497/// visitJumpTable - Emit JumpTable node in the current MBB
1498void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1499 // Emit the code for the jump table
1500 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001501 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001502 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1503 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001504 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001505 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001506 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001507 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001508}
1509
1510/// visitJumpTableHeader - This function emits necessary code to produce index
1511/// in the JumpTable from switch case.
1512void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1513 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001514 // Subtract the lowest switch case value from the value being switched on and
1515 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516 // difference between smallest and largest cases.
1517 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001518 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001519 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001520 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001521
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001522 // The SDNode we just created, which holds the value being switched on minus
1523 // the the smallest case value, needs to be copied to a virtual register so it
1524 // can be used as an index into the jump table in a subsequent basic block.
1525 // This value may be smaller or larger than the target's pointer type, and
1526 // therefore require extension or truncating.
Duncan Sands3a66a682009-10-13 21:04:12 +00001527 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001528
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001529 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001530 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1531 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001532 JT.Reg = JumpTableReg;
1533
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001534 // Emit the range check for the jump table, and branch to the default block
1535 // for the switch statement if the value being switched on exceeds the largest
1536 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001537 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1538 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001539 DAG.getConstant(JTH.Last-JTH.First,VT),
1540 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001541
1542 // Set NextBlock to be the MBB immediately after the current one, if any.
1543 // This is used to avoid emitting unnecessary branches to the next block.
1544 MachineBasicBlock *NextBlock = 0;
1545 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001546 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001547 NextBlock = BBI;
1548
Dale Johannesen66978ee2009-01-31 02:22:37 +00001549 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001550 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001551 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001552
1553 if (JT.MBB == NextBlock)
1554 DAG.setRoot(BrCond);
1555 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001556 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001557 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558}
1559
1560/// visitBitTestHeader - This function emits necessary code to produce value
1561/// suitable for "bit tests"
1562void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1563 // Subtract the minimum value
1564 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001565 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001566 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001567 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001568
1569 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001570 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1571 TLI.getSetCCResultType(SUB.getValueType()),
1572 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001573 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001574
Duncan Sands3a66a682009-10-13 21:04:12 +00001575 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001576
Duncan Sands92abc622009-01-31 15:50:11 +00001577 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001578 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1579 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001580
1581 // Set NextBlock to be the MBB immediately after the current one, if any.
1582 // This is used to avoid emitting unnecessary branches to the next block.
1583 MachineBasicBlock *NextBlock = 0;
1584 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001585 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001586 NextBlock = BBI;
1587
1588 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1589
1590 CurMBB->addSuccessor(B.Default);
1591 CurMBB->addSuccessor(MBB);
1592
Dale Johannesen66978ee2009-01-31 02:22:37 +00001593 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001594 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001595 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001596
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001597 if (MBB == NextBlock)
1598 DAG.setRoot(BrRange);
1599 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001600 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001602}
1603
1604/// visitBitTestCase - this function produces one "bit test"
1605void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1606 unsigned Reg,
1607 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001608 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001609 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001610 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001611 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001612 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001613 DAG.getConstant(1, TLI.getPointerTy()),
1614 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001615
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001616 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001617 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001618 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001619 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001620 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1621 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001622 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001623 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624
1625 CurMBB->addSuccessor(B.TargetBB);
1626 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001627
Dale Johannesen66978ee2009-01-31 02:22:37 +00001628 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001629 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001630 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001631
1632 // Set NextBlock to be the MBB immediately after the current one, if any.
1633 // This is used to avoid emitting unnecessary branches to the next block.
1634 MachineBasicBlock *NextBlock = 0;
1635 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001636 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637 NextBlock = BBI;
1638
1639 if (NextMBB == NextBlock)
1640 DAG.setRoot(BrAnd);
1641 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001642 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001643 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001644}
1645
1646void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1647 // Retrieve successors.
1648 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1649 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1650
Gabor Greifb67e6b32009-01-15 11:10:44 +00001651 const Value *Callee(I.getCalledValue());
1652 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001653 visitInlineAsm(&I);
1654 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001655 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001656
1657 // If the value of the invoke is used outside of its defining block, make it
1658 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001659 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660
1661 // Update successor info
1662 CurMBB->addSuccessor(Return);
1663 CurMBB->addSuccessor(LandingPad);
1664
1665 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001666 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001667 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001668 DAG.getBasicBlock(Return)));
1669}
1670
1671void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1672}
1673
1674/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1675/// small case ranges).
1676bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1677 CaseRecVector& WorkList,
1678 Value* SV,
1679 MachineBasicBlock* Default) {
1680 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001683 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001684 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001685 return false;
1686
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001687 // Get the MachineFunction which holds the current MBB. This is used when
1688 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001689 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001690
1691 // Figure out which block is immediately after the current one.
1692 MachineBasicBlock *NextBlock = 0;
1693 MachineFunction::iterator BBI = CR.CaseBB;
1694
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001695 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696 NextBlock = BBI;
1697
1698 // TODO: If any two of the cases has the same destination, and if one value
1699 // is the same as the other, but has one bit unset that the other has set,
1700 // use bit manipulation to do two compares at once. For example:
1701 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001702
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703 // Rearrange the case blocks so that the last one falls through if possible.
1704 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1705 // The last case block won't fall through into 'NextBlock' if we emit the
1706 // branches in this order. See if rearranging a case value would help.
1707 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1708 if (I->BB == NextBlock) {
1709 std::swap(*I, BackCase);
1710 break;
1711 }
1712 }
1713 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001714
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001715 // Create a CaseBlock record representing a conditional branch to
1716 // the Case's target mbb if the value being switched on SV is equal
1717 // to C.
1718 MachineBasicBlock *CurBlock = CR.CaseBB;
1719 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1720 MachineBasicBlock *FallThrough;
1721 if (I != E-1) {
1722 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1723 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001724
1725 // Put SV in a virtual register to make it available from the new blocks.
1726 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001727 } else {
1728 // If the last case doesn't match, go to the default block.
1729 FallThrough = Default;
1730 }
1731
1732 Value *RHS, *LHS, *MHS;
1733 ISD::CondCode CC;
1734 if (I->High == I->Low) {
1735 // This is just small small case range :) containing exactly 1 case
1736 CC = ISD::SETEQ;
1737 LHS = SV; RHS = I->High; MHS = NULL;
1738 } else {
1739 CC = ISD::SETLE;
1740 LHS = I->Low; MHS = SV; RHS = I->High;
1741 }
1742 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001743
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001744 // If emitting the first comparison, just call visitSwitchCase to emit the
1745 // code into the current block. Otherwise, push the CaseBlock onto the
1746 // vector to be later processed by SDISel, and insert the node's MBB
1747 // before the next MBB.
1748 if (CurBlock == CurMBB)
1749 visitSwitchCase(CB);
1750 else
1751 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001752
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001753 CurBlock = FallThrough;
1754 }
1755
1756 return true;
1757}
1758
1759static inline bool areJTsAllowed(const TargetLowering &TLI) {
1760 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001761 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1762 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001763}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001764
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001765static APInt ComputeRange(const APInt &First, const APInt &Last) {
1766 APInt LastExt(Last), FirstExt(First);
1767 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1768 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1769 return (LastExt - FirstExt + 1ULL);
1770}
1771
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001772/// handleJTSwitchCase - Emit jumptable for current switch case range
1773bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1774 CaseRecVector& WorkList,
1775 Value* SV,
1776 MachineBasicBlock* Default) {
1777 Case& FrontCase = *CR.Range.first;
1778 Case& BackCase = *(CR.Range.second-1);
1779
Chris Lattnere880efe2009-11-07 07:50:34 +00001780 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1781 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001782
Chris Lattnere880efe2009-11-07 07:50:34 +00001783 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001784 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1785 I!=E; ++I)
1786 TSize += I->size();
1787
Chris Lattnere880efe2009-11-07 07:50:34 +00001788 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001789 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001790
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001791 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001792 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793 if (Density < 0.4)
1794 return false;
1795
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001796 DEBUG(errs() << "Lowering jump table\n"
1797 << "First entry: " << First << ". Last entry: " << Last << '\n'
1798 << "Range: " << Range
1799 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001800
1801 // Get the MachineFunction which holds the current MBB. This is used when
1802 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001803 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001804
1805 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001806 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001807 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001808
1809 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1810
1811 // Create a new basic block to hold the code for loading the address
1812 // of the jump table, and jumping to it. Update successor information;
1813 // we will either branch to the default case for the switch, or the jump
1814 // table.
1815 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1816 CurMF->insert(BBI, JumpTableBB);
1817 CR.CaseBB->addSuccessor(Default);
1818 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001819
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001820 // Build a vector of destination BBs, corresponding to each target
1821 // of the jump table. If the value of the jump table slot corresponds to
1822 // a case statement, push the case's BB onto the vector, otherwise, push
1823 // the default BB.
1824 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001825 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001826 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001827 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1828 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1829
1830 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001831 DestBBs.push_back(I->BB);
1832 if (TEI==High)
1833 ++I;
1834 } else {
1835 DestBBs.push_back(Default);
1836 }
1837 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001838
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001840 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1841 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001842 E = DestBBs.end(); I != E; ++I) {
1843 if (!SuccsHandled[(*I)->getNumber()]) {
1844 SuccsHandled[(*I)->getNumber()] = true;
1845 JumpTableBB->addSuccessor(*I);
1846 }
1847 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001848
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 // Create a jump table index for this jump table, or return an existing
1850 // one.
1851 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001852
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001853 // Set the jump table information so that we can codegen it as a second
1854 // MachineBasicBlock
1855 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1856 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1857 if (CR.CaseBB == CurMBB)
1858 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001860 JTCases.push_back(JumpTableBlock(JTH, JT));
1861
1862 return true;
1863}
1864
1865/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1866/// 2 subtrees.
1867bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1868 CaseRecVector& WorkList,
1869 Value* SV,
1870 MachineBasicBlock* Default) {
1871 // Get the MachineFunction which holds the current MBB. This is used when
1872 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001873 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001874
1875 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001876 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001877 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001878
1879 Case& FrontCase = *CR.Range.first;
1880 Case& BackCase = *(CR.Range.second-1);
1881 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1882
1883 // Size is the number of Cases represented by this range.
1884 unsigned Size = CR.Range.second - CR.Range.first;
1885
Chris Lattnere880efe2009-11-07 07:50:34 +00001886 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1887 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001888 double FMetric = 0;
1889 CaseItr Pivot = CR.Range.first + Size/2;
1890
1891 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1892 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001893 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001894 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1895 I!=E; ++I)
1896 TSize += I->size();
1897
Chris Lattnere880efe2009-11-07 07:50:34 +00001898 APInt LSize = FrontCase.size();
1899 APInt RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001900 DEBUG(errs() << "Selecting best pivot: \n"
1901 << "First: " << First << ", Last: " << Last <<'\n'
1902 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001903 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1904 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001905 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1906 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001907 APInt Range = ComputeRange(LEnd, RBegin);
1908 assert((Range - 2ULL).isNonNegative() &&
1909 "Invalid case distance");
Chris Lattnere880efe2009-11-07 07:50:34 +00001910 double LDensity = (double)LSize.roundToDouble() /
1911 (LEnd - First + 1ULL).roundToDouble();
1912 double RDensity = (double)RSize.roundToDouble() /
1913 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001914 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001915 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001916 DEBUG(errs() <<"=>Step\n"
1917 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1918 << "LDensity: " << LDensity
1919 << ", RDensity: " << RDensity << '\n'
1920 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921 if (FMetric < Metric) {
1922 Pivot = J;
1923 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001924 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001925 }
1926
1927 LSize += J->size();
1928 RSize -= J->size();
1929 }
1930 if (areJTsAllowed(TLI)) {
1931 // If our case is dense we *really* should handle it earlier!
1932 assert((FMetric > 0) && "Should handle dense range earlier!");
1933 } else {
1934 Pivot = CR.Range.first + Size/2;
1935 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001936
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001937 CaseRange LHSR(CR.Range.first, Pivot);
1938 CaseRange RHSR(Pivot, CR.Range.second);
1939 Constant *C = Pivot->Low;
1940 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001943 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001944 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001945 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001946 // Pivot's Value, then we can branch directly to the LHS's Target,
1947 // rather than creating a leaf node for it.
1948 if ((LHSR.second - LHSR.first) == 1 &&
1949 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950 cast<ConstantInt>(C)->getValue() ==
1951 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001952 TrueBB = LHSR.first->BB;
1953 } else {
1954 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1955 CurMF->insert(BBI, TrueBB);
1956 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001957
1958 // Put SV in a virtual register to make it available from the new blocks.
1959 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962 // Similar to the optimization above, if the Value being switched on is
1963 // known to be less than the Constant CR.LT, and the current Case Value
1964 // is CR.LT - 1, then we can branch directly to the target block for
1965 // the current Case Value, rather than emitting a RHS leaf node for it.
1966 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001967 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1968 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001969 FalseBB = RHSR.first->BB;
1970 } else {
1971 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1972 CurMF->insert(BBI, FalseBB);
1973 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001974
1975 // Put SV in a virtual register to make it available from the new blocks.
1976 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001977 }
1978
1979 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001980 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001981 // Otherwise, branch to LHS.
1982 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1983
1984 if (CR.CaseBB == CurMBB)
1985 visitSwitchCase(CB);
1986 else
1987 SwitchCases.push_back(CB);
1988
1989 return true;
1990}
1991
1992/// handleBitTestsSwitchCase - if current case range has few destination and
1993/// range span less, than machine word bitwidth, encode case range into series
1994/// of masks and emit bit tests with these masks.
1995bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1996 CaseRecVector& WorkList,
1997 Value* SV,
1998 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001999 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002000 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002001
2002 Case& FrontCase = *CR.Range.first;
2003 Case& BackCase = *(CR.Range.second-1);
2004
2005 // Get the MachineFunction which holds the current MBB. This is used when
2006 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002007 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002008
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00002009 // If target does not have legal shift left, do not emit bit tests at all.
2010 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2011 return false;
2012
Anton Korobeynikov23218582008-12-23 22:25:27 +00002013 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002014 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2015 I!=E; ++I) {
2016 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002017 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002019
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002020 // Count unique destinations
2021 SmallSet<MachineBasicBlock*, 4> Dests;
2022 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2023 Dests.insert(I->BB);
2024 if (Dests.size() > 3)
2025 // Don't bother the code below, if there are too much unique destinations
2026 return false;
2027 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002028 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
2029 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002030
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002031 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002032 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2033 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002034 APInt cmpRange = maxValue - minValue;
2035
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002036 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
2037 << "Low bound: " << minValue << '\n'
2038 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002039
2040 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041 (!(Dests.size() == 1 && numCmps >= 3) &&
2042 !(Dests.size() == 2 && numCmps >= 5) &&
2043 !(Dests.size() >= 3 && numCmps >= 6)))
2044 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002045
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002046 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00002047 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002049 // Optimize the case where all the case values fit in a
2050 // word without having to subtract minValue. In this case,
2051 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002052 if (minValue.isNonNegative() &&
2053 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
2054 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002055 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002056 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002057 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002058
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002059 CaseBitsVector CasesBits;
2060 unsigned i, count = 0;
2061
2062 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2063 MachineBasicBlock* Dest = I->BB;
2064 for (i = 0; i < count; ++i)
2065 if (Dest == CasesBits[i].BB)
2066 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002067
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002068 if (i == count) {
2069 assert((count < 3) && "Too much destinations to test!");
2070 CasesBits.push_back(CaseBits(0, Dest, 0));
2071 count++;
2072 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002073
2074 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2075 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2076
2077 uint64_t lo = (lowValue - lowBound).getZExtValue();
2078 uint64_t hi = (highValue - lowBound).getZExtValue();
2079
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002080 for (uint64_t j = lo; j <= hi; j++) {
2081 CasesBits[i].Mask |= 1ULL << j;
2082 CasesBits[i].Bits++;
2083 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002084
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002085 }
2086 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002087
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002088 BitTestInfo BTC;
2089
2090 // Figure out which block is immediately after the current one.
2091 MachineFunction::iterator BBI = CR.CaseBB;
2092 ++BBI;
2093
2094 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2095
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002096 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002097 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002098 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2099 << ", Bits: " << CasesBits[i].Bits
2100 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002101
2102 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2103 CurMF->insert(BBI, CaseBB);
2104 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2105 CaseBB,
2106 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002107
2108 // Put SV in a virtual register to make it available from the new blocks.
2109 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002110 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002111
2112 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002113 -1U, (CR.CaseBB == CurMBB),
2114 CR.CaseBB, Default, BTC);
2115
2116 if (CR.CaseBB == CurMBB)
2117 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002118
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002119 BitTestCases.push_back(BTB);
2120
2121 return true;
2122}
2123
2124
2125/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002126size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002127 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002128 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002129
2130 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002131 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2133 Cases.push_back(Case(SI.getSuccessorValue(i),
2134 SI.getSuccessorValue(i),
2135 SMBB));
2136 }
2137 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2138
2139 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002140 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141 // Must recompute end() each iteration because it may be
2142 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002143 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2144 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2145 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002146 MachineBasicBlock* nextBB = J->BB;
2147 MachineBasicBlock* currentBB = I->BB;
2148
2149 // If the two neighboring cases go to the same destination, merge them
2150 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002151 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002152 I->High = J->High;
2153 J = Cases.erase(J);
2154 } else {
2155 I = J++;
2156 }
2157 }
2158
2159 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2160 if (I->Low != I->High)
2161 // A range counts double, since it requires two compares.
2162 ++numCmps;
2163 }
2164
2165 return numCmps;
2166}
2167
Anton Korobeynikov23218582008-12-23 22:25:27 +00002168void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002169 // Figure out which block is immediately after the current one.
2170 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002171
2172 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2173
2174 // If there is only the default destination, branch to it if it is not the
2175 // next basic block. Otherwise, just fall through.
2176 if (SI.getNumOperands() == 2) {
2177 // Update machine-CFG edges.
2178
2179 // If this is not a fall-through branch, emit the branch.
2180 CurMBB->addSuccessor(Default);
2181 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002182 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002183 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002184 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002185 return;
2186 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002187
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002188 // If there are any non-default case statements, create a vector of Cases
2189 // representing each one, and sort the vector so that we can efficiently
2190 // create a binary search tree from them.
2191 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002192 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002193 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2194 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002195 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002196
2197 // Get the Value to be switched on and default basic blocks, which will be
2198 // inserted into CaseBlock records, representing basic blocks in the binary
2199 // search tree.
2200 Value *SV = SI.getOperand(0);
2201
2202 // Push the initial CaseRec onto the worklist
2203 CaseRecVector WorkList;
2204 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2205
2206 while (!WorkList.empty()) {
2207 // Grab a record representing a case range to process off the worklist
2208 CaseRec CR = WorkList.back();
2209 WorkList.pop_back();
2210
2211 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2212 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002213
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002214 // If the range has few cases (two or less) emit a series of specific
2215 // tests.
2216 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2217 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002218
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002219 // If the switch has more than 5 blocks, and at least 40% dense, and the
2220 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221 // lowering the switch to a binary tree of conditional branches.
2222 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2223 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002224
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002225 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2226 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2227 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2228 }
2229}
2230
Chris Lattnerab21db72009-10-28 00:19:10 +00002231void SelectionDAGLowering::visitIndirectBr(IndirectBrInst &I) {
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002232 // Update machine-CFG edges.
2233 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2234 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2235
Dan Gohman64825152009-10-27 21:56:26 +00002236 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2237 MVT::Other, getControlRoot(),
2238 getValue(I.getAddress())));
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002239}
2240
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002241
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002242void SelectionDAGLowering::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002243 // -0.0 - X --> fneg
2244 const Type *Ty = I.getType();
2245 if (isa<VectorType>(Ty)) {
2246 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2247 const VectorType *DestTy = cast<VectorType>(I.getType());
2248 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002249 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002250 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002251 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002252 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002253 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002254 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002255 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002256 return;
2257 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002258 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002259 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002260 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002261 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002262 SDValue Op2 = getValue(I.getOperand(1));
2263 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2264 Op2.getValueType(), Op2));
2265 return;
2266 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002267
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002268 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269}
2270
2271void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2272 SDValue Op1 = getValue(I.getOperand(0));
2273 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002274
Scott Michelfdc40a02009-02-17 22:15:04 +00002275 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002276 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002277}
2278
2279void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2280 SDValue Op1 = getValue(I.getOperand(0));
2281 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002282 if (!isa<VectorType>(I.getType()) &&
2283 Op2.getValueType() != TLI.getShiftAmountTy()) {
2284 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002285 EVT PTy = TLI.getPointerTy();
2286 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002287 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002288 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2289 TLI.getShiftAmountTy(), Op2);
2290 // If the operand is larger than the shift count type but the shift
2291 // count type has enough bits to represent any shift value, truncate
2292 // it now. This is a common case and it exposes the truncate to
2293 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002294 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002295 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2296 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2297 TLI.getShiftAmountTy(), Op2);
2298 // Otherwise we'll need to temporarily settle for some other
2299 // convenient type; type legalization will make adjustments as
2300 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002301 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002302 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002303 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002304 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002305 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002306 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002307 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002308
Scott Michelfdc40a02009-02-17 22:15:04 +00002309 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002310 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002311}
2312
2313void SelectionDAGLowering::visitICmp(User &I) {
2314 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2315 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2316 predicate = IC->getPredicate();
2317 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2318 predicate = ICmpInst::Predicate(IC->getPredicate());
2319 SDValue Op1 = getValue(I.getOperand(0));
2320 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002321 ISD::CondCode Opcode = getICmpCondCode(predicate);
Chris Lattner9800e842009-07-07 22:41:32 +00002322
Owen Andersone50ed302009-08-10 22:56:29 +00002323 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002324 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002325}
2326
2327void SelectionDAGLowering::visitFCmp(User &I) {
2328 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2329 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2330 predicate = FC->getPredicate();
2331 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2332 predicate = FCmpInst::Predicate(FC->getPredicate());
2333 SDValue Op1 = getValue(I.getOperand(0));
2334 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002335 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002336 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002337 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002338}
2339
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002340void SelectionDAGLowering::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002341 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002342 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2343 unsigned NumValues = ValueVTs.size();
2344 if (NumValues != 0) {
2345 SmallVector<SDValue, 4> Values(NumValues);
2346 SDValue Cond = getValue(I.getOperand(0));
2347 SDValue TrueVal = getValue(I.getOperand(1));
2348 SDValue FalseVal = getValue(I.getOperand(2));
2349
2350 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002351 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002352 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002353 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2354 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2355
Scott Michelfdc40a02009-02-17 22:15:04 +00002356 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002357 DAG.getVTList(&ValueVTs[0], NumValues),
2358 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002359 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002360}
2361
2362
2363void SelectionDAGLowering::visitTrunc(User &I) {
2364 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2365 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002366 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002367 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002368}
2369
2370void SelectionDAGLowering::visitZExt(User &I) {
2371 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2372 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2373 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002374 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002375 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002376}
2377
2378void SelectionDAGLowering::visitSExt(User &I) {
2379 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2380 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2381 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002382 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002383 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002384}
2385
2386void SelectionDAGLowering::visitFPTrunc(User &I) {
2387 // FPTrunc is never a no-op cast, no need to check
2388 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002389 EVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002390 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002391 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002392}
2393
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002394void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002395 // FPTrunc is never a no-op cast, no need to check
2396 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002397 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002398 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002399}
2400
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002401void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002402 // FPToUI is never a no-op cast, no need to check
2403 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002404 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002405 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002406}
2407
2408void SelectionDAGLowering::visitFPToSI(User &I) {
2409 // FPToSI is never a no-op cast, no need to check
2410 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002411 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002412 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002413}
2414
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002415void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002416 // UIToFP is never a no-op cast, no need to check
2417 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002418 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002419 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002420}
2421
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002422void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002423 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002424 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002425 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002426 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002427}
2428
2429void SelectionDAGLowering::visitPtrToInt(User &I) {
2430 // What to do depends on the size of the integer and the size of the pointer.
2431 // We can either truncate, zero extend, or no-op, accordingly.
2432 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002433 EVT SrcVT = N.getValueType();
2434 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002435 SDValue Result = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002436 setValue(&I, Result);
2437}
2438
2439void SelectionDAGLowering::visitIntToPtr(User &I) {
2440 // What to do depends on the size of the integer and the size of the pointer.
2441 // We can either truncate, zero extend, or no-op, accordingly.
2442 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002443 EVT SrcVT = N.getValueType();
2444 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002445 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002446}
2447
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002448void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002449 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002450 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002451
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002452 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002453 // is either a BIT_CONVERT or a no-op.
2454 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002455 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002456 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002457 else
2458 setValue(&I, N); // noop cast.
2459}
2460
2461void SelectionDAGLowering::visitInsertElement(User &I) {
2462 SDValue InVec = getValue(I.getOperand(0));
2463 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002464 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002465 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002466 getValue(I.getOperand(2)));
2467
Scott Michelfdc40a02009-02-17 22:15:04 +00002468 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002469 TLI.getValueType(I.getType()),
2470 InVec, InVal, InIdx));
2471}
2472
2473void SelectionDAGLowering::visitExtractElement(User &I) {
2474 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002475 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002476 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002477 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002478 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002479 TLI.getValueType(I.getType()), InVec, InIdx));
2480}
2481
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482
2483// Utility for visitShuffleVector - Returns true if the mask is mask starting
2484// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002485static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2486 unsigned MaskNumElts = Mask.size();
2487 for (unsigned i = 0; i != MaskNumElts; ++i)
2488 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002489 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002490 return true;
2491}
2492
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002493void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002494 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002495 SDValue Src1 = getValue(I.getOperand(0));
2496 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002497
Nate Begeman9008ca62009-04-27 18:41:29 +00002498 // Convert the ConstantVector mask operand into an array of ints, with -1
2499 // representing undef values.
2500 SmallVector<Constant*, 8> MaskElts;
Owen Anderson001dbfe2009-07-16 18:04:31 +00002501 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2502 MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002503 unsigned MaskNumElts = MaskElts.size();
2504 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002505 if (isa<UndefValue>(MaskElts[i]))
2506 Mask.push_back(-1);
2507 else
2508 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2509 }
2510
Owen Andersone50ed302009-08-10 22:56:29 +00002511 EVT VT = TLI.getValueType(I.getType());
2512 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002513 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002514
Mon P Wangc7849c22008-11-16 05:06:27 +00002515 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002516 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2517 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002518 return;
2519 }
2520
2521 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002522 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2523 // Mask is longer than the source vectors and is a multiple of the source
2524 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002525 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002526 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2527 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002528 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002529 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002530 return;
2531 }
2532
Mon P Wangc7849c22008-11-16 05:06:27 +00002533 // Pad both vectors with undefs to make them the same length as the mask.
2534 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002535 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2536 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002537 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002538
Nate Begeman9008ca62009-04-27 18:41:29 +00002539 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2540 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002541 MOps1[0] = Src1;
2542 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002543
2544 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2545 getCurDebugLoc(), VT,
2546 &MOps1[0], NumConcat);
2547 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2548 getCurDebugLoc(), VT,
2549 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002550
Mon P Wangaeb06d22008-11-10 04:46:22 +00002551 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002552 SmallVector<int, 8> MappedOps;
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];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002555 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002556 MappedOps.push_back(Idx);
2557 else
2558 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002559 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002560 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2561 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002562 return;
2563 }
2564
Mon P Wangc7849c22008-11-16 05:06:27 +00002565 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002566 // Analyze the access pattern of the vector to see if we can extract
2567 // two subvectors and do the shuffle. The analysis is done by calculating
2568 // the range of elements the mask access on both vectors.
2569 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2570 int MaxRange[2] = {-1, -1};
2571
Nate Begeman5a5ca152009-04-29 05:20:52 +00002572 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002573 int Idx = Mask[i];
2574 int Input = 0;
2575 if (Idx < 0)
2576 continue;
2577
Nate Begeman5a5ca152009-04-29 05:20:52 +00002578 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002579 Input = 1;
2580 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002581 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002582 if (Idx > MaxRange[Input])
2583 MaxRange[Input] = Idx;
2584 if (Idx < MinRange[Input])
2585 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002586 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002587
Mon P Wangc7849c22008-11-16 05:06:27 +00002588 // Check if the access is smaller than the vector size and can we find
2589 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002590 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002591 int StartIdx[2]; // StartIdx to extract from
2592 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002593 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002594 RangeUse[Input] = 0; // Unused
2595 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002596 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002597 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002598 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002599 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002600 RangeUse[Input] = 1; // Extract from beginning of the vector
2601 StartIdx[Input] = 0;
2602 } else {
2603 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002604 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002605 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002606 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002607 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002608 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002609 }
2610
Bill Wendling636e2582009-08-21 18:16:06 +00002611 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002612 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002613 return;
2614 }
2615 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2616 // Extract appropriate subvector and generate a vector shuffle
2617 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002618 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002619 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002620 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002621 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002622 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002623 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002624 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002625 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002626 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002627 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002628 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002629 int Idx = Mask[i];
2630 if (Idx < 0)
2631 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002632 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002633 MappedOps.push_back(Idx - StartIdx[0]);
2634 else
2635 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002636 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002637 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2638 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002639 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002640 }
2641 }
2642
Mon P Wangc7849c22008-11-16 05:06:27 +00002643 // We can't use either concat vectors or extract subvectors so fall back to
2644 // replacing the shuffle with extract and build vector.
2645 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002646 EVT EltVT = VT.getVectorElementType();
2647 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002648 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002649 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002650 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002651 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002652 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002653 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002654 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002655 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002656 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002657 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002658 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002659 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002660 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002661 }
2662 }
Evan Chenga87008d2009-02-25 22:49:59 +00002663 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2664 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002665}
2666
2667void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2668 const Value *Op0 = I.getOperand(0);
2669 const Value *Op1 = I.getOperand(1);
2670 const Type *AggTy = I.getType();
2671 const Type *ValTy = Op1->getType();
2672 bool IntoUndef = isa<UndefValue>(Op0);
2673 bool FromUndef = isa<UndefValue>(Op1);
2674
2675 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2676 I.idx_begin(), I.idx_end());
2677
Owen Andersone50ed302009-08-10 22:56:29 +00002678 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002679 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002680 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002681 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2682
2683 unsigned NumAggValues = AggValueVTs.size();
2684 unsigned NumValValues = ValValueVTs.size();
2685 SmallVector<SDValue, 4> Values(NumAggValues);
2686
2687 SDValue Agg = getValue(Op0);
2688 SDValue Val = getValue(Op1);
2689 unsigned i = 0;
2690 // Copy the beginning value(s) from the original aggregate.
2691 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002692 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002693 SDValue(Agg.getNode(), Agg.getResNo() + i);
2694 // Copy values from the inserted value(s).
2695 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002696 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002697 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2698 // Copy remaining value(s) from the original aggregate.
2699 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002700 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002701 SDValue(Agg.getNode(), Agg.getResNo() + i);
2702
Scott Michelfdc40a02009-02-17 22:15:04 +00002703 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002704 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2705 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002706}
2707
2708void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2709 const Value *Op0 = I.getOperand(0);
2710 const Type *AggTy = Op0->getType();
2711 const Type *ValTy = I.getType();
2712 bool OutOfUndef = isa<UndefValue>(Op0);
2713
2714 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2715 I.idx_begin(), I.idx_end());
2716
Owen Andersone50ed302009-08-10 22:56:29 +00002717 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002718 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2719
2720 unsigned NumValValues = ValValueVTs.size();
2721 SmallVector<SDValue, 4> Values(NumValValues);
2722
2723 SDValue Agg = getValue(Op0);
2724 // Copy out the selected value(s).
2725 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2726 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002727 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002728 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002729 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002730
Scott Michelfdc40a02009-02-17 22:15:04 +00002731 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002732 DAG.getVTList(&ValValueVTs[0], NumValValues),
2733 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002734}
2735
2736
2737void SelectionDAGLowering::visitGetElementPtr(User &I) {
2738 SDValue N = getValue(I.getOperand(0));
2739 const Type *Ty = I.getOperand(0)->getType();
2740
2741 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2742 OI != E; ++OI) {
2743 Value *Idx = *OI;
2744 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2745 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2746 if (Field) {
2747 // N = N + Offset
2748 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002749 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002750 DAG.getIntPtrConstant(Offset));
2751 }
2752 Ty = StTy->getElementType(Field);
2753 } else {
2754 Ty = cast<SequentialType>(Ty)->getElementType();
2755
2756 // If this is a constant subscript, handle it quickly.
2757 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2758 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002759 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002760 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002761 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002762 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002763 unsigned PtrBits = PTy.getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002764 if (PtrBits < 64) {
2765 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2766 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002767 DAG.getConstant(Offs, MVT::i64));
Evan Cheng65b52df2009-02-09 21:01:06 +00002768 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002769 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002770 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002771 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772 continue;
2773 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002774
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002775 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002776 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2777 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002778 SDValue IdxN = getValue(Idx);
2779
2780 // If the index is smaller or larger than intptr_t, truncate or extend
2781 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002782 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002783
2784 // If this is a multiply by a power of two, turn it into a shl
2785 // immediately. This is a very common case.
2786 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002787 if (ElementSize.isPowerOf2()) {
2788 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002789 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002790 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002791 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002792 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002793 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002794 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002795 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002796 }
2797 }
2798
Scott Michelfdc40a02009-02-17 22:15:04 +00002799 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002800 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002801 }
2802 }
2803 setValue(&I, N);
2804}
2805
2806void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2807 // If this is a fixed sized alloca in the entry block of the function,
2808 // allocate it statically on the stack.
2809 if (FuncInfo.StaticAllocaMap.count(&I))
2810 return; // getValue will auto-populate this.
2811
2812 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002813 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002814 unsigned Align =
2815 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2816 I.getAlignment());
2817
2818 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002819
2820 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2821 AllocSize,
2822 DAG.getConstant(TySize, AllocSize.getValueType()));
2823
2824
2825
Owen Andersone50ed302009-08-10 22:56:29 +00002826 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002827 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002828
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002829 // Handle alignment. If the requested alignment is less than or equal to
2830 // the stack alignment, ignore it. If the size is greater than or equal to
2831 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2832 unsigned StackAlign =
2833 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2834 if (Align <= StackAlign)
2835 Align = 0;
2836
2837 // Round the size of the allocation up to the stack alignment size
2838 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002839 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002840 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002841 DAG.getIntPtrConstant(StackAlign-1));
2842 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002843 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002844 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002845 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2846
2847 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002848 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002849 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002850 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002851 setValue(&I, DSA);
2852 DAG.setRoot(DSA.getValue(1));
2853
2854 // Inform the Frame Information that we have just allocated a variable-sized
2855 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002856 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857}
2858
2859void SelectionDAGLowering::visitLoad(LoadInst &I) {
2860 const Value *SV = I.getOperand(0);
2861 SDValue Ptr = getValue(SV);
2862
2863 const Type *Ty = I.getType();
2864 bool isVolatile = I.isVolatile();
2865 unsigned Alignment = I.getAlignment();
2866
Owen Andersone50ed302009-08-10 22:56:29 +00002867 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002868 SmallVector<uint64_t, 4> Offsets;
2869 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2870 unsigned NumValues = ValueVTs.size();
2871 if (NumValues == 0)
2872 return;
2873
2874 SDValue Root;
2875 bool ConstantMemory = false;
2876 if (I.isVolatile())
2877 // Serialize volatile loads with other side effects.
2878 Root = getRoot();
2879 else if (AA->pointsToConstantMemory(SV)) {
2880 // Do not serialize (non-volatile) loads of constant memory with anything.
2881 Root = DAG.getEntryNode();
2882 ConstantMemory = true;
2883 } else {
2884 // Do not serialize non-volatile loads against each other.
2885 Root = DAG.getRoot();
2886 }
2887
2888 SmallVector<SDValue, 4> Values(NumValues);
2889 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002890 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002891 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002892 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Nate Begemane6798372009-09-15 00:13:12 +00002893 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2894 PtrVT, Ptr,
2895 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002896 SV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002897 Values[i] = L;
2898 Chains[i] = L.getValue(1);
2899 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002900
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002901 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002902 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002903 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002904 &Chains[0], NumValues);
2905 if (isVolatile)
2906 DAG.setRoot(Chain);
2907 else
2908 PendingLoads.push_back(Chain);
2909 }
2910
Scott Michelfdc40a02009-02-17 22:15:04 +00002911 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002912 DAG.getVTList(&ValueVTs[0], NumValues),
2913 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002914}
2915
2916
2917void SelectionDAGLowering::visitStore(StoreInst &I) {
2918 Value *SrcV = I.getOperand(0);
2919 Value *PtrV = I.getOperand(1);
2920
Owen Andersone50ed302009-08-10 22:56:29 +00002921 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002922 SmallVector<uint64_t, 4> Offsets;
2923 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2924 unsigned NumValues = ValueVTs.size();
2925 if (NumValues == 0)
2926 return;
2927
2928 // Get the lowered operands. Note that we do this after
2929 // checking if NumResults is zero, because with zero results
2930 // the operands won't have values in the map.
2931 SDValue Src = getValue(SrcV);
2932 SDValue Ptr = getValue(PtrV);
2933
2934 SDValue Root = getRoot();
2935 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002936 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002937 bool isVolatile = I.isVolatile();
2938 unsigned Alignment = I.getAlignment();
2939 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002940 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002941 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002942 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002943 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002944 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002945 PtrV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002946
Scott Michelfdc40a02009-02-17 22:15:04 +00002947 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002948 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002949}
2950
2951/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2952/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002953void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002954 unsigned Intrinsic) {
2955 bool HasChain = !I.doesNotAccessMemory();
2956 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2957
2958 // Build the operand list.
2959 SmallVector<SDValue, 8> Ops;
2960 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2961 if (OnlyLoad) {
2962 // We don't need to serialize loads against other loads.
2963 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002964 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002965 Ops.push_back(getRoot());
2966 }
2967 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002968
2969 // Info is set by getTgtMemInstrinsic
2970 TargetLowering::IntrinsicInfo Info;
2971 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2972
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002973 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002974 if (!IsTgtIntrinsic)
2975 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002976
2977 // Add all operands of the call to the operand list.
2978 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2979 SDValue Op = getValue(I.getOperand(i));
2980 assert(TLI.isTypeLegal(Op.getValueType()) &&
2981 "Intrinsic uses a non-legal type?");
2982 Ops.push_back(Op);
2983 }
2984
Owen Andersone50ed302009-08-10 22:56:29 +00002985 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002986 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2987#ifndef NDEBUG
2988 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2989 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2990 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002991 }
Bob Wilson8d919552009-07-31 22:41:21 +00002992#endif // NDEBUG
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002993 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002994 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002995
Bob Wilson8d919552009-07-31 22:41:21 +00002996 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002997
2998 // Create the node.
2999 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003000 if (IsTgtIntrinsic) {
3001 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00003002 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003003 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003004 Info.memVT, Info.ptrVal, Info.offset,
3005 Info.align, Info.vol,
3006 Info.readMem, Info.writeMem);
3007 }
3008 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00003009 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003010 VTs, &Ops[0], Ops.size());
Owen Anderson1d0be152009-08-13 21:58:54 +00003011 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
Scott Michelfdc40a02009-02-17 22:15:04 +00003012 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003013 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003014 else
Scott Michelfdc40a02009-02-17 22:15:04 +00003015 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003016 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003017
3018 if (HasChain) {
3019 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3020 if (OnlyLoad)
3021 PendingLoads.push_back(Chain);
3022 else
3023 DAG.setRoot(Chain);
3024 }
Owen Anderson1d0be152009-08-13 21:58:54 +00003025 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003026 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00003027 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003028 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003029 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003030 setValue(&I, Result);
3031 }
3032}
3033
3034/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3035static GlobalVariable *ExtractTypeInfo(Value *V) {
3036 V = V->stripPointerCasts();
3037 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3038 assert ((GV || isa<ConstantPointerNull>(V)) &&
3039 "TypeInfo must be a global variable or NULL");
3040 return GV;
3041}
3042
3043namespace llvm {
3044
3045/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3046/// call, and add them to the specified machine basic block.
3047void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3048 MachineBasicBlock *MBB) {
3049 // Inform the MachineModuleInfo of the personality for this landing pad.
3050 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3051 assert(CE->getOpcode() == Instruction::BitCast &&
3052 isa<Function>(CE->getOperand(0)) &&
3053 "Personality should be a function");
3054 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3055
3056 // Gather all the type infos for this landing pad and pass them along to
3057 // MachineModuleInfo.
3058 std::vector<GlobalVariable *> TyInfo;
3059 unsigned N = I.getNumOperands();
3060
3061 for (unsigned i = N - 1; i > 2; --i) {
3062 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3063 unsigned FilterLength = CI->getZExtValue();
3064 unsigned FirstCatch = i + FilterLength + !FilterLength;
3065 assert (FirstCatch <= N && "Invalid filter length");
3066
3067 if (FirstCatch < N) {
3068 TyInfo.reserve(N - FirstCatch);
3069 for (unsigned j = FirstCatch; j < N; ++j)
3070 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3071 MMI->addCatchTypeInfo(MBB, TyInfo);
3072 TyInfo.clear();
3073 }
3074
3075 if (!FilterLength) {
3076 // Cleanup.
3077 MMI->addCleanup(MBB);
3078 } else {
3079 // Filter.
3080 TyInfo.reserve(FilterLength - 1);
3081 for (unsigned j = i + 1; j < FirstCatch; ++j)
3082 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3083 MMI->addFilterTypeInfo(MBB, TyInfo);
3084 TyInfo.clear();
3085 }
3086
3087 N = i;
3088 }
3089 }
3090
3091 if (N > 3) {
3092 TyInfo.reserve(N - 3);
3093 for (unsigned j = 3; j < N; ++j)
3094 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3095 MMI->addCatchTypeInfo(MBB, TyInfo);
3096 }
3097}
3098
3099}
3100
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003101/// GetSignificand - Get the significand and build it into a floating-point
3102/// number with exponent of 1:
3103///
3104/// Op = (Op & 0x007fffff) | 0x3f800000;
3105///
3106/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003107static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003108GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003109 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3110 DAG.getConstant(0x007fffff, MVT::i32));
3111 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3112 DAG.getConstant(0x3f800000, MVT::i32));
3113 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003114}
3115
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003116/// GetExponent - Get the exponent:
3117///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003118/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003119///
3120/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003121static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003122GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3123 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003124 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3125 DAG.getConstant(0x7f800000, MVT::i32));
3126 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003127 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003128 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3129 DAG.getConstant(127, MVT::i32));
3130 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003131}
3132
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003133/// getF32Constant - Get 32-bit floating point constant.
3134static SDValue
3135getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003136 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003137}
3138
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003139/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003140/// visitIntrinsicCall: I is a call instruction
3141/// Op is the associated NodeType for I
3142const char *
3143SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003144 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003145 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003146 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003147 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003148 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003149 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003150 getValue(I.getOperand(2)),
3151 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003152 setValue(&I, L);
3153 DAG.setRoot(L.getValue(1));
3154 return 0;
3155}
3156
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003157// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003158const char *
3159SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003160 SDValue Op1 = getValue(I.getOperand(1));
3161 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003162
Owen Anderson825b72b2009-08-11 20:47:22 +00003163 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Dan Gohmanfc166572009-04-09 23:54:40 +00003164 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003165
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003166 setValue(&I, Result);
3167 return 0;
3168}
Bill Wendling74c37652008-12-09 22:08:41 +00003169
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003170/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3171/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003172void
3173SelectionDAGLowering::visitExp(CallInst &I) {
3174 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003175 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003176
Owen Anderson825b72b2009-08-11 20:47:22 +00003177 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003178 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3179 SDValue Op = getValue(I.getOperand(1));
3180
3181 // Put the exponent in the right bit position for later addition to the
3182 // final result:
3183 //
3184 // #define LOG2OFe 1.4426950f
3185 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003186 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003187 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003188 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003189
3190 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003191 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3192 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003193
3194 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003195 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003196 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003197
3198 if (LimitFloatPrecision <= 6) {
3199 // For floating-point precision of 6:
3200 //
3201 // TwoToFractionalPartOfX =
3202 // 0.997535578f +
3203 // (0.735607626f + 0.252464424f * x) * x;
3204 //
3205 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003206 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003207 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003208 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003209 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003210 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3211 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003212 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003213 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003214
3215 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003216 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003217 TwoToFracPartOfX, IntegerPartOfX);
3218
Owen Anderson825b72b2009-08-11 20:47:22 +00003219 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003220 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3221 // For floating-point precision of 12:
3222 //
3223 // TwoToFractionalPartOfX =
3224 // 0.999892986f +
3225 // (0.696457318f +
3226 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3227 //
3228 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003229 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003230 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003231 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003232 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003233 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3234 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003235 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003236 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3237 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003238 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003239 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003240
3241 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003242 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003243 TwoToFracPartOfX, IntegerPartOfX);
3244
Owen Anderson825b72b2009-08-11 20:47:22 +00003245 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003246 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3247 // For floating-point precision of 18:
3248 //
3249 // TwoToFractionalPartOfX =
3250 // 0.999999982f +
3251 // (0.693148872f +
3252 // (0.240227044f +
3253 // (0.554906021e-1f +
3254 // (0.961591928e-2f +
3255 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3256 //
3257 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003258 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003259 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003260 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003261 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003262 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3263 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003265 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3266 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003267 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003268 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3269 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003270 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003271 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3272 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003273 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003274 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3275 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003276 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003277 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003278 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003279
3280 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003281 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003282 TwoToFracPartOfX, IntegerPartOfX);
3283
Owen Anderson825b72b2009-08-11 20:47:22 +00003284 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003285 }
3286 } else {
3287 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003288 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003289 getValue(I.getOperand(1)).getValueType(),
3290 getValue(I.getOperand(1)));
3291 }
3292
Dale Johannesen59e577f2008-09-05 18:38:42 +00003293 setValue(&I, result);
3294}
3295
Bill Wendling39150252008-09-09 20:39:27 +00003296/// visitLog - Lower a log intrinsic. Handles the special sequences for
3297/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003298void
3299SelectionDAGLowering::visitLog(CallInst &I) {
3300 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003301 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003302
Owen Anderson825b72b2009-08-11 20:47:22 +00003303 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003304 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3305 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003306 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003307
3308 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003309 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003310 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003312
3313 // Get the significand and build it into a floating-point number with
3314 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003315 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003316
3317 if (LimitFloatPrecision <= 6) {
3318 // For floating-point precision of 6:
3319 //
3320 // LogofMantissa =
3321 // -1.1609546f +
3322 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003323 //
Bill Wendling39150252008-09-09 20:39:27 +00003324 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003326 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003327 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003328 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3330 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003331 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003332
Scott Michelfdc40a02009-02-17 22:15:04 +00003333 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003334 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003335 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3336 // For floating-point precision of 12:
3337 //
3338 // LogOfMantissa =
3339 // -1.7417939f +
3340 // (2.8212026f +
3341 // (-1.4699568f +
3342 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3343 //
3344 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003345 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003346 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003347 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003348 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3350 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003352 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3353 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003354 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003355 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3356 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003357 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003358
Scott Michelfdc40a02009-02-17 22:15:04 +00003359 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003360 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003361 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3362 // For floating-point precision of 18:
3363 //
3364 // LogOfMantissa =
3365 // -2.1072184f +
3366 // (4.2372794f +
3367 // (-3.7029485f +
3368 // (2.2781945f +
3369 // (-0.87823314f +
3370 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3371 //
3372 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003373 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003374 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003375 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003376 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003377 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3378 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003379 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003380 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3381 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003382 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003383 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3384 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003385 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003386 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3387 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003388 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003389 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3390 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003392
Scott Michelfdc40a02009-02-17 22:15:04 +00003393 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003394 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003395 }
3396 } else {
3397 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003398 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003399 getValue(I.getOperand(1)).getValueType(),
3400 getValue(I.getOperand(1)));
3401 }
3402
Dale Johannesen59e577f2008-09-05 18:38:42 +00003403 setValue(&I, result);
3404}
3405
Bill Wendling3eb59402008-09-09 00:28:24 +00003406/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3407/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003408void
3409SelectionDAGLowering::visitLog2(CallInst &I) {
3410 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003411 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003412
Owen Anderson825b72b2009-08-11 20:47:22 +00003413 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003414 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3415 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003416 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003417
Bill Wendling39150252008-09-09 20:39:27 +00003418 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003419 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003420
3421 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003422 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003423 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003424
Bill Wendling3eb59402008-09-09 00:28:24 +00003425 // Different possible minimax approximations of significand in
3426 // floating-point for various degrees of accuracy over [1,2].
3427 if (LimitFloatPrecision <= 6) {
3428 // For floating-point precision of 6:
3429 //
3430 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3431 //
3432 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003433 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003434 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003435 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003436 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003437 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3438 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003439 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003440
Scott Michelfdc40a02009-02-17 22:15:04 +00003441 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003442 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003443 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3444 // For floating-point precision of 12:
3445 //
3446 // Log2ofMantissa =
3447 // -2.51285454f +
3448 // (4.07009056f +
3449 // (-2.12067489f +
3450 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003451 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003452 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003453 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003454 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003455 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003456 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003457 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3458 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003459 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003460 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3461 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003462 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003463 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3464 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003465 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003466
Scott Michelfdc40a02009-02-17 22:15:04 +00003467 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003468 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003469 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3470 // For floating-point precision of 18:
3471 //
3472 // Log2ofMantissa =
3473 // -3.0400495f +
3474 // (6.1129976f +
3475 // (-5.3420409f +
3476 // (3.2865683f +
3477 // (-1.2669343f +
3478 // (0.27515199f -
3479 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3480 //
3481 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003482 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003483 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003484 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003486 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3487 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003488 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003489 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3490 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003491 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003492 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3493 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003494 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003495 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3496 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003497 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003498 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3499 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003500 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003501
Scott Michelfdc40a02009-02-17 22:15:04 +00003502 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003503 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003504 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003505 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003506 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003507 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003508 getValue(I.getOperand(1)).getValueType(),
3509 getValue(I.getOperand(1)));
3510 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003511
Dale Johannesen59e577f2008-09-05 18:38:42 +00003512 setValue(&I, result);
3513}
3514
Bill Wendling3eb59402008-09-09 00:28:24 +00003515/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3516/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003517void
3518SelectionDAGLowering::visitLog10(CallInst &I) {
3519 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003520 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003521
Owen Anderson825b72b2009-08-11 20:47:22 +00003522 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003523 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3524 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003525 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003526
Bill Wendling39150252008-09-09 20:39:27 +00003527 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003528 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003529 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003530 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003531
3532 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003533 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003534 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003535
3536 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003537 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003538 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003539 // Log10ofMantissa =
3540 // -0.50419619f +
3541 // (0.60948995f - 0.10380950f * x) * x;
3542 //
3543 // error 0.0014886165, which is 6 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, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003546 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003547 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003548 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3549 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003550 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003551
Scott Michelfdc40a02009-02-17 22:15:04 +00003552 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003553 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003554 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3555 // For floating-point precision of 12:
3556 //
3557 // Log10ofMantissa =
3558 // -0.64831180f +
3559 // (0.91751397f +
3560 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3561 //
3562 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003563 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003564 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003565 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003566 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003567 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3568 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003569 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003570 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3571 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003572 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003573
Scott Michelfdc40a02009-02-17 22:15:04 +00003574 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003575 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003576 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003577 // For floating-point precision of 18:
3578 //
3579 // Log10ofMantissa =
3580 // -0.84299375f +
3581 // (1.5327582f +
3582 // (-1.0688956f +
3583 // (0.49102474f +
3584 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3585 //
3586 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003587 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003588 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003589 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003590 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003591 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3592 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003593 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003594 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3595 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003596 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003597 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3598 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003599 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003600 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3601 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003602 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003603
Scott Michelfdc40a02009-02-17 22:15:04 +00003604 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003605 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003606 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003607 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003608 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003609 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003610 getValue(I.getOperand(1)).getValueType(),
3611 getValue(I.getOperand(1)));
3612 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003613
Dale Johannesen59e577f2008-09-05 18:38:42 +00003614 setValue(&I, result);
3615}
3616
Bill Wendlinge10c8142008-09-09 22:39:21 +00003617/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3618/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003619void
3620SelectionDAGLowering::visitExp2(CallInst &I) {
3621 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003622 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003623
Owen Anderson825b72b2009-08-11 20:47:22 +00003624 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003625 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3626 SDValue Op = getValue(I.getOperand(1));
3627
Owen Anderson825b72b2009-08-11 20:47:22 +00003628 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003629
3630 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003631 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3632 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003633
3634 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003635 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003636 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003637
3638 if (LimitFloatPrecision <= 6) {
3639 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003640 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003641 // TwoToFractionalPartOfX =
3642 // 0.997535578f +
3643 // (0.735607626f + 0.252464424f * x) * x;
3644 //
3645 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003646 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003648 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003649 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003650 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3651 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003653 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003654 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003655 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003656
Scott Michelfdc40a02009-02-17 22:15:04 +00003657 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003658 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003659 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3660 // For floating-point precision of 12:
3661 //
3662 // TwoToFractionalPartOfX =
3663 // 0.999892986f +
3664 // (0.696457318f +
3665 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3666 //
3667 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003668 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003669 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003670 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003671 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003672 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3673 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003674 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003675 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3676 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003677 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003678 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003679 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003680 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003681
Scott Michelfdc40a02009-02-17 22:15:04 +00003682 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003683 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003684 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3685 // For floating-point precision of 18:
3686 //
3687 // TwoToFractionalPartOfX =
3688 // 0.999999982f +
3689 // (0.693148872f +
3690 // (0.240227044f +
3691 // (0.554906021e-1f +
3692 // (0.961591928e-2f +
3693 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3694 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003695 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003696 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003697 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003698 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003699 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3700 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003701 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003702 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3703 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003704 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003705 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3706 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003707 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003708 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3709 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003710 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003711 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3712 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003713 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003714 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003715 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003716 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003717
Scott Michelfdc40a02009-02-17 22:15:04 +00003718 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003719 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003720 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003721 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003722 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003723 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003724 getValue(I.getOperand(1)).getValueType(),
3725 getValue(I.getOperand(1)));
3726 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003727
Dale Johannesen601d3c02008-09-05 01:48:15 +00003728 setValue(&I, result);
3729}
3730
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003731/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3732/// limited-precision mode with x == 10.0f.
3733void
3734SelectionDAGLowering::visitPow(CallInst &I) {
3735 SDValue result;
3736 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003737 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003738 bool IsExp10 = false;
3739
Owen Anderson825b72b2009-08-11 20:47:22 +00003740 if (getValue(Val).getValueType() == MVT::f32 &&
3741 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003742 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3743 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3744 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3745 APFloat Ten(10.0f);
3746 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3747 }
3748 }
3749 }
3750
3751 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3752 SDValue Op = getValue(I.getOperand(2));
3753
3754 // Put the exponent in the right bit position for later addition to the
3755 // final result:
3756 //
3757 // #define LOG2OF10 3.3219281f
3758 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003759 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003760 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003761 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003762
3763 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003764 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3765 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003766
3767 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003768 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003769 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003770
3771 if (LimitFloatPrecision <= 6) {
3772 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003773 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003774 // twoToFractionalPartOfX =
3775 // 0.997535578f +
3776 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003777 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003778 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003779 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003780 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003781 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003782 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003783 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3784 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003785 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003786 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003787 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003788 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003789
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003790 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003791 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003792 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3793 // For floating-point precision of 12:
3794 //
3795 // TwoToFractionalPartOfX =
3796 // 0.999892986f +
3797 // (0.696457318f +
3798 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3799 //
3800 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003802 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003804 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3806 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003807 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003810 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003811 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003812 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003813 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003814
Scott Michelfdc40a02009-02-17 22:15:04 +00003815 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003816 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003817 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3818 // For floating-point precision of 18:
3819 //
3820 // TwoToFractionalPartOfX =
3821 // 0.999999982f +
3822 // (0.693148872f +
3823 // (0.240227044f +
3824 // (0.554906021e-1f +
3825 // (0.961591928e-2f +
3826 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3827 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003828 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003829 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003830 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003831 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003832 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3833 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003834 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003835 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3836 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003837 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003838 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3839 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003840 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003841 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3842 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003843 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003844 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3845 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003846 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003847 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003848 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003849 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003850
Scott Michelfdc40a02009-02-17 22:15:04 +00003851 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003852 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003853 }
3854 } else {
3855 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003856 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003857 getValue(I.getOperand(1)).getValueType(),
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2)));
3860 }
3861
3862 setValue(&I, result);
3863}
3864
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003865/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3866/// we want to emit this as a call to a named external function, return the name
3867/// otherwise lower it and return null.
3868const char *
3869SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003870 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003871 switch (Intrinsic) {
3872 default:
3873 // By default, turn this into a target intrinsic node.
3874 visitTargetIntrinsic(I, Intrinsic);
3875 return 0;
3876 case Intrinsic::vastart: visitVAStart(I); return 0;
3877 case Intrinsic::vaend: visitVAEnd(I); return 0;
3878 case Intrinsic::vacopy: visitVACopy(I); return 0;
3879 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003880 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003881 getValue(I.getOperand(1))));
3882 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003883 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003884 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 getValue(I.getOperand(1))));
3886 return 0;
3887 case Intrinsic::setjmp:
3888 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3889 break;
3890 case Intrinsic::longjmp:
3891 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3892 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003893 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003894 SDValue Op1 = getValue(I.getOperand(1));
3895 SDValue Op2 = getValue(I.getOperand(2));
3896 SDValue Op3 = getValue(I.getOperand(3));
3897 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003898 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003899 I.getOperand(1), 0, I.getOperand(2), 0));
3900 return 0;
3901 }
Chris Lattner824b9582008-11-21 16:42:48 +00003902 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 SDValue Op1 = getValue(I.getOperand(1));
3904 SDValue Op2 = getValue(I.getOperand(2));
3905 SDValue Op3 = getValue(I.getOperand(3));
3906 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003907 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003908 I.getOperand(1), 0));
3909 return 0;
3910 }
Chris Lattner824b9582008-11-21 16:42:48 +00003911 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003912 SDValue Op1 = getValue(I.getOperand(1));
3913 SDValue Op2 = getValue(I.getOperand(2));
3914 SDValue Op3 = getValue(I.getOperand(3));
3915 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3916
3917 // If the source and destination are known to not be aliases, we can
3918 // lower memmove as memcpy.
3919 uint64_t Size = -1ULL;
3920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003921 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003922 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3923 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003924 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003925 I.getOperand(1), 0, I.getOperand(2), 0));
3926 return 0;
3927 }
3928
Dale Johannesena04b7572009-02-03 23:04:43 +00003929 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003930 I.getOperand(1), 0, I.getOperand(2), 0));
3931 return 0;
3932 }
3933 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003934 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003935 if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003936 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003937 DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
Chris Lattneraf29a522009-05-04 22:10:05 +00003938 setCurDebugLoc(Loc);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003939
Bill Wendling98a366d2009-04-29 23:29:43 +00003940 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003941 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003942 SPI.getLine(),
3943 SPI.getColumn(),
3944 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003945 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003946 return 0;
3947 }
3948 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003949 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003950 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003951 if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
3952 && DW->ShouldEmitDwarfDebug()) {
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003953 unsigned LabelID =
Devang Patele4b27562009-08-28 23:24:31 +00003954 DW->RecordRegionStart(RSI.getContext());
Devang Patel48c7fa22009-04-13 18:13:16 +00003955 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3956 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003957 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003958 return 0;
3959 }
3960 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003961 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003962 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel0f7fef32009-04-13 17:02:03 +00003963
Devang Patel7e1e31f2009-07-02 22:43:26 +00003964 if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
3965 || !DW->ShouldEmitDwarfDebug())
3966 return 0;
Bill Wendling6c4311d2009-05-08 21:14:49 +00003967
Devang Patele4b27562009-08-28 23:24:31 +00003968 DISubprogram Subprogram(REI.getContext());
Devang Patel7e1e31f2009-07-02 22:43:26 +00003969
Devang Patel7e1e31f2009-07-02 22:43:26 +00003970 unsigned LabelID =
Devang Patele4b27562009-08-28 23:24:31 +00003971 DW->RecordRegionEnd(REI.getContext());
Devang Patel7e1e31f2009-07-02 22:43:26 +00003972 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3973 getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003974 return 0;
3975 }
3976 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003977 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003978 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00003979 if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None))
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003980 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003981
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003982 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003983 MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00003984
3985 if (!DW || !DW->ShouldEmitDwarfDebug())
3986 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003987 // llvm.dbg.func_start also defines beginning of function scope.
Devang Patele4b27562009-08-28 23:24:31 +00003988 DW->RecordRegionStart(FSI.getSubprogram());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003989 return 0;
3990 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003991 case Intrinsic::dbg_declare: {
Devang Patel7e1e31f2009-07-02 22:43:26 +00003992 if (OptLevel != CodeGenOpt::None)
3993 // FIXME: Variable debug info is not supported here.
3994 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003995 DwarfWriter *DW = DAG.getDwarfWriter();
3996 if (!DW)
3997 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003998 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3999 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
4000 return 0;
4001
Devang Patelac1ceb32009-10-09 22:42:28 +00004002 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00004003 Value *Address = DI.getAddress();
4004 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4005 Address = BCI->getOperand(0);
4006 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4007 // Don't handle byval struct arguments or VLAs, for example.
4008 if (!AI)
4009 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00004010 DenseMap<const AllocaInst*, int>::iterator SI =
4011 FuncInfo.StaticAllocaMap.find(AI);
4012 if (SI == FuncInfo.StaticAllocaMap.end())
4013 return 0; // VLAs.
4014 int FI = SI->second;
Devang Patelac1ceb32009-10-09 22:42:28 +00004015#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
4016 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Devang Patel53bb5c92009-11-10 23:06:00 +00004017 if (MMI) {
4018 MetadataContext &TheMetadata =
4019 DI.getParent()->getContext().getMetadata();
4020 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
4021 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
4022 MMI->setVariableDbgInfo(Variable, FI, Dbg);
4023 }
Devang Patelac1ceb32009-10-09 22:42:28 +00004024#else
4025 DW->RecordVariable(Variable, FI);
4026#endif
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004027 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004028 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004029 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004030 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00004031 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00004032 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004033 SDValue Ops[1];
4034 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004035 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004036 setValue(&I, Op);
4037 DAG.setRoot(Op.getValue(1));
4038 return 0;
4039 }
4040
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004041 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004042 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004043
Chris Lattner3a5815f2009-09-17 23:54:54 +00004044 if (CurMBB->isLandingPad())
4045 AddCatchInfo(I, MMI, CurMBB);
4046 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004047#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00004048 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004049#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00004050 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4051 unsigned Reg = TLI.getExceptionSelectorRegister();
4052 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004053 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004054
Chris Lattner3a5815f2009-09-17 23:54:54 +00004055 // Insert the EHSELECTION instruction.
4056 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4057 SDValue Ops[2];
4058 Ops[0] = getValue(I.getOperand(1));
4059 Ops[1] = getRoot();
4060 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4061
4062 DAG.setRoot(Op.getValue(1));
4063
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004064 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004065 return 0;
4066 }
4067
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004068 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004069 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004070
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004071 if (MMI) {
4072 // Find the type id for the given typeinfo.
4073 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4074
4075 unsigned TypeID = MMI->getTypeIDFor(GV);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004076 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004077 } else {
4078 // Return something different to eh_selector.
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004079 setValue(&I, DAG.getConstant(1, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004080 }
4081
4082 return 0;
4083 }
4084
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004085 case Intrinsic::eh_return_i32:
4086 case Intrinsic::eh_return_i64:
4087 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004088 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004089 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004090 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004091 getControlRoot(),
4092 getValue(I.getOperand(1)),
4093 getValue(I.getOperand(2))));
4094 } else {
4095 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4096 }
4097
4098 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004099 case Intrinsic::eh_unwind_init:
4100 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4101 MMI->setCallsUnwindInit(true);
4102 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004103
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004104 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004105
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004106 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00004107 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00004108 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4109 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004110
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004111 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004112 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004113 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004114 TLI.getPointerTy()),
4115 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004116 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004117 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004118 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004119 TLI.getPointerTy(),
4120 DAG.getConstant(0,
4121 TLI.getPointerTy())),
4122 Offset));
4123 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004124 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004125 case Intrinsic::convertff:
4126 case Intrinsic::convertfsi:
4127 case Intrinsic::convertfui:
4128 case Intrinsic::convertsif:
4129 case Intrinsic::convertuif:
4130 case Intrinsic::convertss:
4131 case Intrinsic::convertsu:
4132 case Intrinsic::convertus:
4133 case Intrinsic::convertuu: {
4134 ISD::CvtCode Code = ISD::CVT_INVALID;
4135 switch (Intrinsic) {
4136 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4137 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4138 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4139 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4140 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4141 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4142 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4143 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4144 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4145 }
Owen Andersone50ed302009-08-10 22:56:29 +00004146 EVT DestVT = TLI.getValueType(I.getType());
Mon P Wang77cdf302008-11-10 20:54:11 +00004147 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004148 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004149 DAG.getValueType(DestVT),
4150 DAG.getValueType(getValue(Op1).getValueType()),
4151 getValue(I.getOperand(2)),
4152 getValue(I.getOperand(3)),
4153 Code));
4154 return 0;
4155 }
4156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004157 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004158 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004159 getValue(I.getOperand(1)).getValueType(),
4160 getValue(I.getOperand(1))));
4161 return 0;
4162 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004163 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004164 getValue(I.getOperand(1)).getValueType(),
4165 getValue(I.getOperand(1)),
4166 getValue(I.getOperand(2))));
4167 return 0;
4168 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004169 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 getValue(I.getOperand(1)).getValueType(),
4171 getValue(I.getOperand(1))));
4172 return 0;
4173 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004174 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004175 getValue(I.getOperand(1)).getValueType(),
4176 getValue(I.getOperand(1))));
4177 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004178 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004179 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004180 return 0;
4181 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004182 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004183 return 0;
4184 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004185 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004186 return 0;
4187 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004188 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004189 return 0;
4190 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004191 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004192 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004193 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004194 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004195 return 0;
4196 case Intrinsic::pcmarker: {
4197 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004198 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004199 return 0;
4200 }
4201 case Intrinsic::readcyclecounter: {
4202 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004203 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004204 DAG.getVTList(MVT::i64, MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004205 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004206 setValue(&I, Tmp);
4207 DAG.setRoot(Tmp.getValue(1));
4208 return 0;
4209 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004210 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004211 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004212 getValue(I.getOperand(1)).getValueType(),
4213 getValue(I.getOperand(1))));
4214 return 0;
4215 case Intrinsic::cttz: {
4216 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004217 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004218 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004219 setValue(&I, result);
4220 return 0;
4221 }
4222 case Intrinsic::ctlz: {
4223 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004224 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004225 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004226 setValue(&I, result);
4227 return 0;
4228 }
4229 case Intrinsic::ctpop: {
4230 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004231 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004232 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004233 setValue(&I, result);
4234 return 0;
4235 }
4236 case Intrinsic::stacksave: {
4237 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004238 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004239 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004240 setValue(&I, Tmp);
4241 DAG.setRoot(Tmp.getValue(1));
4242 return 0;
4243 }
4244 case Intrinsic::stackrestore: {
4245 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004246 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004247 return 0;
4248 }
Bill Wendling57344502008-11-18 11:01:33 +00004249 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004250 // Emit code into the DAG to store the stack guard onto the stack.
4251 MachineFunction &MF = DAG.getMachineFunction();
4252 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004253 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004254
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004255 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4256 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004257
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004258 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004259 MFI->setStackProtectorIndex(FI);
4260
4261 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4262
4263 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004264 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Evan Chengff89dcb2009-10-18 18:16:27 +00004265 PseudoSourceValue::getFixedStack(FI),
4266 0, true);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004267 setValue(&I, Result);
4268 DAG.setRoot(Result);
4269 return 0;
4270 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004271 case Intrinsic::objectsize: {
4272 // If we don't know by now, we're never going to know.
4273 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4274
4275 assert(CI && "Non-constant type in __builtin_object_size?");
4276
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004277 SDValue Arg = getValue(I.getOperand(0));
4278 EVT Ty = Arg.getValueType();
4279
Eric Christopher7b5e6172009-10-27 00:52:25 +00004280 if (CI->getZExtValue() < 2)
Mike Stump70e5e682009-11-09 22:28:21 +00004281 setValue(&I, DAG.getConstant(-1ULL, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004282 else
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004283 setValue(&I, DAG.getConstant(0, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004284 return 0;
4285 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004286 case Intrinsic::var_annotation:
4287 // Discard annotate attributes
4288 return 0;
4289
4290 case Intrinsic::init_trampoline: {
4291 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4292
4293 SDValue Ops[6];
4294 Ops[0] = getRoot();
4295 Ops[1] = getValue(I.getOperand(1));
4296 Ops[2] = getValue(I.getOperand(2));
4297 Ops[3] = getValue(I.getOperand(3));
4298 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4299 Ops[5] = DAG.getSrcValue(F);
4300
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004301 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004302 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004303 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004304
4305 setValue(&I, Tmp);
4306 DAG.setRoot(Tmp.getValue(1));
4307 return 0;
4308 }
4309
4310 case Intrinsic::gcroot:
4311 if (GFI) {
4312 Value *Alloca = I.getOperand(1);
4313 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004315 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4316 GFI->addStackRoot(FI->getIndex(), TypeMap);
4317 }
4318 return 0;
4319
4320 case Intrinsic::gcread:
4321 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004322 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004323 return 0;
4324
4325 case Intrinsic::flt_rounds: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004326 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004327 return 0;
4328 }
4329
4330 case Intrinsic::trap: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004331 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004332 return 0;
4333 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004334
Bill Wendlingef375462008-11-21 02:38:44 +00004335 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004336 return implVisitAluOverflow(I, ISD::UADDO);
4337 case Intrinsic::sadd_with_overflow:
4338 return implVisitAluOverflow(I, ISD::SADDO);
4339 case Intrinsic::usub_with_overflow:
4340 return implVisitAluOverflow(I, ISD::USUBO);
4341 case Intrinsic::ssub_with_overflow:
4342 return implVisitAluOverflow(I, ISD::SSUBO);
4343 case Intrinsic::umul_with_overflow:
4344 return implVisitAluOverflow(I, ISD::UMULO);
4345 case Intrinsic::smul_with_overflow:
4346 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004347
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004348 case Intrinsic::prefetch: {
4349 SDValue Ops[4];
4350 Ops[0] = getRoot();
4351 Ops[1] = getValue(I.getOperand(1));
4352 Ops[2] = getValue(I.getOperand(2));
4353 Ops[3] = getValue(I.getOperand(3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004354 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004355 return 0;
4356 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004357
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004358 case Intrinsic::memory_barrier: {
4359 SDValue Ops[6];
4360 Ops[0] = getRoot();
4361 for (int x = 1; x < 6; ++x)
4362 Ops[x] = getValue(I.getOperand(x));
4363
Owen Anderson825b72b2009-08-11 20:47:22 +00004364 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004365 return 0;
4366 }
4367 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004368 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004369 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004370 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004371 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4372 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004373 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004374 getValue(I.getOperand(2)),
4375 getValue(I.getOperand(3)),
4376 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004377 setValue(&I, L);
4378 DAG.setRoot(L.getValue(1));
4379 return 0;
4380 }
4381 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004382 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004383 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004384 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004385 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004386 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004387 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004388 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004389 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004390 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004391 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004392 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004393 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004394 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004395 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004396 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004397 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004398 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004399 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004400 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004401 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004402 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004403
4404 case Intrinsic::invariant_start:
4405 case Intrinsic::lifetime_start:
4406 // Discard region information.
4407 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4408 return 0;
4409 case Intrinsic::invariant_end:
4410 case Intrinsic::lifetime_end:
4411 // Discard region information.
4412 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004413 }
4414}
4415
Dan Gohman98ca4f22009-08-05 01:29:28 +00004416/// Test if the given instruction is in a position to be optimized
4417/// with a tail-call. This roughly means that it's in a block with
4418/// a return and there's nothing that needs to be scheduled
4419/// between it and the return.
4420///
4421/// This function only tests target-independent requirements.
4422/// For target-dependent requirements, a target should override
4423/// TargetLowering::IsEligibleForTailCallOptimization.
4424///
4425static bool
4426isInTailCallPosition(const Instruction *I, Attributes RetAttr,
4427 const TargetLowering &TLI) {
4428 const BasicBlock *ExitBB = I->getParent();
4429 const TerminatorInst *Term = ExitBB->getTerminator();
4430 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4431 const Function *F = ExitBB->getParent();
4432
4433 // The block must end in a return statement or an unreachable.
4434 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4435
4436 // If I will have a chain, make sure no other instruction that will have a
4437 // chain interposes between I and the return.
4438 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4439 !I->isSafeToSpeculativelyExecute())
4440 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4441 --BBI) {
4442 if (&*BBI == I)
4443 break;
4444 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4445 !BBI->isSafeToSpeculativelyExecute())
4446 return false;
4447 }
4448
4449 // If the block ends with a void return or unreachable, it doesn't matter
4450 // what the call's return type is.
4451 if (!Ret || Ret->getNumOperands() == 0) return true;
4452
4453 // Conservatively require the attributes of the call to match those of
4454 // the return.
4455 if (F->getAttributes().getRetAttributes() != RetAttr)
4456 return false;
4457
4458 // Otherwise, make sure the unmodified return value of I is the return value.
4459 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4460 U = dyn_cast<Instruction>(U->getOperand(0))) {
4461 if (!U)
4462 return false;
4463 if (!U->hasOneUse())
4464 return false;
4465 if (U == I)
4466 break;
4467 // Check for a truly no-op truncate.
4468 if (isa<TruncInst>(U) &&
4469 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4470 continue;
4471 // Check for a truly no-op bitcast.
4472 if (isa<BitCastInst>(U) &&
4473 (U->getOperand(0)->getType() == U->getType() ||
4474 (isa<PointerType>(U->getOperand(0)->getType()) &&
4475 isa<PointerType>(U->getType()))))
4476 continue;
4477 // Otherwise it's not a true no-op.
4478 return false;
4479 }
4480
4481 return true;
4482}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004483
4484void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004485 bool isTailCall,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004486 MachineBasicBlock *LandingPad) {
4487 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4488 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004489 const Type *RetTy = FTy->getReturnType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004490 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4491 unsigned BeginLabel = 0, EndLabel = 0;
4492
4493 TargetLowering::ArgListTy Args;
4494 TargetLowering::ArgListEntry Entry;
4495 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004496
4497 // Check whether the function can return without sret-demotion.
4498 SmallVector<EVT, 4> OutVTs;
4499 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4500 SmallVector<uint64_t, 4> Offsets;
4501 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4502 OutVTs, OutsFlags, TLI, &Offsets);
4503
4504
4505 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4506 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4507
4508 SDValue DemoteStackSlot;
4509
4510 if (!CanLowerReturn) {
4511 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4512 FTy->getReturnType());
4513 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4514 FTy->getReturnType());
4515 MachineFunction &MF = DAG.getMachineFunction();
4516 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4517 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4518
4519 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4520 Entry.Node = DemoteStackSlot;
4521 Entry.Ty = StackSlotPtrType;
4522 Entry.isSExt = false;
4523 Entry.isZExt = false;
4524 Entry.isInReg = false;
4525 Entry.isSRet = true;
4526 Entry.isNest = false;
4527 Entry.isByVal = false;
4528 Entry.Alignment = Align;
4529 Args.push_back(Entry);
4530 RetTy = Type::getVoidTy(FTy->getContext());
4531 }
4532
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004533 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004534 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004535 SDValue ArgNode = getValue(*i);
4536 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4537
4538 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004539 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4540 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4541 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4542 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4543 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4544 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004545 Entry.Alignment = CS.getParamAlignment(attrInd);
4546 Args.push_back(Entry);
4547 }
4548
4549 if (LandingPad && MMI) {
4550 // Insert a label before the invoke call to mark the try range. This can be
4551 // used to detect deletion of the invoke via the MachineModuleInfo.
4552 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004553
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004554 // Both PendingLoads and PendingExports must be flushed here;
4555 // this call might not return.
4556 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004557 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4558 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004559 }
4560
Dan Gohman98ca4f22009-08-05 01:29:28 +00004561 // Check if target-independent constraints permit a tail call here.
4562 // Target-dependent constraints are checked within TLI.LowerCallTo.
4563 if (isTailCall &&
4564 !isInTailCallPosition(CS.getInstruction(),
4565 CS.getAttributes().getRetAttributes(),
4566 TLI))
4567 isTailCall = false;
4568
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004569 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004570 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004571 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004572 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004573 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004574 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004575 isTailCall,
4576 !CS.getInstruction()->use_empty(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004577 Callee, Args, DAG, getCurDebugLoc());
Dan Gohman98ca4f22009-08-05 01:29:28 +00004578 assert((isTailCall || Result.second.getNode()) &&
4579 "Non-null chain expected with non-tail call!");
4580 assert((Result.second.getNode() || !Result.first.getNode()) &&
4581 "Null value expected with tail call!");
4582 if (Result.first.getNode())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004583 setValue(CS.getInstruction(), Result.first);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004584 else if (!CanLowerReturn && Result.second.getNode()) {
4585 // The instruction result is the result of loading from the
4586 // hidden sret parameter.
4587 SmallVector<EVT, 1> PVTs;
4588 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4589
4590 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4591 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4592 EVT PtrVT = PVTs[0];
4593 unsigned NumValues = OutVTs.size();
4594 SmallVector<SDValue, 4> Values(NumValues);
4595 SmallVector<SDValue, 4> Chains(NumValues);
4596
4597 for (unsigned i = 0; i < NumValues; ++i) {
4598 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4599 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot,
4600 DAG.getConstant(Offsets[i], PtrVT)),
4601 NULL, Offsets[i], false, 1);
4602 Values[i] = L;
4603 Chains[i] = L.getValue(1);
4604 }
4605 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4606 MVT::Other, &Chains[0], NumValues);
4607 PendingLoads.push_back(Chain);
4608
4609 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES,
4610 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues),
4611 &Values[0], NumValues));
4612 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00004613 // As a special case, a null chain means that a tail call has
4614 // been emitted and the DAG root is already updated.
4615 if (Result.second.getNode())
4616 DAG.setRoot(Result.second);
4617 else
4618 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004619
4620 if (LandingPad && MMI) {
4621 // Insert a label at the end of the invoke call to mark the try range. This
4622 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4623 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004624 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4625 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004626
4627 // Inform MachineModuleInfo of range.
4628 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4629 }
4630}
4631
4632
4633void SelectionDAGLowering::visitCall(CallInst &I) {
4634 const char *RenameFn = 0;
4635 if (Function *F = I.getCalledFunction()) {
4636 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004637 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4638 if (II) {
4639 if (unsigned IID = II->getIntrinsicID(F)) {
4640 RenameFn = visitIntrinsicCall(I, IID);
4641 if (!RenameFn)
4642 return;
4643 }
4644 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004645 if (unsigned IID = F->getIntrinsicID()) {
4646 RenameFn = visitIntrinsicCall(I, IID);
4647 if (!RenameFn)
4648 return;
4649 }
4650 }
4651
4652 // Check for well-known libc/libm calls. If the function is internal, it
4653 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004654 if (!F->hasLocalLinkage() && F->hasName()) {
4655 StringRef Name = F->getName();
4656 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657 if (I.getNumOperands() == 3 && // Basic sanity checks.
4658 I.getOperand(1)->getType()->isFloatingPoint() &&
4659 I.getType() == I.getOperand(1)->getType() &&
4660 I.getType() == I.getOperand(2)->getType()) {
4661 SDValue LHS = getValue(I.getOperand(1));
4662 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004663 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004664 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004665 return;
4666 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004667 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004668 if (I.getNumOperands() == 2 && // Basic sanity checks.
4669 I.getOperand(1)->getType()->isFloatingPoint() &&
4670 I.getType() == I.getOperand(1)->getType()) {
4671 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004672 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004673 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004674 return;
4675 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004676 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004677 if (I.getNumOperands() == 2 && // Basic sanity checks.
4678 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004679 I.getType() == I.getOperand(1)->getType() &&
4680 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004681 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004682 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004683 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004684 return;
4685 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004686 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004687 if (I.getNumOperands() == 2 && // Basic sanity checks.
4688 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004689 I.getType() == I.getOperand(1)->getType() &&
4690 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004691 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004692 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004693 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004694 return;
4695 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004696 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4697 if (I.getNumOperands() == 2 && // Basic sanity checks.
4698 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004699 I.getType() == I.getOperand(1)->getType() &&
4700 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004701 SDValue Tmp = getValue(I.getOperand(1));
4702 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4703 Tmp.getValueType(), Tmp));
4704 return;
4705 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004706 }
4707 }
4708 } else if (isa<InlineAsm>(I.getOperand(0))) {
4709 visitInlineAsm(&I);
4710 return;
4711 }
4712
4713 SDValue Callee;
4714 if (!RenameFn)
4715 Callee = getValue(I.getOperand(0));
4716 else
Bill Wendling056292f2008-09-16 21:48:12 +00004717 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004718
Dan Gohman98ca4f22009-08-05 01:29:28 +00004719 // Check if we can potentially perform a tail call. More detailed
4720 // checking is be done within LowerCallTo, after more information
4721 // about the call is known.
4722 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4723
4724 LowerCallTo(&I, Callee, isTailCall);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004725}
4726
4727
4728/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004729/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004730/// Chain/Flag as the input and updates them for the output Chain/Flag.
4731/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004732SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 SDValue &Chain,
4734 SDValue *Flag) const {
4735 // Assemble the legal parts into the final values.
4736 SmallVector<SDValue, 4> Values(ValueVTs.size());
4737 SmallVector<SDValue, 8> Parts;
4738 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4739 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004740 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004741 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004742 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004743
4744 Parts.resize(NumRegs);
4745 for (unsigned i = 0; i != NumRegs; ++i) {
4746 SDValue P;
4747 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004748 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004750 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751 *Flag = P.getValue(2);
4752 }
4753 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004754
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004755 // If the source register was virtual and if we know something about it,
4756 // add an assert node.
4757 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4758 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4759 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4760 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4761 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4762 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004763
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004764 unsigned RegSize = RegisterVT.getSizeInBits();
4765 unsigned NumSignBits = LOI.NumSignBits;
4766 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004767
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004768 // FIXME: We capture more information than the dag can represent. For
4769 // now, just use the tightest assertzext/assertsext possible.
4770 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004771 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004772 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004773 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004774 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004775 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004777 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004778 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004779 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004780 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004781 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004782 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004783 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004784 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004785 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004786 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004787 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004788
Owen Anderson825b72b2009-08-11 20:47:22 +00004789 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004790 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004791 RegisterVT, P, DAG.getValueType(FromVT));
4792
4793 }
4794 }
4795 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004796
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004797 Parts[i] = P;
4798 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004799
Scott Michelfdc40a02009-02-17 22:15:04 +00004800 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004801 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004802 Part += NumRegs;
4803 Parts.clear();
4804 }
4805
Dale Johannesen66978ee2009-01-31 02:22:37 +00004806 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004807 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4808 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004809}
4810
4811/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004812/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004813/// Chain/Flag as the input and updates them for the output Chain/Flag.
4814/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004815void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004816 SDValue &Chain, SDValue *Flag) const {
4817 // Get the list of the values's legal parts.
4818 unsigned NumRegs = Regs.size();
4819 SmallVector<SDValue, 8> Parts(NumRegs);
4820 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004821 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004822 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004823 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004824
Dale Johannesen66978ee2009-01-31 02:22:37 +00004825 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004826 &Parts[Part], NumParts, RegisterVT);
4827 Part += NumParts;
4828 }
4829
4830 // Copy the parts into the registers.
4831 SmallVector<SDValue, 8> Chains(NumRegs);
4832 for (unsigned i = 0; i != NumRegs; ++i) {
4833 SDValue Part;
4834 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004835 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004837 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004838 *Flag = Part.getValue(1);
4839 }
4840 Chains[i] = Part.getValue(0);
4841 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004842
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004843 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004844 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004845 // flagged to it. That is the CopyToReg nodes and the user are considered
4846 // a single scheduling unit. If we create a TokenFactor and return it as
4847 // chain, then the TokenFactor is both a predecessor (operand) of the
4848 // user as well as a successor (the TF operands are flagged to the user).
4849 // c1, f1 = CopyToReg
4850 // c2, f2 = CopyToReg
4851 // c3 = TokenFactor c1, c2
4852 // ...
4853 // = op c3, ..., f2
4854 Chain = Chains[NumRegs-1];
4855 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004856 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004857}
4858
4859/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004860/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004861/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004862void RegsForValue::AddInlineAsmOperands(unsigned Code,
4863 bool HasMatching,unsigned MatchingIdx,
4864 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004865 std::vector<SDValue> &Ops) const {
Owen Andersone50ed302009-08-10 22:56:29 +00004866 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004867 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4868 unsigned Flag = Code | (Regs.size() << 3);
4869 if (HasMatching)
4870 Flag |= 0x80000000 | (MatchingIdx << 16);
4871 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004872 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004873 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004874 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004875 for (unsigned i = 0; i != NumRegs; ++i) {
4876 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004878 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004879 }
4880}
4881
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004882/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004883/// i.e. it isn't a stack pointer or some other special register, return the
4884/// register class for the register. Otherwise, return null.
4885static const TargetRegisterClass *
4886isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4887 const TargetLowering &TLI,
4888 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004889 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004890 const TargetRegisterClass *FoundRC = 0;
4891 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4892 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004893 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894
4895 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004896 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004897 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4898 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4899 I != E; ++I) {
4900 if (TLI.isTypeLegal(*I)) {
4901 // If we have already found this register in a different register class,
4902 // choose the one with the largest VT specified. For example, on
4903 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004904 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004905 ThisVT = *I;
4906 break;
4907 }
4908 }
4909 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004910
Owen Anderson825b72b2009-08-11 20:47:22 +00004911 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004912
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004913 // NOTE: This isn't ideal. In particular, this might allocate the
4914 // frame pointer in functions that need it (due to them not being taken
4915 // out of allocation, because a variable sized allocation hasn't been seen
4916 // yet). This is a slight code pessimization, but should still work.
4917 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4918 E = RC->allocation_order_end(MF); I != E; ++I)
4919 if (*I == Reg) {
4920 // We found a matching register class. Keep looking at others in case
4921 // we find one with larger registers that this physreg is also in.
4922 FoundRC = RC;
4923 FoundVT = ThisVT;
4924 break;
4925 }
4926 }
4927 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004928}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004929
4930
4931namespace llvm {
4932/// AsmOperandInfo - This contains information for each constraint that we are
4933/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004934class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004935 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004936public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004937 /// CallOperand - If this is the result output operand or a clobber
4938 /// this is null, otherwise it is the incoming operand to the CallInst.
4939 /// This gets modified as the asm is processed.
4940 SDValue CallOperand;
4941
4942 /// AssignedRegs - If this is a register or register class operand, this
4943 /// contains the set of register corresponding to the operand.
4944 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4947 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4948 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004950 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4951 /// busy in OutputRegs/InputRegs.
4952 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004954 std::set<unsigned> &InputRegs,
4955 const TargetRegisterInfo &TRI) const {
4956 if (isOutReg) {
4957 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4958 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4959 }
4960 if (isInReg) {
4961 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4962 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4963 }
4964 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004965
Owen Andersone50ed302009-08-10 22:56:29 +00004966 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004967 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004968 /// MVT::Other.
Owen Anderson1d0be152009-08-13 21:58:54 +00004969 EVT getCallOperandValEVT(LLVMContext &Context,
4970 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004971 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004972 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004973
Chris Lattner81249c92008-10-17 17:05:25 +00004974 if (isa<BasicBlock>(CallOperandVal))
4975 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004976
Chris Lattner81249c92008-10-17 17:05:25 +00004977 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004978
Chris Lattner81249c92008-10-17 17:05:25 +00004979 // If this is an indirect operand, the operand is a pointer to the
4980 // accessed type.
4981 if (isIndirect)
4982 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004983
Chris Lattner81249c92008-10-17 17:05:25 +00004984 // If OpTy is not a single value, it may be a struct/union that we
4985 // can tile with integers.
4986 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4987 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4988 switch (BitSize) {
4989 default: break;
4990 case 1:
4991 case 8:
4992 case 16:
4993 case 32:
4994 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004995 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004996 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004997 break;
4998 }
4999 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005000
Chris Lattner81249c92008-10-17 17:05:25 +00005001 return TLI.getValueType(OpTy, true);
5002 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005004private:
5005 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5006 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005007 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005008 const TargetRegisterInfo &TRI) {
5009 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5010 Regs.insert(Reg);
5011 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5012 for (; *Aliases; ++Aliases)
5013 Regs.insert(*Aliases);
5014 }
5015};
5016} // end llvm namespace.
5017
5018
5019/// GetRegistersForValue - Assign registers (virtual or physical) for the
5020/// specified operand. We prefer to assign virtual registers, to allow the
5021/// register allocator handle the assignment process. However, if the asm uses
5022/// features that we can't model on machineinstrs, we have SDISel do the
5023/// allocation. This produces generally horrible, but correct, code.
5024///
5025/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005026/// Input and OutputRegs are the set of already allocated physical registers.
5027///
5028void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005029GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005030 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005031 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00005032 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005033
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005034 // Compute whether this value requires an input register, an output register,
5035 // or both.
5036 bool isOutReg = false;
5037 bool isInReg = false;
5038 switch (OpInfo.Type) {
5039 case InlineAsm::isOutput:
5040 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005041
5042 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005043 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00005044 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045 break;
5046 case InlineAsm::isInput:
5047 isInReg = true;
5048 isOutReg = false;
5049 break;
5050 case InlineAsm::isClobber:
5051 isOutReg = true;
5052 isInReg = true;
5053 break;
5054 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005055
5056
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005057 MachineFunction &MF = DAG.getMachineFunction();
5058 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005059
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005060 // If this is a constraint for a single physreg, or a constraint for a
5061 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005062 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005063 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5064 OpInfo.ConstraintVT);
5065
5066 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005067 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005068 // If this is a FP input in an integer register (or visa versa) insert a bit
5069 // cast of the input value. More generally, handle any case where the input
5070 // value disagrees with the register class we plan to stick this in.
5071 if (OpInfo.Type == InlineAsm::isInput &&
5072 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005073 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005074 // types are identical size, use a bitcast to convert (e.g. two differing
5075 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005076 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005077 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005078 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005079 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005080 OpInfo.ConstraintVT = RegVT;
5081 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5082 // If the input is a FP value and we want it in FP registers, do a
5083 // bitcast to the corresponding integer type. This turns an f64 value
5084 // into i64, which can be passed with two i32 values on a 32-bit
5085 // machine.
Owen Anderson23b9b192009-08-12 00:36:31 +00005086 RegVT = EVT::getIntegerVT(Context,
5087 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005088 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005089 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005090 OpInfo.ConstraintVT = RegVT;
5091 }
5092 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005093
Owen Anderson23b9b192009-08-12 00:36:31 +00005094 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005095 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005096
Owen Andersone50ed302009-08-10 22:56:29 +00005097 EVT RegVT;
5098 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005099
5100 // If this is a constraint for a specific physical register, like {r17},
5101 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005102 if (unsigned AssignedReg = PhysReg.first) {
5103 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005104 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005105 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 // Get the actual register value type. This is important, because the user
5108 // may have asked for (e.g.) the AX register in i32 type. We need to
5109 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005110 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005111
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005112 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005113 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005114
5115 // If this is an expanded reference, add the rest of the regs to Regs.
5116 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005117 TargetRegisterClass::iterator I = RC->begin();
5118 for (; *I != AssignedReg; ++I)
5119 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005120
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121 // Already added the first reg.
5122 --NumRegs; ++I;
5123 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005124 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005125 Regs.push_back(*I);
5126 }
5127 }
5128 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5129 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5130 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5131 return;
5132 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005133
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005134 // Otherwise, if this was a reference to an LLVM register class, create vregs
5135 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005136 if (const TargetRegisterClass *RC = PhysReg.second) {
5137 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005138 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005139 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005140
Evan Chengfb112882009-03-23 08:01:15 +00005141 // Create the appropriate number of virtual registers.
5142 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5143 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005144 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005145
Evan Chengfb112882009-03-23 08:01:15 +00005146 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5147 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005148 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005149
5150 // This is a reference to a register class that doesn't directly correspond
5151 // to an LLVM register class. Allocate NumRegs consecutive, available,
5152 // registers from the class.
5153 std::vector<unsigned> RegClassRegs
5154 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5155 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005157 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5158 unsigned NumAllocated = 0;
5159 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5160 unsigned Reg = RegClassRegs[i];
5161 // See if this register is available.
5162 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5163 (isInReg && InputRegs.count(Reg))) { // Already used.
5164 // Make sure we find consecutive registers.
5165 NumAllocated = 0;
5166 continue;
5167 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005168
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005169 // Check to see if this register is allocatable (i.e. don't give out the
5170 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005171 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5172 if (!RC) { // Couldn't allocate this register.
5173 // Reset NumAllocated to make sure we return consecutive registers.
5174 NumAllocated = 0;
5175 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005176 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005178 // Okay, this register is good, we can use it.
5179 ++NumAllocated;
5180
5181 // If we allocated enough consecutive registers, succeed.
5182 if (NumAllocated == NumRegs) {
5183 unsigned RegStart = (i-NumAllocated)+1;
5184 unsigned RegEnd = i+1;
5185 // Mark all of the allocated registers used.
5186 for (unsigned i = RegStart; i != RegEnd; ++i)
5187 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005188
5189 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005190 OpInfo.ConstraintVT);
5191 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5192 return;
5193 }
5194 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005195
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005196 // Otherwise, we couldn't allocate enough registers for this.
5197}
5198
Evan Chengda43bcf2008-09-24 00:05:32 +00005199/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5200/// processed uses a memory 'm' constraint.
5201static bool
5202hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005203 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005204 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5205 InlineAsm::ConstraintInfo &CI = CInfos[i];
5206 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5207 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5208 if (CType == TargetLowering::C_Memory)
5209 return true;
5210 }
Chris Lattner6c147292009-04-30 00:48:50 +00005211
5212 // Indirect operand accesses access memory.
5213 if (CI.isIndirect)
5214 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005215 }
5216
5217 return false;
5218}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005219
5220/// visitInlineAsm - Handle a call to an InlineAsm object.
5221///
5222void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5223 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5224
5225 /// ConstraintOperands - Information about all of the constraints.
5226 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005227
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005228 std::set<unsigned> OutputRegs, InputRegs;
5229
5230 // Do a prepass over the constraints, canonicalizing them, and building up the
5231 // ConstraintOperands list.
5232 std::vector<InlineAsm::ConstraintInfo>
5233 ConstraintInfos = IA->ParseConstraints();
5234
Evan Chengda43bcf2008-09-24 00:05:32 +00005235 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005236
5237 SDValue Chain, Flag;
5238
5239 // We won't need to flush pending loads if this asm doesn't touch
5240 // memory and is nonvolatile.
5241 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005242 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005243 else
5244 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005245
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005246 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5247 unsigned ResNo = 0; // ResNo - The result number of the next output.
5248 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5249 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5250 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005251
Owen Anderson825b72b2009-08-11 20:47:22 +00005252 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005253
5254 // Compute the value type for each operand.
5255 switch (OpInfo.Type) {
5256 case InlineAsm::isOutput:
5257 // Indirect outputs just consume an argument.
5258 if (OpInfo.isIndirect) {
5259 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5260 break;
5261 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005262
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005263 // The return value of the call is this value. As such, there is no
5264 // corresponding argument.
Owen Anderson1d0be152009-08-13 21:58:54 +00005265 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5266 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005267 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5268 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5269 } else {
5270 assert(ResNo == 0 && "Asm only has one result!");
5271 OpVT = TLI.getValueType(CS.getType());
5272 }
5273 ++ResNo;
5274 break;
5275 case InlineAsm::isInput:
5276 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5277 break;
5278 case InlineAsm::isClobber:
5279 // Nothing to do.
5280 break;
5281 }
5282
5283 // If this is an input or an indirect output, process the call argument.
5284 // BasicBlocks are labels, currently appearing only in asm's.
5285 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005286 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005287 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5288
Chris Lattner81249c92008-10-17 17:05:25 +00005289 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005290 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005291 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005292 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005294
Owen Anderson1d0be152009-08-13 21:58:54 +00005295 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005296 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005297
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005298 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005299 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005300
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005301 // Second pass over the constraints: compute which constraint option to use
5302 // and assign registers to constraints that want a specific physreg.
5303 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5304 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005305
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005306 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005307 // matching input. If their types mismatch, e.g. one is an integer, the
5308 // other is floating point, or their sizes are different, flag it as an
5309 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005310 if (OpInfo.hasMatchingInput()) {
5311 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5312 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005313 if ((OpInfo.ConstraintVT.isInteger() !=
5314 Input.ConstraintVT.isInteger()) ||
5315 (OpInfo.ConstraintVT.getSizeInBits() !=
5316 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005317 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005318 " with a matching output constraint of incompatible"
5319 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005320 }
5321 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005322 }
5323 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005324
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005325 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005326 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005328 // If this is a memory input, and if the operand is not indirect, do what we
5329 // need to to provide an address for the memory input.
5330 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5331 !OpInfo.isIndirect) {
5332 assert(OpInfo.Type == InlineAsm::isInput &&
5333 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005334
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335 // Memory operands really want the address of the value. If we don't have
5336 // an indirect input, put it in the constpool if we can, otherwise spill
5337 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005338
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005339 // If the operand is a float, integer, or vector constant, spill to a
5340 // constant pool entry to get its address.
5341 Value *OpVal = OpInfo.CallOperandVal;
5342 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5343 isa<ConstantVector>(OpVal)) {
5344 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5345 TLI.getPointerTy());
5346 } else {
5347 // Otherwise, create a stack slot and emit a store to it before the
5348 // asm.
5349 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005350 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005351 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5352 MachineFunction &MF = DAG.getMachineFunction();
5353 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5354 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005355 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005356 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005357 OpInfo.CallOperand = StackSlot;
5358 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005359
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005360 // There is no longer a Value* corresponding to this operand.
5361 OpInfo.CallOperandVal = 0;
5362 // It is now an indirect operand.
5363 OpInfo.isIndirect = true;
5364 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005365
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005366 // If this constraint is for a specific register, allocate it before
5367 // anything else.
5368 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005369 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 }
5371 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005372
5373
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005374 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005375 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005376 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5377 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005378
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005379 // C_Register operands have already been allocated, Other/Memory don't need
5380 // to be.
5381 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005382 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005383 }
5384
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005385 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5386 std::vector<SDValue> AsmNodeOperands;
5387 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5388 AsmNodeOperands.push_back(
Owen Anderson825b72b2009-08-11 20:47:22 +00005389 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005390
5391
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005392 // Loop over all of the inputs, copying the operand values into the
5393 // appropriate registers and processing the output regs.
5394 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005395
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005396 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5397 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005398
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005399 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5400 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5401
5402 switch (OpInfo.Type) {
5403 case InlineAsm::isOutput: {
5404 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5405 OpInfo.ConstraintType != TargetLowering::C_Register) {
5406 // Memory output, or 'other' output (e.g. 'X' constraint).
5407 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5408
5409 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005410 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5411 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005412 TLI.getPointerTy()));
5413 AsmNodeOperands.push_back(OpInfo.CallOperand);
5414 break;
5415 }
5416
5417 // Otherwise, this is a register or register class output.
5418
5419 // Copy the output from the appropriate register. Find a register that
5420 // we can use.
5421 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005422 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005423 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005424 }
5425
5426 // If this is an indirect operand, store through the pointer after the
5427 // asm.
5428 if (OpInfo.isIndirect) {
5429 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5430 OpInfo.CallOperandVal));
5431 } else {
5432 // This is the result value of the call.
Owen Anderson1d0be152009-08-13 21:58:54 +00005433 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5434 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005435 // Concatenate this output onto the outputs list.
5436 RetValRegs.append(OpInfo.AssignedRegs);
5437 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 // Add information to the INLINEASM node to know that this register is
5440 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005441 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5442 6 /* EARLYCLOBBER REGDEF */ :
5443 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005444 false,
5445 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005446 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 break;
5448 }
5449 case InlineAsm::isInput: {
5450 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005451
Chris Lattner6bdcda32008-10-17 16:47:46 +00005452 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 // If this is required to match an output register we have already set,
5454 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005455 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005456
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005457 // Scan until we find the definition we already emitted of this operand.
5458 // When we find it, create a RegsForValue operand.
5459 unsigned CurOp = 2; // The first operand.
5460 for (; OperandNo; --OperandNo) {
5461 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005462 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005463 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005464 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5465 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5466 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005467 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005468 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005469 }
5470
Evan Cheng697cbbf2009-03-20 18:03:34 +00005471 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005472 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005473 if ((OpFlag & 7) == 2 /*REGDEF*/
5474 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5475 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005476 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005477 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005478 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005479 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005480 RegsForValue MatchedRegs;
5481 MatchedRegs.TLI = &TLI;
5482 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005483 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005484 MatchedRegs.RegVTs.push_back(RegVT);
5485 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005486 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005487 i != e; ++i)
5488 MatchedRegs.Regs.
5489 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005490
5491 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005492 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5493 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005494 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5495 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005496 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005497 break;
5498 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005499 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5500 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5501 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005502 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005503 // See InlineAsm.h isUseOperandTiedToDef.
5504 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005505 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 TLI.getPointerTy()));
5507 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5508 break;
5509 }
5510 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005512 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005513 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005514 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005515
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005516 std::vector<SDValue> Ops;
5517 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005518 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005519 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005520 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005521 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005523
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005524 // Add information to the INLINEASM node to know about this input.
5525 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005526 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527 TLI.getPointerTy()));
5528 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5529 break;
5530 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5531 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5532 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5533 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005534
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005535 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005536 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5537 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005538 TLI.getPointerTy()));
5539 AsmNodeOperands.push_back(InOperandVal);
5540 break;
5541 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5544 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5545 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005546 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005547 "Don't know how to handle indirect register inputs yet!");
5548
5549 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005550 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005551 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005552 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005553 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005554
Dale Johannesen66978ee2009-01-31 02:22:37 +00005555 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5556 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005557
Evan Cheng697cbbf2009-03-20 18:03:34 +00005558 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005559 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005560 break;
5561 }
5562 case InlineAsm::isClobber: {
5563 // Add the clobbered value to the operand list, so that the register
5564 // allocator is aware that the physreg got clobbered.
5565 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005566 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005567 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005568 break;
5569 }
5570 }
5571 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005572
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005573 // Finish up input operands.
5574 AsmNodeOperands[0] = Chain;
5575 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005576
Dale Johannesen66978ee2009-01-31 02:22:37 +00005577 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005578 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005579 &AsmNodeOperands[0], AsmNodeOperands.size());
5580 Flag = Chain.getValue(1);
5581
5582 // If this asm returns a register value, copy the result from that register
5583 // and set it as the value of the call.
5584 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005585 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005586 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005587
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005588 // FIXME: Why don't we do this for inline asms with MRVs?
5589 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005590 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005591
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005592 // If any of the results of the inline asm is a vector, it may have the
5593 // wrong width/num elts. This can happen for register classes that can
5594 // contain multiple different value types. The preg or vreg allocated may
5595 // not have the same VT as was expected. Convert it to the right type
5596 // with bit_convert.
5597 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005598 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005599 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005600
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005601 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005602 ResultType.isInteger() && Val.getValueType().isInteger()) {
5603 // If a result value was tied to an input value, the computed result may
5604 // have a wider width than the expected result. Extract the relevant
5605 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005606 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005607 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005608
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005609 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005610 }
Dan Gohman95915732008-10-18 01:03:45 +00005611
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005612 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005613 // Don't need to use this as a chain in this case.
5614 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5615 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005616 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005617
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005618 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005619
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005620 // Process indirect outputs, first output all of the flagged copies out of
5621 // physregs.
5622 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5623 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5624 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005625 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5626 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005628
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005629 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005630
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005631 // Emit the non-flagged stores from the physregs.
5632 SmallVector<SDValue, 8> OutChains;
5633 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005634 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005635 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005636 getValue(StoresToEmit[i].second),
5637 StoresToEmit[i].second, 0));
5638 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005639 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005640 &OutChains[0], OutChains.size());
5641 DAG.setRoot(Chain);
5642}
5643
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005644void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005645 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005646 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005647 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005648 DAG.getSrcValue(I.getOperand(1))));
5649}
5650
5651void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005652 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5653 getRoot(), getValue(I.getOperand(0)),
5654 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005655 setValue(&I, V);
5656 DAG.setRoot(V.getValue(1));
5657}
5658
5659void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005660 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005661 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005662 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005663 DAG.getSrcValue(I.getOperand(1))));
5664}
5665
5666void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005667 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005668 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005669 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005670 getValue(I.getOperand(2)),
5671 DAG.getSrcValue(I.getOperand(1)),
5672 DAG.getSrcValue(I.getOperand(2))));
5673}
5674
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005675/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005676/// implementation, which just calls LowerCall.
5677/// FIXME: When all targets are
5678/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005679std::pair<SDValue, SDValue>
5680TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5681 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005682 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005683 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005684 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005685 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005686 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00005687
Dan Gohman1937e2f2008-09-16 01:42:28 +00005688 assert((!isTailCall || PerformTailCallOpt) &&
5689 "isTailCall set when tail-call optimizations are disabled!");
5690
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005691 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005692 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005693 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005694 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005695 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5696 for (unsigned Value = 0, NumValues = ValueVTs.size();
5697 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005698 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005699 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005700 SDValue Op = SDValue(Args[i].Node.getNode(),
5701 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005702 ISD::ArgFlagsTy Flags;
5703 unsigned OriginalAlignment =
5704 getTargetData()->getABITypeAlignment(ArgTy);
5705
5706 if (Args[i].isZExt)
5707 Flags.setZExt();
5708 if (Args[i].isSExt)
5709 Flags.setSExt();
5710 if (Args[i].isInReg)
5711 Flags.setInReg();
5712 if (Args[i].isSRet)
5713 Flags.setSRet();
5714 if (Args[i].isByVal) {
5715 Flags.setByVal();
5716 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5717 const Type *ElementTy = Ty->getElementType();
5718 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005719 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005720 // For ByVal, alignment should come from FE. BE will guess if this
5721 // info is not there but there are cases it cannot get right.
5722 if (Args[i].Alignment)
5723 FrameAlign = Args[i].Alignment;
5724 Flags.setByValAlign(FrameAlign);
5725 Flags.setByValSize(FrameSize);
5726 }
5727 if (Args[i].isNest)
5728 Flags.setNest();
5729 Flags.setOrigAlign(OriginalAlignment);
5730
Owen Anderson23b9b192009-08-12 00:36:31 +00005731 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5732 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005733 SmallVector<SDValue, 4> Parts(NumParts);
5734 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5735
5736 if (Args[i].isSExt)
5737 ExtendKind = ISD::SIGN_EXTEND;
5738 else if (Args[i].isZExt)
5739 ExtendKind = ISD::ZERO_EXTEND;
5740
Dale Johannesen66978ee2009-01-31 02:22:37 +00005741 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005742
Dan Gohman98ca4f22009-08-05 01:29:28 +00005743 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005744 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005745 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5746 if (NumParts > 1 && j == 0)
5747 MyFlags.Flags.setSplit();
5748 else if (j != 0)
5749 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005750
Dan Gohman98ca4f22009-08-05 01:29:28 +00005751 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005752 }
5753 }
5754 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005755
Dan Gohman98ca4f22009-08-05 01:29:28 +00005756 // Handle the incoming return values from the call.
5757 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005758 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005759 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005760 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005761 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005762 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5763 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005764 for (unsigned i = 0; i != NumRegs; ++i) {
5765 ISD::InputArg MyFlags;
5766 MyFlags.VT = RegisterVT;
5767 MyFlags.Used = isReturnValueUsed;
5768 if (RetSExt)
5769 MyFlags.Flags.setSExt();
5770 if (RetZExt)
5771 MyFlags.Flags.setZExt();
5772 if (isInreg)
5773 MyFlags.Flags.setInReg();
5774 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005775 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005776 }
5777
Dan Gohman98ca4f22009-08-05 01:29:28 +00005778 // Check if target-dependent constraints permit a tail call here.
5779 // Target-independent constraints should be checked by the caller.
5780 if (isTailCall &&
5781 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5782 isTailCall = false;
5783
5784 SmallVector<SDValue, 4> InVals;
5785 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5786 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005787
5788 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005789 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005790 "LowerCall didn't return a valid chain!");
5791 assert((!isTailCall || InVals.empty()) &&
5792 "LowerCall emitted a return value for a tail call!");
5793 assert((isTailCall || InVals.size() == Ins.size()) &&
5794 "LowerCall didn't emit the correct number of values!");
5795 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5796 assert(InVals[i].getNode() &&
5797 "LowerCall emitted a null value!");
5798 assert(Ins[i].VT == InVals[i].getValueType() &&
5799 "LowerCall emitted a value with the wrong type!");
5800 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005801
5802 // For a tail call, the return value is merely live-out and there aren't
5803 // any nodes in the DAG representing it. Return a special value to
5804 // indicate that a tail call has been emitted and no more Instructions
5805 // should be processed in the current block.
5806 if (isTailCall) {
5807 DAG.setRoot(Chain);
5808 return std::make_pair(SDValue(), SDValue());
5809 }
5810
5811 // Collect the legal value parts into potentially illegal values
5812 // that correspond to the original function's return values.
5813 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5814 if (RetSExt)
5815 AssertOp = ISD::AssertSext;
5816 else if (RetZExt)
5817 AssertOp = ISD::AssertZext;
5818 SmallVector<SDValue, 4> ReturnValues;
5819 unsigned CurReg = 0;
5820 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005821 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005822 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5823 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005824
5825 SDValue ReturnValue =
5826 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5827 AssertOp);
5828 ReturnValues.push_back(ReturnValue);
5829 CurReg += NumRegs;
5830 }
5831
5832 // For a function returning void, there is no return value. We can't create
5833 // such a node, so we just return a null return value in that case. In
5834 // that case, nothing will actualy look at the value.
5835 if (ReturnValues.empty())
5836 return std::make_pair(SDValue(), Chain);
5837
5838 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5839 DAG.getVTList(&RetTys[0], RetTys.size()),
5840 &ReturnValues[0], ReturnValues.size());
5841
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005842 return std::make_pair(Res, Chain);
5843}
5844
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005845void TargetLowering::LowerOperationWrapper(SDNode *N,
5846 SmallVectorImpl<SDValue> &Results,
5847 SelectionDAG &DAG) {
5848 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005849 if (Res.getNode())
5850 Results.push_back(Res);
5851}
5852
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005853SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005854 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005855 return SDValue();
5856}
5857
5858
5859void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5860 SDValue Op = getValue(V);
5861 assert((Op.getOpcode() != ISD::CopyFromReg ||
5862 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5863 "Copy from a reg to the same reg!");
5864 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5865
Owen Anderson23b9b192009-08-12 00:36:31 +00005866 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005867 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005868 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005869 PendingExports.push_back(Chain);
5870}
5871
5872#include "llvm/CodeGen/SelectionDAGISel.h"
5873
Dan Gohman8c2b5252009-10-30 01:27:03 +00005874void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005875 // If this is the entry block, emit arguments.
5876 Function &F = *LLVMBB->getParent();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005877 SelectionDAG &DAG = SDL->DAG;
5878 SDValue OldRoot = DAG.getRoot();
5879 DebugLoc dl = SDL->getCurDebugLoc();
5880 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005881 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005882
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005883 // Check whether the function can return without sret-demotion.
5884 SmallVector<EVT, 4> OutVTs;
5885 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005886 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5887 OutVTs, OutsFlags, TLI);
5888 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5889
5890 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5891 OutVTs, OutsFlags, DAG);
5892 if (!FLI.CanLowerReturn) {
5893 // Put in an sret pointer parameter before all the other parameters.
5894 SmallVector<EVT, 1> ValueVTs;
5895 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5896
5897 // NOTE: Assuming that a pointer will never break down to more than one VT
5898 // or one register.
5899 ISD::ArgFlagsTy Flags;
5900 Flags.setSRet();
5901 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5902 ISD::InputArg RetArg(Flags, RegisterVT, true);
5903 Ins.push_back(RetArg);
5904 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005905
Dan Gohman98ca4f22009-08-05 01:29:28 +00005906 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005907 unsigned Idx = 1;
5908 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5909 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005910 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005911 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5912 bool isArgValueUsed = !I->use_empty();
5913 for (unsigned Value = 0, NumValues = ValueVTs.size();
5914 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005915 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005916 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005917 ISD::ArgFlagsTy Flags;
5918 unsigned OriginalAlignment =
5919 TD->getABITypeAlignment(ArgTy);
5920
5921 if (F.paramHasAttr(Idx, Attribute::ZExt))
5922 Flags.setZExt();
5923 if (F.paramHasAttr(Idx, Attribute::SExt))
5924 Flags.setSExt();
5925 if (F.paramHasAttr(Idx, Attribute::InReg))
5926 Flags.setInReg();
5927 if (F.paramHasAttr(Idx, Attribute::StructRet))
5928 Flags.setSRet();
5929 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5930 Flags.setByVal();
5931 const PointerType *Ty = cast<PointerType>(I->getType());
5932 const Type *ElementTy = Ty->getElementType();
5933 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5934 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5935 // For ByVal, alignment should be passed from FE. BE will guess if
5936 // this info is not there but there are cases it cannot get right.
5937 if (F.getParamAlignment(Idx))
5938 FrameAlign = F.getParamAlignment(Idx);
5939 Flags.setByValAlign(FrameAlign);
5940 Flags.setByValSize(FrameSize);
5941 }
5942 if (F.paramHasAttr(Idx, Attribute::Nest))
5943 Flags.setNest();
5944 Flags.setOrigAlign(OriginalAlignment);
5945
Owen Anderson23b9b192009-08-12 00:36:31 +00005946 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5947 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005948 for (unsigned i = 0; i != NumRegs; ++i) {
5949 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5950 if (NumRegs > 1 && i == 0)
5951 MyFlags.Flags.setSplit();
5952 // if it isn't first piece, alignment must be 1
5953 else if (i > 0)
5954 MyFlags.Flags.setOrigAlign(1);
5955 Ins.push_back(MyFlags);
5956 }
5957 }
5958 }
5959
5960 // Call the target to set up the argument values.
5961 SmallVector<SDValue, 8> InVals;
5962 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5963 F.isVarArg(), Ins,
5964 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005965
5966 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005967 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005968 "LowerFormalArguments didn't return a valid chain!");
5969 assert(InVals.size() == Ins.size() &&
5970 "LowerFormalArguments didn't emit the correct number of values!");
5971 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5972 assert(InVals[i].getNode() &&
5973 "LowerFormalArguments emitted a null value!");
5974 assert(Ins[i].VT == InVals[i].getValueType() &&
5975 "LowerFormalArguments emitted a value with the wrong type!");
5976 });
5977
5978 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005979 DAG.setRoot(NewRoot);
5980
5981 // Set up the argument values.
5982 unsigned i = 0;
5983 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005984 if (!FLI.CanLowerReturn) {
5985 // Create a virtual register for the sret pointer, and put in a copy
5986 // from the sret argument into it.
5987 SmallVector<EVT, 1> ValueVTs;
5988 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5989 EVT VT = ValueVTs[0];
5990 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5991 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5992 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
5993 VT, AssertOp);
5994
5995 MachineFunction& MF = SDL->DAG.getMachineFunction();
5996 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5997 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5998 FLI.DemoteRegister = SRetReg;
5999 NewRoot = SDL->DAG.getCopyToReg(NewRoot, SDL->getCurDebugLoc(), SRetReg, ArgValue);
6000 DAG.setRoot(NewRoot);
6001
6002 // i indexes lowered arguments. Bump it past the hidden sret argument.
6003 // Idx indexes LLVM arguments. Don't touch it.
6004 ++i;
6005 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00006006 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6007 ++I, ++Idx) {
6008 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006009 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006010 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006011 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006012 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006013 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00006014 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6015 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006016
6017 if (!I->use_empty()) {
6018 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6019 if (F.paramHasAttr(Idx, Attribute::SExt))
6020 AssertOp = ISD::AssertSext;
6021 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6022 AssertOp = ISD::AssertZext;
6023
6024 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
6025 PartVT, VT, AssertOp));
6026 }
6027 i += NumParts;
6028 }
6029 if (!I->use_empty()) {
6030 SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
6031 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006032 // If this argument is live outside of the entry block, insert a copy from
6033 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006034 SDL->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006035 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006036 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00006037 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006038
6039 // Finally, if the target has anything special to do, allow it to do so.
6040 // FIXME: this should insert code into the DAG!
6041 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
6042}
6043
6044/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6045/// ensure constants are generated when needed. Remember the virtual registers
6046/// that need to be added to the Machine PHI nodes as input. We cannot just
6047/// directly add them, because expansion might result in multiple MBB's for one
6048/// BB. As such, the start of the BB might correspond to a different MBB than
6049/// the end.
6050///
6051void
6052SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6053 TerminatorInst *TI = LLVMBB->getTerminator();
6054
6055 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6056
6057 // Check successor nodes' PHI nodes that expect a constant to be available
6058 // from this block.
6059 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6060 BasicBlock *SuccBB = TI->getSuccessor(succ);
6061 if (!isa<PHINode>(SuccBB->begin())) continue;
6062 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006063
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006064 // If this terminator has multiple identical successors (common for
6065 // switches), only handle each succ once.
6066 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006067
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006068 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6069 PHINode *PN;
6070
6071 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6072 // nodes and Machine PHI nodes, but the incoming operands have not been
6073 // emitted yet.
6074 for (BasicBlock::iterator I = SuccBB->begin();
6075 (PN = dyn_cast<PHINode>(I)); ++I) {
6076 // Ignore dead phi's.
6077 if (PN->use_empty()) continue;
6078
6079 unsigned Reg;
6080 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6081
6082 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6083 unsigned &RegOut = SDL->ConstantsOut[C];
6084 if (RegOut == 0) {
6085 RegOut = FuncInfo->CreateRegForValue(C);
6086 SDL->CopyValueToVirtualRegister(C, RegOut);
6087 }
6088 Reg = RegOut;
6089 } else {
6090 Reg = FuncInfo->ValueMap[PHIOp];
6091 if (Reg == 0) {
6092 assert(isa<AllocaInst>(PHIOp) &&
6093 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6094 "Didn't codegen value into a register!??");
6095 Reg = FuncInfo->CreateRegForValue(PHIOp);
6096 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
6097 }
6098 }
6099
6100 // Remember that this register needs to added to the machine PHI node as
6101 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006102 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006103 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6104 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006105 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006106 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006107 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6108 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6109 Reg += NumRegisters;
6110 }
6111 }
6112 }
6113 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006114}
6115
Dan Gohman3df24e62008-09-03 23:12:08 +00006116/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6117/// supports legal types, and it emits MachineInstrs directly instead of
6118/// creating SelectionDAG nodes.
6119///
6120bool
6121SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6122 FastISel *F) {
6123 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006124
Dan Gohman3df24e62008-09-03 23:12:08 +00006125 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6126 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6127
6128 // Check successor nodes' PHI nodes that expect a constant to be available
6129 // from this block.
6130 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6131 BasicBlock *SuccBB = TI->getSuccessor(succ);
6132 if (!isa<PHINode>(SuccBB->begin())) continue;
6133 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006134
Dan Gohman3df24e62008-09-03 23:12:08 +00006135 // If this terminator has multiple identical successors (common for
6136 // switches), only handle each succ once.
6137 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006138
Dan Gohman3df24e62008-09-03 23:12:08 +00006139 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6140 PHINode *PN;
6141
6142 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6143 // nodes and Machine PHI nodes, but the incoming operands have not been
6144 // emitted yet.
6145 for (BasicBlock::iterator I = SuccBB->begin();
6146 (PN = dyn_cast<PHINode>(I)); ++I) {
6147 // Ignore dead phi's.
6148 if (PN->use_empty()) continue;
6149
6150 // Only handle legal types. Two interesting things to note here. First,
6151 // by bailing out early, we may leave behind some dead instructions,
6152 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6153 // own moves. Second, this check is necessary becuase FastISel doesn't
6154 // use CreateRegForValue to create registers, so it always creates
6155 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006156 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006157 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6158 // Promote MVT::i1.
6159 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006160 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006161 else {
6162 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6163 return false;
6164 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006165 }
6166
6167 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6168
6169 unsigned Reg = F->getRegForValue(PHIOp);
6170 if (Reg == 0) {
6171 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6172 return false;
6173 }
6174 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6175 }
6176 }
6177
6178 return true;
6179}