blob: c0d2a4d39a322ca07a41c39041c4055237d54551 [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"
Bill Wendlingb2a42982008-11-06 02:29:10 +000029#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000030#include "llvm/CodeGen/FastISel.h"
31#include "llvm/CodeGen/GCStrategy.h"
32#include "llvm/CodeGen/GCMetadata.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFrameInfo.h"
35#include "llvm/CodeGen/MachineInstrBuilder.h"
36#include "llvm/CodeGen/MachineJumpTableInfo.h"
37#include "llvm/CodeGen/MachineModuleInfo.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000039#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000040#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000041#include "llvm/CodeGen/DwarfWriter.h"
42#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000043#include "llvm/Target/TargetRegisterInfo.h"
44#include "llvm/Target/TargetData.h"
45#include "llvm/Target/TargetFrameInfo.h"
46#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000047#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000048#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000049#include "llvm/Target/TargetOptions.h"
50#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000051#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000054#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000055#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000056#include <algorithm>
57using namespace llvm;
58
Dale Johannesen601d3c02008-09-05 01:48:15 +000059/// LimitFloatPrecision - Generate low-precision inline sequences for
60/// some float libcalls (6, 8 or 12 bits).
61static unsigned LimitFloatPrecision;
62
63static cl::opt<unsigned, true>
64LimitFPPrecision("limit-float-precision",
65 cl::desc("Generate low-precision inline sequences "
66 "for some float libcalls"),
67 cl::location(LimitFloatPrecision),
68 cl::init(0));
69
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000070/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000071/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000072/// the linearized index of the start of the member.
73///
74static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
75 const unsigned *Indices,
76 const unsigned *IndicesEnd,
77 unsigned CurIndex = 0) {
78 // Base case: We're done.
79 if (Indices && Indices == IndicesEnd)
80 return CurIndex;
81
82 // Given a struct type, recursively traverse the elements.
83 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
84 for (StructType::element_iterator EB = STy->element_begin(),
85 EI = EB,
86 EE = STy->element_end();
87 EI != EE; ++EI) {
88 if (Indices && *Indices == unsigned(EI - EB))
89 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
90 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
91 }
Dan Gohman2c91d102009-01-06 22:53:52 +000092 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000093 }
94 // Given an array type, recursively traverse the elements.
95 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
96 const Type *EltTy = ATy->getElementType();
97 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
98 if (Indices && *Indices == i)
99 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
100 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
101 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000102 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000103 }
104 // We haven't found the type we're looking for, so keep searching.
105 return CurIndex + 1;
106}
107
108/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
Owen Andersone50ed302009-08-10 22:56:29 +0000109/// EVTs that represent all the individual underlying
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000110/// non-aggregate types that comprise it.
111///
112/// If Offsets is non-null, it points to a vector to be filled in
113/// with the in-memory offsets of each of the individual values.
114///
115static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
Owen Andersone50ed302009-08-10 22:56:29 +0000116 SmallVectorImpl<EVT> &ValueVTs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000117 SmallVectorImpl<uint64_t> *Offsets = 0,
118 uint64_t StartingOffset = 0) {
119 // Given a struct type, recursively traverse the elements.
120 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
121 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
122 for (StructType::element_iterator EB = STy->element_begin(),
123 EI = EB,
124 EE = STy->element_end();
125 EI != EE; ++EI)
126 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
127 StartingOffset + SL->getElementOffset(EI - EB));
128 return;
129 }
130 // Given an array type, recursively traverse the elements.
131 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
132 const Type *EltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000133 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000134 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
135 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
136 StartingOffset + i * EltSize);
137 return;
138 }
Dan Gohman5e5558b2009-04-23 22:50:03 +0000139 // Interpret void as zero return values.
Owen Anderson1d0be152009-08-13 21:58:54 +0000140 if (Ty == Type::getVoidTy(Ty->getContext()))
Dan Gohman5e5558b2009-04-23 22:50:03 +0000141 return;
Owen Andersone50ed302009-08-10 22:56:29 +0000142 // Base case: we can get an EVT for this LLVM IR type.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000143 ValueVTs.push_back(TLI.getValueType(Ty));
144 if (Offsets)
145 Offsets->push_back(StartingOffset);
146}
147
Dan Gohman2a7c6712008-09-03 23:18:39 +0000148namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000149 /// RegsForValue - This struct represents the registers (physical or virtual)
150 /// that a particular set of values is assigned, and the type information about
151 /// the value. The most common situation is to represent one value at a time,
152 /// but struct or array values are handled element-wise as multiple values.
153 /// The splitting of aggregates is performed recursively, so that we never
154 /// have aggregate-typed registers. The values at this point do not necessarily
155 /// have legal types, so each value may require one or more registers of some
156 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000157 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000158 struct VISIBILITY_HIDDEN RegsForValue {
159 /// TLI - The TargetLowering object.
160 ///
161 const TargetLowering *TLI;
162
163 /// ValueVTs - The value types of the values, which may not be legal, and
164 /// may need be promoted or synthesized from one or more registers.
165 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000166 SmallVector<EVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000168 /// RegVTs - The value types of the registers. This is the same size as
169 /// ValueVTs and it records, for each value, what the type of the assigned
170 /// register or registers are. (Individual values are never synthesized
171 /// from more than one type of register.)
172 ///
173 /// With virtual registers, the contents of RegVTs is redundant with TLI's
174 /// getRegisterType member function, however when with physical registers
175 /// it is necessary to have a separate record of the types.
176 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000177 SmallVector<EVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000179 /// Regs - This list holds the registers assigned to the values.
180 /// Each legal or promoted value requires one register, and each
181 /// expanded value requires multiple registers.
182 ///
183 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000186
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000188 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000189 EVT regvt, EVT valuevt)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000190 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
191 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000192 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000193 const SmallVector<EVT, 4> &regvts,
194 const SmallVector<EVT, 4> &valuevts)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000195 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Owen Anderson23b9b192009-08-12 00:36:31 +0000196 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000197 unsigned Reg, const Type *Ty) : TLI(&tli) {
198 ComputeValueVTs(tli, Ty, ValueVTs);
199
200 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000201 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000202 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
203 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000204 for (unsigned i = 0; i != NumRegs; ++i)
205 Regs.push_back(Reg + i);
206 RegVTs.push_back(RegisterVT);
207 Reg += NumRegs;
208 }
209 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000210
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000211 /// append - Add the specified values to this one.
212 void append(const RegsForValue &RHS) {
213 TLI = RHS.TLI;
214 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
215 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
216 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
217 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000218
219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000220 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000221 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000222 /// Chain/Flag as the input and updates them for the output Chain/Flag.
223 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000224 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000225 SDValue &Chain, SDValue *Flag) const;
226
227 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000228 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000229 /// Chain/Flag as the input and updates them for the output Chain/Flag.
230 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000231 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000232 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000233
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000234 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000235 /// operand list. This adds the code marker, matching input operand index
236 /// (if applicable), and includes the number of values added into it.
237 void AddInlineAsmOperands(unsigned Code,
238 bool HasMatching, unsigned MatchingIdx,
239 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000240 };
241}
242
243/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000244/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000245/// switch or atomic instruction, which may expand to multiple basic blocks.
246static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
247 if (isa<PHINode>(I)) return true;
248 BasicBlock *BB = I->getParent();
249 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Dan Gohman8e5c0da2009-04-09 02:33:36 +0000250 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000251 return true;
252 return false;
253}
254
255/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
256/// entry block, return true. This includes arguments used by switches, since
257/// the switch may expand into multiple basic blocks.
258static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
259 // With FastISel active, we may be splitting blocks, so force creation
260 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000261 // Don't force virtual registers for byval arguments though, because
262 // fast-isel can't handle those in all cases.
263 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000264 return A->use_empty();
265
266 BasicBlock *Entry = A->getParent()->begin();
267 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
268 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
269 return false; // Use not in entry block.
270 return true;
271}
272
273FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
274 : TLI(tli) {
275}
276
277void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000278 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000279 bool EnableFastISel) {
280 Fn = &fn;
281 MF = &mf;
282 RegInfo = &MF->getRegInfo();
283
284 // Create a vreg for each argument register that is not dead and is used
285 // outside of the entry block for the function.
286 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
287 AI != E; ++AI)
288 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
289 InitializeRegForValue(AI);
290
291 // Initialize the mapping of values to registers. This is only set up for
292 // instruction values that are used outside of the block that defines
293 // them.
294 Function::iterator BB = Fn->begin(), EB = Fn->end();
295 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
296 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
297 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
298 const Type *Ty = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000299 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000300 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000301 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
302 AI->getAlignment());
303
304 TySize *= CUI->getZExtValue(); // Get total allocated size.
305 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
306 StaticAllocaMap[AI] =
307 MF->getFrameInfo()->CreateStackObject(TySize, Align);
308 }
309
310 for (; BB != EB; ++BB)
311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
312 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
313 if (!isa<AllocaInst>(I) ||
314 !StaticAllocaMap.count(cast<AllocaInst>(I)))
315 InitializeRegForValue(I);
316
317 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
318 // also creates the initial PHI MachineInstrs, though none of the input
319 // operands are populated.
320 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
321 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
322 MBBMap[BB] = MBB;
323 MF->push_back(MBB);
324
Dan Gohman8c2b5252009-10-30 01:27:03 +0000325 // Transfer the address-taken flag. This is necessary because there could
326 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
327 // the first one should be marked.
328 if (BB->hasAddressTaken())
329 MBB->setHasAddressTaken();
330
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000331 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
332 // appropriate.
333 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000334 DebugLoc DL;
335 for (BasicBlock::iterator
336 I = BB->begin(), E = BB->end(); I != E; ++I) {
337 if (CallInst *CI = dyn_cast<CallInst>(I)) {
338 if (Function *F = CI->getCalledFunction()) {
339 switch (F->getIntrinsicID()) {
340 default: break;
341 case Intrinsic::dbg_stoppoint: {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000342 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000343 if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default))
344 DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000345 break;
346 }
347 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000348 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000349 if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default))
350 DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000351 break;
352 }
353 }
354 }
355 }
356
357 PN = dyn_cast<PHINode>(I);
358 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000359
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000360 unsigned PHIReg = ValueMap[PN];
361 assert(PHIReg && "PHI node does not have an assigned virtual register!");
362
Owen Andersone50ed302009-08-10 22:56:29 +0000363 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000364 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
365 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +0000366 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +0000367 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000368 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000369 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000370 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000371 PHIReg += NumRegisters;
372 }
373 }
374 }
375}
376
Owen Andersone50ed302009-08-10 22:56:29 +0000377unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000378 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
379}
380
381/// CreateRegForValue - Allocate the appropriate number of virtual registers of
382/// the correctly promoted or expanded types. Assign these registers
383/// consecutive vreg numbers and return the first assigned number.
384///
385/// In the case that the given value has struct or array type, this function
386/// will assign registers for each member or element.
387///
388unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Owen Andersone50ed302009-08-10 22:56:29 +0000389 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000390 ComputeValueVTs(TLI, V->getType(), ValueVTs);
391
392 unsigned FirstReg = 0;
393 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000394 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000395 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000396
Owen Anderson23b9b192009-08-12 00:36:31 +0000397 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000398 for (unsigned i = 0; i != NumRegs; ++i) {
399 unsigned R = MakeReg(RegisterVT);
400 if (!FirstReg) FirstReg = R;
401 }
402 }
403 return FirstReg;
404}
405
406/// getCopyFromParts - Create a value that contains the specified legal parts
407/// combined into the value they represent. If the parts combine to a type
408/// larger then ValueVT then AssertOp can be used to specify whether the extra
409/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
410/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000411static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
412 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000413 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000414 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000415 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000416 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000417 SDValue Val = Parts[0];
418
419 if (NumParts > 1) {
420 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000421 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000422 unsigned PartBits = PartVT.getSizeInBits();
423 unsigned ValueBits = ValueVT.getSizeInBits();
424
425 // Assemble the power of 2 part.
426 unsigned RoundParts = NumParts & (NumParts - 1) ?
427 1 << Log2_32(NumParts) : NumParts;
428 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000429 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000430 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000431 SDValue Lo, Hi;
432
Owen Anderson23b9b192009-08-12 00:36:31 +0000433 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000434
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000435 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000436 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
437 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000438 PartVT, HalfVT);
439 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000440 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
441 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000442 }
443 if (TLI.isBigEndian())
444 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000445 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000446
447 if (RoundParts < NumParts) {
448 // Assemble the trailing non-power-of-2 part.
449 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000450 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000451 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000452 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453
454 // Combine the round and odd parts.
455 Lo = Val;
456 if (TLI.isBigEndian())
457 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000458 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000459 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
460 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000461 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000462 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000463 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
464 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000465 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000466 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000467 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000468 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000469 unsigned NumIntermediates;
470 unsigned NumRegs =
Owen Anderson23b9b192009-08-12 00:36:31 +0000471 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
472 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
474 NumParts = NumRegs; // Silence a compiler warning.
475 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
476 assert(RegisterVT == Parts[0].getValueType() &&
477 "Part type doesn't match part!");
478
479 // Assemble the parts into intermediate operands.
480 SmallVector<SDValue, 8> Ops(NumIntermediates);
481 if (NumIntermediates == NumParts) {
482 // If the register was not expanded, truncate or copy the value,
483 // as appropriate.
484 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000485 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000486 PartVT, IntermediateVT);
487 } else if (NumParts > 0) {
488 // If the intermediate type was expanded, build the intermediate operands
489 // from the parts.
490 assert(NumParts % NumIntermediates == 0 &&
491 "Must expand into a divisible number of parts!");
492 unsigned Factor = NumParts / NumIntermediates;
493 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000494 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000495 PartVT, IntermediateVT);
496 }
497
498 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
499 // operands.
500 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000501 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000502 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000503 } else if (PartVT.isFloatingPoint()) {
504 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000505 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000506 "Unexpected split");
507 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000508 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
509 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000510 if (TLI.isBigEndian())
511 std::swap(Lo, Hi);
512 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
513 } else {
514 // FP split into integer parts (soft fp)
515 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
516 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000517 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Eli Friedman2ac8b322009-05-20 06:02:09 +0000518 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000519 }
520 }
521
522 // There is now one part, held in Val. Correct it to match ValueVT.
523 PartVT = Val.getValueType();
524
525 if (PartVT == ValueVT)
526 return Val;
527
528 if (PartVT.isVector()) {
529 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000530 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000531 }
532
533 if (ValueVT.isVector()) {
534 assert(ValueVT.getVectorElementType() == PartVT &&
535 ValueVT.getVectorNumElements() == 1 &&
536 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000537 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000538 }
539
540 if (PartVT.isInteger() &&
541 ValueVT.isInteger()) {
542 if (ValueVT.bitsLT(PartVT)) {
543 // For a truncate, see if we have any information to
544 // indicate whether the truncated bits will always be
545 // zero or sign-extension.
546 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000547 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000548 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000549 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000551 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000552 }
553 }
554
555 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
556 if (ValueVT.bitsLT(Val.getValueType()))
557 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000558 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000559 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000560 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000561 }
562
563 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000564 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000565
Torok Edwinc23197a2009-07-14 16:55:14 +0000566 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567 return SDValue();
568}
569
570/// getCopyToParts - Create a series of nodes that contain the specified value
571/// split into legal parts. If the parts contain more bits than Val, then, for
572/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000573static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Owen Andersone50ed302009-08-10 22:56:29 +0000574 SDValue *Parts, unsigned NumParts, EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000575 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000577 EVT PtrVT = TLI.getPointerTy();
578 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000579 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000580 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000581 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
582
583 if (!NumParts)
584 return;
585
586 if (!ValueVT.isVector()) {
587 if (PartVT == ValueVT) {
588 assert(NumParts == 1 && "No-op copy with multiple parts!");
589 Parts[0] = Val;
590 return;
591 }
592
593 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
594 // If the parts cover more bits than the value has, promote the value.
595 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
596 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000597 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000598 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000599 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000600 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000601 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000602 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000603 }
604 } else if (PartBits == ValueVT.getSizeInBits()) {
605 // Different types of the same size.
606 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000607 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000608 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
609 // If the parts cover less bits than value has, truncate the value.
610 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000611 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000612 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000613 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000614 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000615 }
616 }
617
618 // The value may have changed - recompute ValueVT.
619 ValueVT = Val.getValueType();
620 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
621 "Failed to tile the value with PartVT!");
622
623 if (NumParts == 1) {
624 assert(PartVT == ValueVT && "Type conversion failed!");
625 Parts[0] = Val;
626 return;
627 }
628
629 // Expand the value into multiple parts.
630 if (NumParts & (NumParts - 1)) {
631 // The number of parts is not a power of 2. Split off and copy the tail.
632 assert(PartVT.isInteger() && ValueVT.isInteger() &&
633 "Do not know what to expand to!");
634 unsigned RoundParts = 1 << Log2_32(NumParts);
635 unsigned RoundBits = RoundParts * PartBits;
636 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000637 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000638 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000639 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000640 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000641 if (TLI.isBigEndian())
642 // The odd parts were reversed by getCopyToParts - unreverse them.
643 std::reverse(Parts + RoundParts, Parts + NumParts);
644 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000645 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000646 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000647 }
648
649 // The number of parts is a power of 2. Repeatedly bisect the value using
650 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000651 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson23b9b192009-08-12 00:36:31 +0000652 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000653 Val);
654 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
655 for (unsigned i = 0; i < NumParts; i += StepSize) {
656 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000657 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000658 SDValue &Part0 = Parts[i];
659 SDValue &Part1 = Parts[i+StepSize/2];
660
Scott Michelfdc40a02009-02-17 22:15:04 +0000661 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000662 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000663 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000664 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000665 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000666 DAG.getConstant(0, PtrVT));
667
668 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000669 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000670 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000671 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000672 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000673 }
674 }
675 }
676
677 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000678 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000679
680 return;
681 }
682
683 // Vector ValueVT.
684 if (NumParts == 1) {
685 if (PartVT != ValueVT) {
686 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000687 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000688 } else {
689 assert(ValueVT.getVectorElementType() == PartVT &&
690 ValueVT.getVectorNumElements() == 1 &&
691 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000692 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000693 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000694 DAG.getConstant(0, PtrVT));
695 }
696 }
697
698 Parts[0] = Val;
699 return;
700 }
701
702 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000703 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000704 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000705 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
706 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000707 unsigned NumElements = ValueVT.getVectorNumElements();
708
709 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
710 NumParts = NumRegs; // Silence a compiler warning.
711 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
712
713 // Split the vector into intermediate operands.
714 SmallVector<SDValue, 8> Ops(NumIntermediates);
715 for (unsigned i = 0; i != NumIntermediates; ++i)
716 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000717 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000718 IntermediateVT, Val,
719 DAG.getConstant(i * (NumElements / NumIntermediates),
720 PtrVT));
721 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000722 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000723 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000724 DAG.getConstant(i, PtrVT));
725
726 // Split the intermediate operands into legal parts.
727 if (NumParts == NumIntermediates) {
728 // If the register was not expanded, promote or copy the value,
729 // as appropriate.
730 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000731 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000732 } else if (NumParts > 0) {
733 // If the intermediate type was expanded, split each the value into
734 // legal parts.
735 assert(NumParts % NumIntermediates == 0 &&
736 "Must expand into a divisible number of parts!");
737 unsigned Factor = NumParts / NumIntermediates;
738 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000739 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000740 }
741}
742
743
744void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
745 AA = &aa;
746 GFI = gfi;
747 TD = DAG.getTarget().getTargetData();
748}
749
750/// clear - Clear out the curret SelectionDAG and the associated
751/// state and prepare this SelectionDAGLowering object to be used
752/// for a new block. This doesn't clear out information about
753/// additional blocks that are needed to complete switch lowering
754/// or PHI node updating; that information is cleared out as it is
755/// consumed.
756void SelectionDAGLowering::clear() {
757 NodeMap.clear();
758 PendingLoads.clear();
759 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000760 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000761 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000762 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000763 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000764}
765
766/// getRoot - Return the current virtual root of the Selection DAG,
767/// flushing any PendingLoad items. This must be done before emitting
768/// a store or any other node that may need to be ordered after any
769/// prior load instructions.
770///
771SDValue SelectionDAGLowering::getRoot() {
772 if (PendingLoads.empty())
773 return DAG.getRoot();
774
775 if (PendingLoads.size() == 1) {
776 SDValue Root = PendingLoads[0];
777 DAG.setRoot(Root);
778 PendingLoads.clear();
779 return Root;
780 }
781
782 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000783 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000784 &PendingLoads[0], PendingLoads.size());
785 PendingLoads.clear();
786 DAG.setRoot(Root);
787 return Root;
788}
789
790/// getControlRoot - Similar to getRoot, but instead of flushing all the
791/// PendingLoad items, flush all the PendingExports items. It is necessary
792/// to do this before emitting a terminator instruction.
793///
794SDValue SelectionDAGLowering::getControlRoot() {
795 SDValue Root = DAG.getRoot();
796
797 if (PendingExports.empty())
798 return Root;
799
800 // Turn all of the CopyToReg chains into one factored node.
801 if (Root.getOpcode() != ISD::EntryToken) {
802 unsigned i = 0, e = PendingExports.size();
803 for (; i != e; ++i) {
804 assert(PendingExports[i].getNode()->getNumOperands() > 1);
805 if (PendingExports[i].getNode()->getOperand(0) == Root)
806 break; // Don't add the root if we already indirectly depend on it.
807 }
808
809 if (i == e)
810 PendingExports.push_back(Root);
811 }
812
Owen Anderson825b72b2009-08-11 20:47:22 +0000813 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000814 &PendingExports[0],
815 PendingExports.size());
816 PendingExports.clear();
817 DAG.setRoot(Root);
818 return Root;
819}
820
821void SelectionDAGLowering::visit(Instruction &I) {
822 visit(I.getOpcode(), I);
823}
824
825void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
826 // Note: this doesn't use InstVisitor, because it has to work with
827 // ConstantExpr's in addition to instructions.
828 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000829 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000830 // Build the switch statement using the Instruction.def file.
831#define HANDLE_INST(NUM, OPCODE, CLASS) \
832 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
833#include "llvm/Instruction.def"
834 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000835}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000836
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000837SDValue SelectionDAGLowering::getValue(const Value *V) {
838 SDValue &N = NodeMap[V];
839 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000840
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000841 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000842 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000844 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000845 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000846
847 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
848 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000849
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000850 if (isa<ConstantPointerNull>(C))
851 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000852
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000853 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000854 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000855
Nate Begeman9008ca62009-04-27 18:41:29 +0000856 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000857 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000858
859 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
860 visit(CE->getOpcode(), *CE);
861 SDValue N1 = NodeMap[V];
862 assert(N1.getNode() && "visit didn't populate the ValueMap!");
863 return N1;
864 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
867 SmallVector<SDValue, 4> Constants;
868 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
869 OI != OE; ++OI) {
870 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000871 // If the operand is an empty aggregate, there are no values.
872 if (!Val) continue;
873 // Add each leaf value from the operand to the Constants list
874 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000875 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
876 Constants.push_back(SDValue(Val, i));
877 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000878 return DAG.getMergeValues(&Constants[0], Constants.size(),
879 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000880 }
881
882 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
883 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
884 "Unknown struct or array constant!");
885
Owen Andersone50ed302009-08-10 22:56:29 +0000886 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000887 ComputeValueVTs(TLI, C->getType(), ValueVTs);
888 unsigned NumElts = ValueVTs.size();
889 if (NumElts == 0)
890 return SDValue(); // empty struct
891 SmallVector<SDValue, 4> Constants(NumElts);
892 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000893 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000894 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000895 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000896 else if (EltVT.isFloatingPoint())
897 Constants[i] = DAG.getConstantFP(0, EltVT);
898 else
899 Constants[i] = DAG.getConstant(0, EltVT);
900 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000901 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000902 }
903
Dan Gohman8c2b5252009-10-30 01:27:03 +0000904 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
905 return DAG.getBlockAddress(BA, getCurDebugLoc());
906
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000907 const VectorType *VecTy = cast<VectorType>(V->getType());
908 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000909
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 // Now that we know the number and type of the elements, get that number of
911 // elements into the Ops array based on what kind of constant it is.
912 SmallVector<SDValue, 16> Ops;
913 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
914 for (unsigned i = 0; i != NumElements; ++i)
915 Ops.push_back(getValue(CP->getOperand(i)));
916 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000917 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000918 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000919
920 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000921 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000922 Op = DAG.getConstantFP(0, EltVT);
923 else
924 Op = DAG.getConstant(0, EltVT);
925 Ops.assign(NumElements, Op);
926 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000927
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000929 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
930 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000931 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000932
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000933 // If this is a static alloca, generate it as the frameindex instead of
934 // computation.
935 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
936 DenseMap<const AllocaInst*, int>::iterator SI =
937 FuncInfo.StaticAllocaMap.find(AI);
938 if (SI != FuncInfo.StaticAllocaMap.end())
939 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
940 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000942 unsigned InReg = FuncInfo.ValueMap[V];
943 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000944
Owen Anderson23b9b192009-08-12 00:36:31 +0000945 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000947 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000948}
949
950
951void SelectionDAGLowering::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000952 SDValue Chain = getControlRoot();
953 SmallVector<ISD::OutputArg, 8> Outs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000954 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000955 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000957 unsigned NumValues = ValueVTs.size();
958 if (NumValues == 0) continue;
959
960 SDValue RetOp = getValue(I.getOperand(i));
961 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Owen Andersone50ed302009-08-10 22:56:29 +0000962 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000963
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000964 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000965
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000966 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000967 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000968 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000969 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000970 ExtendKind = ISD::ZERO_EXTEND;
971
Evan Cheng3927f432009-03-25 20:20:11 +0000972 // FIXME: C calling convention requires the return type to be promoted to
973 // at least 32-bit. But this is not necessary for non-C calling
974 // conventions. The frontend should mark functions whose return values
975 // require promoting with signext or zeroext attributes.
976 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000977 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
Evan Cheng3927f432009-03-25 20:20:11 +0000978 if (VT.bitsLT(MinVT))
979 VT = MinVT;
980 }
981
Owen Anderson23b9b192009-08-12 00:36:31 +0000982 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
983 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
Evan Cheng3927f432009-03-25 20:20:11 +0000984 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000985 getCopyToParts(DAG, getCurDebugLoc(),
986 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000987 &Parts[0], NumParts, PartVT, ExtendKind);
988
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000989 // 'inreg' on function refers to return value
990 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000991 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000992 Flags.setInReg();
Anton Korobeynikov0692fab2009-07-16 13:35:48 +0000993
994 // Propagate extension type if any
995 if (F->paramHasAttr(0, Attribute::SExt))
996 Flags.setSExt();
997 else if (F->paramHasAttr(0, Attribute::ZExt))
998 Flags.setZExt();
999
Dan Gohman98ca4f22009-08-05 01:29:28 +00001000 for (unsigned i = 0; i < NumParts; ++i)
1001 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001002 }
1003 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001004
1005 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001006 CallingConv::ID CallConv =
1007 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001008 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1009 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001010
1011 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001012 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001013 "LowerReturn didn't return a valid chain!");
1014
1015 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001016 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001017}
1018
Dan Gohmanad62f532009-04-23 23:13:24 +00001019/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1020/// created for it, emit nodes to copy the value into the virtual
1021/// registers.
1022void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1023 if (!V->use_empty()) {
1024 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1025 if (VMI != FuncInfo.ValueMap.end())
1026 CopyValueToVirtualRegister(V, VMI->second);
1027 }
1028}
1029
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001030/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1031/// the current basic block, add it to ValueMap now so that we'll get a
1032/// CopyTo/FromReg.
1033void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1034 // No need to export constants.
1035 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001036
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001037 // Already exported?
1038 if (FuncInfo.isExportedInst(V)) return;
1039
1040 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1041 CopyValueToVirtualRegister(V, Reg);
1042}
1043
1044bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1045 const BasicBlock *FromBB) {
1046 // The operands of the setcc have to be in this block. We don't know
1047 // how to export them from some other block.
1048 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1049 // Can export from current BB.
1050 if (VI->getParent() == FromBB)
1051 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001052
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001053 // Is already exported, noop.
1054 return FuncInfo.isExportedInst(V);
1055 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001056
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001057 // If this is an argument, we can export it if the BB is the entry block or
1058 // if it is already exported.
1059 if (isa<Argument>(V)) {
1060 if (FromBB == &FromBB->getParent()->getEntryBlock())
1061 return true;
1062
1063 // Otherwise, can only export this if it is already exported.
1064 return FuncInfo.isExportedInst(V);
1065 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001066
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001067 // Otherwise, constants can always be exported.
1068 return true;
1069}
1070
1071static bool InBlock(const Value *V, const BasicBlock *BB) {
1072 if (const Instruction *I = dyn_cast<Instruction>(V))
1073 return I->getParent() == BB;
1074 return true;
1075}
1076
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001077/// getFCmpCondCode - Return the ISD condition code corresponding to
1078/// the given LLVM IR floating-point condition code. This includes
1079/// consideration of global floating-point math flags.
1080///
1081static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1082 ISD::CondCode FPC, FOC;
1083 switch (Pred) {
1084 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1085 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1086 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1087 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1088 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1089 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1090 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1091 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1092 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1093 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1094 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1095 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1096 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1097 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1098 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1099 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1100 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001101 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001102 FOC = FPC = ISD::SETFALSE;
1103 break;
1104 }
1105 if (FiniteOnlyFPMath())
1106 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001107 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001108 return FPC;
1109}
1110
1111/// getICmpCondCode - Return the ISD condition code corresponding to
1112/// the given LLVM IR integer condition code.
1113///
1114static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1115 switch (Pred) {
1116 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1117 case ICmpInst::ICMP_NE: return ISD::SETNE;
1118 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1119 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1120 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1121 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1122 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1123 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1124 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1125 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1126 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001127 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001128 return ISD::SETNE;
1129 }
1130}
1131
Dan Gohmanc2277342008-10-17 21:16:08 +00001132/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1133/// This function emits a branch and is used at the leaves of an OR or an
1134/// AND operator tree.
1135///
1136void
1137SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1138 MachineBasicBlock *TBB,
1139 MachineBasicBlock *FBB,
1140 MachineBasicBlock *CurBB) {
1141 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001142
Dan Gohmanc2277342008-10-17 21:16:08 +00001143 // If the leaf of the tree is a comparison, merge the condition into
1144 // the caseblock.
1145 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1146 // The operands of the cmp have to be in this block. We don't know
1147 // how to export them from some other block. If this is the first block
1148 // of the sequence, no exporting is needed.
1149 if (CurBB == CurMBB ||
1150 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1151 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001152 ISD::CondCode Condition;
1153 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001154 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001155 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001156 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001157 } else {
1158 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001159 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001160 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001161
1162 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001163 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1164 SwitchCases.push_back(CB);
1165 return;
1166 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001167 }
1168
1169 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001170 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001171 NULL, TBB, FBB, CurBB);
1172 SwitchCases.push_back(CB);
1173}
1174
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001175/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001176void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1177 MachineBasicBlock *TBB,
1178 MachineBasicBlock *FBB,
1179 MachineBasicBlock *CurBB,
1180 unsigned Opc) {
1181 // If this node is not part of the or/and tree, emit it as a branch.
1182 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001183 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001184 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1185 BOp->getParent() != CurBB->getBasicBlock() ||
1186 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1187 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1188 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001189 return;
1190 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001191
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001192 // Create TmpBB after CurBB.
1193 MachineFunction::iterator BBI = CurBB;
1194 MachineFunction &MF = DAG.getMachineFunction();
1195 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1196 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001197
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001198 if (Opc == Instruction::Or) {
1199 // Codegen X | Y as:
1200 // jmp_if_X TBB
1201 // jmp TmpBB
1202 // TmpBB:
1203 // jmp_if_Y TBB
1204 // jmp FBB
1205 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001207 // Emit the LHS condition.
1208 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001209
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001210 // Emit the RHS condition into TmpBB.
1211 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1212 } else {
1213 assert(Opc == Instruction::And && "Unknown merge op!");
1214 // Codegen X & Y as:
1215 // jmp_if_X TmpBB
1216 // jmp FBB
1217 // TmpBB:
1218 // jmp_if_Y TBB
1219 // jmp FBB
1220 //
1221 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001222
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001223 // Emit the LHS condition.
1224 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001225
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001226 // Emit the RHS condition into TmpBB.
1227 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1228 }
1229}
1230
1231/// If the set of cases should be emitted as a series of branches, return true.
1232/// If we should emit this as a bunch of and/or'd together conditions, return
1233/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001234bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001235SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1236 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001237
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001238 // If this is two comparisons of the same values or'd or and'd together, they
1239 // will get folded into a single comparison, so don't emit two blocks.
1240 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1241 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1242 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1243 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1244 return false;
1245 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001246
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001247 return true;
1248}
1249
1250void SelectionDAGLowering::visitBr(BranchInst &I) {
1251 // Update machine-CFG edges.
1252 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1253
1254 // Figure out which block is immediately after the current one.
1255 MachineBasicBlock *NextBlock = 0;
1256 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001257 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001258 NextBlock = BBI;
1259
1260 if (I.isUnconditional()) {
1261 // Update machine-CFG edges.
1262 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001264 // If this is not a fall-through branch, emit the branch.
1265 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001266 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001267 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001268 DAG.getBasicBlock(Succ0MBB)));
1269 return;
1270 }
1271
1272 // If this condition is one of the special cases we handle, do special stuff
1273 // now.
1274 Value *CondVal = I.getCondition();
1275 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1276
1277 // If this is a series of conditions that are or'd or and'd together, emit
1278 // this as a sequence of branches instead of setcc's with and/or operations.
1279 // For example, instead of something like:
1280 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001281 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001282 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001283 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 // or C, F
1285 // jnz foo
1286 // Emit:
1287 // cmp A, B
1288 // je foo
1289 // cmp D, E
1290 // jle foo
1291 //
1292 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001293 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001294 (BOp->getOpcode() == Instruction::And ||
1295 BOp->getOpcode() == Instruction::Or)) {
1296 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1297 // If the compares in later blocks need to use values not currently
1298 // exported from this block, export them now. This block should always
1299 // be the first entry.
1300 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001302 // Allow some cases to be rejected.
1303 if (ShouldEmitAsBranches(SwitchCases)) {
1304 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1305 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1306 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1307 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 // Emit the branch for this block.
1310 visitSwitchCase(SwitchCases[0]);
1311 SwitchCases.erase(SwitchCases.begin());
1312 return;
1313 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001315 // Okay, we decided not to do this, remove any inserted MBB's and clear
1316 // SwitchCases.
1317 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001318 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001319
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001320 SwitchCases.clear();
1321 }
1322 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001323
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001324 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001325 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001326 NULL, Succ0MBB, Succ1MBB, CurMBB);
1327 // Use visitSwitchCase to actually insert the fast branch sequence for this
1328 // cond branch.
1329 visitSwitchCase(CB);
1330}
1331
1332/// visitSwitchCase - Emits the necessary code to represent a single node in
1333/// the binary search tree resulting from lowering a switch instruction.
1334void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1335 SDValue Cond;
1336 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001337 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001338
1339 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001340 if (CB.CmpMHS == NULL) {
1341 // Fold "(X == true)" to X and "(X == false)" to !X to
1342 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001343 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001344 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001345 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001346 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001347 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001348 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001349 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001350 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001351 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001352 } else {
1353 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1354
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1356 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001357
1358 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001359 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360
1361 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001362 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001363 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001364 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001365 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001366 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001367 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001368 DAG.getConstant(High-Low, VT), ISD::SETULE);
1369 }
1370 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001371
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001372 // Update successor info
1373 CurMBB->addSuccessor(CB.TrueBB);
1374 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001380 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001381 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001382
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001383 // If the lhs block is the next block, invert the condition so that we can
1384 // fall through to the lhs instead of the rhs block.
1385 if (CB.TrueBB == NextBlock) {
1386 std::swap(CB.TrueBB, CB.FalseBB);
1387 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001388 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001389 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001390 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001391 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001392 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001393
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001394 // If the branch was constant folded, fix up the CFG.
1395 if (BrCond.getOpcode() == ISD::BR) {
1396 CurMBB->removeSuccessor(CB.FalseBB);
1397 DAG.setRoot(BrCond);
1398 } else {
1399 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001400 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001401 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001402
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001403 if (CB.FalseBB == NextBlock)
1404 DAG.setRoot(BrCond);
1405 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001406 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407 DAG.getBasicBlock(CB.FalseBB)));
1408 }
1409}
1410
1411/// visitJumpTable - Emit JumpTable node in the current MBB
1412void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1413 // Emit the code for the jump table
1414 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001415 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001416 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1417 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001418 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001419 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001420 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001422}
1423
1424/// visitJumpTableHeader - This function emits necessary code to produce index
1425/// in the JumpTable from switch case.
1426void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1427 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001428 // Subtract the lowest switch case value from the value being switched on and
1429 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001430 // difference between smallest and largest cases.
1431 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001432 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001433 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001434 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001435
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001436 // The SDNode we just created, which holds the value being switched on minus
1437 // the the smallest case value, needs to be copied to a virtual register so it
1438 // can be used as an index into the jump table in a subsequent basic block.
1439 // This value may be smaller or larger than the target's pointer type, and
1440 // therefore require extension or truncating.
Duncan Sands3a66a682009-10-13 21:04:12 +00001441 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001443 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001444 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1445 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001446 JT.Reg = JumpTableReg;
1447
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001448 // Emit the range check for the jump table, and branch to the default block
1449 // for the switch statement if the value being switched on exceeds the largest
1450 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001451 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1452 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001453 DAG.getConstant(JTH.Last-JTH.First,VT),
1454 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001455
1456 // Set NextBlock to be the MBB immediately after the current one, if any.
1457 // This is used to avoid emitting unnecessary branches to the next block.
1458 MachineBasicBlock *NextBlock = 0;
1459 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001460 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461 NextBlock = BBI;
1462
Dale Johannesen66978ee2009-01-31 02:22:37 +00001463 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001464 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001465 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466
1467 if (JT.MBB == NextBlock)
1468 DAG.setRoot(BrCond);
1469 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001470 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001471 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001472}
1473
1474/// visitBitTestHeader - This function emits necessary code to produce value
1475/// suitable for "bit tests"
1476void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1477 // Subtract the minimum value
1478 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001479 EVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001480 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001481 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001482
1483 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001484 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1485 TLI.getSetCCResultType(SUB.getValueType()),
1486 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001487 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001488
Duncan Sands3a66a682009-10-13 21:04:12 +00001489 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001490
Duncan Sands92abc622009-01-31 15:50:11 +00001491 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001492 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1493 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001494
1495 // Set NextBlock to be the MBB immediately after the current one, if any.
1496 // This is used to avoid emitting unnecessary branches to the next block.
1497 MachineBasicBlock *NextBlock = 0;
1498 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001499 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001500 NextBlock = BBI;
1501
1502 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1503
1504 CurMBB->addSuccessor(B.Default);
1505 CurMBB->addSuccessor(MBB);
1506
Dale Johannesen66978ee2009-01-31 02:22:37 +00001507 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001508 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001509 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 if (MBB == NextBlock)
1512 DAG.setRoot(BrRange);
1513 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001514 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001515 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516}
1517
1518/// visitBitTestCase - this function produces one "bit test"
1519void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1520 unsigned Reg,
1521 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001522 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001523 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001524 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001525 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001526 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001527 DAG.getConstant(1, TLI.getPointerTy()),
1528 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001529
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001530 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001531 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001532 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001533 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001534 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1535 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001536 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001537 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001538
1539 CurMBB->addSuccessor(B.TargetBB);
1540 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001541
Dale Johannesen66978ee2009-01-31 02:22:37 +00001542 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001543 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001544 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001545
1546 // Set NextBlock to be the MBB immediately after the current one, if any.
1547 // This is used to avoid emitting unnecessary branches to the next block.
1548 MachineBasicBlock *NextBlock = 0;
1549 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001550 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001551 NextBlock = BBI;
1552
1553 if (NextMBB == NextBlock)
1554 DAG.setRoot(BrAnd);
1555 else
Owen Anderson825b72b2009-08-11 20:47:22 +00001556 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001557 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558}
1559
1560void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1561 // Retrieve successors.
1562 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1563 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1564
Gabor Greifb67e6b32009-01-15 11:10:44 +00001565 const Value *Callee(I.getCalledValue());
1566 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001567 visitInlineAsm(&I);
1568 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001569 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001570
1571 // If the value of the invoke is used outside of its defining block, make it
1572 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001573 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001574
1575 // Update successor info
1576 CurMBB->addSuccessor(Return);
1577 CurMBB->addSuccessor(LandingPad);
1578
1579 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001580 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001581 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582 DAG.getBasicBlock(Return)));
1583}
1584
1585void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1586}
1587
1588/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1589/// small case ranges).
1590bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1591 CaseRecVector& WorkList,
1592 Value* SV,
1593 MachineBasicBlock* Default) {
1594 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001595
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001597 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001598 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001599 return false;
1600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 // Get the MachineFunction which holds the current MBB. This is used when
1602 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001603 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001604
1605 // Figure out which block is immediately after the current one.
1606 MachineBasicBlock *NextBlock = 0;
1607 MachineFunction::iterator BBI = CR.CaseBB;
1608
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001609 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001610 NextBlock = BBI;
1611
1612 // TODO: If any two of the cases has the same destination, and if one value
1613 // is the same as the other, but has one bit unset that the other has set,
1614 // use bit manipulation to do two compares at once. For example:
1615 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001616
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001617 // Rearrange the case blocks so that the last one falls through if possible.
1618 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1619 // The last case block won't fall through into 'NextBlock' if we emit the
1620 // branches in this order. See if rearranging a case value would help.
1621 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1622 if (I->BB == NextBlock) {
1623 std::swap(*I, BackCase);
1624 break;
1625 }
1626 }
1627 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001628
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001629 // Create a CaseBlock record representing a conditional branch to
1630 // the Case's target mbb if the value being switched on SV is equal
1631 // to C.
1632 MachineBasicBlock *CurBlock = CR.CaseBB;
1633 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1634 MachineBasicBlock *FallThrough;
1635 if (I != E-1) {
1636 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1637 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001638
1639 // Put SV in a virtual register to make it available from the new blocks.
1640 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001641 } else {
1642 // If the last case doesn't match, go to the default block.
1643 FallThrough = Default;
1644 }
1645
1646 Value *RHS, *LHS, *MHS;
1647 ISD::CondCode CC;
1648 if (I->High == I->Low) {
1649 // This is just small small case range :) containing exactly 1 case
1650 CC = ISD::SETEQ;
1651 LHS = SV; RHS = I->High; MHS = NULL;
1652 } else {
1653 CC = ISD::SETLE;
1654 LHS = I->Low; MHS = SV; RHS = I->High;
1655 }
1656 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001657
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001658 // If emitting the first comparison, just call visitSwitchCase to emit the
1659 // code into the current block. Otherwise, push the CaseBlock onto the
1660 // vector to be later processed by SDISel, and insert the node's MBB
1661 // before the next MBB.
1662 if (CurBlock == CurMBB)
1663 visitSwitchCase(CB);
1664 else
1665 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001667 CurBlock = FallThrough;
1668 }
1669
1670 return true;
1671}
1672
1673static inline bool areJTsAllowed(const TargetLowering &TLI) {
1674 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001675 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1676 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001677}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001678
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001679static APInt ComputeRange(const APInt &First, const APInt &Last) {
1680 APInt LastExt(Last), FirstExt(First);
1681 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1682 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1683 return (LastExt - FirstExt + 1ULL);
1684}
1685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001686/// handleJTSwitchCase - Emit jumptable for current switch case range
1687bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1688 CaseRecVector& WorkList,
1689 Value* SV,
1690 MachineBasicBlock* Default) {
1691 Case& FrontCase = *CR.Range.first;
1692 Case& BackCase = *(CR.Range.second-1);
1693
Anton Korobeynikov23218582008-12-23 22:25:27 +00001694 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1695 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696
Anton Korobeynikov23218582008-12-23 22:25:27 +00001697 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1699 I!=E; ++I)
1700 TSize += I->size();
1701
1702 if (!areJTsAllowed(TLI) || TSize <= 3)
1703 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001704
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001705 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001706 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707 if (Density < 0.4)
1708 return false;
1709
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001710 DEBUG(errs() << "Lowering jump table\n"
1711 << "First entry: " << First << ". Last entry: " << Last << '\n'
1712 << "Range: " << Range
1713 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001714
1715 // Get the MachineFunction which holds the current MBB. This is used when
1716 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001717 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001718
1719 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001720 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001721 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001722
1723 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1724
1725 // Create a new basic block to hold the code for loading the address
1726 // of the jump table, and jumping to it. Update successor information;
1727 // we will either branch to the default case for the switch, or the jump
1728 // table.
1729 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1730 CurMF->insert(BBI, JumpTableBB);
1731 CR.CaseBB->addSuccessor(Default);
1732 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001733
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001734 // Build a vector of destination BBs, corresponding to each target
1735 // of the jump table. If the value of the jump table slot corresponds to
1736 // a case statement, push the case's BB onto the vector, otherwise, push
1737 // the default BB.
1738 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001739 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001740 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001741 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1742 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1743
1744 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001745 DestBBs.push_back(I->BB);
1746 if (TEI==High)
1747 ++I;
1748 } else {
1749 DestBBs.push_back(Default);
1750 }
1751 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001752
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001753 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001754 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1755 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001756 E = DestBBs.end(); I != E; ++I) {
1757 if (!SuccsHandled[(*I)->getNumber()]) {
1758 SuccsHandled[(*I)->getNumber()] = true;
1759 JumpTableBB->addSuccessor(*I);
1760 }
1761 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001762
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001763 // Create a jump table index for this jump table, or return an existing
1764 // one.
1765 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001766
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001767 // Set the jump table information so that we can codegen it as a second
1768 // MachineBasicBlock
1769 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1770 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1771 if (CR.CaseBB == CurMBB)
1772 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001773
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001774 JTCases.push_back(JumpTableBlock(JTH, JT));
1775
1776 return true;
1777}
1778
1779/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1780/// 2 subtrees.
1781bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1782 CaseRecVector& WorkList,
1783 Value* SV,
1784 MachineBasicBlock* Default) {
1785 // Get the MachineFunction which holds the current MBB. This is used when
1786 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001787 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001788
1789 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001790 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001791 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001792
1793 Case& FrontCase = *CR.Range.first;
1794 Case& BackCase = *(CR.Range.second-1);
1795 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1796
1797 // Size is the number of Cases represented by this range.
1798 unsigned Size = CR.Range.second - CR.Range.first;
1799
Anton Korobeynikov23218582008-12-23 22:25:27 +00001800 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1801 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001802 double FMetric = 0;
1803 CaseItr Pivot = CR.Range.first + Size/2;
1804
1805 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1806 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001807 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001808 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1809 I!=E; ++I)
1810 TSize += I->size();
1811
Anton Korobeynikov23218582008-12-23 22:25:27 +00001812 size_t LSize = FrontCase.size();
1813 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001814 DEBUG(errs() << "Selecting best pivot: \n"
1815 << "First: " << First << ", Last: " << Last <<'\n'
1816 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001817 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1818 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001819 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1820 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001821 APInt Range = ComputeRange(LEnd, RBegin);
1822 assert((Range - 2ULL).isNonNegative() &&
1823 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001824 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1825 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001826 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001827 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001828 DEBUG(errs() <<"=>Step\n"
1829 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1830 << "LDensity: " << LDensity
1831 << ", RDensity: " << RDensity << '\n'
1832 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001833 if (FMetric < Metric) {
1834 Pivot = J;
1835 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001836 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001837 }
1838
1839 LSize += J->size();
1840 RSize -= J->size();
1841 }
1842 if (areJTsAllowed(TLI)) {
1843 // If our case is dense we *really* should handle it earlier!
1844 assert((FMetric > 0) && "Should handle dense range earlier!");
1845 } else {
1846 Pivot = CR.Range.first + Size/2;
1847 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001848
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 CaseRange LHSR(CR.Range.first, Pivot);
1850 CaseRange RHSR(Pivot, CR.Range.second);
1851 Constant *C = Pivot->Low;
1852 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001855 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001856 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001857 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001858 // Pivot's Value, then we can branch directly to the LHS's Target,
1859 // rather than creating a leaf node for it.
1860 if ((LHSR.second - LHSR.first) == 1 &&
1861 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862 cast<ConstantInt>(C)->getValue() ==
1863 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 TrueBB = LHSR.first->BB;
1865 } else {
1866 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1867 CurMF->insert(BBI, TrueBB);
1868 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001869
1870 // Put SV in a virtual register to make it available from the new blocks.
1871 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001872 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001873
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001874 // Similar to the optimization above, if the Value being switched on is
1875 // known to be less than the Constant CR.LT, and the current Case Value
1876 // is CR.LT - 1, then we can branch directly to the target block for
1877 // the current Case Value, rather than emitting a RHS leaf node for it.
1878 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1880 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001881 FalseBB = RHSR.first->BB;
1882 } else {
1883 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1884 CurMF->insert(BBI, FalseBB);
1885 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001886
1887 // Put SV in a virtual register to make it available from the new blocks.
1888 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 }
1890
1891 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001892 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001893 // Otherwise, branch to LHS.
1894 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1895
1896 if (CR.CaseBB == CurMBB)
1897 visitSwitchCase(CB);
1898 else
1899 SwitchCases.push_back(CB);
1900
1901 return true;
1902}
1903
1904/// handleBitTestsSwitchCase - if current case range has few destination and
1905/// range span less, than machine word bitwidth, encode case range into series
1906/// of masks and emit bit tests with these masks.
1907bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1908 CaseRecVector& WorkList,
1909 Value* SV,
1910 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001911 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001912 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001913
1914 Case& FrontCase = *CR.Range.first;
1915 Case& BackCase = *(CR.Range.second-1);
1916
1917 // Get the MachineFunction which holds the current MBB. This is used when
1918 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001919 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001921 // If target does not have legal shift left, do not emit bit tests at all.
1922 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1923 return false;
1924
Anton Korobeynikov23218582008-12-23 22:25:27 +00001925 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001926 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1927 I!=E; ++I) {
1928 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001929 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001930 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001932 // Count unique destinations
1933 SmallSet<MachineBasicBlock*, 4> Dests;
1934 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1935 Dests.insert(I->BB);
1936 if (Dests.size() > 3)
1937 // Don't bother the code below, if there are too much unique destinations
1938 return false;
1939 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001940 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1941 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001943 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001944 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1945 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001946 APInt cmpRange = maxValue - minValue;
1947
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001948 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1949 << "Low bound: " << minValue << '\n'
1950 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001951
1952 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001953 (!(Dests.size() == 1 && numCmps >= 3) &&
1954 !(Dests.size() == 2 && numCmps >= 5) &&
1955 !(Dests.size() >= 3 && numCmps >= 6)))
1956 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001957
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001958 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001959 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1960
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001961 // Optimize the case where all the case values fit in a
1962 // word without having to subtract minValue. In this case,
1963 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001964 if (minValue.isNonNegative() &&
1965 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1966 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001967 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001968 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001969 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001971 CaseBitsVector CasesBits;
1972 unsigned i, count = 0;
1973
1974 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1975 MachineBasicBlock* Dest = I->BB;
1976 for (i = 0; i < count; ++i)
1977 if (Dest == CasesBits[i].BB)
1978 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001979
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001980 if (i == count) {
1981 assert((count < 3) && "Too much destinations to test!");
1982 CasesBits.push_back(CaseBits(0, Dest, 0));
1983 count++;
1984 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001985
1986 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1987 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1988
1989 uint64_t lo = (lowValue - lowBound).getZExtValue();
1990 uint64_t hi = (highValue - lowBound).getZExtValue();
1991
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001992 for (uint64_t j = lo; j <= hi; j++) {
1993 CasesBits[i].Mask |= 1ULL << j;
1994 CasesBits[i].Bits++;
1995 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001996
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001997 }
1998 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001999
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 BitTestInfo BTC;
2001
2002 // Figure out which block is immediately after the current one.
2003 MachineFunction::iterator BBI = CR.CaseBB;
2004 ++BBI;
2005
2006 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2007
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002008 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002009 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002010 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2011 << ", Bits: " << CasesBits[i].Bits
2012 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002013
2014 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2015 CurMF->insert(BBI, CaseBB);
2016 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2017 CaseBB,
2018 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002019
2020 // Put SV in a virtual register to make it available from the new blocks.
2021 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002022 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002023
2024 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002025 -1U, (CR.CaseBB == CurMBB),
2026 CR.CaseBB, Default, BTC);
2027
2028 if (CR.CaseBB == CurMBB)
2029 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002030
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002031 BitTestCases.push_back(BTB);
2032
2033 return true;
2034}
2035
2036
2037/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002038size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002039 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002040 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041
2042 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002043 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002044 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2045 Cases.push_back(Case(SI.getSuccessorValue(i),
2046 SI.getSuccessorValue(i),
2047 SMBB));
2048 }
2049 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2050
2051 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002052 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002053 // Must recompute end() each iteration because it may be
2054 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002055 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2056 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2057 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 MachineBasicBlock* nextBB = J->BB;
2059 MachineBasicBlock* currentBB = I->BB;
2060
2061 // If the two neighboring cases go to the same destination, merge them
2062 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002063 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002064 I->High = J->High;
2065 J = Cases.erase(J);
2066 } else {
2067 I = J++;
2068 }
2069 }
2070
2071 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2072 if (I->Low != I->High)
2073 // A range counts double, since it requires two compares.
2074 ++numCmps;
2075 }
2076
2077 return numCmps;
2078}
2079
Anton Korobeynikov23218582008-12-23 22:25:27 +00002080void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002081 // Figure out which block is immediately after the current one.
2082 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002083
2084 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2085
2086 // If there is only the default destination, branch to it if it is not the
2087 // next basic block. Otherwise, just fall through.
2088 if (SI.getNumOperands() == 2) {
2089 // Update machine-CFG edges.
2090
2091 // If this is not a fall-through branch, emit the branch.
2092 CurMBB->addSuccessor(Default);
2093 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002094 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002095 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002096 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002097 return;
2098 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100 // If there are any non-default case statements, create a vector of Cases
2101 // representing each one, and sort the vector so that we can efficiently
2102 // create a binary search tree from them.
2103 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002104 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002105 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2106 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002107 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002108
2109 // Get the Value to be switched on and default basic blocks, which will be
2110 // inserted into CaseBlock records, representing basic blocks in the binary
2111 // search tree.
2112 Value *SV = SI.getOperand(0);
2113
2114 // Push the initial CaseRec onto the worklist
2115 CaseRecVector WorkList;
2116 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2117
2118 while (!WorkList.empty()) {
2119 // Grab a record representing a case range to process off the worklist
2120 CaseRec CR = WorkList.back();
2121 WorkList.pop_back();
2122
2123 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2124 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002126 // If the range has few cases (two or less) emit a series of specific
2127 // tests.
2128 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2129 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002130
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002131 // If the switch has more than 5 blocks, and at least 40% dense, and the
2132 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002133 // lowering the switch to a binary tree of conditional branches.
2134 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2135 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002136
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002137 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2138 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2139 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2140 }
2141}
2142
Chris Lattnerab21db72009-10-28 00:19:10 +00002143void SelectionDAGLowering::visitIndirectBr(IndirectBrInst &I) {
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002144 // Update machine-CFG edges.
2145 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2146 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2147
Dan Gohman64825152009-10-27 21:56:26 +00002148 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2149 MVT::Other, getControlRoot(),
2150 getValue(I.getAddress())));
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002151}
2152
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002153
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002154void SelectionDAGLowering::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002155 // -0.0 - X --> fneg
2156 const Type *Ty = I.getType();
2157 if (isa<VectorType>(Ty)) {
2158 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2159 const VectorType *DestTy = cast<VectorType>(I.getType());
2160 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002161 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002162 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002163 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002164 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002166 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002167 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002168 return;
2169 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002170 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002171 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002172 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002173 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002174 SDValue Op2 = getValue(I.getOperand(1));
2175 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2176 Op2.getValueType(), Op2));
2177 return;
2178 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002179
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002180 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002181}
2182
2183void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2184 SDValue Op1 = getValue(I.getOperand(0));
2185 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002186
Scott Michelfdc40a02009-02-17 22:15:04 +00002187 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002188 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002189}
2190
2191void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2192 SDValue Op1 = getValue(I.getOperand(0));
2193 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002194 if (!isa<VectorType>(I.getType()) &&
2195 Op2.getValueType() != TLI.getShiftAmountTy()) {
2196 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002197 EVT PTy = TLI.getPointerTy();
2198 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002199 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002200 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2201 TLI.getShiftAmountTy(), Op2);
2202 // If the operand is larger than the shift count type but the shift
2203 // count type has enough bits to represent any shift value, truncate
2204 // it now. This is a common case and it exposes the truncate to
2205 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002206 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002207 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2208 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2209 TLI.getShiftAmountTy(), Op2);
2210 // Otherwise we'll need to temporarily settle for some other
2211 // convenient type; type legalization will make adjustments as
2212 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002213 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002214 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002215 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002216 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002217 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002218 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002219 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002220
Scott Michelfdc40a02009-02-17 22:15:04 +00002221 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002222 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002223}
2224
2225void SelectionDAGLowering::visitICmp(User &I) {
2226 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2227 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2228 predicate = IC->getPredicate();
2229 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2230 predicate = ICmpInst::Predicate(IC->getPredicate());
2231 SDValue Op1 = getValue(I.getOperand(0));
2232 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002233 ISD::CondCode Opcode = getICmpCondCode(predicate);
Chris Lattner9800e842009-07-07 22:41:32 +00002234
Owen Andersone50ed302009-08-10 22:56:29 +00002235 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002236 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002237}
2238
2239void SelectionDAGLowering::visitFCmp(User &I) {
2240 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2241 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2242 predicate = FC->getPredicate();
2243 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2244 predicate = FCmpInst::Predicate(FC->getPredicate());
2245 SDValue Op1 = getValue(I.getOperand(0));
2246 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002247 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002248 EVT DestVT = TLI.getValueType(I.getType());
Chris Lattner9800e842009-07-07 22:41:32 +00002249 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002250}
2251
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002252void SelectionDAGLowering::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002253 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002254 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2255 unsigned NumValues = ValueVTs.size();
2256 if (NumValues != 0) {
2257 SmallVector<SDValue, 4> Values(NumValues);
2258 SDValue Cond = getValue(I.getOperand(0));
2259 SDValue TrueVal = getValue(I.getOperand(1));
2260 SDValue FalseVal = getValue(I.getOperand(2));
2261
2262 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002263 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002264 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002265 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2266 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2267
Scott Michelfdc40a02009-02-17 22:15:04 +00002268 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002269 DAG.getVTList(&ValueVTs[0], NumValues),
2270 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002271 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272}
2273
2274
2275void SelectionDAGLowering::visitTrunc(User &I) {
2276 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2277 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002278 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002279 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002280}
2281
2282void SelectionDAGLowering::visitZExt(User &I) {
2283 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2284 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2285 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002286 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002287 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002288}
2289
2290void SelectionDAGLowering::visitSExt(User &I) {
2291 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2292 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2293 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002294 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002295 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002296}
2297
2298void SelectionDAGLowering::visitFPTrunc(User &I) {
2299 // FPTrunc is never a no-op cast, no need to check
2300 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002301 EVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002302 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002303 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002304}
2305
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002306void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002307 // FPTrunc is never a no-op cast, no need to check
2308 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002309 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002310 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002311}
2312
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002313void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314 // FPToUI is never a no-op cast, no need to check
2315 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002316 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002317 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002318}
2319
2320void SelectionDAGLowering::visitFPToSI(User &I) {
2321 // FPToSI is never a no-op cast, no need to check
2322 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002323 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002324 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002325}
2326
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002327void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328 // UIToFP is never a no-op cast, no need to check
2329 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002330 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002331 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002332}
2333
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002334void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002335 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002336 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002337 EVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002338 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002339}
2340
2341void SelectionDAGLowering::visitPtrToInt(User &I) {
2342 // What to do depends on the size of the integer and the size of the pointer.
2343 // We can either truncate, zero extend, or no-op, accordingly.
2344 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002345 EVT SrcVT = N.getValueType();
2346 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002347 SDValue Result = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002348 setValue(&I, Result);
2349}
2350
2351void SelectionDAGLowering::visitIntToPtr(User &I) {
2352 // What to do depends on the size of the integer and the size of the pointer.
2353 // We can either truncate, zero extend, or no-op, accordingly.
2354 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002355 EVT SrcVT = N.getValueType();
2356 EVT DestVT = TLI.getValueType(I.getType());
Duncan Sands3a66a682009-10-13 21:04:12 +00002357 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002358}
2359
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002360void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002361 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002362 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002363
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002364 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002365 // is either a BIT_CONVERT or a no-op.
2366 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002367 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002368 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002369 else
2370 setValue(&I, N); // noop cast.
2371}
2372
2373void SelectionDAGLowering::visitInsertElement(User &I) {
2374 SDValue InVec = getValue(I.getOperand(0));
2375 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002376 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002377 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002378 getValue(I.getOperand(2)));
2379
Scott Michelfdc40a02009-02-17 22:15:04 +00002380 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002381 TLI.getValueType(I.getType()),
2382 InVec, InVal, InIdx));
2383}
2384
2385void SelectionDAGLowering::visitExtractElement(User &I) {
2386 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002387 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002388 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002389 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002390 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002391 TLI.getValueType(I.getType()), InVec, InIdx));
2392}
2393
Mon P Wangaeb06d22008-11-10 04:46:22 +00002394
2395// Utility for visitShuffleVector - Returns true if the mask is mask starting
2396// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002397static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2398 unsigned MaskNumElts = Mask.size();
2399 for (unsigned i = 0; i != MaskNumElts; ++i)
2400 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002401 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002402 return true;
2403}
2404
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002405void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002406 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002407 SDValue Src1 = getValue(I.getOperand(0));
2408 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002409
Nate Begeman9008ca62009-04-27 18:41:29 +00002410 // Convert the ConstantVector mask operand into an array of ints, with -1
2411 // representing undef values.
2412 SmallVector<Constant*, 8> MaskElts;
Owen Anderson001dbfe2009-07-16 18:04:31 +00002413 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2414 MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002415 unsigned MaskNumElts = MaskElts.size();
2416 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002417 if (isa<UndefValue>(MaskElts[i]))
2418 Mask.push_back(-1);
2419 else
2420 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2421 }
2422
Owen Andersone50ed302009-08-10 22:56:29 +00002423 EVT VT = TLI.getValueType(I.getType());
2424 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002425 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002426
Mon P Wangc7849c22008-11-16 05:06:27 +00002427 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002428 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2429 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002430 return;
2431 }
2432
2433 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002434 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2435 // Mask is longer than the source vectors and is a multiple of the source
2436 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002437 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002438 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2439 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002440 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002441 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002442 return;
2443 }
2444
Mon P Wangc7849c22008-11-16 05:06:27 +00002445 // Pad both vectors with undefs to make them the same length as the mask.
2446 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002447 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2448 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002449 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002450
Nate Begeman9008ca62009-04-27 18:41:29 +00002451 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2452 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002453 MOps1[0] = Src1;
2454 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002455
2456 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2457 getCurDebugLoc(), VT,
2458 &MOps1[0], NumConcat);
2459 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2460 getCurDebugLoc(), VT,
2461 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002462
Mon P Wangaeb06d22008-11-10 04:46:22 +00002463 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002464 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002465 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002466 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002467 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002468 MappedOps.push_back(Idx);
2469 else
2470 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002471 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002472 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2473 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002474 return;
2475 }
2476
Mon P Wangc7849c22008-11-16 05:06:27 +00002477 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002478 // Analyze the access pattern of the vector to see if we can extract
2479 // two subvectors and do the shuffle. The analysis is done by calculating
2480 // the range of elements the mask access on both vectors.
2481 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2482 int MaxRange[2] = {-1, -1};
2483
Nate Begeman5a5ca152009-04-29 05:20:52 +00002484 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002485 int Idx = Mask[i];
2486 int Input = 0;
2487 if (Idx < 0)
2488 continue;
2489
Nate Begeman5a5ca152009-04-29 05:20:52 +00002490 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002491 Input = 1;
2492 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002493 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002494 if (Idx > MaxRange[Input])
2495 MaxRange[Input] = Idx;
2496 if (Idx < MinRange[Input])
2497 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002498 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002499
Mon P Wangc7849c22008-11-16 05:06:27 +00002500 // Check if the access is smaller than the vector size and can we find
2501 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002502 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002503 int StartIdx[2]; // StartIdx to extract from
2504 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002505 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002506 RangeUse[Input] = 0; // Unused
2507 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002508 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002509 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002510 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002511 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002512 RangeUse[Input] = 1; // Extract from beginning of the vector
2513 StartIdx[Input] = 0;
2514 } else {
2515 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002516 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002517 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002518 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002519 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002520 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002521 }
2522
Bill Wendling636e2582009-08-21 18:16:06 +00002523 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002524 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002525 return;
2526 }
2527 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2528 // Extract appropriate subvector and generate a vector shuffle
2529 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002530 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002531 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002532 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002533 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002534 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002535 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002536 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002537 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002538 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002539 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002540 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002541 int Idx = Mask[i];
2542 if (Idx < 0)
2543 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002544 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002545 MappedOps.push_back(Idx - StartIdx[0]);
2546 else
2547 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002548 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002549 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2550 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002551 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002552 }
2553 }
2554
Mon P Wangc7849c22008-11-16 05:06:27 +00002555 // We can't use either concat vectors or extract subvectors so fall back to
2556 // replacing the shuffle with extract and build vector.
2557 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002558 EVT EltVT = VT.getVectorElementType();
2559 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002560 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002561 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002562 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002563 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002564 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002565 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002566 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002567 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002568 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002569 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002570 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002571 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002572 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002573 }
2574 }
Evan Chenga87008d2009-02-25 22:49:59 +00002575 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2576 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002577}
2578
2579void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2580 const Value *Op0 = I.getOperand(0);
2581 const Value *Op1 = I.getOperand(1);
2582 const Type *AggTy = I.getType();
2583 const Type *ValTy = Op1->getType();
2584 bool IntoUndef = isa<UndefValue>(Op0);
2585 bool FromUndef = isa<UndefValue>(Op1);
2586
2587 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2588 I.idx_begin(), I.idx_end());
2589
Owen Andersone50ed302009-08-10 22:56:29 +00002590 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002591 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002592 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002593 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2594
2595 unsigned NumAggValues = AggValueVTs.size();
2596 unsigned NumValValues = ValValueVTs.size();
2597 SmallVector<SDValue, 4> Values(NumAggValues);
2598
2599 SDValue Agg = getValue(Op0);
2600 SDValue Val = getValue(Op1);
2601 unsigned i = 0;
2602 // Copy the beginning value(s) from the original aggregate.
2603 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002604 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002605 SDValue(Agg.getNode(), Agg.getResNo() + i);
2606 // Copy values from the inserted value(s).
2607 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002608 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002609 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2610 // Copy remaining value(s) from the original aggregate.
2611 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002612 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002613 SDValue(Agg.getNode(), Agg.getResNo() + i);
2614
Scott Michelfdc40a02009-02-17 22:15:04 +00002615 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002616 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2617 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002618}
2619
2620void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2621 const Value *Op0 = I.getOperand(0);
2622 const Type *AggTy = Op0->getType();
2623 const Type *ValTy = I.getType();
2624 bool OutOfUndef = isa<UndefValue>(Op0);
2625
2626 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2627 I.idx_begin(), I.idx_end());
2628
Owen Andersone50ed302009-08-10 22:56:29 +00002629 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002630 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2631
2632 unsigned NumValValues = ValValueVTs.size();
2633 SmallVector<SDValue, 4> Values(NumValValues);
2634
2635 SDValue Agg = getValue(Op0);
2636 // Copy out the selected value(s).
2637 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2638 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002639 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002640 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002641 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642
Scott Michelfdc40a02009-02-17 22:15:04 +00002643 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002644 DAG.getVTList(&ValValueVTs[0], NumValValues),
2645 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002646}
2647
2648
2649void SelectionDAGLowering::visitGetElementPtr(User &I) {
2650 SDValue N = getValue(I.getOperand(0));
2651 const Type *Ty = I.getOperand(0)->getType();
2652
2653 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2654 OI != E; ++OI) {
2655 Value *Idx = *OI;
2656 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2657 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2658 if (Field) {
2659 // N = N + Offset
2660 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002661 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002662 DAG.getIntPtrConstant(Offset));
2663 }
2664 Ty = StTy->getElementType(Field);
2665 } else {
2666 Ty = cast<SequentialType>(Ty)->getElementType();
2667
2668 // If this is a constant subscript, handle it quickly.
2669 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2670 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002671 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002672 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002673 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002674 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002675 unsigned PtrBits = PTy.getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002676 if (PtrBits < 64) {
2677 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2678 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002679 DAG.getConstant(Offs, MVT::i64));
Evan Cheng65b52df2009-02-09 21:01:06 +00002680 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002681 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002682 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002683 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002684 continue;
2685 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002686
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002688 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2689 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002690 SDValue IdxN = getValue(Idx);
2691
2692 // If the index is smaller or larger than intptr_t, truncate or extend
2693 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002694 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695
2696 // If this is a multiply by a power of two, turn it into a shl
2697 // immediately. This is a very common case.
2698 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002699 if (ElementSize.isPowerOf2()) {
2700 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002701 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002702 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002703 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002704 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002705 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002706 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002707 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002708 }
2709 }
2710
Scott Michelfdc40a02009-02-17 22:15:04 +00002711 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002712 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002713 }
2714 }
2715 setValue(&I, N);
2716}
2717
2718void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2719 // If this is a fixed sized alloca in the entry block of the function,
2720 // allocate it statically on the stack.
2721 if (FuncInfo.StaticAllocaMap.count(&I))
2722 return; // getValue will auto-populate this.
2723
2724 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002725 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002726 unsigned Align =
2727 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2728 I.getAlignment());
2729
2730 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002731
2732 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2733 AllocSize,
2734 DAG.getConstant(TySize, AllocSize.getValueType()));
2735
2736
2737
Owen Andersone50ed302009-08-10 22:56:29 +00002738 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002739 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002741 // Handle alignment. If the requested alignment is less than or equal to
2742 // the stack alignment, ignore it. If the size is greater than or equal to
2743 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2744 unsigned StackAlign =
2745 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2746 if (Align <= StackAlign)
2747 Align = 0;
2748
2749 // Round the size of the allocation up to the stack alignment size
2750 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002751 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002752 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002753 DAG.getIntPtrConstant(StackAlign-1));
2754 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002755 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002756 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002757 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2758
2759 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002760 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002761 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002762 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002763 setValue(&I, DSA);
2764 DAG.setRoot(DSA.getValue(1));
2765
2766 // Inform the Frame Information that we have just allocated a variable-sized
2767 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002768 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002769}
2770
2771void SelectionDAGLowering::visitLoad(LoadInst &I) {
2772 const Value *SV = I.getOperand(0);
2773 SDValue Ptr = getValue(SV);
2774
2775 const Type *Ty = I.getType();
2776 bool isVolatile = I.isVolatile();
2777 unsigned Alignment = I.getAlignment();
2778
Owen Andersone50ed302009-08-10 22:56:29 +00002779 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002780 SmallVector<uint64_t, 4> Offsets;
2781 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2782 unsigned NumValues = ValueVTs.size();
2783 if (NumValues == 0)
2784 return;
2785
2786 SDValue Root;
2787 bool ConstantMemory = false;
2788 if (I.isVolatile())
2789 // Serialize volatile loads with other side effects.
2790 Root = getRoot();
2791 else if (AA->pointsToConstantMemory(SV)) {
2792 // Do not serialize (non-volatile) loads of constant memory with anything.
2793 Root = DAG.getEntryNode();
2794 ConstantMemory = true;
2795 } else {
2796 // Do not serialize non-volatile loads against each other.
2797 Root = DAG.getRoot();
2798 }
2799
2800 SmallVector<SDValue, 4> Values(NumValues);
2801 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002802 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002803 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002804 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Nate Begemane6798372009-09-15 00:13:12 +00002805 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2806 PtrVT, Ptr,
2807 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002808 SV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002809 Values[i] = L;
2810 Chains[i] = L.getValue(1);
2811 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002812
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002813 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002814 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002815 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002816 &Chains[0], NumValues);
2817 if (isVolatile)
2818 DAG.setRoot(Chain);
2819 else
2820 PendingLoads.push_back(Chain);
2821 }
2822
Scott Michelfdc40a02009-02-17 22:15:04 +00002823 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002824 DAG.getVTList(&ValueVTs[0], NumValues),
2825 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002826}
2827
2828
2829void SelectionDAGLowering::visitStore(StoreInst &I) {
2830 Value *SrcV = I.getOperand(0);
2831 Value *PtrV = I.getOperand(1);
2832
Owen Andersone50ed302009-08-10 22:56:29 +00002833 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002834 SmallVector<uint64_t, 4> Offsets;
2835 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2836 unsigned NumValues = ValueVTs.size();
2837 if (NumValues == 0)
2838 return;
2839
2840 // Get the lowered operands. Note that we do this after
2841 // checking if NumResults is zero, because with zero results
2842 // the operands won't have values in the map.
2843 SDValue Src = getValue(SrcV);
2844 SDValue Ptr = getValue(PtrV);
2845
2846 SDValue Root = getRoot();
2847 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002848 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002849 bool isVolatile = I.isVolatile();
2850 unsigned Alignment = I.getAlignment();
2851 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002852 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002853 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002854 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002855 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002856 DAG.getConstant(Offsets[i], PtrVT)),
Nate Begeman101b25c2009-09-15 19:05:41 +00002857 PtrV, Offsets[i], isVolatile, Alignment);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002858
Scott Michelfdc40a02009-02-17 22:15:04 +00002859 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002860 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002861}
2862
2863/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2864/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002865void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002866 unsigned Intrinsic) {
2867 bool HasChain = !I.doesNotAccessMemory();
2868 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2869
2870 // Build the operand list.
2871 SmallVector<SDValue, 8> Ops;
2872 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2873 if (OnlyLoad) {
2874 // We don't need to serialize loads against other loads.
2875 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002876 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002877 Ops.push_back(getRoot());
2878 }
2879 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002880
2881 // Info is set by getTgtMemInstrinsic
2882 TargetLowering::IntrinsicInfo Info;
2883 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2884
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002885 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002886 if (!IsTgtIntrinsic)
2887 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002888
2889 // Add all operands of the call to the operand list.
2890 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2891 SDValue Op = getValue(I.getOperand(i));
2892 assert(TLI.isTypeLegal(Op.getValueType()) &&
2893 "Intrinsic uses a non-legal type?");
2894 Ops.push_back(Op);
2895 }
2896
Owen Andersone50ed302009-08-10 22:56:29 +00002897 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002898 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2899#ifndef NDEBUG
2900 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2901 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2902 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002903 }
Bob Wilson8d919552009-07-31 22:41:21 +00002904#endif // NDEBUG
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002905 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002906 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002907
Bob Wilson8d919552009-07-31 22:41:21 +00002908 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002909
2910 // Create the node.
2911 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002912 if (IsTgtIntrinsic) {
2913 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002914 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002915 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002916 Info.memVT, Info.ptrVal, Info.offset,
2917 Info.align, Info.vol,
2918 Info.readMem, Info.writeMem);
2919 }
2920 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002921 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002922 VTs, &Ops[0], Ops.size());
Owen Anderson1d0be152009-08-13 21:58:54 +00002923 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002924 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002925 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002926 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002927 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002928 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002929
2930 if (HasChain) {
2931 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2932 if (OnlyLoad)
2933 PendingLoads.push_back(Chain);
2934 else
2935 DAG.setRoot(Chain);
2936 }
Owen Anderson1d0be152009-08-13 21:58:54 +00002937 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002938 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00002939 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002940 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002941 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002942 setValue(&I, Result);
2943 }
2944}
2945
2946/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2947static GlobalVariable *ExtractTypeInfo(Value *V) {
2948 V = V->stripPointerCasts();
2949 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2950 assert ((GV || isa<ConstantPointerNull>(V)) &&
2951 "TypeInfo must be a global variable or NULL");
2952 return GV;
2953}
2954
2955namespace llvm {
2956
2957/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2958/// call, and add them to the specified machine basic block.
2959void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2960 MachineBasicBlock *MBB) {
2961 // Inform the MachineModuleInfo of the personality for this landing pad.
2962 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2963 assert(CE->getOpcode() == Instruction::BitCast &&
2964 isa<Function>(CE->getOperand(0)) &&
2965 "Personality should be a function");
2966 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2967
2968 // Gather all the type infos for this landing pad and pass them along to
2969 // MachineModuleInfo.
2970 std::vector<GlobalVariable *> TyInfo;
2971 unsigned N = I.getNumOperands();
2972
2973 for (unsigned i = N - 1; i > 2; --i) {
2974 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2975 unsigned FilterLength = CI->getZExtValue();
2976 unsigned FirstCatch = i + FilterLength + !FilterLength;
2977 assert (FirstCatch <= N && "Invalid filter length");
2978
2979 if (FirstCatch < N) {
2980 TyInfo.reserve(N - FirstCatch);
2981 for (unsigned j = FirstCatch; j < N; ++j)
2982 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2983 MMI->addCatchTypeInfo(MBB, TyInfo);
2984 TyInfo.clear();
2985 }
2986
2987 if (!FilterLength) {
2988 // Cleanup.
2989 MMI->addCleanup(MBB);
2990 } else {
2991 // Filter.
2992 TyInfo.reserve(FilterLength - 1);
2993 for (unsigned j = i + 1; j < FirstCatch; ++j)
2994 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2995 MMI->addFilterTypeInfo(MBB, TyInfo);
2996 TyInfo.clear();
2997 }
2998
2999 N = i;
3000 }
3001 }
3002
3003 if (N > 3) {
3004 TyInfo.reserve(N - 3);
3005 for (unsigned j = 3; j < N; ++j)
3006 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3007 MMI->addCatchTypeInfo(MBB, TyInfo);
3008 }
3009}
3010
3011}
3012
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003013/// GetSignificand - Get the significand and build it into a floating-point
3014/// number with exponent of 1:
3015///
3016/// Op = (Op & 0x007fffff) | 0x3f800000;
3017///
3018/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003019static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003020GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003021 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3022 DAG.getConstant(0x007fffff, MVT::i32));
3023 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3024 DAG.getConstant(0x3f800000, MVT::i32));
3025 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003026}
3027
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003028/// GetExponent - Get the exponent:
3029///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003030/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003031///
3032/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003033static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003034GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3035 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003036 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3037 DAG.getConstant(0x7f800000, MVT::i32));
3038 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003039 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003040 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3041 DAG.getConstant(127, MVT::i32));
3042 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003043}
3044
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003045/// getF32Constant - Get 32-bit floating point constant.
3046static SDValue
3047getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003048 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003049}
3050
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003051/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003052/// visitIntrinsicCall: I is a call instruction
3053/// Op is the associated NodeType for I
3054const char *
3055SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003056 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003057 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003058 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003059 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003060 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003061 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003062 getValue(I.getOperand(2)),
3063 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003064 setValue(&I, L);
3065 DAG.setRoot(L.getValue(1));
3066 return 0;
3067}
3068
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003069// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003070const char *
3071SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003072 SDValue Op1 = getValue(I.getOperand(1));
3073 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003074
Owen Anderson825b72b2009-08-11 20:47:22 +00003075 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Dan Gohmanfc166572009-04-09 23:54:40 +00003076 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003077
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003078 setValue(&I, Result);
3079 return 0;
3080}
Bill Wendling74c37652008-12-09 22:08:41 +00003081
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003082/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3083/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003084void
3085SelectionDAGLowering::visitExp(CallInst &I) {
3086 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003087 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003088
Owen Anderson825b72b2009-08-11 20:47:22 +00003089 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003090 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3091 SDValue Op = getValue(I.getOperand(1));
3092
3093 // Put the exponent in the right bit position for later addition to the
3094 // final result:
3095 //
3096 // #define LOG2OFe 1.4426950f
3097 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003098 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003099 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003100 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003101
3102 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003103 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3104 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003105
3106 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003107 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003108 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003109
3110 if (LimitFloatPrecision <= 6) {
3111 // For floating-point precision of 6:
3112 //
3113 // TwoToFractionalPartOfX =
3114 // 0.997535578f +
3115 // (0.735607626f + 0.252464424f * x) * x;
3116 //
3117 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003118 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003119 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003120 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003121 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003122 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3123 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003124 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003125 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003126
3127 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003128 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003129 TwoToFracPartOfX, IntegerPartOfX);
3130
Owen Anderson825b72b2009-08-11 20:47:22 +00003131 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003132 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3133 // For floating-point precision of 12:
3134 //
3135 // TwoToFractionalPartOfX =
3136 // 0.999892986f +
3137 // (0.696457318f +
3138 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3139 //
3140 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003141 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003142 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003143 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003144 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003145 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3146 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003147 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003148 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3149 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003150 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003151 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003152
3153 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003154 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003155 TwoToFracPartOfX, IntegerPartOfX);
3156
Owen Anderson825b72b2009-08-11 20:47:22 +00003157 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003158 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3159 // For floating-point precision of 18:
3160 //
3161 // TwoToFractionalPartOfX =
3162 // 0.999999982f +
3163 // (0.693148872f +
3164 // (0.240227044f +
3165 // (0.554906021e-1f +
3166 // (0.961591928e-2f +
3167 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3168 //
3169 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003171 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003172 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003173 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003174 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3175 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003176 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003177 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3178 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003179 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003180 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3181 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003182 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003183 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3184 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003185 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003186 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3187 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003188 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003189 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003190 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003191
3192 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003193 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003194 TwoToFracPartOfX, IntegerPartOfX);
3195
Owen Anderson825b72b2009-08-11 20:47:22 +00003196 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003197 }
3198 } else {
3199 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003200 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003201 getValue(I.getOperand(1)).getValueType(),
3202 getValue(I.getOperand(1)));
3203 }
3204
Dale Johannesen59e577f2008-09-05 18:38:42 +00003205 setValue(&I, result);
3206}
3207
Bill Wendling39150252008-09-09 20:39:27 +00003208/// visitLog - Lower a log intrinsic. Handles the special sequences for
3209/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003210void
3211SelectionDAGLowering::visitLog(CallInst &I) {
3212 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003213 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003214
Owen Anderson825b72b2009-08-11 20:47:22 +00003215 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003216 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3217 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003218 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003219
3220 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003221 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003222 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003223 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003224
3225 // Get the significand and build it into a floating-point number with
3226 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003227 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003228
3229 if (LimitFloatPrecision <= 6) {
3230 // For floating-point precision of 6:
3231 //
3232 // LogofMantissa =
3233 // -1.1609546f +
3234 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003235 //
Bill Wendling39150252008-09-09 20:39:27 +00003236 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003237 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003238 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003239 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003240 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003241 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3242 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003243 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003244
Scott Michelfdc40a02009-02-17 22:15:04 +00003245 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003246 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003247 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3248 // For floating-point precision of 12:
3249 //
3250 // LogOfMantissa =
3251 // -1.7417939f +
3252 // (2.8212026f +
3253 // (-1.4699568f +
3254 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3255 //
3256 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003257 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003259 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003260 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003261 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3262 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003263 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003264 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3265 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003267 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3268 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003269 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003270
Scott Michelfdc40a02009-02-17 22:15:04 +00003271 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003272 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003273 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3274 // For floating-point precision of 18:
3275 //
3276 // LogOfMantissa =
3277 // -2.1072184f +
3278 // (4.2372794f +
3279 // (-3.7029485f +
3280 // (2.2781945f +
3281 // (-0.87823314f +
3282 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3283 //
3284 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003285 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003286 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003287 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003288 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003289 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3290 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003291 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003292 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3293 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003294 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003295 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3296 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003297 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003298 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3299 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003300 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003301 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3302 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003303 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003304
Scott Michelfdc40a02009-02-17 22:15:04 +00003305 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003306 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003307 }
3308 } else {
3309 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003310 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003311 getValue(I.getOperand(1)).getValueType(),
3312 getValue(I.getOperand(1)));
3313 }
3314
Dale Johannesen59e577f2008-09-05 18:38:42 +00003315 setValue(&I, result);
3316}
3317
Bill Wendling3eb59402008-09-09 00:28:24 +00003318/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3319/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003320void
3321SelectionDAGLowering::visitLog2(CallInst &I) {
3322 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003323 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003324
Owen Anderson825b72b2009-08-11 20:47:22 +00003325 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003326 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3327 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003328 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003329
Bill Wendling39150252008-09-09 20:39:27 +00003330 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003331 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003332
3333 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003334 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003335 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003336
Bill Wendling3eb59402008-09-09 00:28:24 +00003337 // Different possible minimax approximations of significand in
3338 // floating-point for various degrees of accuracy over [1,2].
3339 if (LimitFloatPrecision <= 6) {
3340 // For floating-point precision of 6:
3341 //
3342 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3343 //
3344 // error 0.0049451742, which is more than 7 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, 0xbeb08fe0));
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, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3350 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003352
Scott Michelfdc40a02009-02-17 22:15:04 +00003353 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003354 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003355 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3356 // For floating-point precision of 12:
3357 //
3358 // Log2ofMantissa =
3359 // -2.51285454f +
3360 // (4.07009056f +
3361 // (-2.12067489f +
3362 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003363 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003364 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003365 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003366 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003367 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003368 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3370 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003371 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003372 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3373 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003374 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003375 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3376 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003377 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003378
Scott Michelfdc40a02009-02-17 22:15:04 +00003379 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003380 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003381 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3382 // For floating-point precision of 18:
3383 //
3384 // Log2ofMantissa =
3385 // -3.0400495f +
3386 // (6.1129976f +
3387 // (-5.3420409f +
3388 // (3.2865683f +
3389 // (-1.2669343f +
3390 // (0.27515199f -
3391 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3392 //
3393 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003394 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003395 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003396 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003397 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003398 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3399 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003400 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003401 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3402 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003403 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003404 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3405 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003406 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003407 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3408 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003409 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003410 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3411 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003412 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003413
Scott Michelfdc40a02009-02-17 22:15:04 +00003414 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003415 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003416 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003417 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003418 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003419 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003420 getValue(I.getOperand(1)).getValueType(),
3421 getValue(I.getOperand(1)));
3422 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003423
Dale Johannesen59e577f2008-09-05 18:38:42 +00003424 setValue(&I, result);
3425}
3426
Bill Wendling3eb59402008-09-09 00:28:24 +00003427/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3428/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003429void
3430SelectionDAGLowering::visitLog10(CallInst &I) {
3431 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003432 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003433
Owen Anderson825b72b2009-08-11 20:47:22 +00003434 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003435 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3436 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003437 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003438
Bill Wendling39150252008-09-09 20:39:27 +00003439 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003440 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003441 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003442 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003443
3444 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003445 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003446 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003447
3448 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003449 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003450 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003451 // Log10ofMantissa =
3452 // -0.50419619f +
3453 // (0.60948995f - 0.10380950f * x) * x;
3454 //
3455 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003456 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003457 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003458 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003459 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003460 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3461 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003462 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003463
Scott Michelfdc40a02009-02-17 22:15:04 +00003464 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003465 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003466 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3467 // For floating-point precision of 12:
3468 //
3469 // Log10ofMantissa =
3470 // -0.64831180f +
3471 // (0.91751397f +
3472 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3473 //
3474 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003475 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003476 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003477 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003478 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003479 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3480 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003481 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003482 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3483 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003484 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003485
Scott Michelfdc40a02009-02-17 22:15:04 +00003486 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003487 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003488 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003489 // For floating-point precision of 18:
3490 //
3491 // Log10ofMantissa =
3492 // -0.84299375f +
3493 // (1.5327582f +
3494 // (-1.0688956f +
3495 // (0.49102474f +
3496 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3497 //
3498 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003499 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003500 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003501 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003502 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003503 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3504 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003505 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003506 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3507 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003508 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003509 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3510 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003512 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3513 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003514 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003515
Scott Michelfdc40a02009-02-17 22:15:04 +00003516 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003517 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003518 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003519 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003520 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003521 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003522 getValue(I.getOperand(1)).getValueType(),
3523 getValue(I.getOperand(1)));
3524 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003525
Dale Johannesen59e577f2008-09-05 18:38:42 +00003526 setValue(&I, result);
3527}
3528
Bill Wendlinge10c8142008-09-09 22:39:21 +00003529/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3530/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003531void
3532SelectionDAGLowering::visitExp2(CallInst &I) {
3533 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003534 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003535
Owen Anderson825b72b2009-08-11 20:47:22 +00003536 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003537 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3538 SDValue Op = getValue(I.getOperand(1));
3539
Owen Anderson825b72b2009-08-11 20:47:22 +00003540 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003541
3542 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003543 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3544 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003545
3546 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003547 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003548 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003549
3550 if (LimitFloatPrecision <= 6) {
3551 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003552 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003553 // TwoToFractionalPartOfX =
3554 // 0.997535578f +
3555 // (0.735607626f + 0.252464424f * x) * x;
3556 //
3557 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003558 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003559 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003560 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003561 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003562 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3563 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003564 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003565 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003566 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003567 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003568
Scott Michelfdc40a02009-02-17 22:15:04 +00003569 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003570 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003571 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3572 // For floating-point precision of 12:
3573 //
3574 // TwoToFractionalPartOfX =
3575 // 0.999892986f +
3576 // (0.696457318f +
3577 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3578 //
3579 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003580 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003581 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003582 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003583 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003584 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3585 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003586 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003587 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3588 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003589 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003590 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003591 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003592 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003593
Scott Michelfdc40a02009-02-17 22:15:04 +00003594 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003595 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003596 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3597 // For floating-point precision of 18:
3598 //
3599 // TwoToFractionalPartOfX =
3600 // 0.999999982f +
3601 // (0.693148872f +
3602 // (0.240227044f +
3603 // (0.554906021e-1f +
3604 // (0.961591928e-2f +
3605 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3606 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003607 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003608 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003609 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003610 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003611 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3612 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003613 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003614 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3615 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003616 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003617 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3618 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003619 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003620 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3621 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003622 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003623 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3624 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003625 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003626 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003627 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003628 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003629
Scott Michelfdc40a02009-02-17 22:15:04 +00003630 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003631 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003632 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003633 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003634 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003635 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003636 getValue(I.getOperand(1)).getValueType(),
3637 getValue(I.getOperand(1)));
3638 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003639
Dale Johannesen601d3c02008-09-05 01:48:15 +00003640 setValue(&I, result);
3641}
3642
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003643/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3644/// limited-precision mode with x == 10.0f.
3645void
3646SelectionDAGLowering::visitPow(CallInst &I) {
3647 SDValue result;
3648 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003649 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003650 bool IsExp10 = false;
3651
Owen Anderson825b72b2009-08-11 20:47:22 +00003652 if (getValue(Val).getValueType() == MVT::f32 &&
3653 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003654 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3655 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3656 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3657 APFloat Ten(10.0f);
3658 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3659 }
3660 }
3661 }
3662
3663 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3664 SDValue Op = getValue(I.getOperand(2));
3665
3666 // Put the exponent in the right bit position for later addition to the
3667 // final result:
3668 //
3669 // #define LOG2OF10 3.3219281f
3670 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003671 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003672 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003673 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003674
3675 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003676 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3677 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003678
3679 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003680 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003681 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003682
3683 if (LimitFloatPrecision <= 6) {
3684 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003685 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003686 // twoToFractionalPartOfX =
3687 // 0.997535578f +
3688 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003689 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003690 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003691 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003692 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003693 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003694 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003695 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3696 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003697 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003698 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003699 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003700 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003701
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003702 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003703 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003704 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3705 // For floating-point precision of 12:
3706 //
3707 // TwoToFractionalPartOfX =
3708 // 0.999892986f +
3709 // (0.696457318f +
3710 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3711 //
3712 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003713 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003714 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003715 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003716 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003717 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3718 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003719 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003720 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3721 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003722 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003723 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003724 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003725 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003726
Scott Michelfdc40a02009-02-17 22:15:04 +00003727 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003728 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003729 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3730 // For floating-point precision of 18:
3731 //
3732 // TwoToFractionalPartOfX =
3733 // 0.999999982f +
3734 // (0.693148872f +
3735 // (0.240227044f +
3736 // (0.554906021e-1f +
3737 // (0.961591928e-2f +
3738 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3739 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003740 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003741 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003742 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003743 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003744 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3745 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003746 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003747 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3748 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003749 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003750 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3751 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003752 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003753 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3754 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003755 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003756 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3757 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003758 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003759 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003760 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003761 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003762
Scott Michelfdc40a02009-02-17 22:15:04 +00003763 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003764 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003765 }
3766 } else {
3767 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003768 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003769 getValue(I.getOperand(1)).getValueType(),
3770 getValue(I.getOperand(1)),
3771 getValue(I.getOperand(2)));
3772 }
3773
3774 setValue(&I, result);
3775}
3776
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003777/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3778/// we want to emit this as a call to a named external function, return the name
3779/// otherwise lower it and return null.
3780const char *
3781SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003782 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003783 switch (Intrinsic) {
3784 default:
3785 // By default, turn this into a target intrinsic node.
3786 visitTargetIntrinsic(I, Intrinsic);
3787 return 0;
3788 case Intrinsic::vastart: visitVAStart(I); return 0;
3789 case Intrinsic::vaend: visitVAEnd(I); return 0;
3790 case Intrinsic::vacopy: visitVACopy(I); return 0;
3791 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003792 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003793 getValue(I.getOperand(1))));
3794 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003795 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003796 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003797 getValue(I.getOperand(1))));
3798 return 0;
3799 case Intrinsic::setjmp:
3800 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3801 break;
3802 case Intrinsic::longjmp:
3803 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3804 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003805 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003806 SDValue Op1 = getValue(I.getOperand(1));
3807 SDValue Op2 = getValue(I.getOperand(2));
3808 SDValue Op3 = getValue(I.getOperand(3));
3809 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003810 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003811 I.getOperand(1), 0, I.getOperand(2), 0));
3812 return 0;
3813 }
Chris Lattner824b9582008-11-21 16:42:48 +00003814 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003815 SDValue Op1 = getValue(I.getOperand(1));
3816 SDValue Op2 = getValue(I.getOperand(2));
3817 SDValue Op3 = getValue(I.getOperand(3));
3818 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003819 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003820 I.getOperand(1), 0));
3821 return 0;
3822 }
Chris Lattner824b9582008-11-21 16:42:48 +00003823 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003824 SDValue Op1 = getValue(I.getOperand(1));
3825 SDValue Op2 = getValue(I.getOperand(2));
3826 SDValue Op3 = getValue(I.getOperand(3));
3827 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3828
3829 // If the source and destination are known to not be aliases, we can
3830 // lower memmove as memcpy.
3831 uint64_t Size = -1ULL;
3832 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003833 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003834 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3835 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003836 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003837 I.getOperand(1), 0, I.getOperand(2), 0));
3838 return 0;
3839 }
3840
Dale Johannesena04b7572009-02-03 23:04:43 +00003841 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003842 I.getOperand(1), 0, I.getOperand(2), 0));
3843 return 0;
3844 }
3845 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003846 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003847 if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003848 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003849 DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
Chris Lattneraf29a522009-05-04 22:10:05 +00003850 setCurDebugLoc(Loc);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003851
Bill Wendling98a366d2009-04-29 23:29:43 +00003852 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003853 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003854 SPI.getLine(),
3855 SPI.getColumn(),
3856 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003857 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003858 return 0;
3859 }
3860 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003861 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003862 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003863 if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
3864 && DW->ShouldEmitDwarfDebug()) {
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003865 unsigned LabelID =
Devang Patele4b27562009-08-28 23:24:31 +00003866 DW->RecordRegionStart(RSI.getContext());
Devang Patel48c7fa22009-04-13 18:13:16 +00003867 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3868 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003869 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003870 return 0;
3871 }
3872 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003873 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003874 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel0f7fef32009-04-13 17:02:03 +00003875
Devang Patel7e1e31f2009-07-02 22:43:26 +00003876 if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
3877 || !DW->ShouldEmitDwarfDebug())
3878 return 0;
Bill Wendling6c4311d2009-05-08 21:14:49 +00003879
Devang Patel7e1e31f2009-07-02 22:43:26 +00003880 MachineFunction &MF = DAG.getMachineFunction();
Devang Patele4b27562009-08-28 23:24:31 +00003881 DISubprogram Subprogram(REI.getContext());
Devang Patel7e1e31f2009-07-02 22:43:26 +00003882
3883 if (isInlinedFnEnd(REI, MF.getFunction())) {
3884 // This is end of inlined function. Debugging information for inlined
3885 // function is not handled yet (only supported by FastISel).
3886 if (OptLevel == CodeGenOpt::None) {
3887 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3888 if (ID != 0)
3889 // Returned ID is 0 if this is unbalanced "end of inlined
3890 // scope". This could happen if optimizer eats dbg intrinsics or
3891 // "beginning of inlined scope" is not recoginized due to missing
3892 // location info. In such cases, do ignore this region.end.
3893 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3894 getRoot(), ID));
Devang Patel0f7fef32009-04-13 17:02:03 +00003895 }
Devang Patel7e1e31f2009-07-02 22:43:26 +00003896 return 0;
3897 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898
Devang Patel7e1e31f2009-07-02 22:43:26 +00003899 unsigned LabelID =
Devang Patele4b27562009-08-28 23:24:31 +00003900 DW->RecordRegionEnd(REI.getContext());
Devang Patel7e1e31f2009-07-02 22:43:26 +00003901 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3902 getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 return 0;
3904 }
3905 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003906 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003907 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00003908 if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None))
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003909 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003910
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003911 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003912 // This is a beginning of an inlined function.
3913 if (isInlinedFnStart(FSI, MF.getFunction())) {
3914 if (OptLevel != CodeGenOpt::None)
3915 // FIXME: Debugging informaation for inlined function is only
3916 // supported at CodeGenOpt::Node.
3917 return 0;
3918
Bill Wendlingc677fe52009-05-10 00:10:50 +00003919 DebugLoc PrevLoc = CurDebugLoc;
Devang Patel07b0ec02009-07-02 00:08:09 +00003920 // If llvm.dbg.func.start is seen in a new block before any
3921 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3922 // FIXME : Why DebugLoc is reset at the beginning of each block ?
3923 if (PrevLoc.isUnknown())
3924 return 0;
Devang Patel07b0ec02009-07-02 00:08:09 +00003925
Devang Patel7e1e31f2009-07-02 22:43:26 +00003926 // Record the source line.
3927 setCurDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3928
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00003929 if (!DW || !DW->ShouldEmitDwarfDebug())
3930 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003931 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
Devang Patele4b27562009-08-28 23:24:31 +00003932 DISubprogram SP(FSI.getSubprogram());
Devang Patel1619dc32009-10-13 23:28:53 +00003933 DICompileUnit CU(PrevLocTpl.Scope);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003934 unsigned LabelID = DW->RecordInlinedFnStart(SP, CU,
3935 PrevLocTpl.Line,
3936 PrevLocTpl.Col);
3937 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3938 getRoot(), LabelID));
Devang Patel07b0ec02009-07-02 00:08:09 +00003939 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003940 }
3941
Devang Patel07b0ec02009-07-02 00:08:09 +00003942 // This is a beginning of a new function.
Devang Patel7e1e31f2009-07-02 22:43:26 +00003943 MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00003944
3945 if (!DW || !DW->ShouldEmitDwarfDebug())
3946 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003947 // llvm.dbg.func_start also defines beginning of function scope.
Devang Patele4b27562009-08-28 23:24:31 +00003948 DW->RecordRegionStart(FSI.getSubprogram());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003949 return 0;
3950 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003951 case Intrinsic::dbg_declare: {
Devang Patel7e1e31f2009-07-02 22:43:26 +00003952 if (OptLevel != CodeGenOpt::None)
3953 // FIXME: Variable debug info is not supported here.
3954 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003955 DwarfWriter *DW = DAG.getDwarfWriter();
3956 if (!DW)
3957 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003958 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3959 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3960 return 0;
3961
Devang Patelac1ceb32009-10-09 22:42:28 +00003962 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003963 Value *Address = DI.getAddress();
3964 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3965 Address = BCI->getOperand(0);
3966 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3967 // Don't handle byval struct arguments or VLAs, for example.
3968 if (!AI)
3969 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003970 DenseMap<const AllocaInst*, int>::iterator SI =
3971 FuncInfo.StaticAllocaMap.find(AI);
3972 if (SI == FuncInfo.StaticAllocaMap.end())
3973 return 0; // VLAs.
3974 int FI = SI->second;
Devang Patelac1ceb32009-10-09 22:42:28 +00003975#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
3976 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3977 if (MMI)
3978 MMI->setVariableDbgInfo(Variable, FI);
3979#else
3980 DW->RecordVariable(Variable, FI);
3981#endif
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003982 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003983 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003984 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003985 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003986 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003987 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003988 SDValue Ops[1];
3989 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003990 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003991 setValue(&I, Op);
3992 DAG.setRoot(Op.getValue(1));
3993 return 0;
3994 }
3995
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003996 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003997 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003998
Chris Lattner3a5815f2009-09-17 23:54:54 +00003999 if (CurMBB->isLandingPad())
4000 AddCatchInfo(I, MMI, CurMBB);
4001 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004002#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00004003 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004004#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00004005 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4006 unsigned Reg = TLI.getExceptionSelectorRegister();
4007 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004008 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004009
Chris Lattner3a5815f2009-09-17 23:54:54 +00004010 // Insert the EHSELECTION instruction.
4011 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4012 SDValue Ops[2];
4013 Ops[0] = getValue(I.getOperand(1));
4014 Ops[1] = getRoot();
4015 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4016
4017 DAG.setRoot(Op.getValue(1));
4018
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004019 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004020 return 0;
4021 }
4022
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004023 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004024 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004025
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004026 if (MMI) {
4027 // Find the type id for the given typeinfo.
4028 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4029
4030 unsigned TypeID = MMI->getTypeIDFor(GV);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004031 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004032 } else {
4033 // Return something different to eh_selector.
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004034 setValue(&I, DAG.getConstant(1, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004035 }
4036
4037 return 0;
4038 }
4039
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004040 case Intrinsic::eh_return_i32:
4041 case Intrinsic::eh_return_i64:
4042 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004043 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004044 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004045 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004046 getControlRoot(),
4047 getValue(I.getOperand(1)),
4048 getValue(I.getOperand(2))));
4049 } else {
4050 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4051 }
4052
4053 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004054 case Intrinsic::eh_unwind_init:
4055 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4056 MMI->setCallsUnwindInit(true);
4057 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004058
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004059 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004060
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004061 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00004062 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00004063 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4064 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004065
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004066 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004067 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004068 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004069 TLI.getPointerTy()),
4070 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004071 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004072 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004073 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004074 TLI.getPointerTy(),
4075 DAG.getConstant(0,
4076 TLI.getPointerTy())),
4077 Offset));
4078 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004079 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004080 case Intrinsic::convertff:
4081 case Intrinsic::convertfsi:
4082 case Intrinsic::convertfui:
4083 case Intrinsic::convertsif:
4084 case Intrinsic::convertuif:
4085 case Intrinsic::convertss:
4086 case Intrinsic::convertsu:
4087 case Intrinsic::convertus:
4088 case Intrinsic::convertuu: {
4089 ISD::CvtCode Code = ISD::CVT_INVALID;
4090 switch (Intrinsic) {
4091 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4092 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4093 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4094 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4095 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4096 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4097 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4098 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4099 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4100 }
Owen Andersone50ed302009-08-10 22:56:29 +00004101 EVT DestVT = TLI.getValueType(I.getType());
Mon P Wang77cdf302008-11-10 20:54:11 +00004102 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004103 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004104 DAG.getValueType(DestVT),
4105 DAG.getValueType(getValue(Op1).getValueType()),
4106 getValue(I.getOperand(2)),
4107 getValue(I.getOperand(3)),
4108 Code));
4109 return 0;
4110 }
4111
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004112 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004113 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004114 getValue(I.getOperand(1)).getValueType(),
4115 getValue(I.getOperand(1))));
4116 return 0;
4117 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004118 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004119 getValue(I.getOperand(1)).getValueType(),
4120 getValue(I.getOperand(1)),
4121 getValue(I.getOperand(2))));
4122 return 0;
4123 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004124 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004125 getValue(I.getOperand(1)).getValueType(),
4126 getValue(I.getOperand(1))));
4127 return 0;
4128 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004129 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004130 getValue(I.getOperand(1)).getValueType(),
4131 getValue(I.getOperand(1))));
4132 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004133 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004134 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004135 return 0;
4136 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004137 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004138 return 0;
4139 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004140 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004141 return 0;
4142 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004143 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004144 return 0;
4145 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004146 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004147 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004148 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004149 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004150 return 0;
4151 case Intrinsic::pcmarker: {
4152 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004153 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004154 return 0;
4155 }
4156 case Intrinsic::readcyclecounter: {
4157 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004158 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004159 DAG.getVTList(MVT::i64, MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004160 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004161 setValue(&I, Tmp);
4162 DAG.setRoot(Tmp.getValue(1));
4163 return 0;
4164 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004165 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004166 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004167 getValue(I.getOperand(1)).getValueType(),
4168 getValue(I.getOperand(1))));
4169 return 0;
4170 case Intrinsic::cttz: {
4171 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004172 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004173 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004174 setValue(&I, result);
4175 return 0;
4176 }
4177 case Intrinsic::ctlz: {
4178 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004179 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004180 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 setValue(&I, result);
4182 return 0;
4183 }
4184 case Intrinsic::ctpop: {
4185 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004186 EVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004187 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004188 setValue(&I, result);
4189 return 0;
4190 }
4191 case Intrinsic::stacksave: {
4192 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004193 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004194 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004195 setValue(&I, Tmp);
4196 DAG.setRoot(Tmp.getValue(1));
4197 return 0;
4198 }
4199 case Intrinsic::stackrestore: {
4200 SDValue Tmp = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00004201 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004202 return 0;
4203 }
Bill Wendling57344502008-11-18 11:01:33 +00004204 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004205 // Emit code into the DAG to store the stack guard onto the stack.
4206 MachineFunction &MF = DAG.getMachineFunction();
4207 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004208 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004209
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004210 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4211 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004212
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004213 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004214 MFI->setStackProtectorIndex(FI);
4215
4216 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4217
4218 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004219 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Evan Chengff89dcb2009-10-18 18:16:27 +00004220 PseudoSourceValue::getFixedStack(FI),
4221 0, true);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004222 setValue(&I, Result);
4223 DAG.setRoot(Result);
4224 return 0;
4225 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004226 case Intrinsic::objectsize: {
4227 // If we don't know by now, we're never going to know.
4228 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4229
4230 assert(CI && "Non-constant type in __builtin_object_size?");
4231
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004232 SDValue Arg = getValue(I.getOperand(0));
4233 EVT Ty = Arg.getValueType();
4234
Eric Christopher7b5e6172009-10-27 00:52:25 +00004235 if (CI->getZExtValue() < 2)
Eric Christophercdfa6662009-10-31 09:24:35 +00004236 setValue(&I, DAG.getConstant(-1U, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004237 else
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004238 setValue(&I, DAG.getConstant(0, Ty));
Eric Christopher7b5e6172009-10-27 00:52:25 +00004239 return 0;
4240 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004241 case Intrinsic::var_annotation:
4242 // Discard annotate attributes
4243 return 0;
4244
4245 case Intrinsic::init_trampoline: {
4246 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4247
4248 SDValue Ops[6];
4249 Ops[0] = getRoot();
4250 Ops[1] = getValue(I.getOperand(1));
4251 Ops[2] = getValue(I.getOperand(2));
4252 Ops[3] = getValue(I.getOperand(3));
4253 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4254 Ops[5] = DAG.getSrcValue(F);
4255
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004256 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004257 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
Dan Gohmanfc166572009-04-09 23:54:40 +00004258 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004259
4260 setValue(&I, Tmp);
4261 DAG.setRoot(Tmp.getValue(1));
4262 return 0;
4263 }
4264
4265 case Intrinsic::gcroot:
4266 if (GFI) {
4267 Value *Alloca = I.getOperand(1);
4268 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004269
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004270 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4271 GFI->addStackRoot(FI->getIndex(), TypeMap);
4272 }
4273 return 0;
4274
4275 case Intrinsic::gcread:
4276 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004277 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004278 return 0;
4279
4280 case Intrinsic::flt_rounds: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004281 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004282 return 0;
4283 }
4284
4285 case Intrinsic::trap: {
Owen Anderson825b72b2009-08-11 20:47:22 +00004286 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004287 return 0;
4288 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004289
Bill Wendlingef375462008-11-21 02:38:44 +00004290 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004291 return implVisitAluOverflow(I, ISD::UADDO);
4292 case Intrinsic::sadd_with_overflow:
4293 return implVisitAluOverflow(I, ISD::SADDO);
4294 case Intrinsic::usub_with_overflow:
4295 return implVisitAluOverflow(I, ISD::USUBO);
4296 case Intrinsic::ssub_with_overflow:
4297 return implVisitAluOverflow(I, ISD::SSUBO);
4298 case Intrinsic::umul_with_overflow:
4299 return implVisitAluOverflow(I, ISD::UMULO);
4300 case Intrinsic::smul_with_overflow:
4301 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004302
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004303 case Intrinsic::prefetch: {
4304 SDValue Ops[4];
4305 Ops[0] = getRoot();
4306 Ops[1] = getValue(I.getOperand(1));
4307 Ops[2] = getValue(I.getOperand(2));
4308 Ops[3] = getValue(I.getOperand(3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004309 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004310 return 0;
4311 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004312
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004313 case Intrinsic::memory_barrier: {
4314 SDValue Ops[6];
4315 Ops[0] = getRoot();
4316 for (int x = 1; x < 6; ++x)
4317 Ops[x] = getValue(I.getOperand(x));
4318
Owen Anderson825b72b2009-08-11 20:47:22 +00004319 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004320 return 0;
4321 }
4322 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004323 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004324 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004325 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004326 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4327 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004328 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004329 getValue(I.getOperand(2)),
4330 getValue(I.getOperand(3)),
4331 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004332 setValue(&I, L);
4333 DAG.setRoot(L.getValue(1));
4334 return 0;
4335 }
4336 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004337 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004338 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004339 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004340 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004341 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004342 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004343 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004344 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004345 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004346 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004347 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004348 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004349 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004350 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004351 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004352 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004353 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004354 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004355 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004356 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004357 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004358 }
4359}
4360
Dan Gohman98ca4f22009-08-05 01:29:28 +00004361/// Test if the given instruction is in a position to be optimized
4362/// with a tail-call. This roughly means that it's in a block with
4363/// a return and there's nothing that needs to be scheduled
4364/// between it and the return.
4365///
4366/// This function only tests target-independent requirements.
4367/// For target-dependent requirements, a target should override
4368/// TargetLowering::IsEligibleForTailCallOptimization.
4369///
4370static bool
4371isInTailCallPosition(const Instruction *I, Attributes RetAttr,
4372 const TargetLowering &TLI) {
4373 const BasicBlock *ExitBB = I->getParent();
4374 const TerminatorInst *Term = ExitBB->getTerminator();
4375 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4376 const Function *F = ExitBB->getParent();
4377
4378 // The block must end in a return statement or an unreachable.
4379 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4380
4381 // If I will have a chain, make sure no other instruction that will have a
4382 // chain interposes between I and the return.
4383 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4384 !I->isSafeToSpeculativelyExecute())
4385 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4386 --BBI) {
4387 if (&*BBI == I)
4388 break;
4389 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4390 !BBI->isSafeToSpeculativelyExecute())
4391 return false;
4392 }
4393
4394 // If the block ends with a void return or unreachable, it doesn't matter
4395 // what the call's return type is.
4396 if (!Ret || Ret->getNumOperands() == 0) return true;
4397
4398 // Conservatively require the attributes of the call to match those of
4399 // the return.
4400 if (F->getAttributes().getRetAttributes() != RetAttr)
4401 return false;
4402
4403 // Otherwise, make sure the unmodified return value of I is the return value.
4404 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4405 U = dyn_cast<Instruction>(U->getOperand(0))) {
4406 if (!U)
4407 return false;
4408 if (!U->hasOneUse())
4409 return false;
4410 if (U == I)
4411 break;
4412 // Check for a truly no-op truncate.
4413 if (isa<TruncInst>(U) &&
4414 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4415 continue;
4416 // Check for a truly no-op bitcast.
4417 if (isa<BitCastInst>(U) &&
4418 (U->getOperand(0)->getType() == U->getType() ||
4419 (isa<PointerType>(U->getOperand(0)->getType()) &&
4420 isa<PointerType>(U->getType()))))
4421 continue;
4422 // Otherwise it's not a true no-op.
4423 return false;
4424 }
4425
4426 return true;
4427}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004428
4429void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004430 bool isTailCall,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004431 MachineBasicBlock *LandingPad) {
4432 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4433 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4434 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4435 unsigned BeginLabel = 0, EndLabel = 0;
4436
4437 TargetLowering::ArgListTy Args;
4438 TargetLowering::ArgListEntry Entry;
4439 Args.reserve(CS.arg_size());
Dan Gohman98ca4f22009-08-05 01:29:28 +00004440 unsigned j = 1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004441 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Dan Gohman98ca4f22009-08-05 01:29:28 +00004442 i != e; ++i, ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004443 SDValue ArgNode = getValue(*i);
4444 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4445
4446 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004447 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4448 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4449 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4450 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4451 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4452 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004453 Entry.Alignment = CS.getParamAlignment(attrInd);
4454 Args.push_back(Entry);
4455 }
4456
4457 if (LandingPad && MMI) {
4458 // Insert a label before the invoke call to mark the try range. This can be
4459 // used to detect deletion of the invoke via the MachineModuleInfo.
4460 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004461
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 // Both PendingLoads and PendingExports must be flushed here;
4463 // this call might not return.
4464 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004465 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4466 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004467 }
4468
Dan Gohman98ca4f22009-08-05 01:29:28 +00004469 // Check if target-independent constraints permit a tail call here.
4470 // Target-dependent constraints are checked within TLI.LowerCallTo.
4471 if (isTailCall &&
4472 !isInTailCallPosition(CS.getInstruction(),
4473 CS.getAttributes().getRetAttributes(),
4474 TLI))
4475 isTailCall = false;
4476
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004477 std::pair<SDValue,SDValue> Result =
4478 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004479 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004480 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004481 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004482 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004483 isTailCall,
4484 !CS.getInstruction()->use_empty(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004485 Callee, Args, DAG, getCurDebugLoc());
Dan Gohman98ca4f22009-08-05 01:29:28 +00004486 assert((isTailCall || Result.second.getNode()) &&
4487 "Non-null chain expected with non-tail call!");
4488 assert((Result.second.getNode() || !Result.first.getNode()) &&
4489 "Null value expected with tail call!");
4490 if (Result.first.getNode())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004491 setValue(CS.getInstruction(), Result.first);
Dan Gohman98ca4f22009-08-05 01:29:28 +00004492 // As a special case, a null chain means that a tail call has
4493 // been emitted and the DAG root is already updated.
4494 if (Result.second.getNode())
4495 DAG.setRoot(Result.second);
4496 else
4497 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004498
4499 if (LandingPad && MMI) {
4500 // Insert a label at the end of the invoke call to mark the try range. This
4501 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4502 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004503 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4504 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004505
4506 // Inform MachineModuleInfo of range.
4507 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4508 }
4509}
4510
4511
4512void SelectionDAGLowering::visitCall(CallInst &I) {
4513 const char *RenameFn = 0;
4514 if (Function *F = I.getCalledFunction()) {
4515 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004516 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4517 if (II) {
4518 if (unsigned IID = II->getIntrinsicID(F)) {
4519 RenameFn = visitIntrinsicCall(I, IID);
4520 if (!RenameFn)
4521 return;
4522 }
4523 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004524 if (unsigned IID = F->getIntrinsicID()) {
4525 RenameFn = visitIntrinsicCall(I, IID);
4526 if (!RenameFn)
4527 return;
4528 }
4529 }
4530
4531 // Check for well-known libc/libm calls. If the function is internal, it
4532 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004533 if (!F->hasLocalLinkage() && F->hasName()) {
4534 StringRef Name = F->getName();
4535 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004536 if (I.getNumOperands() == 3 && // Basic sanity checks.
4537 I.getOperand(1)->getType()->isFloatingPoint() &&
4538 I.getType() == I.getOperand(1)->getType() &&
4539 I.getType() == I.getOperand(2)->getType()) {
4540 SDValue LHS = getValue(I.getOperand(1));
4541 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004542 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004543 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004544 return;
4545 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004546 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004547 if (I.getNumOperands() == 2 && // Basic sanity checks.
4548 I.getOperand(1)->getType()->isFloatingPoint() &&
4549 I.getType() == I.getOperand(1)->getType()) {
4550 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004551 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004552 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004553 return;
4554 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004555 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004556 if (I.getNumOperands() == 2 && // Basic sanity checks.
4557 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004558 I.getType() == I.getOperand(1)->getType() &&
4559 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004560 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004561 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004562 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004563 return;
4564 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004565 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004566 if (I.getNumOperands() == 2 && // Basic sanity checks.
4567 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004568 I.getType() == I.getOperand(1)->getType() &&
4569 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004570 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004571 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004572 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004573 return;
4574 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004575 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4576 if (I.getNumOperands() == 2 && // Basic sanity checks.
4577 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004578 I.getType() == I.getOperand(1)->getType() &&
4579 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004580 SDValue Tmp = getValue(I.getOperand(1));
4581 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4582 Tmp.getValueType(), Tmp));
4583 return;
4584 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004585 }
4586 }
4587 } else if (isa<InlineAsm>(I.getOperand(0))) {
4588 visitInlineAsm(&I);
4589 return;
4590 }
4591
4592 SDValue Callee;
4593 if (!RenameFn)
4594 Callee = getValue(I.getOperand(0));
4595 else
Bill Wendling056292f2008-09-16 21:48:12 +00004596 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004597
Dan Gohman98ca4f22009-08-05 01:29:28 +00004598 // Check if we can potentially perform a tail call. More detailed
4599 // checking is be done within LowerCallTo, after more information
4600 // about the call is known.
4601 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4602
4603 LowerCallTo(&I, Callee, isTailCall);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004604}
4605
4606
4607/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004608/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004609/// Chain/Flag as the input and updates them for the output Chain/Flag.
4610/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004611SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004612 SDValue &Chain,
4613 SDValue *Flag) const {
4614 // Assemble the legal parts into the final values.
4615 SmallVector<SDValue, 4> Values(ValueVTs.size());
4616 SmallVector<SDValue, 8> Parts;
4617 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4618 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004619 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004620 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004621 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004622
4623 Parts.resize(NumRegs);
4624 for (unsigned i = 0; i != NumRegs; ++i) {
4625 SDValue P;
4626 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004627 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004628 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004629 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004630 *Flag = P.getValue(2);
4631 }
4632 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004633
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004634 // If the source register was virtual and if we know something about it,
4635 // add an assert node.
4636 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4637 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4638 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4639 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4640 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4641 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004642
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004643 unsigned RegSize = RegisterVT.getSizeInBits();
4644 unsigned NumSignBits = LOI.NumSignBits;
4645 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004646
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004647 // FIXME: We capture more information than the dag can represent. For
4648 // now, just use the tightest assertzext/assertsext possible.
4649 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004650 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004651 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004652 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004653 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004654 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004655 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004656 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004657 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004658 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004659 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004660 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004661 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004662 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004663 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004664 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004665 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004666 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004667
Owen Anderson825b72b2009-08-11 20:47:22 +00004668 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004669 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004670 RegisterVT, P, DAG.getValueType(FromVT));
4671
4672 }
4673 }
4674 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004675
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004676 Parts[i] = P;
4677 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004678
Scott Michelfdc40a02009-02-17 22:15:04 +00004679 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004680 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004681 Part += NumRegs;
4682 Parts.clear();
4683 }
4684
Dale Johannesen66978ee2009-01-31 02:22:37 +00004685 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004686 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4687 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004688}
4689
4690/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004691/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004692/// Chain/Flag as the input and updates them for the output Chain/Flag.
4693/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004694void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695 SDValue &Chain, SDValue *Flag) const {
4696 // Get the list of the values's legal parts.
4697 unsigned NumRegs = Regs.size();
4698 SmallVector<SDValue, 8> Parts(NumRegs);
4699 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004700 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004701 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004702 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004703
Dale Johannesen66978ee2009-01-31 02:22:37 +00004704 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004705 &Parts[Part], NumParts, RegisterVT);
4706 Part += NumParts;
4707 }
4708
4709 // Copy the parts into the registers.
4710 SmallVector<SDValue, 8> Chains(NumRegs);
4711 for (unsigned i = 0; i != NumRegs; ++i) {
4712 SDValue Part;
4713 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004714 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004715 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004716 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004717 *Flag = Part.getValue(1);
4718 }
4719 Chains[i] = Part.getValue(0);
4720 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004721
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004722 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004723 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004724 // flagged to it. That is the CopyToReg nodes and the user are considered
4725 // a single scheduling unit. If we create a TokenFactor and return it as
4726 // chain, then the TokenFactor is both a predecessor (operand) of the
4727 // user as well as a successor (the TF operands are flagged to the user).
4728 // c1, f1 = CopyToReg
4729 // c2, f2 = CopyToReg
4730 // c3 = TokenFactor c1, c2
4731 // ...
4732 // = op c3, ..., f2
4733 Chain = Chains[NumRegs-1];
4734 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004735 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004736}
4737
4738/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004739/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004740/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004741void RegsForValue::AddInlineAsmOperands(unsigned Code,
4742 bool HasMatching,unsigned MatchingIdx,
4743 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744 std::vector<SDValue> &Ops) const {
Owen Andersone50ed302009-08-10 22:56:29 +00004745 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004746 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4747 unsigned Flag = Code | (Regs.size() << 3);
4748 if (HasMatching)
4749 Flag |= 0x80000000 | (MatchingIdx << 16);
4750 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004752 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004753 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004754 for (unsigned i = 0; i != NumRegs; ++i) {
4755 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004756 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004757 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004758 }
4759}
4760
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004761/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762/// i.e. it isn't a stack pointer or some other special register, return the
4763/// register class for the register. Otherwise, return null.
4764static const TargetRegisterClass *
4765isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4766 const TargetLowering &TLI,
4767 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004768 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004769 const TargetRegisterClass *FoundRC = 0;
4770 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4771 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004772 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004773
4774 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004775 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4777 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4778 I != E; ++I) {
4779 if (TLI.isTypeLegal(*I)) {
4780 // If we have already found this register in a different register class,
4781 // choose the one with the largest VT specified. For example, on
4782 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004783 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004784 ThisVT = *I;
4785 break;
4786 }
4787 }
4788 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004789
Owen Anderson825b72b2009-08-11 20:47:22 +00004790 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004791
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004792 // NOTE: This isn't ideal. In particular, this might allocate the
4793 // frame pointer in functions that need it (due to them not being taken
4794 // out of allocation, because a variable sized allocation hasn't been seen
4795 // yet). This is a slight code pessimization, but should still work.
4796 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4797 E = RC->allocation_order_end(MF); I != E; ++I)
4798 if (*I == Reg) {
4799 // We found a matching register class. Keep looking at others in case
4800 // we find one with larger registers that this physreg is also in.
4801 FoundRC = RC;
4802 FoundVT = ThisVT;
4803 break;
4804 }
4805 }
4806 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004807}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004808
4809
4810namespace llvm {
4811/// AsmOperandInfo - This contains information for each constraint that we are
4812/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004813class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004814 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004815public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004816 /// CallOperand - If this is the result output operand or a clobber
4817 /// this is null, otherwise it is the incoming operand to the CallInst.
4818 /// This gets modified as the asm is processed.
4819 SDValue CallOperand;
4820
4821 /// AssignedRegs - If this is a register or register class operand, this
4822 /// contains the set of register corresponding to the operand.
4823 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004824
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004825 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4826 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4827 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004828
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004829 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4830 /// busy in OutputRegs/InputRegs.
4831 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004832 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004833 std::set<unsigned> &InputRegs,
4834 const TargetRegisterInfo &TRI) const {
4835 if (isOutReg) {
4836 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4837 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4838 }
4839 if (isInReg) {
4840 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4841 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4842 }
4843 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004844
Owen Andersone50ed302009-08-10 22:56:29 +00004845 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004846 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004847 /// MVT::Other.
Owen Anderson1d0be152009-08-13 21:58:54 +00004848 EVT getCallOperandValEVT(LLVMContext &Context,
4849 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004850 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004851 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004852
Chris Lattner81249c92008-10-17 17:05:25 +00004853 if (isa<BasicBlock>(CallOperandVal))
4854 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004855
Chris Lattner81249c92008-10-17 17:05:25 +00004856 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004857
Chris Lattner81249c92008-10-17 17:05:25 +00004858 // If this is an indirect operand, the operand is a pointer to the
4859 // accessed type.
4860 if (isIndirect)
4861 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004862
Chris Lattner81249c92008-10-17 17:05:25 +00004863 // If OpTy is not a single value, it may be a struct/union that we
4864 // can tile with integers.
4865 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4866 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4867 switch (BitSize) {
4868 default: break;
4869 case 1:
4870 case 8:
4871 case 16:
4872 case 32:
4873 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004874 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004875 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004876 break;
4877 }
4878 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004879
Chris Lattner81249c92008-10-17 17:05:25 +00004880 return TLI.getValueType(OpTy, true);
4881 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004883private:
4884 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4885 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004886 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004887 const TargetRegisterInfo &TRI) {
4888 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4889 Regs.insert(Reg);
4890 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4891 for (; *Aliases; ++Aliases)
4892 Regs.insert(*Aliases);
4893 }
4894};
4895} // end llvm namespace.
4896
4897
4898/// GetRegistersForValue - Assign registers (virtual or physical) for the
4899/// specified operand. We prefer to assign virtual registers, to allow the
4900/// register allocator handle the assignment process. However, if the asm uses
4901/// features that we can't model on machineinstrs, we have SDISel do the
4902/// allocation. This produces generally horrible, but correct, code.
4903///
4904/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004905/// Input and OutputRegs are the set of already allocated physical registers.
4906///
4907void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004908GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004909 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004910 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00004911 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00004912
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004913 // Compute whether this value requires an input register, an output register,
4914 // or both.
4915 bool isOutReg = false;
4916 bool isInReg = false;
4917 switch (OpInfo.Type) {
4918 case InlineAsm::isOutput:
4919 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004920
4921 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004922 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004923 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004924 break;
4925 case InlineAsm::isInput:
4926 isInReg = true;
4927 isOutReg = false;
4928 break;
4929 case InlineAsm::isClobber:
4930 isOutReg = true;
4931 isInReg = true;
4932 break;
4933 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004934
4935
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004936 MachineFunction &MF = DAG.getMachineFunction();
4937 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004938
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004939 // If this is a constraint for a single physreg, or a constraint for a
4940 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004941 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004942 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4943 OpInfo.ConstraintVT);
4944
4945 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00004946 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00004947 // If this is a FP input in an integer register (or visa versa) insert a bit
4948 // cast of the input value. More generally, handle any case where the input
4949 // value disagrees with the register class we plan to stick this in.
4950 if (OpInfo.Type == InlineAsm::isInput &&
4951 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00004952 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00004953 // types are identical size, use a bitcast to convert (e.g. two differing
4954 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00004955 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00004956 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004957 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004958 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004959 OpInfo.ConstraintVT = RegVT;
4960 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4961 // If the input is a FP value and we want it in FP registers, do a
4962 // bitcast to the corresponding integer type. This turns an f64 value
4963 // into i64, which can be passed with two i32 values on a 32-bit
4964 // machine.
Owen Anderson23b9b192009-08-12 00:36:31 +00004965 RegVT = EVT::getIntegerVT(Context,
4966 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004967 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004968 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004969 OpInfo.ConstraintVT = RegVT;
4970 }
4971 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004972
Owen Anderson23b9b192009-08-12 00:36:31 +00004973 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004974 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004975
Owen Andersone50ed302009-08-10 22:56:29 +00004976 EVT RegVT;
4977 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004978
4979 // If this is a constraint for a specific physical register, like {r17},
4980 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004981 if (unsigned AssignedReg = PhysReg.first) {
4982 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00004983 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004984 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004986 // Get the actual register value type. This is important, because the user
4987 // may have asked for (e.g.) the AX register in i32 type. We need to
4988 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004989 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004992 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004993
4994 // If this is an expanded reference, add the rest of the regs to Regs.
4995 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004996 TargetRegisterClass::iterator I = RC->begin();
4997 for (; *I != AssignedReg; ++I)
4998 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004999
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005000 // Already added the first reg.
5001 --NumRegs; ++I;
5002 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005003 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005004 Regs.push_back(*I);
5005 }
5006 }
5007 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5008 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5009 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5010 return;
5011 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005012
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005013 // Otherwise, if this was a reference to an LLVM register class, create vregs
5014 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005015 if (const TargetRegisterClass *RC = PhysReg.second) {
5016 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005017 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005018 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005019
Evan Chengfb112882009-03-23 08:01:15 +00005020 // Create the appropriate number of virtual registers.
5021 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5022 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005023 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005024
Evan Chengfb112882009-03-23 08:01:15 +00005025 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5026 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005027 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005028
5029 // This is a reference to a register class that doesn't directly correspond
5030 // to an LLVM register class. Allocate NumRegs consecutive, available,
5031 // registers from the class.
5032 std::vector<unsigned> RegClassRegs
5033 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5034 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005035
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005036 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5037 unsigned NumAllocated = 0;
5038 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5039 unsigned Reg = RegClassRegs[i];
5040 // See if this register is available.
5041 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5042 (isInReg && InputRegs.count(Reg))) { // Already used.
5043 // Make sure we find consecutive registers.
5044 NumAllocated = 0;
5045 continue;
5046 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005047
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005048 // Check to see if this register is allocatable (i.e. don't give out the
5049 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005050 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5051 if (!RC) { // Couldn't allocate this register.
5052 // Reset NumAllocated to make sure we return consecutive registers.
5053 NumAllocated = 0;
5054 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005055 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005056
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005057 // Okay, this register is good, we can use it.
5058 ++NumAllocated;
5059
5060 // If we allocated enough consecutive registers, succeed.
5061 if (NumAllocated == NumRegs) {
5062 unsigned RegStart = (i-NumAllocated)+1;
5063 unsigned RegEnd = i+1;
5064 // Mark all of the allocated registers used.
5065 for (unsigned i = RegStart; i != RegEnd; ++i)
5066 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005067
5068 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005069 OpInfo.ConstraintVT);
5070 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5071 return;
5072 }
5073 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075 // Otherwise, we couldn't allocate enough registers for this.
5076}
5077
Evan Chengda43bcf2008-09-24 00:05:32 +00005078/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5079/// processed uses a memory 'm' constraint.
5080static bool
5081hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005082 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005083 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5084 InlineAsm::ConstraintInfo &CI = CInfos[i];
5085 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5086 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5087 if (CType == TargetLowering::C_Memory)
5088 return true;
5089 }
Chris Lattner6c147292009-04-30 00:48:50 +00005090
5091 // Indirect operand accesses access memory.
5092 if (CI.isIndirect)
5093 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005094 }
5095
5096 return false;
5097}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005098
5099/// visitInlineAsm - Handle a call to an InlineAsm object.
5100///
5101void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5102 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5103
5104 /// ConstraintOperands - Information about all of the constraints.
5105 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 std::set<unsigned> OutputRegs, InputRegs;
5108
5109 // Do a prepass over the constraints, canonicalizing them, and building up the
5110 // ConstraintOperands list.
5111 std::vector<InlineAsm::ConstraintInfo>
5112 ConstraintInfos = IA->ParseConstraints();
5113
Evan Chengda43bcf2008-09-24 00:05:32 +00005114 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005115
5116 SDValue Chain, Flag;
5117
5118 // We won't need to flush pending loads if this asm doesn't touch
5119 // memory and is nonvolatile.
5120 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005121 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005122 else
5123 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005124
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005125 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5126 unsigned ResNo = 0; // ResNo - The result number of the next output.
5127 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5128 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5129 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005130
Owen Anderson825b72b2009-08-11 20:47:22 +00005131 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005132
5133 // Compute the value type for each operand.
5134 switch (OpInfo.Type) {
5135 case InlineAsm::isOutput:
5136 // Indirect outputs just consume an argument.
5137 if (OpInfo.isIndirect) {
5138 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5139 break;
5140 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005141
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 // The return value of the call is this value. As such, there is no
5143 // corresponding argument.
Owen Anderson1d0be152009-08-13 21:58:54 +00005144 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5145 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005146 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5147 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5148 } else {
5149 assert(ResNo == 0 && "Asm only has one result!");
5150 OpVT = TLI.getValueType(CS.getType());
5151 }
5152 ++ResNo;
5153 break;
5154 case InlineAsm::isInput:
5155 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5156 break;
5157 case InlineAsm::isClobber:
5158 // Nothing to do.
5159 break;
5160 }
5161
5162 // If this is an input or an indirect output, process the call argument.
5163 // BasicBlocks are labels, currently appearing only in asm's.
5164 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005165 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005166 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5167
Chris Lattner81249c92008-10-17 17:05:25 +00005168 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005169 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005170 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005171 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005172 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005173
Owen Anderson1d0be152009-08-13 21:58:54 +00005174 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005175 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005176
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005177 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005178 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005179
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005180 // Second pass over the constraints: compute which constraint option to use
5181 // and assign registers to constraints that want a specific physreg.
5182 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5183 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005184
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005185 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005186 // matching input. If their types mismatch, e.g. one is an integer, the
5187 // other is floating point, or their sizes are different, flag it as an
5188 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005189 if (OpInfo.hasMatchingInput()) {
5190 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5191 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005192 if ((OpInfo.ConstraintVT.isInteger() !=
5193 Input.ConstraintVT.isInteger()) ||
5194 (OpInfo.ConstraintVT.getSizeInBits() !=
5195 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005196 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005197 " with a matching output constraint of incompatible"
5198 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005199 }
5200 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005201 }
5202 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005203
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005204 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005205 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005207 // If this is a memory input, and if the operand is not indirect, do what we
5208 // need to to provide an address for the memory input.
5209 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5210 !OpInfo.isIndirect) {
5211 assert(OpInfo.Type == InlineAsm::isInput &&
5212 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005213
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005214 // Memory operands really want the address of the value. If we don't have
5215 // an indirect input, put it in the constpool if we can, otherwise spill
5216 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005217
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005218 // If the operand is a float, integer, or vector constant, spill to a
5219 // constant pool entry to get its address.
5220 Value *OpVal = OpInfo.CallOperandVal;
5221 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5222 isa<ConstantVector>(OpVal)) {
5223 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5224 TLI.getPointerTy());
5225 } else {
5226 // Otherwise, create a stack slot and emit a store to it before the
5227 // asm.
5228 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005229 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005230 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5231 MachineFunction &MF = DAG.getMachineFunction();
5232 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5233 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005234 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005235 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005236 OpInfo.CallOperand = StackSlot;
5237 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005238
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005239 // There is no longer a Value* corresponding to this operand.
5240 OpInfo.CallOperandVal = 0;
5241 // It is now an indirect operand.
5242 OpInfo.isIndirect = true;
5243 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005244
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005245 // If this constraint is for a specific register, allocate it before
5246 // anything else.
5247 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005248 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005249 }
5250 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005251
5252
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005253 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005254 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005255 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5256 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005257
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005258 // C_Register operands have already been allocated, Other/Memory don't need
5259 // to be.
5260 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005261 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005262 }
5263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5265 std::vector<SDValue> AsmNodeOperands;
5266 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5267 AsmNodeOperands.push_back(
Owen Anderson825b72b2009-08-11 20:47:22 +00005268 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005269
5270
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005271 // Loop over all of the inputs, copying the operand values into the
5272 // appropriate registers and processing the output regs.
5273 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005274
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005275 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5276 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005277
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005278 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5279 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5280
5281 switch (OpInfo.Type) {
5282 case InlineAsm::isOutput: {
5283 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5284 OpInfo.ConstraintType != TargetLowering::C_Register) {
5285 // Memory output, or 'other' output (e.g. 'X' constraint).
5286 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5287
5288 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005289 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5290 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005291 TLI.getPointerTy()));
5292 AsmNodeOperands.push_back(OpInfo.CallOperand);
5293 break;
5294 }
5295
5296 // Otherwise, this is a register or register class output.
5297
5298 // Copy the output from the appropriate register. Find a register that
5299 // we can use.
5300 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005301 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005302 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005303 }
5304
5305 // If this is an indirect operand, store through the pointer after the
5306 // asm.
5307 if (OpInfo.isIndirect) {
5308 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5309 OpInfo.CallOperandVal));
5310 } else {
5311 // This is the result value of the call.
Owen Anderson1d0be152009-08-13 21:58:54 +00005312 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5313 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005314 // Concatenate this output onto the outputs list.
5315 RetValRegs.append(OpInfo.AssignedRegs);
5316 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005317
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005318 // Add information to the INLINEASM node to know that this register is
5319 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005320 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5321 6 /* EARLYCLOBBER REGDEF */ :
5322 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005323 false,
5324 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005325 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005326 break;
5327 }
5328 case InlineAsm::isInput: {
5329 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005330
Chris Lattner6bdcda32008-10-17 16:47:46 +00005331 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 // If this is required to match an output register we have already set,
5333 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005334 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005335
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005336 // Scan until we find the definition we already emitted of this operand.
5337 // When we find it, create a RegsForValue operand.
5338 unsigned CurOp = 2; // The first operand.
5339 for (; OperandNo; --OperandNo) {
5340 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005341 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005342 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005343 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5344 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5345 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005347 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348 }
5349
Evan Cheng697cbbf2009-03-20 18:03:34 +00005350 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005351 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005352 if ((OpFlag & 7) == 2 /*REGDEF*/
5353 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5354 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005355 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005356 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005357 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005358 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005359 RegsForValue MatchedRegs;
5360 MatchedRegs.TLI = &TLI;
5361 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005362 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005363 MatchedRegs.RegVTs.push_back(RegVT);
5364 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005365 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005366 i != e; ++i)
5367 MatchedRegs.Regs.
5368 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005369
5370 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005371 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5372 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005373 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5374 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005375 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005376 break;
5377 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005378 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5379 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5380 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005381 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005382 // See InlineAsm.h isUseOperandTiedToDef.
5383 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005384 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005385 TLI.getPointerTy()));
5386 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5387 break;
5388 }
5389 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005390
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005391 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005392 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005393 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005394
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005395 std::vector<SDValue> Ops;
5396 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005397 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005398 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005399 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005400 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005401 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005402
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 // Add information to the INLINEASM node to know about this input.
5404 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005405 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005406 TLI.getPointerTy()));
5407 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5408 break;
5409 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5410 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5411 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5412 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005414 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005415 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5416 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 TLI.getPointerTy()));
5418 AsmNodeOperands.push_back(InOperandVal);
5419 break;
5420 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005421
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005422 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5423 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5424 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005425 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005426 "Don't know how to handle indirect register inputs yet!");
5427
5428 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005429 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005430 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005431 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005432 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005433
Dale Johannesen66978ee2009-01-31 02:22:37 +00005434 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5435 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005436
Evan Cheng697cbbf2009-03-20 18:03:34 +00005437 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005438 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 break;
5440 }
5441 case InlineAsm::isClobber: {
5442 // Add the clobbered value to the operand list, so that the register
5443 // allocator is aware that the physreg got clobbered.
5444 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005445 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005446 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 break;
5448 }
5449 }
5450 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005451
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005452 // Finish up input operands.
5453 AsmNodeOperands[0] = Chain;
5454 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005455
Dale Johannesen66978ee2009-01-31 02:22:37 +00005456 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005457 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005458 &AsmNodeOperands[0], AsmNodeOperands.size());
5459 Flag = Chain.getValue(1);
5460
5461 // If this asm returns a register value, copy the result from that register
5462 // and set it as the value of the call.
5463 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005464 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005465 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005466
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005467 // FIXME: Why don't we do this for inline asms with MRVs?
5468 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005469 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005470
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005471 // If any of the results of the inline asm is a vector, it may have the
5472 // wrong width/num elts. This can happen for register classes that can
5473 // contain multiple different value types. The preg or vreg allocated may
5474 // not have the same VT as was expected. Convert it to the right type
5475 // with bit_convert.
5476 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005477 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005478 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005479
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005480 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005481 ResultType.isInteger() && Val.getValueType().isInteger()) {
5482 // If a result value was tied to an input value, the computed result may
5483 // have a wider width than the expected result. Extract the relevant
5484 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005485 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005486 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005487
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005488 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005489 }
Dan Gohman95915732008-10-18 01:03:45 +00005490
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005492 // Don't need to use this as a chain in this case.
5493 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5494 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005495 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005496
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005497 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005498
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005499 // Process indirect outputs, first output all of the flagged copies out of
5500 // physregs.
5501 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5502 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5503 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005504 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5505 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005507
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005508 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005509
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005510 // Emit the non-flagged stores from the physregs.
5511 SmallVector<SDValue, 8> OutChains;
5512 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005513 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005514 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005515 getValue(StoresToEmit[i].second),
5516 StoresToEmit[i].second, 0));
5517 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005518 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005519 &OutChains[0], OutChains.size());
5520 DAG.setRoot(Chain);
5521}
5522
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005523void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005524 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005525 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005526 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527 DAG.getSrcValue(I.getOperand(1))));
5528}
5529
5530void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005531 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5532 getRoot(), getValue(I.getOperand(0)),
5533 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005534 setValue(&I, V);
5535 DAG.setRoot(V.getValue(1));
5536}
5537
5538void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005539 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005540 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005541 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005542 DAG.getSrcValue(I.getOperand(1))));
5543}
5544
5545void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005546 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005547 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005548 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005549 getValue(I.getOperand(2)),
5550 DAG.getSrcValue(I.getOperand(1)),
5551 DAG.getSrcValue(I.getOperand(2))));
5552}
5553
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005554/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005555/// implementation, which just calls LowerCall.
5556/// FIXME: When all targets are
5557/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558std::pair<SDValue, SDValue>
5559TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5560 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005561 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005562 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005563 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005565 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00005566
Dan Gohman1937e2f2008-09-16 01:42:28 +00005567 assert((!isTailCall || PerformTailCallOpt) &&
5568 "isTailCall set when tail-call optimizations are disabled!");
5569
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005570 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005571 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005572 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005573 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005574 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5575 for (unsigned Value = 0, NumValues = ValueVTs.size();
5576 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005577 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005578 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005579 SDValue Op = SDValue(Args[i].Node.getNode(),
5580 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005581 ISD::ArgFlagsTy Flags;
5582 unsigned OriginalAlignment =
5583 getTargetData()->getABITypeAlignment(ArgTy);
5584
5585 if (Args[i].isZExt)
5586 Flags.setZExt();
5587 if (Args[i].isSExt)
5588 Flags.setSExt();
5589 if (Args[i].isInReg)
5590 Flags.setInReg();
5591 if (Args[i].isSRet)
5592 Flags.setSRet();
5593 if (Args[i].isByVal) {
5594 Flags.setByVal();
5595 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5596 const Type *ElementTy = Ty->getElementType();
5597 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005598 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005599 // For ByVal, alignment should come from FE. BE will guess if this
5600 // info is not there but there are cases it cannot get right.
5601 if (Args[i].Alignment)
5602 FrameAlign = Args[i].Alignment;
5603 Flags.setByValAlign(FrameAlign);
5604 Flags.setByValSize(FrameSize);
5605 }
5606 if (Args[i].isNest)
5607 Flags.setNest();
5608 Flags.setOrigAlign(OriginalAlignment);
5609
Owen Anderson23b9b192009-08-12 00:36:31 +00005610 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5611 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005612 SmallVector<SDValue, 4> Parts(NumParts);
5613 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5614
5615 if (Args[i].isSExt)
5616 ExtendKind = ISD::SIGN_EXTEND;
5617 else if (Args[i].isZExt)
5618 ExtendKind = ISD::ZERO_EXTEND;
5619
Dale Johannesen66978ee2009-01-31 02:22:37 +00005620 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005621
Dan Gohman98ca4f22009-08-05 01:29:28 +00005622 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005623 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005624 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5625 if (NumParts > 1 && j == 0)
5626 MyFlags.Flags.setSplit();
5627 else if (j != 0)
5628 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005629
Dan Gohman98ca4f22009-08-05 01:29:28 +00005630 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005631 }
5632 }
5633 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005634
Dan Gohman98ca4f22009-08-05 01:29:28 +00005635 // Handle the incoming return values from the call.
5636 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005637 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005638 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005639 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005640 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005641 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5642 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005643 for (unsigned i = 0; i != NumRegs; ++i) {
5644 ISD::InputArg MyFlags;
5645 MyFlags.VT = RegisterVT;
5646 MyFlags.Used = isReturnValueUsed;
5647 if (RetSExt)
5648 MyFlags.Flags.setSExt();
5649 if (RetZExt)
5650 MyFlags.Flags.setZExt();
5651 if (isInreg)
5652 MyFlags.Flags.setInReg();
5653 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005654 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005655 }
5656
Dan Gohman98ca4f22009-08-05 01:29:28 +00005657 // Check if target-dependent constraints permit a tail call here.
5658 // Target-independent constraints should be checked by the caller.
5659 if (isTailCall &&
5660 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5661 isTailCall = false;
5662
5663 SmallVector<SDValue, 4> InVals;
5664 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5665 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005666
5667 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005668 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005669 "LowerCall didn't return a valid chain!");
5670 assert((!isTailCall || InVals.empty()) &&
5671 "LowerCall emitted a return value for a tail call!");
5672 assert((isTailCall || InVals.size() == Ins.size()) &&
5673 "LowerCall didn't emit the correct number of values!");
5674 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5675 assert(InVals[i].getNode() &&
5676 "LowerCall emitted a null value!");
5677 assert(Ins[i].VT == InVals[i].getValueType() &&
5678 "LowerCall emitted a value with the wrong type!");
5679 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005680
5681 // For a tail call, the return value is merely live-out and there aren't
5682 // any nodes in the DAG representing it. Return a special value to
5683 // indicate that a tail call has been emitted and no more Instructions
5684 // should be processed in the current block.
5685 if (isTailCall) {
5686 DAG.setRoot(Chain);
5687 return std::make_pair(SDValue(), SDValue());
5688 }
5689
5690 // Collect the legal value parts into potentially illegal values
5691 // that correspond to the original function's return values.
5692 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5693 if (RetSExt)
5694 AssertOp = ISD::AssertSext;
5695 else if (RetZExt)
5696 AssertOp = ISD::AssertZext;
5697 SmallVector<SDValue, 4> ReturnValues;
5698 unsigned CurReg = 0;
5699 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005700 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005701 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5702 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005703
5704 SDValue ReturnValue =
5705 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5706 AssertOp);
5707 ReturnValues.push_back(ReturnValue);
5708 CurReg += NumRegs;
5709 }
5710
5711 // For a function returning void, there is no return value. We can't create
5712 // such a node, so we just return a null return value in that case. In
5713 // that case, nothing will actualy look at the value.
5714 if (ReturnValues.empty())
5715 return std::make_pair(SDValue(), Chain);
5716
5717 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5718 DAG.getVTList(&RetTys[0], RetTys.size()),
5719 &ReturnValues[0], ReturnValues.size());
5720
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005721 return std::make_pair(Res, Chain);
5722}
5723
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005724void TargetLowering::LowerOperationWrapper(SDNode *N,
5725 SmallVectorImpl<SDValue> &Results,
5726 SelectionDAG &DAG) {
5727 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005728 if (Res.getNode())
5729 Results.push_back(Res);
5730}
5731
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005732SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005733 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005734 return SDValue();
5735}
5736
5737
5738void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5739 SDValue Op = getValue(V);
5740 assert((Op.getOpcode() != ISD::CopyFromReg ||
5741 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5742 "Copy from a reg to the same reg!");
5743 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5744
Owen Anderson23b9b192009-08-12 00:36:31 +00005745 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005746 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005747 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005748 PendingExports.push_back(Chain);
5749}
5750
5751#include "llvm/CodeGen/SelectionDAGISel.h"
5752
Dan Gohman8c2b5252009-10-30 01:27:03 +00005753void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005754 // If this is the entry block, emit arguments.
5755 Function &F = *LLVMBB->getParent();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005756 SelectionDAG &DAG = SDL->DAG;
5757 SDValue OldRoot = DAG.getRoot();
5758 DebugLoc dl = SDL->getCurDebugLoc();
5759 const TargetData *TD = TLI.getTargetData();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005760
Dan Gohman98ca4f22009-08-05 01:29:28 +00005761 // Set up the incoming argument description vector.
5762 SmallVector<ISD::InputArg, 16> Ins;
5763 unsigned Idx = 1;
5764 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5765 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005766 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005767 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5768 bool isArgValueUsed = !I->use_empty();
5769 for (unsigned Value = 0, NumValues = ValueVTs.size();
5770 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005771 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005772 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005773 ISD::ArgFlagsTy Flags;
5774 unsigned OriginalAlignment =
5775 TD->getABITypeAlignment(ArgTy);
5776
5777 if (F.paramHasAttr(Idx, Attribute::ZExt))
5778 Flags.setZExt();
5779 if (F.paramHasAttr(Idx, Attribute::SExt))
5780 Flags.setSExt();
5781 if (F.paramHasAttr(Idx, Attribute::InReg))
5782 Flags.setInReg();
5783 if (F.paramHasAttr(Idx, Attribute::StructRet))
5784 Flags.setSRet();
5785 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5786 Flags.setByVal();
5787 const PointerType *Ty = cast<PointerType>(I->getType());
5788 const Type *ElementTy = Ty->getElementType();
5789 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5790 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5791 // For ByVal, alignment should be passed from FE. BE will guess if
5792 // this info is not there but there are cases it cannot get right.
5793 if (F.getParamAlignment(Idx))
5794 FrameAlign = F.getParamAlignment(Idx);
5795 Flags.setByValAlign(FrameAlign);
5796 Flags.setByValSize(FrameSize);
5797 }
5798 if (F.paramHasAttr(Idx, Attribute::Nest))
5799 Flags.setNest();
5800 Flags.setOrigAlign(OriginalAlignment);
5801
Owen Anderson23b9b192009-08-12 00:36:31 +00005802 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5803 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005804 for (unsigned i = 0; i != NumRegs; ++i) {
5805 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5806 if (NumRegs > 1 && i == 0)
5807 MyFlags.Flags.setSplit();
5808 // if it isn't first piece, alignment must be 1
5809 else if (i > 0)
5810 MyFlags.Flags.setOrigAlign(1);
5811 Ins.push_back(MyFlags);
5812 }
5813 }
5814 }
5815
5816 // Call the target to set up the argument values.
5817 SmallVector<SDValue, 8> InVals;
5818 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5819 F.isVarArg(), Ins,
5820 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005821
5822 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005823 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005824 "LowerFormalArguments didn't return a valid chain!");
5825 assert(InVals.size() == Ins.size() &&
5826 "LowerFormalArguments didn't emit the correct number of values!");
5827 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5828 assert(InVals[i].getNode() &&
5829 "LowerFormalArguments emitted a null value!");
5830 assert(Ins[i].VT == InVals[i].getValueType() &&
5831 "LowerFormalArguments emitted a value with the wrong type!");
5832 });
5833
5834 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005835 DAG.setRoot(NewRoot);
5836
5837 // Set up the argument values.
5838 unsigned i = 0;
5839 Idx = 1;
5840 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5841 ++I, ++Idx) {
5842 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00005843 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005844 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005845 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005846 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005847 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005848 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5849 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005850
5851 if (!I->use_empty()) {
5852 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5853 if (F.paramHasAttr(Idx, Attribute::SExt))
5854 AssertOp = ISD::AssertSext;
5855 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5856 AssertOp = ISD::AssertZext;
5857
5858 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5859 PartVT, VT, AssertOp));
5860 }
5861 i += NumParts;
5862 }
5863 if (!I->use_empty()) {
5864 SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5865 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005866 // If this argument is live outside of the entry block, insert a copy from
5867 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005868 SDL->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005869 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005870 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00005871 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005872
5873 // Finally, if the target has anything special to do, allow it to do so.
5874 // FIXME: this should insert code into the DAG!
5875 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5876}
5877
5878/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5879/// ensure constants are generated when needed. Remember the virtual registers
5880/// that need to be added to the Machine PHI nodes as input. We cannot just
5881/// directly add them, because expansion might result in multiple MBB's for one
5882/// BB. As such, the start of the BB might correspond to a different MBB than
5883/// the end.
5884///
5885void
5886SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5887 TerminatorInst *TI = LLVMBB->getTerminator();
5888
5889 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5890
5891 // Check successor nodes' PHI nodes that expect a constant to be available
5892 // from this block.
5893 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5894 BasicBlock *SuccBB = TI->getSuccessor(succ);
5895 if (!isa<PHINode>(SuccBB->begin())) continue;
5896 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005897
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005898 // If this terminator has multiple identical successors (common for
5899 // switches), only handle each succ once.
5900 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005901
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005902 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5903 PHINode *PN;
5904
5905 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5906 // nodes and Machine PHI nodes, but the incoming operands have not been
5907 // emitted yet.
5908 for (BasicBlock::iterator I = SuccBB->begin();
5909 (PN = dyn_cast<PHINode>(I)); ++I) {
5910 // Ignore dead phi's.
5911 if (PN->use_empty()) continue;
5912
5913 unsigned Reg;
5914 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5915
5916 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5917 unsigned &RegOut = SDL->ConstantsOut[C];
5918 if (RegOut == 0) {
5919 RegOut = FuncInfo->CreateRegForValue(C);
5920 SDL->CopyValueToVirtualRegister(C, RegOut);
5921 }
5922 Reg = RegOut;
5923 } else {
5924 Reg = FuncInfo->ValueMap[PHIOp];
5925 if (Reg == 0) {
5926 assert(isa<AllocaInst>(PHIOp) &&
5927 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5928 "Didn't codegen value into a register!??");
5929 Reg = FuncInfo->CreateRegForValue(PHIOp);
5930 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5931 }
5932 }
5933
5934 // Remember that this register needs to added to the machine PHI node as
5935 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00005936 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005937 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5938 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00005939 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00005940 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005941 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5942 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5943 Reg += NumRegisters;
5944 }
5945 }
5946 }
5947 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005948}
5949
Dan Gohman3df24e62008-09-03 23:12:08 +00005950/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5951/// supports legal types, and it emits MachineInstrs directly instead of
5952/// creating SelectionDAG nodes.
5953///
5954bool
5955SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5956 FastISel *F) {
5957 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005958
Dan Gohman3df24e62008-09-03 23:12:08 +00005959 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5960 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5961
5962 // Check successor nodes' PHI nodes that expect a constant to be available
5963 // from this block.
5964 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5965 BasicBlock *SuccBB = TI->getSuccessor(succ);
5966 if (!isa<PHINode>(SuccBB->begin())) continue;
5967 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005968
Dan Gohman3df24e62008-09-03 23:12:08 +00005969 // If this terminator has multiple identical successors (common for
5970 // switches), only handle each succ once.
5971 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005972
Dan Gohman3df24e62008-09-03 23:12:08 +00005973 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5974 PHINode *PN;
5975
5976 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5977 // nodes and Machine PHI nodes, but the incoming operands have not been
5978 // emitted yet.
5979 for (BasicBlock::iterator I = SuccBB->begin();
5980 (PN = dyn_cast<PHINode>(I)); ++I) {
5981 // Ignore dead phi's.
5982 if (PN->use_empty()) continue;
5983
5984 // Only handle legal types. Two interesting things to note here. First,
5985 // by bailing out early, we may leave behind some dead instructions,
5986 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5987 // own moves. Second, this check is necessary becuase FastISel doesn't
5988 // use CreateRegForValue to create registers, so it always creates
5989 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00005990 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00005991 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5992 // Promote MVT::i1.
5993 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00005994 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00005995 else {
5996 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5997 return false;
5998 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005999 }
6000
6001 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6002
6003 unsigned Reg = F->getRegForValue(PHIOp);
6004 if (Reg == 0) {
6005 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6006 return false;
6007 }
6008 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6009 }
6010 }
6011
6012 return true;
6013}