blob: 430dcfd28674fa4702b8b7cf1e1a55d099214e1c [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"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000028#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000029#include "llvm/CodeGen/FastISel.h"
30#include "llvm/CodeGen/GCStrategy.h"
31#include "llvm/CodeGen/GCMetadata.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000038#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000040#include "llvm/CodeGen/DwarfWriter.h"
41#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000042#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Target/TargetFrameInfo.h"
45#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000046#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000047#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000048#include "llvm/Target/TargetOptions.h"
49#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000050#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000053#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000054#include <algorithm>
55using namespace llvm;
56
Dale Johannesen601d3c02008-09-05 01:48:15 +000057/// LimitFloatPrecision - Generate low-precision inline sequences for
58/// some float libcalls (6, 8 or 12 bits).
59static unsigned LimitFloatPrecision;
60
61static cl::opt<unsigned, true>
62LimitFPPrecision("limit-float-precision",
63 cl::desc("Generate low-precision inline sequences "
64 "for some float libcalls"),
65 cl::location(LimitFloatPrecision),
66 cl::init(0));
67
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000068/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000069/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000070/// the linearized index of the start of the member.
71///
72static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
73 const unsigned *Indices,
74 const unsigned *IndicesEnd,
75 unsigned CurIndex = 0) {
76 // Base case: We're done.
77 if (Indices && Indices == IndicesEnd)
78 return CurIndex;
79
80 // Given a struct type, recursively traverse the elements.
81 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
82 for (StructType::element_iterator EB = STy->element_begin(),
83 EI = EB,
84 EE = STy->element_end();
85 EI != EE; ++EI) {
86 if (Indices && *Indices == unsigned(EI - EB))
87 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
88 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
89 }
Dan Gohman2c91d102009-01-06 22:53:52 +000090 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000091 }
92 // Given an array type, recursively traverse the elements.
93 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
94 const Type *EltTy = ATy->getElementType();
95 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
96 if (Indices && *Indices == i)
97 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
98 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
99 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000100 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000101 }
102 // We haven't found the type we're looking for, so keep searching.
103 return CurIndex + 1;
104}
105
106/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
107/// MVTs that represent all the individual underlying
108/// non-aggregate types that comprise it.
109///
110/// If Offsets is non-null, it points to a vector to be filled in
111/// with the in-memory offsets of each of the individual values.
112///
113static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
114 SmallVectorImpl<MVT> &ValueVTs,
115 SmallVectorImpl<uint64_t> *Offsets = 0,
116 uint64_t StartingOffset = 0) {
117 // Given a struct type, recursively traverse the elements.
118 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
119 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
120 for (StructType::element_iterator EB = STy->element_begin(),
121 EI = EB,
122 EE = STy->element_end();
123 EI != EE; ++EI)
124 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
125 StartingOffset + SL->getElementOffset(EI - EB));
126 return;
127 }
128 // Given an array type, recursively traverse the elements.
129 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
130 const Type *EltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000131 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000132 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
133 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
134 StartingOffset + i * EltSize);
135 return;
136 }
Dan Gohman5e5558b2009-04-23 22:50:03 +0000137 // Interpret void as zero return values.
138 if (Ty == Type::VoidTy)
139 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000140 // Base case: we can get an MVT for this LLVM IR type.
141 ValueVTs.push_back(TLI.getValueType(Ty));
142 if (Offsets)
143 Offsets->push_back(StartingOffset);
144}
145
Dan Gohman2a7c6712008-09-03 23:18:39 +0000146namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000147 /// RegsForValue - This struct represents the registers (physical or virtual)
148 /// that a particular set of values is assigned, and the type information about
149 /// the value. The most common situation is to represent one value at a time,
150 /// but struct or array values are handled element-wise as multiple values.
151 /// The splitting of aggregates is performed recursively, so that we never
152 /// have aggregate-typed registers. The values at this point do not necessarily
153 /// have legal types, so each value may require one or more registers of some
154 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000155 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000156 struct VISIBILITY_HIDDEN RegsForValue {
157 /// TLI - The TargetLowering object.
158 ///
159 const TargetLowering *TLI;
160
161 /// ValueVTs - The value types of the values, which may not be legal, and
162 /// may need be promoted or synthesized from one or more registers.
163 ///
164 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000165
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000166 /// RegVTs - The value types of the registers. This is the same size as
167 /// ValueVTs and it records, for each value, what the type of the assigned
168 /// register or registers are. (Individual values are never synthesized
169 /// from more than one type of register.)
170 ///
171 /// With virtual registers, the contents of RegVTs is redundant with TLI's
172 /// getRegisterType member function, however when with physical registers
173 /// it is necessary to have a separate record of the types.
174 ///
175 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000176
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000177 /// Regs - This list holds the registers assigned to the values.
178 /// Each legal or promoted value requires one register, and each
179 /// expanded value requires multiple registers.
180 ///
181 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000186 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 MVT regvt, MVT valuevt)
188 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
189 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000190 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000191 const SmallVector<MVT, 4> &regvts,
192 const SmallVector<MVT, 4> &valuevts)
193 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
194 RegsForValue(const TargetLowering &tli,
195 unsigned Reg, const Type *Ty) : TLI(&tli) {
196 ComputeValueVTs(tli, Ty, ValueVTs);
197
198 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
199 MVT ValueVT = ValueVTs[Value];
200 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
201 MVT RegisterVT = TLI->getRegisterType(ValueVT);
202 for (unsigned i = 0; i != NumRegs; ++i)
203 Regs.push_back(Reg + i);
204 RegVTs.push_back(RegisterVT);
205 Reg += NumRegs;
206 }
207 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000208
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209 /// append - Add the specified values to this one.
210 void append(const RegsForValue &RHS) {
211 TLI = RHS.TLI;
212 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
213 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
214 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
215 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216
217
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000218 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000219 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000220 /// Chain/Flag as the input and updates them for the output Chain/Flag.
221 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000222 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000223 SDValue &Chain, SDValue *Flag) const;
224
225 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000226 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000227 /// Chain/Flag as the input and updates them for the output Chain/Flag.
228 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000229 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000232 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000233 /// operand list. This adds the code marker, matching input operand index
234 /// (if applicable), and includes the number of values added into it.
235 void AddInlineAsmOperands(unsigned Code,
236 bool HasMatching, unsigned MatchingIdx,
237 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000238 };
239}
240
241/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000242/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000243/// switch or atomic instruction, which may expand to multiple basic blocks.
244static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
245 if (isa<PHINode>(I)) return true;
246 BasicBlock *BB = I->getParent();
247 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Dan Gohman8e5c0da2009-04-09 02:33:36 +0000248 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000249 return true;
250 return false;
251}
252
253/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
254/// entry block, return true. This includes arguments used by switches, since
255/// the switch may expand into multiple basic blocks.
256static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
257 // With FastISel active, we may be splitting blocks, so force creation
258 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000259 // Don't force virtual registers for byval arguments though, because
260 // fast-isel can't handle those in all cases.
261 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000262 return A->use_empty();
263
264 BasicBlock *Entry = A->getParent()->begin();
265 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
266 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
267 return false; // Use not in entry block.
268 return true;
269}
270
271FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
272 : TLI(tli) {
273}
274
275void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000276 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000277 bool EnableFastISel) {
278 Fn = &fn;
279 MF = &mf;
280 RegInfo = &MF->getRegInfo();
281
282 // Create a vreg for each argument register that is not dead and is used
283 // outside of the entry block for the function.
284 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
285 AI != E; ++AI)
286 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
287 InitializeRegForValue(AI);
288
289 // Initialize the mapping of values to registers. This is only set up for
290 // instruction values that are used outside of the block that defines
291 // them.
292 Function::iterator BB = Fn->begin(), EB = Fn->end();
293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
294 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
295 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
296 const Type *Ty = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000297 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000298 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000299 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
300 AI->getAlignment());
301
302 TySize *= CUI->getZExtValue(); // Get total allocated size.
303 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
304 StaticAllocaMap[AI] =
305 MF->getFrameInfo()->CreateStackObject(TySize, Align);
306 }
307
308 for (; BB != EB; ++BB)
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
311 if (!isa<AllocaInst>(I) ||
312 !StaticAllocaMap.count(cast<AllocaInst>(I)))
313 InitializeRegForValue(I);
314
315 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
316 // also creates the initial PHI MachineInstrs, though none of the input
317 // operands are populated.
318 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
319 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
320 MBBMap[BB] = MBB;
321 MF->push_back(MBB);
322
323 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
324 // appropriate.
325 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000326 DebugLoc DL;
327 for (BasicBlock::iterator
328 I = BB->begin(), E = BB->end(); I != E; ++I) {
329 if (CallInst *CI = dyn_cast<CallInst>(I)) {
330 if (Function *F = CI->getCalledFunction()) {
331 switch (F->getIntrinsicID()) {
332 default: break;
333 case Intrinsic::dbg_stoppoint: {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000334 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
335
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000336 if (DIDescriptor::ValidDebugInfo(SPI->getContext(),
337 CodeGenOpt::Default)) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000338 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Argyrios Kyrtzidisa26eae62009-04-30 23:22:31 +0000339 unsigned idx = MF->getOrCreateDebugLocID(CU.getGV(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000340 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000341 SPI->getColumn());
342 DL = DebugLoc::get(idx);
343 }
344
345 break;
346 }
347 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000348 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
349 Value *SP = FSI->getSubprogram();
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000350
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000351 if (DIDescriptor::ValidDebugInfo(SP, CodeGenOpt::Default)) {
352 DISubprogram Subprogram(cast<GlobalVariable>(SP));
353 DICompileUnit CU(Subprogram.getCompileUnit());
354 unsigned Line = Subprogram.getLineNumber();
Bill Wendlingdf7d5d32009-05-21 00:04:55 +0000355 DL = DebugLoc::get(MF->getOrCreateDebugLocID(CU.getGV(),
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000356 Line, 0));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000357 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000358
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000359 break;
360 }
361 }
362 }
363 }
364
365 PN = dyn_cast<PHINode>(I);
366 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000367
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000368 unsigned PHIReg = ValueMap[PN];
369 assert(PHIReg && "PHI node does not have an assigned virtual register!");
370
371 SmallVector<MVT, 4> ValueVTs;
372 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
373 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
374 MVT VT = ValueVTs[vti];
375 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000376 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000377 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000378 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000379 PHIReg += NumRegisters;
380 }
381 }
382 }
383}
384
385unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
386 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
387}
388
389/// CreateRegForValue - Allocate the appropriate number of virtual registers of
390/// the correctly promoted or expanded types. Assign these registers
391/// consecutive vreg numbers and return the first assigned number.
392///
393/// In the case that the given value has struct or array type, this function
394/// will assign registers for each member or element.
395///
396unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
397 SmallVector<MVT, 4> ValueVTs;
398 ComputeValueVTs(TLI, V->getType(), ValueVTs);
399
400 unsigned FirstReg = 0;
401 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
402 MVT ValueVT = ValueVTs[Value];
403 MVT RegisterVT = TLI.getRegisterType(ValueVT);
404
405 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
406 for (unsigned i = 0; i != NumRegs; ++i) {
407 unsigned R = MakeReg(RegisterVT);
408 if (!FirstReg) FirstReg = R;
409 }
410 }
411 return FirstReg;
412}
413
414/// getCopyFromParts - Create a value that contains the specified legal parts
415/// combined into the value they represent. If the parts combine to a type
416/// larger then ValueVT then AssertOp can be used to specify whether the extra
417/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
418/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000419static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
420 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000421 unsigned NumParts, MVT PartVT, MVT ValueVT,
422 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000423 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000425 SDValue Val = Parts[0];
426
427 if (NumParts > 1) {
428 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000429 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 unsigned PartBits = PartVT.getSizeInBits();
431 unsigned ValueBits = ValueVT.getSizeInBits();
432
433 // Assemble the power of 2 part.
434 unsigned RoundParts = NumParts & (NumParts - 1) ?
435 1 << Log2_32(NumParts) : NumParts;
436 unsigned RoundBits = PartBits * RoundParts;
437 MVT RoundVT = RoundBits == ValueBits ?
438 ValueVT : MVT::getIntegerVT(RoundBits);
439 SDValue Lo, Hi;
440
Eli Friedman2ac8b322009-05-20 06:02:09 +0000441 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000444 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
445 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000446 PartVT, HalfVT);
447 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000448 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
449 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000450 }
451 if (TLI.isBigEndian())
452 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000453 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000454
455 if (RoundParts < NumParts) {
456 // Assemble the trailing non-power-of-2 part.
457 unsigned OddParts = NumParts - RoundParts;
458 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000459 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000460 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000461
462 // Combine the round and odd parts.
463 Lo = Val;
464 if (TLI.isBigEndian())
465 std::swap(Lo, Hi);
466 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000467 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
468 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000469 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000470 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000471 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
472 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000474 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000475 // Handle a multi-element vector.
476 MVT IntermediateVT, RegisterVT;
477 unsigned NumIntermediates;
478 unsigned NumRegs =
479 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
480 RegisterVT);
481 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
482 NumParts = NumRegs; // Silence a compiler warning.
483 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
484 assert(RegisterVT == Parts[0].getValueType() &&
485 "Part type doesn't match part!");
486
487 // Assemble the parts into intermediate operands.
488 SmallVector<SDValue, 8> Ops(NumIntermediates);
489 if (NumIntermediates == NumParts) {
490 // If the register was not expanded, truncate or copy the value,
491 // as appropriate.
492 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000493 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000494 PartVT, IntermediateVT);
495 } else if (NumParts > 0) {
496 // If the intermediate type was expanded, build the intermediate operands
497 // from the parts.
498 assert(NumParts % NumIntermediates == 0 &&
499 "Must expand into a divisible number of parts!");
500 unsigned Factor = NumParts / NumIntermediates;
501 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000502 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000503 PartVT, IntermediateVT);
504 }
505
506 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
507 // operands.
508 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000509 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000510 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000511 } else if (PartVT.isFloatingPoint()) {
512 // FP split into multiple FP parts (for ppcf128)
513 assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
514 "Unexpected split");
515 SDValue Lo, Hi;
516 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
517 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[1]);
518 if (TLI.isBigEndian())
519 std::swap(Lo, Hi);
520 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
521 } else {
522 // FP split into integer parts (soft fp)
523 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
524 !PartVT.isVector() && "Unexpected split");
525 MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
526 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000527 }
528 }
529
530 // There is now one part, held in Val. Correct it to match ValueVT.
531 PartVT = Val.getValueType();
532
533 if (PartVT == ValueVT)
534 return Val;
535
536 if (PartVT.isVector()) {
537 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000538 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539 }
540
541 if (ValueVT.isVector()) {
542 assert(ValueVT.getVectorElementType() == PartVT &&
543 ValueVT.getVectorNumElements() == 1 &&
544 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000545 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000546 }
547
548 if (PartVT.isInteger() &&
549 ValueVT.isInteger()) {
550 if (ValueVT.bitsLT(PartVT)) {
551 // For a truncate, see if we have any information to
552 // indicate whether the truncated bits will always be
553 // zero or sign-extension.
554 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000555 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000556 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000557 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000559 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000560 }
561 }
562
563 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
564 if (ValueVT.bitsLT(Val.getValueType()))
565 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000566 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000568 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000569 }
570
571 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000572 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000573
574 assert(0 && "Unknown mismatch!");
575 return SDValue();
576}
577
578/// getCopyToParts - Create a series of nodes that contain the specified value
579/// split into legal parts. If the parts contain more bits than Val, then, for
580/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000581static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000582 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000583 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000585 MVT PtrVT = TLI.getPointerTy();
586 MVT ValueVT = Val.getValueType();
587 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000588 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000589 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
590
591 if (!NumParts)
592 return;
593
594 if (!ValueVT.isVector()) {
595 if (PartVT == ValueVT) {
596 assert(NumParts == 1 && "No-op copy with multiple parts!");
597 Parts[0] = Val;
598 return;
599 }
600
601 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
602 // If the parts cover more bits than the value has, promote the value.
603 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
604 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000605 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000606 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
607 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000608 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000609 } else {
610 assert(0 && "Unknown mismatch!");
611 }
612 } else if (PartBits == ValueVT.getSizeInBits()) {
613 // Different types of the same size.
614 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000615 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
617 // If the parts cover less bits than value has, truncate the value.
618 if (PartVT.isInteger() && ValueVT.isInteger()) {
619 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000620 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000621 } else {
622 assert(0 && "Unknown mismatch!");
623 }
624 }
625
626 // The value may have changed - recompute ValueVT.
627 ValueVT = Val.getValueType();
628 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
629 "Failed to tile the value with PartVT!");
630
631 if (NumParts == 1) {
632 assert(PartVT == ValueVT && "Type conversion failed!");
633 Parts[0] = Val;
634 return;
635 }
636
637 // Expand the value into multiple parts.
638 if (NumParts & (NumParts - 1)) {
639 // The number of parts is not a power of 2. Split off and copy the tail.
640 assert(PartVT.isInteger() && ValueVT.isInteger() &&
641 "Do not know what to expand to!");
642 unsigned RoundParts = 1 << Log2_32(NumParts);
643 unsigned RoundBits = RoundParts * PartBits;
644 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000645 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000646 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000647 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000648 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000649 if (TLI.isBigEndian())
650 // The odd parts were reversed by getCopyToParts - unreverse them.
651 std::reverse(Parts + RoundParts, Parts + NumParts);
652 NumParts = RoundParts;
653 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000654 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 }
656
657 // The number of parts is a power of 2. Repeatedly bisect the value using
658 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000659 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000660 MVT::getIntegerVT(ValueVT.getSizeInBits()),
661 Val);
662 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
663 for (unsigned i = 0; i < NumParts; i += StepSize) {
664 unsigned ThisBits = StepSize * PartBits / 2;
665 MVT ThisVT = MVT::getIntegerVT (ThisBits);
666 SDValue &Part0 = Parts[i];
667 SDValue &Part1 = Parts[i+StepSize/2];
668
Scott Michelfdc40a02009-02-17 22:15:04 +0000669 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000670 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000671 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000672 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000673 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000674 DAG.getConstant(0, PtrVT));
675
676 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000677 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000678 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000679 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000680 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681 }
682 }
683 }
684
685 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000686 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000687
688 return;
689 }
690
691 // Vector ValueVT.
692 if (NumParts == 1) {
693 if (PartVT != ValueVT) {
694 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000695 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000696 } else {
697 assert(ValueVT.getVectorElementType() == PartVT &&
698 ValueVT.getVectorNumElements() == 1 &&
699 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000700 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000701 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000702 DAG.getConstant(0, PtrVT));
703 }
704 }
705
706 Parts[0] = Val;
707 return;
708 }
709
710 // Handle a multi-element vector.
711 MVT IntermediateVT, RegisterVT;
712 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000713 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000714 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
715 RegisterVT);
716 unsigned NumElements = ValueVT.getVectorNumElements();
717
718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719 NumParts = NumRegs; // Silence a compiler warning.
720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
721
722 // Split the vector into intermediate operands.
723 SmallVector<SDValue, 8> Ops(NumIntermediates);
724 for (unsigned i = 0; i != NumIntermediates; ++i)
725 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000726 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000727 IntermediateVT, Val,
728 DAG.getConstant(i * (NumElements / NumIntermediates),
729 PtrVT));
730 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000731 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000732 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000733 DAG.getConstant(i, PtrVT));
734
735 // Split the intermediate operands into legal parts.
736 if (NumParts == NumIntermediates) {
737 // If the register was not expanded, promote or copy the value,
738 // as appropriate.
739 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000740 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000741 } else if (NumParts > 0) {
742 // If the intermediate type was expanded, split each the value into
743 // legal parts.
744 assert(NumParts % NumIntermediates == 0 &&
745 "Must expand into a divisible number of parts!");
746 unsigned Factor = NumParts / NumIntermediates;
747 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000748 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000749 }
750}
751
752
753void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
754 AA = &aa;
755 GFI = gfi;
756 TD = DAG.getTarget().getTargetData();
757}
758
759/// clear - Clear out the curret SelectionDAG and the associated
760/// state and prepare this SelectionDAGLowering object to be used
761/// for a new block. This doesn't clear out information about
762/// additional blocks that are needed to complete switch lowering
763/// or PHI node updating; that information is cleared out as it is
764/// consumed.
765void SelectionDAGLowering::clear() {
766 NodeMap.clear();
767 PendingLoads.clear();
768 PendingExports.clear();
769 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000770 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000771}
772
773/// getRoot - Return the current virtual root of the Selection DAG,
774/// flushing any PendingLoad items. This must be done before emitting
775/// a store or any other node that may need to be ordered after any
776/// prior load instructions.
777///
778SDValue SelectionDAGLowering::getRoot() {
779 if (PendingLoads.empty())
780 return DAG.getRoot();
781
782 if (PendingLoads.size() == 1) {
783 SDValue Root = PendingLoads[0];
784 DAG.setRoot(Root);
785 PendingLoads.clear();
786 return Root;
787 }
788
789 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000790 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000791 &PendingLoads[0], PendingLoads.size());
792 PendingLoads.clear();
793 DAG.setRoot(Root);
794 return Root;
795}
796
797/// getControlRoot - Similar to getRoot, but instead of flushing all the
798/// PendingLoad items, flush all the PendingExports items. It is necessary
799/// to do this before emitting a terminator instruction.
800///
801SDValue SelectionDAGLowering::getControlRoot() {
802 SDValue Root = DAG.getRoot();
803
804 if (PendingExports.empty())
805 return Root;
806
807 // Turn all of the CopyToReg chains into one factored node.
808 if (Root.getOpcode() != ISD::EntryToken) {
809 unsigned i = 0, e = PendingExports.size();
810 for (; i != e; ++i) {
811 assert(PendingExports[i].getNode()->getNumOperands() > 1);
812 if (PendingExports[i].getNode()->getOperand(0) == Root)
813 break; // Don't add the root if we already indirectly depend on it.
814 }
815
816 if (i == e)
817 PendingExports.push_back(Root);
818 }
819
Dale Johannesen66978ee2009-01-31 02:22:37 +0000820 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000821 &PendingExports[0],
822 PendingExports.size());
823 PendingExports.clear();
824 DAG.setRoot(Root);
825 return Root;
826}
827
828void SelectionDAGLowering::visit(Instruction &I) {
829 visit(I.getOpcode(), I);
830}
831
832void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
833 // Note: this doesn't use InstVisitor, because it has to work with
834 // ConstantExpr's in addition to instructions.
835 switch (Opcode) {
836 default: assert(0 && "Unknown instruction type encountered!");
837 abort();
838 // Build the switch statement using the Instruction.def file.
839#define HANDLE_INST(NUM, OPCODE, CLASS) \
840 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
841#include "llvm/Instruction.def"
842 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000843}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000844
845void SelectionDAGLowering::visitAdd(User &I) {
846 if (I.getType()->isFPOrFPVector())
847 visitBinary(I, ISD::FADD);
848 else
849 visitBinary(I, ISD::ADD);
850}
851
852void SelectionDAGLowering::visitMul(User &I) {
853 if (I.getType()->isFPOrFPVector())
854 visitBinary(I, ISD::FMUL);
855 else
856 visitBinary(I, ISD::MUL);
857}
858
859SDValue SelectionDAGLowering::getValue(const Value *V) {
860 SDValue &N = NodeMap[V];
861 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000862
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000863 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
864 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000867 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000868
869 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
870 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000872 if (isa<ConstantPointerNull>(C))
873 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000874
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000875 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000876 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000877
Nate Begeman9008ca62009-04-27 18:41:29 +0000878 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000879 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000880
881 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
882 visit(CE->getOpcode(), *CE);
883 SDValue N1 = NodeMap[V];
884 assert(N1.getNode() && "visit didn't populate the ValueMap!");
885 return N1;
886 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000887
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000888 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
889 SmallVector<SDValue, 4> Constants;
890 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
891 OI != OE; ++OI) {
892 SDNode *Val = getValue(*OI).getNode();
893 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
894 Constants.push_back(SDValue(Val, i));
895 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000896 return DAG.getMergeValues(&Constants[0], Constants.size(),
897 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000898 }
899
900 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
901 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
902 "Unknown struct or array constant!");
903
904 SmallVector<MVT, 4> ValueVTs;
905 ComputeValueVTs(TLI, C->getType(), ValueVTs);
906 unsigned NumElts = ValueVTs.size();
907 if (NumElts == 0)
908 return SDValue(); // empty struct
909 SmallVector<SDValue, 4> Constants(NumElts);
910 for (unsigned i = 0; i != NumElts; ++i) {
911 MVT EltVT = ValueVTs[i];
912 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000913 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000914 else if (EltVT.isFloatingPoint())
915 Constants[i] = DAG.getConstantFP(0, EltVT);
916 else
917 Constants[i] = DAG.getConstant(0, EltVT);
918 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000919 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000920 }
921
922 const VectorType *VecTy = cast<VectorType>(V->getType());
923 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000924
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000925 // Now that we know the number and type of the elements, get that number of
926 // elements into the Ops array based on what kind of constant it is.
927 SmallVector<SDValue, 16> Ops;
928 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
929 for (unsigned i = 0; i != NumElements; ++i)
930 Ops.push_back(getValue(CP->getOperand(i)));
931 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000932 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000933 MVT EltVT = TLI.getValueType(VecTy->getElementType());
934
935 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000936 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000937 Op = DAG.getConstantFP(0, EltVT);
938 else
939 Op = DAG.getConstant(0, EltVT);
940 Ops.assign(NumElements, Op);
941 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000943 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000944 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
945 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000947
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000948 // If this is a static alloca, generate it as the frameindex instead of
949 // computation.
950 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
951 DenseMap<const AllocaInst*, int>::iterator SI =
952 FuncInfo.StaticAllocaMap.find(AI);
953 if (SI != FuncInfo.StaticAllocaMap.end())
954 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
955 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000956
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000957 unsigned InReg = FuncInfo.ValueMap[V];
958 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000959
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000960 RegsForValue RFV(TLI, InReg, V->getType());
961 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000962 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000963}
964
965
966void SelectionDAGLowering::visitRet(ReturnInst &I) {
967 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000968 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000969 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000970 return;
971 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000972
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000973 SmallVector<SDValue, 8> NewValues;
974 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000975 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000976 SmallVector<MVT, 4> ValueVTs;
977 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000978 unsigned NumValues = ValueVTs.size();
979 if (NumValues == 0) continue;
980
981 SDValue RetOp = getValue(I.getOperand(i));
982 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000983 MVT VT = ValueVTs[j];
984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000985 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000986
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000987 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000988 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000989 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000990 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000991 ExtendKind = ISD::ZERO_EXTEND;
992
Evan Cheng3927f432009-03-25 20:20:11 +0000993 // FIXME: C calling convention requires the return type to be promoted to
994 // at least 32-bit. But this is not necessary for non-C calling
995 // conventions. The frontend should mark functions whose return values
996 // require promoting with signext or zeroext attributes.
997 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
998 MVT MinVT = TLI.getRegisterType(MVT::i32);
999 if (VT.bitsLT(MinVT))
1000 VT = MinVT;
1001 }
1002
1003 unsigned NumParts = TLI.getNumRegisters(VT);
1004 MVT PartVT = TLI.getRegisterType(VT);
1005 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +00001006 getCopyToParts(DAG, getCurDebugLoc(),
1007 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001008 &Parts[0], NumParts, PartVT, ExtendKind);
1009
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001010 // 'inreg' on function refers to return value
1011 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001012 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001013 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001014 for (unsigned i = 0; i < NumParts; ++i) {
1015 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001016 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001017 }
1018 }
1019 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001020 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001021 &NewValues[0], NewValues.size()));
1022}
1023
Dan Gohmanad62f532009-04-23 23:13:24 +00001024/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1025/// created for it, emit nodes to copy the value into the virtual
1026/// registers.
1027void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1028 if (!V->use_empty()) {
1029 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1030 if (VMI != FuncInfo.ValueMap.end())
1031 CopyValueToVirtualRegister(V, VMI->second);
1032 }
1033}
1034
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001035/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1036/// the current basic block, add it to ValueMap now so that we'll get a
1037/// CopyTo/FromReg.
1038void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1039 // No need to export constants.
1040 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001041
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001042 // Already exported?
1043 if (FuncInfo.isExportedInst(V)) return;
1044
1045 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1046 CopyValueToVirtualRegister(V, Reg);
1047}
1048
1049bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1050 const BasicBlock *FromBB) {
1051 // The operands of the setcc have to be in this block. We don't know
1052 // how to export them from some other block.
1053 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1054 // Can export from current BB.
1055 if (VI->getParent() == FromBB)
1056 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001057
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001058 // Is already exported, noop.
1059 return FuncInfo.isExportedInst(V);
1060 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001062 // If this is an argument, we can export it if the BB is the entry block or
1063 // if it is already exported.
1064 if (isa<Argument>(V)) {
1065 if (FromBB == &FromBB->getParent()->getEntryBlock())
1066 return true;
1067
1068 // Otherwise, can only export this if it is already exported.
1069 return FuncInfo.isExportedInst(V);
1070 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001071
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001072 // Otherwise, constants can always be exported.
1073 return true;
1074}
1075
1076static bool InBlock(const Value *V, const BasicBlock *BB) {
1077 if (const Instruction *I = dyn_cast<Instruction>(V))
1078 return I->getParent() == BB;
1079 return true;
1080}
1081
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001082/// getFCmpCondCode - Return the ISD condition code corresponding to
1083/// the given LLVM IR floating-point condition code. This includes
1084/// consideration of global floating-point math flags.
1085///
1086static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1087 ISD::CondCode FPC, FOC;
1088 switch (Pred) {
1089 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1090 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1091 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1092 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1093 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1094 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1095 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1096 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1097 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1098 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1099 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1100 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1101 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1102 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1103 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1104 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1105 default:
1106 assert(0 && "Invalid FCmp predicate opcode!");
1107 FOC = FPC = ISD::SETFALSE;
1108 break;
1109 }
1110 if (FiniteOnlyFPMath())
1111 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001112 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001113 return FPC;
1114}
1115
1116/// getICmpCondCode - Return the ISD condition code corresponding to
1117/// the given LLVM IR integer condition code.
1118///
1119static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1120 switch (Pred) {
1121 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1122 case ICmpInst::ICMP_NE: return ISD::SETNE;
1123 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1124 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1125 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1126 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1127 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1128 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1129 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1130 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1131 default:
1132 assert(0 && "Invalid ICmp predicate opcode!");
1133 return ISD::SETNE;
1134 }
1135}
1136
Dan Gohmanc2277342008-10-17 21:16:08 +00001137/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1138/// This function emits a branch and is used at the leaves of an OR or an
1139/// AND operator tree.
1140///
1141void
1142SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1143 MachineBasicBlock *TBB,
1144 MachineBasicBlock *FBB,
1145 MachineBasicBlock *CurBB) {
1146 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001147
Dan Gohmanc2277342008-10-17 21:16:08 +00001148 // If the leaf of the tree is a comparison, merge the condition into
1149 // the caseblock.
1150 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1151 // The operands of the cmp have to be in this block. We don't know
1152 // how to export them from some other block. If this is the first block
1153 // of the sequence, no exporting is needed.
1154 if (CurBB == CurMBB ||
1155 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1156 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001157 ISD::CondCode Condition;
1158 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001159 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001160 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001161 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001162 } else {
1163 Condition = ISD::SETEQ; // silence warning.
1164 assert(0 && "Unknown compare instruction");
1165 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001166
1167 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001168 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1169 SwitchCases.push_back(CB);
1170 return;
1171 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001172 }
1173
1174 // Create a CaseBlock record representing this branch.
1175 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1176 NULL, TBB, FBB, CurBB);
1177 SwitchCases.push_back(CB);
1178}
1179
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001180/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001181void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1182 MachineBasicBlock *TBB,
1183 MachineBasicBlock *FBB,
1184 MachineBasicBlock *CurBB,
1185 unsigned Opc) {
1186 // If this node is not part of the or/and tree, emit it as a branch.
1187 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001188 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001189 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1190 BOp->getParent() != CurBB->getBasicBlock() ||
1191 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1192 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1193 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001194 return;
1195 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001196
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001197 // Create TmpBB after CurBB.
1198 MachineFunction::iterator BBI = CurBB;
1199 MachineFunction &MF = DAG.getMachineFunction();
1200 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1201 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001202
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001203 if (Opc == Instruction::Or) {
1204 // Codegen X | Y as:
1205 // jmp_if_X TBB
1206 // jmp TmpBB
1207 // TmpBB:
1208 // jmp_if_Y TBB
1209 // jmp FBB
1210 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001212 // Emit the LHS condition.
1213 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001215 // Emit the RHS condition into TmpBB.
1216 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1217 } else {
1218 assert(Opc == Instruction::And && "Unknown merge op!");
1219 // Codegen X & Y as:
1220 // jmp_if_X TmpBB
1221 // jmp FBB
1222 // TmpBB:
1223 // jmp_if_Y TBB
1224 // jmp FBB
1225 //
1226 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001227
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001228 // Emit the LHS condition.
1229 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001230
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001231 // Emit the RHS condition into TmpBB.
1232 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1233 }
1234}
1235
1236/// If the set of cases should be emitted as a series of branches, return true.
1237/// If we should emit this as a bunch of and/or'd together conditions, return
1238/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001239bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001240SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1241 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001242
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001243 // If this is two comparisons of the same values or'd or and'd together, they
1244 // will get folded into a single comparison, so don't emit two blocks.
1245 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1246 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1247 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1248 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1249 return false;
1250 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001251
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001252 return true;
1253}
1254
1255void SelectionDAGLowering::visitBr(BranchInst &I) {
1256 // Update machine-CFG edges.
1257 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1258
1259 // Figure out which block is immediately after the current one.
1260 MachineBasicBlock *NextBlock = 0;
1261 MachineFunction::iterator BBI = CurMBB;
1262 if (++BBI != CurMBB->getParent()->end())
1263 NextBlock = BBI;
1264
1265 if (I.isUnconditional()) {
1266 // Update machine-CFG edges.
1267 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001268
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001269 // If this is not a fall-through branch, emit the branch.
1270 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001271 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001272 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001273 DAG.getBasicBlock(Succ0MBB)));
1274 return;
1275 }
1276
1277 // If this condition is one of the special cases we handle, do special stuff
1278 // now.
1279 Value *CondVal = I.getCondition();
1280 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1281
1282 // If this is a series of conditions that are or'd or and'd together, emit
1283 // this as a sequence of branches instead of setcc's with and/or operations.
1284 // For example, instead of something like:
1285 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001286 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001287 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001288 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001289 // or C, F
1290 // jnz foo
1291 // Emit:
1292 // cmp A, B
1293 // je foo
1294 // cmp D, E
1295 // jle foo
1296 //
1297 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001298 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001299 (BOp->getOpcode() == Instruction::And ||
1300 BOp->getOpcode() == Instruction::Or)) {
1301 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1302 // If the compares in later blocks need to use values not currently
1303 // exported from this block, export them now. This block should always
1304 // be the first entry.
1305 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001306
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001307 // Allow some cases to be rejected.
1308 if (ShouldEmitAsBranches(SwitchCases)) {
1309 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1310 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1311 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1312 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001313
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001314 // Emit the branch for this block.
1315 visitSwitchCase(SwitchCases[0]);
1316 SwitchCases.erase(SwitchCases.begin());
1317 return;
1318 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001319
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001320 // Okay, we decided not to do this, remove any inserted MBB's and clear
1321 // SwitchCases.
1322 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1323 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001324
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 SwitchCases.clear();
1326 }
1327 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001328
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001329 // Create a CaseBlock record representing this branch.
1330 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1331 NULL, Succ0MBB, Succ1MBB, CurMBB);
1332 // Use visitSwitchCase to actually insert the fast branch sequence for this
1333 // cond branch.
1334 visitSwitchCase(CB);
1335}
1336
1337/// visitSwitchCase - Emits the necessary code to represent a single node in
1338/// the binary search tree resulting from lowering a switch instruction.
1339void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1340 SDValue Cond;
1341 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001342 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001343
1344 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001345 if (CB.CmpMHS == NULL) {
1346 // Fold "(X == true)" to X and "(X == false)" to !X to
1347 // handle common cases produced by branch lowering.
1348 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1349 Cond = CondLHS;
1350 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1351 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001352 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001353 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001354 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001355 } else {
1356 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1357
Anton Korobeynikov23218582008-12-23 22:25:27 +00001358 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1359 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360
1361 SDValue CmpOp = getValue(CB.CmpMHS);
1362 MVT VT = CmpOp.getValueType();
1363
1364 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001365 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001366 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001368 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001369 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001370 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001371 DAG.getConstant(High-Low, VT), ISD::SETULE);
1372 }
1373 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001374
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001375 // Update successor info
1376 CurMBB->addSuccessor(CB.TrueBB);
1377 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001378
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001379 // Set NextBlock to be the MBB immediately after the current one, if any.
1380 // This is used to avoid emitting unnecessary branches to the next block.
1381 MachineBasicBlock *NextBlock = 0;
1382 MachineFunction::iterator BBI = CurMBB;
1383 if (++BBI != CurMBB->getParent()->end())
1384 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001385
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001386 // If the lhs block is the next block, invert the condition so that we can
1387 // fall through to the lhs instead of the rhs block.
1388 if (CB.TrueBB == NextBlock) {
1389 std::swap(CB.TrueBB, CB.FalseBB);
1390 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001391 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001392 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001393 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001394 MVT::Other, getControlRoot(), Cond,
1395 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001396
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001397 // If the branch was constant folded, fix up the CFG.
1398 if (BrCond.getOpcode() == ISD::BR) {
1399 CurMBB->removeSuccessor(CB.FalseBB);
1400 DAG.setRoot(BrCond);
1401 } else {
1402 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001403 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001404 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001405
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406 if (CB.FalseBB == NextBlock)
1407 DAG.setRoot(BrCond);
1408 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001409 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001410 DAG.getBasicBlock(CB.FalseBB)));
1411 }
1412}
1413
1414/// visitJumpTable - Emit JumpTable node in the current MBB
1415void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1416 // Emit the code for the jump table
1417 assert(JT.Reg != -1U && "Should lower JT Header first!");
1418 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001419 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1420 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001422 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001423 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001424 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001425}
1426
1427/// visitJumpTableHeader - This function emits necessary code to produce index
1428/// in the JumpTable from switch case.
1429void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1430 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001431 // Subtract the lowest switch case value from the value being switched on and
1432 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001433 // difference between smallest and largest cases.
1434 SDValue SwitchOp = getValue(JTH.SValue);
1435 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001436 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001437 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001438
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001439 // The SDNode we just created, which holds the value being switched on minus
1440 // the the smallest case value, needs to be copied to a virtual register so it
1441 // can be used as an index into the jump table in a subsequent basic block.
1442 // This value may be smaller or larger than the target's pointer type, and
1443 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001444 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001445 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001446 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001447 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001448 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001449 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001450
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001451 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001452 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1453 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001454 JT.Reg = JumpTableReg;
1455
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001456 // Emit the range check for the jump table, and branch to the default block
1457 // for the switch statement if the value being switched on exceeds the largest
1458 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001459 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1460 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001461 DAG.getConstant(JTH.Last-JTH.First,VT),
1462 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001463
1464 // Set NextBlock to be the MBB immediately after the current one, if any.
1465 // This is used to avoid emitting unnecessary branches to the next block.
1466 MachineBasicBlock *NextBlock = 0;
1467 MachineFunction::iterator BBI = CurMBB;
1468 if (++BBI != CurMBB->getParent()->end())
1469 NextBlock = BBI;
1470
Dale Johannesen66978ee2009-01-31 02:22:37 +00001471 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001472 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001473 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001474
1475 if (JT.MBB == NextBlock)
1476 DAG.setRoot(BrCond);
1477 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001478 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001479 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001480}
1481
1482/// visitBitTestHeader - This function emits necessary code to produce value
1483/// suitable for "bit tests"
1484void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1485 // Subtract the minimum value
1486 SDValue SwitchOp = getValue(B.SValue);
1487 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001488 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001489 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001490
1491 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001492 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1493 TLI.getSetCCResultType(SUB.getValueType()),
1494 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001495 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001496
1497 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001498 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001499 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001500 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001501 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001502 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001503 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001504
Duncan Sands92abc622009-01-31 15:50:11 +00001505 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001506 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1507 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001508
1509 // Set NextBlock to be the MBB immediately after the current one, if any.
1510 // This is used to avoid emitting unnecessary branches to the next block.
1511 MachineBasicBlock *NextBlock = 0;
1512 MachineFunction::iterator BBI = CurMBB;
1513 if (++BBI != CurMBB->getParent()->end())
1514 NextBlock = BBI;
1515
1516 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1517
1518 CurMBB->addSuccessor(B.Default);
1519 CurMBB->addSuccessor(MBB);
1520
Dale Johannesen66978ee2009-01-31 02:22:37 +00001521 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001522 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001523 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001524
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001525 if (MBB == NextBlock)
1526 DAG.setRoot(BrRange);
1527 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001528 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001529 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001530}
1531
1532/// visitBitTestCase - this function produces one "bit test"
1533void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1534 unsigned Reg,
1535 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001536 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001537 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001538 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001539 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001540 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001541 DAG.getConstant(1, TLI.getPointerTy()),
1542 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001543
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001544 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001545 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001546 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001547 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001548 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1549 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001550 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001551 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001552
1553 CurMBB->addSuccessor(B.TargetBB);
1554 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001555
Dale Johannesen66978ee2009-01-31 02:22:37 +00001556 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001557 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001558 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001559
1560 // Set NextBlock to be the MBB immediately after the current one, if any.
1561 // This is used to avoid emitting unnecessary branches to the next block.
1562 MachineBasicBlock *NextBlock = 0;
1563 MachineFunction::iterator BBI = CurMBB;
1564 if (++BBI != CurMBB->getParent()->end())
1565 NextBlock = BBI;
1566
1567 if (NextMBB == NextBlock)
1568 DAG.setRoot(BrAnd);
1569 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001570 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001571 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001572}
1573
1574void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1575 // Retrieve successors.
1576 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1577 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1578
Gabor Greifb67e6b32009-01-15 11:10:44 +00001579 const Value *Callee(I.getCalledValue());
1580 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 visitInlineAsm(&I);
1582 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001583 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001584
1585 // If the value of the invoke is used outside of its defining block, make it
1586 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001587 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001588
1589 // Update successor info
1590 CurMBB->addSuccessor(Return);
1591 CurMBB->addSuccessor(LandingPad);
1592
1593 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001594 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001595 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596 DAG.getBasicBlock(Return)));
1597}
1598
1599void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1600}
1601
1602/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1603/// small case ranges).
1604bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1605 CaseRecVector& WorkList,
1606 Value* SV,
1607 MachineBasicBlock* Default) {
1608 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001609
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001610 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001611 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001613 return false;
1614
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001615 // Get the MachineFunction which holds the current MBB. This is used when
1616 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001617 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618
1619 // Figure out which block is immediately after the current one.
1620 MachineBasicBlock *NextBlock = 0;
1621 MachineFunction::iterator BBI = CR.CaseBB;
1622
1623 if (++BBI != CurMBB->getParent()->end())
1624 NextBlock = BBI;
1625
1626 // TODO: If any two of the cases has the same destination, and if one value
1627 // is the same as the other, but has one bit unset that the other has set,
1628 // use bit manipulation to do two compares at once. For example:
1629 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001630
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001631 // Rearrange the case blocks so that the last one falls through if possible.
1632 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1633 // The last case block won't fall through into 'NextBlock' if we emit the
1634 // branches in this order. See if rearranging a case value would help.
1635 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1636 if (I->BB == NextBlock) {
1637 std::swap(*I, BackCase);
1638 break;
1639 }
1640 }
1641 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001642
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001643 // Create a CaseBlock record representing a conditional branch to
1644 // the Case's target mbb if the value being switched on SV is equal
1645 // to C.
1646 MachineBasicBlock *CurBlock = CR.CaseBB;
1647 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1648 MachineBasicBlock *FallThrough;
1649 if (I != E-1) {
1650 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1651 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001652
1653 // Put SV in a virtual register to make it available from the new blocks.
1654 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001655 } else {
1656 // If the last case doesn't match, go to the default block.
1657 FallThrough = Default;
1658 }
1659
1660 Value *RHS, *LHS, *MHS;
1661 ISD::CondCode CC;
1662 if (I->High == I->Low) {
1663 // This is just small small case range :) containing exactly 1 case
1664 CC = ISD::SETEQ;
1665 LHS = SV; RHS = I->High; MHS = NULL;
1666 } else {
1667 CC = ISD::SETLE;
1668 LHS = I->Low; MHS = SV; RHS = I->High;
1669 }
1670 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001671
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001672 // If emitting the first comparison, just call visitSwitchCase to emit the
1673 // code into the current block. Otherwise, push the CaseBlock onto the
1674 // vector to be later processed by SDISel, and insert the node's MBB
1675 // before the next MBB.
1676 if (CurBlock == CurMBB)
1677 visitSwitchCase(CB);
1678 else
1679 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001680
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001681 CurBlock = FallThrough;
1682 }
1683
1684 return true;
1685}
1686
1687static inline bool areJTsAllowed(const TargetLowering &TLI) {
1688 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001689 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1690 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001691}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001693static APInt ComputeRange(const APInt &First, const APInt &Last) {
1694 APInt LastExt(Last), FirstExt(First);
1695 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1696 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1697 return (LastExt - FirstExt + 1ULL);
1698}
1699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001700/// handleJTSwitchCase - Emit jumptable for current switch case range
1701bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1702 CaseRecVector& WorkList,
1703 Value* SV,
1704 MachineBasicBlock* Default) {
1705 Case& FrontCase = *CR.Range.first;
1706 Case& BackCase = *(CR.Range.second-1);
1707
Anton Korobeynikov23218582008-12-23 22:25:27 +00001708 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1709 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001710
Anton Korobeynikov23218582008-12-23 22:25:27 +00001711 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001712 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1713 I!=E; ++I)
1714 TSize += I->size();
1715
1716 if (!areJTsAllowed(TLI) || TSize <= 3)
1717 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001718
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001719 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001720 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001721 if (Density < 0.4)
1722 return false;
1723
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001724 DEBUG(errs() << "Lowering jump table\n"
1725 << "First entry: " << First << ". Last entry: " << Last << '\n'
1726 << "Range: " << Range
1727 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001728
1729 // Get the MachineFunction which holds the current MBB. This is used when
1730 // inserting any additional MBBs necessary to represent the switch.
1731 MachineFunction *CurMF = CurMBB->getParent();
1732
1733 // Figure out which block is immediately after the current one.
1734 MachineBasicBlock *NextBlock = 0;
1735 MachineFunction::iterator BBI = CR.CaseBB;
1736
1737 if (++BBI != CurMBB->getParent()->end())
1738 NextBlock = BBI;
1739
1740 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1741
1742 // Create a new basic block to hold the code for loading the address
1743 // of the jump table, and jumping to it. Update successor information;
1744 // we will either branch to the default case for the switch, or the jump
1745 // table.
1746 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1747 CurMF->insert(BBI, JumpTableBB);
1748 CR.CaseBB->addSuccessor(Default);
1749 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001750
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001751 // Build a vector of destination BBs, corresponding to each target
1752 // of the jump table. If the value of the jump table slot corresponds to
1753 // a case statement, push the case's BB onto the vector, otherwise, push
1754 // the default BB.
1755 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001756 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001757 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001758 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1759 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1760
1761 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001762 DestBBs.push_back(I->BB);
1763 if (TEI==High)
1764 ++I;
1765 } else {
1766 DestBBs.push_back(Default);
1767 }
1768 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001769
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001770 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001771 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1772 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001773 E = DestBBs.end(); I != E; ++I) {
1774 if (!SuccsHandled[(*I)->getNumber()]) {
1775 SuccsHandled[(*I)->getNumber()] = true;
1776 JumpTableBB->addSuccessor(*I);
1777 }
1778 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001779
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001780 // Create a jump table index for this jump table, or return an existing
1781 // one.
1782 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001783
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001784 // Set the jump table information so that we can codegen it as a second
1785 // MachineBasicBlock
1786 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1787 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1788 if (CR.CaseBB == CurMBB)
1789 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001790
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001791 JTCases.push_back(JumpTableBlock(JTH, JT));
1792
1793 return true;
1794}
1795
1796/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1797/// 2 subtrees.
1798bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1799 CaseRecVector& WorkList,
1800 Value* SV,
1801 MachineBasicBlock* Default) {
1802 // Get the MachineFunction which holds the current MBB. This is used when
1803 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001804 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001805
1806 // Figure out which block is immediately after the current one.
1807 MachineBasicBlock *NextBlock = 0;
1808 MachineFunction::iterator BBI = CR.CaseBB;
1809
1810 if (++BBI != CurMBB->getParent()->end())
1811 NextBlock = BBI;
1812
1813 Case& FrontCase = *CR.Range.first;
1814 Case& BackCase = *(CR.Range.second-1);
1815 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1816
1817 // Size is the number of Cases represented by this range.
1818 unsigned Size = CR.Range.second - CR.Range.first;
1819
Anton Korobeynikov23218582008-12-23 22:25:27 +00001820 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1821 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001822 double FMetric = 0;
1823 CaseItr Pivot = CR.Range.first + Size/2;
1824
1825 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1826 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001827 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001828 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1829 I!=E; ++I)
1830 TSize += I->size();
1831
Anton Korobeynikov23218582008-12-23 22:25:27 +00001832 size_t LSize = FrontCase.size();
1833 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001834 DEBUG(errs() << "Selecting best pivot: \n"
1835 << "First: " << First << ", Last: " << Last <<'\n'
1836 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001837 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1838 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001839 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1840 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001841 APInt Range = ComputeRange(LEnd, RBegin);
1842 assert((Range - 2ULL).isNonNegative() &&
1843 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001844 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1845 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001846 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001848 DEBUG(errs() <<"=>Step\n"
1849 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1850 << "LDensity: " << LDensity
1851 << ", RDensity: " << RDensity << '\n'
1852 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001853 if (FMetric < Metric) {
1854 Pivot = J;
1855 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001856 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001857 }
1858
1859 LSize += J->size();
1860 RSize -= J->size();
1861 }
1862 if (areJTsAllowed(TLI)) {
1863 // If our case is dense we *really* should handle it earlier!
1864 assert((FMetric > 0) && "Should handle dense range earlier!");
1865 } else {
1866 Pivot = CR.Range.first + Size/2;
1867 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001869 CaseRange LHSR(CR.Range.first, Pivot);
1870 CaseRange RHSR(Pivot, CR.Range.second);
1871 Constant *C = Pivot->Low;
1872 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001873
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001874 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001875 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001876 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001877 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001878 // Pivot's Value, then we can branch directly to the LHS's Target,
1879 // rather than creating a leaf node for it.
1880 if ((LHSR.second - LHSR.first) == 1 &&
1881 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001882 cast<ConstantInt>(C)->getValue() ==
1883 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001884 TrueBB = LHSR.first->BB;
1885 } else {
1886 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1887 CurMF->insert(BBI, TrueBB);
1888 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001889
1890 // Put SV in a virtual register to make it available from the new blocks.
1891 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001892 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001893
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001894 // Similar to the optimization above, if the Value being switched on is
1895 // known to be less than the Constant CR.LT, and the current Case Value
1896 // is CR.LT - 1, then we can branch directly to the target block for
1897 // the current Case Value, rather than emitting a RHS leaf node for it.
1898 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001899 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1900 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001901 FalseBB = RHSR.first->BB;
1902 } else {
1903 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1904 CurMF->insert(BBI, FalseBB);
1905 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001906
1907 // Put SV in a virtual register to make it available from the new blocks.
1908 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001909 }
1910
1911 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001912 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001913 // Otherwise, branch to LHS.
1914 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1915
1916 if (CR.CaseBB == CurMBB)
1917 visitSwitchCase(CB);
1918 else
1919 SwitchCases.push_back(CB);
1920
1921 return true;
1922}
1923
1924/// handleBitTestsSwitchCase - if current case range has few destination and
1925/// range span less, than machine word bitwidth, encode case range into series
1926/// of masks and emit bit tests with these masks.
1927bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1928 CaseRecVector& WorkList,
1929 Value* SV,
1930 MachineBasicBlock* Default){
1931 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1932
1933 Case& FrontCase = *CR.Range.first;
1934 Case& BackCase = *(CR.Range.second-1);
1935
1936 // Get the MachineFunction which holds the current MBB. This is used when
1937 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001938 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001939
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001940 // If target does not have legal shift left, do not emit bit tests at all.
1941 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1942 return false;
1943
Anton Korobeynikov23218582008-12-23 22:25:27 +00001944 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001945 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1946 I!=E; ++I) {
1947 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001949 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001951 // Count unique destinations
1952 SmallSet<MachineBasicBlock*, 4> Dests;
1953 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1954 Dests.insert(I->BB);
1955 if (Dests.size() > 3)
1956 // Don't bother the code below, if there are too much unique destinations
1957 return false;
1958 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001959 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1960 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001963 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1964 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001965 APInt cmpRange = maxValue - minValue;
1966
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001967 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1968 << "Low bound: " << minValue << '\n'
1969 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001970
1971 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001972 (!(Dests.size() == 1 && numCmps >= 3) &&
1973 !(Dests.size() == 2 && numCmps >= 5) &&
1974 !(Dests.size() >= 3 && numCmps >= 6)))
1975 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001976
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001977 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001978 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1979
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001980 // Optimize the case where all the case values fit in a
1981 // word without having to subtract minValue. In this case,
1982 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001983 if (minValue.isNonNegative() &&
1984 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1985 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001986 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001987 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001988 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001989
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001990 CaseBitsVector CasesBits;
1991 unsigned i, count = 0;
1992
1993 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1994 MachineBasicBlock* Dest = I->BB;
1995 for (i = 0; i < count; ++i)
1996 if (Dest == CasesBits[i].BB)
1997 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001998
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001999 if (i == count) {
2000 assert((count < 3) && "Too much destinations to test!");
2001 CasesBits.push_back(CaseBits(0, Dest, 0));
2002 count++;
2003 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002004
2005 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2006 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2007
2008 uint64_t lo = (lowValue - lowBound).getZExtValue();
2009 uint64_t hi = (highValue - lowBound).getZExtValue();
2010
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002011 for (uint64_t j = lo; j <= hi; j++) {
2012 CasesBits[i].Mask |= 1ULL << j;
2013 CasesBits[i].Bits++;
2014 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002015
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002016 }
2017 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002019 BitTestInfo BTC;
2020
2021 // Figure out which block is immediately after the current one.
2022 MachineFunction::iterator BBI = CR.CaseBB;
2023 ++BBI;
2024
2025 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2026
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002027 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002028 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002029 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2030 << ", Bits: " << CasesBits[i].Bits
2031 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002032
2033 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2034 CurMF->insert(BBI, CaseBB);
2035 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2036 CaseBB,
2037 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002038
2039 // Put SV in a virtual register to make it available from the new blocks.
2040 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002042
2043 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002044 -1U, (CR.CaseBB == CurMBB),
2045 CR.CaseBB, Default, BTC);
2046
2047 if (CR.CaseBB == CurMBB)
2048 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002050 BitTestCases.push_back(BTB);
2051
2052 return true;
2053}
2054
2055
2056/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002057size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002059 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002060
2061 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002062 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002063 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2064 Cases.push_back(Case(SI.getSuccessorValue(i),
2065 SI.getSuccessorValue(i),
2066 SMBB));
2067 }
2068 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2069
2070 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002071 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002072 // Must recompute end() each iteration because it may be
2073 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002074 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2075 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2076 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002077 MachineBasicBlock* nextBB = J->BB;
2078 MachineBasicBlock* currentBB = I->BB;
2079
2080 // If the two neighboring cases go to the same destination, merge them
2081 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002082 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002083 I->High = J->High;
2084 J = Cases.erase(J);
2085 } else {
2086 I = J++;
2087 }
2088 }
2089
2090 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2091 if (I->Low != I->High)
2092 // A range counts double, since it requires two compares.
2093 ++numCmps;
2094 }
2095
2096 return numCmps;
2097}
2098
Anton Korobeynikov23218582008-12-23 22:25:27 +00002099void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100 // Figure out which block is immediately after the current one.
2101 MachineBasicBlock *NextBlock = 0;
2102 MachineFunction::iterator BBI = CurMBB;
2103
2104 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2105
2106 // If there is only the default destination, branch to it if it is not the
2107 // next basic block. Otherwise, just fall through.
2108 if (SI.getNumOperands() == 2) {
2109 // Update machine-CFG edges.
2110
2111 // If this is not a fall-through branch, emit the branch.
2112 CurMBB->addSuccessor(Default);
2113 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002114 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002115 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002116 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002117 return;
2118 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002119
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002120 // If there are any non-default case statements, create a vector of Cases
2121 // representing each one, and sort the vector so that we can efficiently
2122 // create a binary search tree from them.
2123 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002124 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002125 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2126 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002127 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002128
2129 // Get the Value to be switched on and default basic blocks, which will be
2130 // inserted into CaseBlock records, representing basic blocks in the binary
2131 // search tree.
2132 Value *SV = SI.getOperand(0);
2133
2134 // Push the initial CaseRec onto the worklist
2135 CaseRecVector WorkList;
2136 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2137
2138 while (!WorkList.empty()) {
2139 // Grab a record representing a case range to process off the worklist
2140 CaseRec CR = WorkList.back();
2141 WorkList.pop_back();
2142
2143 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2144 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002145
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002146 // If the range has few cases (two or less) emit a series of specific
2147 // tests.
2148 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2149 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002150
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002151 // If the switch has more than 5 blocks, and at least 40% dense, and the
2152 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002153 // lowering the switch to a binary tree of conditional branches.
2154 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2155 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002157 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2158 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2159 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2160 }
2161}
2162
2163
2164void SelectionDAGLowering::visitSub(User &I) {
2165 // -0.0 - X --> fneg
2166 const Type *Ty = I.getType();
2167 if (isa<VectorType>(Ty)) {
2168 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2169 const VectorType *DestTy = cast<VectorType>(I.getType());
2170 const Type *ElTy = DestTy->getElementType();
2171 if (ElTy->isFloatingPoint()) {
2172 unsigned VL = DestTy->getNumElements();
2173 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2174 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2175 if (CV == CNZ) {
2176 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002177 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002178 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002179 return;
2180 }
2181 }
2182 }
2183 }
2184 if (Ty->isFloatingPoint()) {
2185 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2186 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2187 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002188 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002189 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002190 return;
2191 }
2192 }
2193
2194 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2195}
2196
2197void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2198 SDValue Op1 = getValue(I.getOperand(0));
2199 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002200
Scott Michelfdc40a02009-02-17 22:15:04 +00002201 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002202 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002203}
2204
2205void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2206 SDValue Op1 = getValue(I.getOperand(0));
2207 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002208 if (!isa<VectorType>(I.getType()) &&
2209 Op2.getValueType() != TLI.getShiftAmountTy()) {
2210 // If the operand is smaller than the shift count type, promote it.
2211 if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2212 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2213 TLI.getShiftAmountTy(), Op2);
2214 // If the operand is larger than the shift count type but the shift
2215 // count type has enough bits to represent any shift value, truncate
2216 // it now. This is a common case and it exposes the truncate to
2217 // optimization early.
2218 else if (TLI.getShiftAmountTy().getSizeInBits() >=
2219 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2220 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2221 TLI.getShiftAmountTy(), Op2);
2222 // Otherwise we'll need to temporarily settle for some other
2223 // convenient type; type legalization will make adjustments as
2224 // needed.
2225 else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002226 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002227 TLI.getPointerTy(), Op2);
2228 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002229 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002230 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002231 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002232
Scott Michelfdc40a02009-02-17 22:15:04 +00002233 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002234 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235}
2236
2237void SelectionDAGLowering::visitICmp(User &I) {
2238 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2239 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2240 predicate = IC->getPredicate();
2241 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2242 predicate = ICmpInst::Predicate(IC->getPredicate());
2243 SDValue Op1 = getValue(I.getOperand(0));
2244 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002245 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002246 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002247}
2248
2249void SelectionDAGLowering::visitFCmp(User &I) {
2250 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2251 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2252 predicate = FC->getPredicate();
2253 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2254 predicate = FCmpInst::Predicate(FC->getPredicate());
2255 SDValue Op1 = getValue(I.getOperand(0));
2256 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002257 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002258 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002259}
2260
2261void SelectionDAGLowering::visitVICmp(User &I) {
2262 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2263 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2264 predicate = IC->getPredicate();
2265 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2266 predicate = ICmpInst::Predicate(IC->getPredicate());
2267 SDValue Op1 = getValue(I.getOperand(0));
2268 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002269 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002270 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002271 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272}
2273
2274void SelectionDAGLowering::visitVFCmp(User &I) {
2275 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2276 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2277 predicate = FC->getPredicate();
2278 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2279 predicate = FCmpInst::Predicate(FC->getPredicate());
2280 SDValue Op1 = getValue(I.getOperand(0));
2281 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002282 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002283 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002284
Dale Johannesenf5d97892009-02-04 01:48:28 +00002285 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002286}
2287
2288void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002289 SmallVector<MVT, 4> ValueVTs;
2290 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2291 unsigned NumValues = ValueVTs.size();
2292 if (NumValues != 0) {
2293 SmallVector<SDValue, 4> Values(NumValues);
2294 SDValue Cond = getValue(I.getOperand(0));
2295 SDValue TrueVal = getValue(I.getOperand(1));
2296 SDValue FalseVal = getValue(I.getOperand(2));
2297
2298 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002299 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002300 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002301 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2302 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2303
Scott Michelfdc40a02009-02-17 22:15:04 +00002304 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002305 DAG.getVTList(&ValueVTs[0], NumValues),
2306 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002307 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002308}
2309
2310
2311void SelectionDAGLowering::visitTrunc(User &I) {
2312 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2313 SDValue N = getValue(I.getOperand(0));
2314 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002315 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002316}
2317
2318void SelectionDAGLowering::visitZExt(User &I) {
2319 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2320 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2321 SDValue N = getValue(I.getOperand(0));
2322 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002323 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002324}
2325
2326void SelectionDAGLowering::visitSExt(User &I) {
2327 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2328 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2329 SDValue N = getValue(I.getOperand(0));
2330 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002331 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002332}
2333
2334void SelectionDAGLowering::visitFPTrunc(User &I) {
2335 // FPTrunc is never a no-op cast, no need to check
2336 SDValue N = getValue(I.getOperand(0));
2337 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002338 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002339 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002340}
2341
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002342void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002343 // FPTrunc is never a no-op cast, no need to check
2344 SDValue N = getValue(I.getOperand(0));
2345 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002346 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002347}
2348
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002349void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002350 // FPToUI is never a no-op cast, no need to check
2351 SDValue N = getValue(I.getOperand(0));
2352 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002353 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002354}
2355
2356void SelectionDAGLowering::visitFPToSI(User &I) {
2357 // FPToSI is never a no-op cast, no need to check
2358 SDValue N = getValue(I.getOperand(0));
2359 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002360 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002361}
2362
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002363void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002364 // UIToFP is never a no-op cast, no need to check
2365 SDValue N = getValue(I.getOperand(0));
2366 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002367 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002368}
2369
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002370void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002371 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002372 SDValue N = getValue(I.getOperand(0));
2373 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002374 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002375}
2376
2377void SelectionDAGLowering::visitPtrToInt(User &I) {
2378 // What to do depends on the size of the integer and the size of the pointer.
2379 // We can either truncate, zero extend, or no-op, accordingly.
2380 SDValue N = getValue(I.getOperand(0));
2381 MVT SrcVT = N.getValueType();
2382 MVT DestVT = TLI.getValueType(I.getType());
2383 SDValue Result;
2384 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002385 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002386 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002387 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002388 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002389 setValue(&I, Result);
2390}
2391
2392void SelectionDAGLowering::visitIntToPtr(User &I) {
2393 // What to do depends on the size of the integer and the size of the pointer.
2394 // We can either truncate, zero extend, or no-op, accordingly.
2395 SDValue N = getValue(I.getOperand(0));
2396 MVT SrcVT = N.getValueType();
2397 MVT DestVT = TLI.getValueType(I.getType());
2398 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002399 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002400 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002401 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002402 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002403 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002404}
2405
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002406void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002407 SDValue N = getValue(I.getOperand(0));
2408 MVT DestVT = TLI.getValueType(I.getType());
2409
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002410 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002411 // is either a BIT_CONVERT or a no-op.
2412 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002413 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002414 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002415 else
2416 setValue(&I, N); // noop cast.
2417}
2418
2419void SelectionDAGLowering::visitInsertElement(User &I) {
2420 SDValue InVec = getValue(I.getOperand(0));
2421 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002422 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002423 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002424 getValue(I.getOperand(2)));
2425
Scott Michelfdc40a02009-02-17 22:15:04 +00002426 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002427 TLI.getValueType(I.getType()),
2428 InVec, InVal, InIdx));
2429}
2430
2431void SelectionDAGLowering::visitExtractElement(User &I) {
2432 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002433 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002434 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002435 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002436 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002437 TLI.getValueType(I.getType()), InVec, InIdx));
2438}
2439
Mon P Wangaeb06d22008-11-10 04:46:22 +00002440
2441// Utility for visitShuffleVector - Returns true if the mask is mask starting
2442// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002443static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2444 unsigned MaskNumElts = Mask.size();
2445 for (unsigned i = 0; i != MaskNumElts; ++i)
2446 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002447 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002448 return true;
2449}
2450
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002451void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002452 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002453 SDValue Src1 = getValue(I.getOperand(0));
2454 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002455
Nate Begeman9008ca62009-04-27 18:41:29 +00002456 // Convert the ConstantVector mask operand into an array of ints, with -1
2457 // representing undef values.
2458 SmallVector<Constant*, 8> MaskElts;
2459 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002460 unsigned MaskNumElts = MaskElts.size();
2461 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002462 if (isa<UndefValue>(MaskElts[i]))
2463 Mask.push_back(-1);
2464 else
2465 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2466 }
2467
Mon P Wangaeb06d22008-11-10 04:46:22 +00002468 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002469 MVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002470 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002471
Mon P Wangc7849c22008-11-16 05:06:27 +00002472 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002473 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2474 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002475 return;
2476 }
2477
2478 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002479 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2480 // Mask is longer than the source vectors and is a multiple of the source
2481 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002482 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002483 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2484 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002485 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002486 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002487 return;
2488 }
2489
Mon P Wangc7849c22008-11-16 05:06:27 +00002490 // Pad both vectors with undefs to make them the same length as the mask.
2491 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002492 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2493 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002494 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002495
Nate Begeman9008ca62009-04-27 18:41:29 +00002496 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2497 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002498 MOps1[0] = Src1;
2499 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002500
2501 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2502 getCurDebugLoc(), VT,
2503 &MOps1[0], NumConcat);
2504 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2505 getCurDebugLoc(), VT,
2506 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002507
Mon P Wangaeb06d22008-11-10 04:46:22 +00002508 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002509 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002510 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002511 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002512 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002513 MappedOps.push_back(Idx);
2514 else
2515 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002516 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002517 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2518 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002519 return;
2520 }
2521
Mon P Wangc7849c22008-11-16 05:06:27 +00002522 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002523 // Analyze the access pattern of the vector to see if we can extract
2524 // two subvectors and do the shuffle. The analysis is done by calculating
2525 // the range of elements the mask access on both vectors.
2526 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2527 int MaxRange[2] = {-1, -1};
2528
Nate Begeman5a5ca152009-04-29 05:20:52 +00002529 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002530 int Idx = Mask[i];
2531 int Input = 0;
2532 if (Idx < 0)
2533 continue;
2534
Nate Begeman5a5ca152009-04-29 05:20:52 +00002535 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002536 Input = 1;
2537 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002538 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002539 if (Idx > MaxRange[Input])
2540 MaxRange[Input] = Idx;
2541 if (Idx < MinRange[Input])
2542 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002543 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002544
Mon P Wangc7849c22008-11-16 05:06:27 +00002545 // Check if the access is smaller than the vector size and can we find
2546 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002547 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002548 int StartIdx[2]; // StartIdx to extract from
2549 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002550 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002551 RangeUse[Input] = 0; // Unused
2552 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002553 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002554 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002555 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002556 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002557 RangeUse[Input] = 1; // Extract from beginning of the vector
2558 StartIdx[Input] = 0;
2559 } else {
2560 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002561 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002562 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002563 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002564 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002565 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002566 }
2567
2568 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002569 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002570 return;
2571 }
2572 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2573 // Extract appropriate subvector and generate a vector shuffle
2574 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002575 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002576 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002577 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002579 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002580 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002581 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002582 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002583 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002584 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002585 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002586 int Idx = Mask[i];
2587 if (Idx < 0)
2588 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002589 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002590 MappedOps.push_back(Idx - StartIdx[0]);
2591 else
2592 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002593 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002594 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2595 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002596 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002597 }
2598 }
2599
Mon P Wangc7849c22008-11-16 05:06:27 +00002600 // We can't use either concat vectors or extract subvectors so fall back to
2601 // replacing the shuffle with extract and build vector.
2602 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002603 MVT EltVT = VT.getVectorElementType();
2604 MVT PtrVT = TLI.getPointerTy();
2605 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002606 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002607 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002608 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002609 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002610 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002611 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002612 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002613 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002614 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002615 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002616 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002617 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002618 }
2619 }
Evan Chenga87008d2009-02-25 22:49:59 +00002620 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2621 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002622}
2623
2624void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2625 const Value *Op0 = I.getOperand(0);
2626 const Value *Op1 = I.getOperand(1);
2627 const Type *AggTy = I.getType();
2628 const Type *ValTy = Op1->getType();
2629 bool IntoUndef = isa<UndefValue>(Op0);
2630 bool FromUndef = isa<UndefValue>(Op1);
2631
2632 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2633 I.idx_begin(), I.idx_end());
2634
2635 SmallVector<MVT, 4> AggValueVTs;
2636 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2637 SmallVector<MVT, 4> ValValueVTs;
2638 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2639
2640 unsigned NumAggValues = AggValueVTs.size();
2641 unsigned NumValValues = ValValueVTs.size();
2642 SmallVector<SDValue, 4> Values(NumAggValues);
2643
2644 SDValue Agg = getValue(Op0);
2645 SDValue Val = getValue(Op1);
2646 unsigned i = 0;
2647 // Copy the beginning value(s) from the original aggregate.
2648 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002649 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002650 SDValue(Agg.getNode(), Agg.getResNo() + i);
2651 // Copy values from the inserted value(s).
2652 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002653 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002654 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2655 // Copy remaining value(s) from the original aggregate.
2656 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002657 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002658 SDValue(Agg.getNode(), Agg.getResNo() + i);
2659
Scott Michelfdc40a02009-02-17 22:15:04 +00002660 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002661 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2662 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002663}
2664
2665void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2666 const Value *Op0 = I.getOperand(0);
2667 const Type *AggTy = Op0->getType();
2668 const Type *ValTy = I.getType();
2669 bool OutOfUndef = isa<UndefValue>(Op0);
2670
2671 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2672 I.idx_begin(), I.idx_end());
2673
2674 SmallVector<MVT, 4> ValValueVTs;
2675 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2676
2677 unsigned NumValValues = ValValueVTs.size();
2678 SmallVector<SDValue, 4> Values(NumValValues);
2679
2680 SDValue Agg = getValue(Op0);
2681 // Copy out the selected value(s).
2682 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2683 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002684 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002685 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002686 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687
Scott Michelfdc40a02009-02-17 22:15:04 +00002688 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002689 DAG.getVTList(&ValValueVTs[0], NumValValues),
2690 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002691}
2692
2693
2694void SelectionDAGLowering::visitGetElementPtr(User &I) {
2695 SDValue N = getValue(I.getOperand(0));
2696 const Type *Ty = I.getOperand(0)->getType();
2697
2698 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2699 OI != E; ++OI) {
2700 Value *Idx = *OI;
2701 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2702 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2703 if (Field) {
2704 // N = N + Offset
2705 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002706 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002707 DAG.getIntPtrConstant(Offset));
2708 }
2709 Ty = StTy->getElementType(Field);
2710 } else {
2711 Ty = cast<SequentialType>(Ty)->getElementType();
2712
2713 // If this is a constant subscript, handle it quickly.
2714 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2715 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002716 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002717 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002718 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002719 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002720 if (PtrBits < 64) {
2721 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2722 TLI.getPointerTy(),
2723 DAG.getConstant(Offs, MVT::i64));
2724 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002725 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002726 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002727 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002728 continue;
2729 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002730
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002731 // N = N + Idx * ElementSize;
Duncan Sands777d2302009-05-09 07:06:46 +00002732 uint64_t ElementSize = TD->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002733 SDValue IdxN = getValue(Idx);
2734
2735 // If the index is smaller or larger than intptr_t, truncate or extend
2736 // it.
2737 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002738 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002739 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002741 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002742 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743
2744 // If this is a multiply by a power of two, turn it into a shl
2745 // immediately. This is a very common case.
2746 if (ElementSize != 1) {
2747 if (isPowerOf2_64(ElementSize)) {
2748 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002749 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002750 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002751 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002752 } else {
2753 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002754 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002755 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002756 }
2757 }
2758
Scott Michelfdc40a02009-02-17 22:15:04 +00002759 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002760 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002761 }
2762 }
2763 setValue(&I, N);
2764}
2765
2766void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2767 // If this is a fixed sized alloca in the entry block of the function,
2768 // allocate it statically on the stack.
2769 if (FuncInfo.StaticAllocaMap.count(&I))
2770 return; // getValue will auto-populate this.
2771
2772 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002773 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002774 unsigned Align =
2775 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2776 I.getAlignment());
2777
2778 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002779
2780 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2781 AllocSize,
2782 DAG.getConstant(TySize, AllocSize.getValueType()));
2783
2784
2785
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002786 MVT IntPtr = TLI.getPointerTy();
2787 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002788 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002789 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002790 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002791 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002792 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002793
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002794 // Handle alignment. If the requested alignment is less than or equal to
2795 // the stack alignment, ignore it. If the size is greater than or equal to
2796 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2797 unsigned StackAlign =
2798 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2799 if (Align <= StackAlign)
2800 Align = 0;
2801
2802 // Round the size of the allocation up to the stack alignment size
2803 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002804 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002805 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806 DAG.getIntPtrConstant(StackAlign-1));
2807 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002808 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002809 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002810 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2811
2812 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Dan Gohmanfc166572009-04-09 23:54:40 +00002813 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002814 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002815 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002816 setValue(&I, DSA);
2817 DAG.setRoot(DSA.getValue(1));
2818
2819 // Inform the Frame Information that we have just allocated a variable-sized
2820 // object.
2821 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2822}
2823
2824void SelectionDAGLowering::visitLoad(LoadInst &I) {
2825 const Value *SV = I.getOperand(0);
2826 SDValue Ptr = getValue(SV);
2827
2828 const Type *Ty = I.getType();
2829 bool isVolatile = I.isVolatile();
2830 unsigned Alignment = I.getAlignment();
2831
2832 SmallVector<MVT, 4> ValueVTs;
2833 SmallVector<uint64_t, 4> Offsets;
2834 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2835 unsigned NumValues = ValueVTs.size();
2836 if (NumValues == 0)
2837 return;
2838
2839 SDValue Root;
2840 bool ConstantMemory = false;
2841 if (I.isVolatile())
2842 // Serialize volatile loads with other side effects.
2843 Root = getRoot();
2844 else if (AA->pointsToConstantMemory(SV)) {
2845 // Do not serialize (non-volatile) loads of constant memory with anything.
2846 Root = DAG.getEntryNode();
2847 ConstantMemory = true;
2848 } else {
2849 // Do not serialize non-volatile loads against each other.
2850 Root = DAG.getRoot();
2851 }
2852
2853 SmallVector<SDValue, 4> Values(NumValues);
2854 SmallVector<SDValue, 4> Chains(NumValues);
2855 MVT PtrVT = Ptr.getValueType();
2856 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002857 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002858 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002859 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002860 DAG.getConstant(Offsets[i], PtrVT)),
2861 SV, Offsets[i],
2862 isVolatile, Alignment);
2863 Values[i] = L;
2864 Chains[i] = L.getValue(1);
2865 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002866
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002867 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002868 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002869 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002870 &Chains[0], NumValues);
2871 if (isVolatile)
2872 DAG.setRoot(Chain);
2873 else
2874 PendingLoads.push_back(Chain);
2875 }
2876
Scott Michelfdc40a02009-02-17 22:15:04 +00002877 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002878 DAG.getVTList(&ValueVTs[0], NumValues),
2879 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002880}
2881
2882
2883void SelectionDAGLowering::visitStore(StoreInst &I) {
2884 Value *SrcV = I.getOperand(0);
2885 Value *PtrV = I.getOperand(1);
2886
2887 SmallVector<MVT, 4> ValueVTs;
2888 SmallVector<uint64_t, 4> Offsets;
2889 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2890 unsigned NumValues = ValueVTs.size();
2891 if (NumValues == 0)
2892 return;
2893
2894 // Get the lowered operands. Note that we do this after
2895 // checking if NumResults is zero, because with zero results
2896 // the operands won't have values in the map.
2897 SDValue Src = getValue(SrcV);
2898 SDValue Ptr = getValue(PtrV);
2899
2900 SDValue Root = getRoot();
2901 SmallVector<SDValue, 4> Chains(NumValues);
2902 MVT PtrVT = Ptr.getValueType();
2903 bool isVolatile = I.isVolatile();
2904 unsigned Alignment = I.getAlignment();
2905 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002906 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002907 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002908 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002909 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002910 DAG.getConstant(Offsets[i], PtrVT)),
2911 PtrV, Offsets[i],
2912 isVolatile, Alignment);
2913
Scott Michelfdc40a02009-02-17 22:15:04 +00002914 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002915 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002916}
2917
2918/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2919/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002920void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002921 unsigned Intrinsic) {
2922 bool HasChain = !I.doesNotAccessMemory();
2923 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2924
2925 // Build the operand list.
2926 SmallVector<SDValue, 8> Ops;
2927 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2928 if (OnlyLoad) {
2929 // We don't need to serialize loads against other loads.
2930 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002931 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002932 Ops.push_back(getRoot());
2933 }
2934 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002935
2936 // Info is set by getTgtMemInstrinsic
2937 TargetLowering::IntrinsicInfo Info;
2938 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2939
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002940 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002941 if (!IsTgtIntrinsic)
2942 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002943
2944 // Add all operands of the call to the operand list.
2945 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2946 SDValue Op = getValue(I.getOperand(i));
2947 assert(TLI.isTypeLegal(Op.getValueType()) &&
2948 "Intrinsic uses a non-legal type?");
2949 Ops.push_back(Op);
2950 }
2951
Dan Gohmanfc166572009-04-09 23:54:40 +00002952 std::vector<MVT> VTArray;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002953 if (I.getType() != Type::VoidTy) {
2954 MVT VT = TLI.getValueType(I.getType());
2955 if (VT.isVector()) {
2956 const VectorType *DestTy = cast<VectorType>(I.getType());
2957 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002958
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002959 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2960 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2961 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002963 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
Dan Gohmanfc166572009-04-09 23:54:40 +00002964 VTArray.push_back(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002965 }
2966 if (HasChain)
Dan Gohmanfc166572009-04-09 23:54:40 +00002967 VTArray.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002968
Dan Gohmanfc166572009-04-09 23:54:40 +00002969 SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002970
2971 // Create the node.
2972 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002973 if (IsTgtIntrinsic) {
2974 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002975 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002976 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002977 Info.memVT, Info.ptrVal, Info.offset,
2978 Info.align, Info.vol,
2979 Info.readMem, Info.writeMem);
2980 }
2981 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002982 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002983 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002984 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002985 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002986 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002987 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002988 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002989 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002990
2991 if (HasChain) {
2992 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2993 if (OnlyLoad)
2994 PendingLoads.push_back(Chain);
2995 else
2996 DAG.setRoot(Chain);
2997 }
2998 if (I.getType() != Type::VoidTy) {
2999 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3000 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003001 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003002 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003003 setValue(&I, Result);
3004 }
3005}
3006
3007/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3008static GlobalVariable *ExtractTypeInfo(Value *V) {
3009 V = V->stripPointerCasts();
3010 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3011 assert ((GV || isa<ConstantPointerNull>(V)) &&
3012 "TypeInfo must be a global variable or NULL");
3013 return GV;
3014}
3015
3016namespace llvm {
3017
3018/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3019/// call, and add them to the specified machine basic block.
3020void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3021 MachineBasicBlock *MBB) {
3022 // Inform the MachineModuleInfo of the personality for this landing pad.
3023 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3024 assert(CE->getOpcode() == Instruction::BitCast &&
3025 isa<Function>(CE->getOperand(0)) &&
3026 "Personality should be a function");
3027 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3028
3029 // Gather all the type infos for this landing pad and pass them along to
3030 // MachineModuleInfo.
3031 std::vector<GlobalVariable *> TyInfo;
3032 unsigned N = I.getNumOperands();
3033
3034 for (unsigned i = N - 1; i > 2; --i) {
3035 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3036 unsigned FilterLength = CI->getZExtValue();
3037 unsigned FirstCatch = i + FilterLength + !FilterLength;
3038 assert (FirstCatch <= N && "Invalid filter length");
3039
3040 if (FirstCatch < N) {
3041 TyInfo.reserve(N - FirstCatch);
3042 for (unsigned j = FirstCatch; j < N; ++j)
3043 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3044 MMI->addCatchTypeInfo(MBB, TyInfo);
3045 TyInfo.clear();
3046 }
3047
3048 if (!FilterLength) {
3049 // Cleanup.
3050 MMI->addCleanup(MBB);
3051 } else {
3052 // Filter.
3053 TyInfo.reserve(FilterLength - 1);
3054 for (unsigned j = i + 1; j < FirstCatch; ++j)
3055 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3056 MMI->addFilterTypeInfo(MBB, TyInfo);
3057 TyInfo.clear();
3058 }
3059
3060 N = i;
3061 }
3062 }
3063
3064 if (N > 3) {
3065 TyInfo.reserve(N - 3);
3066 for (unsigned j = 3; j < N; ++j)
3067 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3068 MMI->addCatchTypeInfo(MBB, TyInfo);
3069 }
3070}
3071
3072}
3073
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003074/// GetSignificand - Get the significand and build it into a floating-point
3075/// number with exponent of 1:
3076///
3077/// Op = (Op & 0x007fffff) | 0x3f800000;
3078///
3079/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003080static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003081GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3082 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003083 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003084 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003085 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003086 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003087}
3088
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003089/// GetExponent - Get the exponent:
3090///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003091/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003092///
3093/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003094static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003095GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3096 DebugLoc dl) {
3097 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003098 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003099 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003100 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003101 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003102 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003103 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003104}
3105
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003106/// getF32Constant - Get 32-bit floating point constant.
3107static SDValue
3108getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3109 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3110}
3111
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003112/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003113/// visitIntrinsicCall: I is a call instruction
3114/// Op is the associated NodeType for I
3115const char *
3116SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003117 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003118 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003119 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003120 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003121 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003122 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003123 getValue(I.getOperand(2)),
3124 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003125 setValue(&I, L);
3126 DAG.setRoot(L.getValue(1));
3127 return 0;
3128}
3129
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003130// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003131const char *
3132SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003133 SDValue Op1 = getValue(I.getOperand(1));
3134 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003135
Dan Gohmanfc166572009-04-09 23:54:40 +00003136 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3137 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003138
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003139 setValue(&I, Result);
3140 return 0;
3141}
Bill Wendling74c37652008-12-09 22:08:41 +00003142
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003143/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3144/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003145void
3146SelectionDAGLowering::visitExp(CallInst &I) {
3147 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003148 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003149
3150 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3151 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3152 SDValue Op = getValue(I.getOperand(1));
3153
3154 // Put the exponent in the right bit position for later addition to the
3155 // final result:
3156 //
3157 // #define LOG2OFe 1.4426950f
3158 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003161 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003162
3163 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003164 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3165 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003166
3167 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003168 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003169 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003170
3171 if (LimitFloatPrecision <= 6) {
3172 // For floating-point precision of 6:
3173 //
3174 // TwoToFractionalPartOfX =
3175 // 0.997535578f +
3176 // (0.735607626f + 0.252464424f * x) * x;
3177 //
3178 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003179 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003180 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003181 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003182 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003183 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3184 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003185 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003186 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003187
3188 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003189 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003190 TwoToFracPartOfX, IntegerPartOfX);
3191
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003192 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003193 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3194 // For floating-point precision of 12:
3195 //
3196 // TwoToFractionalPartOfX =
3197 // 0.999892986f +
3198 // (0.696457318f +
3199 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3200 //
3201 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003202 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003204 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003205 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003206 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3207 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003208 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003209 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3210 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003211 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003212 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003213
3214 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003215 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003216 TwoToFracPartOfX, IntegerPartOfX);
3217
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003218 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003219 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3220 // For floating-point precision of 18:
3221 //
3222 // TwoToFractionalPartOfX =
3223 // 0.999999982f +
3224 // (0.693148872f +
3225 // (0.240227044f +
3226 // (0.554906021e-1f +
3227 // (0.961591928e-2f +
3228 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3229 //
3230 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003231 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003232 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003233 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003234 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003235 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3236 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003237 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003238 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3239 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003240 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003241 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3242 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003243 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003244 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3245 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003246 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003247 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3248 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003249 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003250 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003251 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003252
3253 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003254 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003255 TwoToFracPartOfX, IntegerPartOfX);
3256
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003257 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003258 }
3259 } else {
3260 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003261 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003262 getValue(I.getOperand(1)).getValueType(),
3263 getValue(I.getOperand(1)));
3264 }
3265
Dale Johannesen59e577f2008-09-05 18:38:42 +00003266 setValue(&I, result);
3267}
3268
Bill Wendling39150252008-09-09 20:39:27 +00003269/// visitLog - Lower a log intrinsic. Handles the special sequences for
3270/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003271void
3272SelectionDAGLowering::visitLog(CallInst &I) {
3273 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003274 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003275
3276 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3277 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3278 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003279 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003280
3281 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003282 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003283 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003284 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003285
3286 // Get the significand and build it into a floating-point number with
3287 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003288 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003289
3290 if (LimitFloatPrecision <= 6) {
3291 // For floating-point precision of 6:
3292 //
3293 // LogofMantissa =
3294 // -1.1609546f +
3295 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003296 //
Bill Wendling39150252008-09-09 20:39:27 +00003297 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003299 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003300 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003301 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003302 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3303 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003304 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003305
Scott Michelfdc40a02009-02-17 22:15:04 +00003306 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003307 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003308 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3309 // For floating-point precision of 12:
3310 //
3311 // LogOfMantissa =
3312 // -1.7417939f +
3313 // (2.8212026f +
3314 // (-1.4699568f +
3315 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3316 //
3317 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003318 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003320 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003321 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003322 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3323 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003324 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003325 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3326 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003328 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3329 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003330 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003331
Scott Michelfdc40a02009-02-17 22:15:04 +00003332 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003333 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003334 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3335 // For floating-point precision of 18:
3336 //
3337 // LogOfMantissa =
3338 // -2.1072184f +
3339 // (4.2372794f +
3340 // (-3.7029485f +
3341 // (2.2781945f +
3342 // (-0.87823314f +
3343 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3344 //
3345 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003346 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003347 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003348 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003349 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003350 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3351 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003352 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003355 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3357 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003358 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003359 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3360 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003361 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003362 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3363 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003364 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003365
Scott Michelfdc40a02009-02-17 22:15:04 +00003366 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003367 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003368 }
3369 } else {
3370 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003371 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003372 getValue(I.getOperand(1)).getValueType(),
3373 getValue(I.getOperand(1)));
3374 }
3375
Dale Johannesen59e577f2008-09-05 18:38:42 +00003376 setValue(&I, result);
3377}
3378
Bill Wendling3eb59402008-09-09 00:28:24 +00003379/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3380/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003381void
3382SelectionDAGLowering::visitLog2(CallInst &I) {
3383 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003384 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003385
Dale Johannesen853244f2008-09-05 23:49:37 +00003386 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003387 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3388 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003389 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003390
Bill Wendling39150252008-09-09 20:39:27 +00003391 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003392 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003393
3394 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003395 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003396 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003397
Bill Wendling3eb59402008-09-09 00:28:24 +00003398 // Different possible minimax approximations of significand in
3399 // floating-point for various degrees of accuracy over [1,2].
3400 if (LimitFloatPrecision <= 6) {
3401 // For floating-point precision of 6:
3402 //
3403 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3404 //
3405 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003406 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003407 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003408 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003409 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003410 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3411 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003412 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003413
Scott Michelfdc40a02009-02-17 22:15:04 +00003414 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003415 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003416 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3417 // For floating-point precision of 12:
3418 //
3419 // Log2ofMantissa =
3420 // -2.51285454f +
3421 // (4.07009056f +
3422 // (-2.12067489f +
3423 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003424 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003425 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003426 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003427 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003428 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003429 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003430 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3431 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003432 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003433 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3434 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003435 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003436 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3437 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003438 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003439
Scott Michelfdc40a02009-02-17 22:15:04 +00003440 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003441 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003442 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3443 // For floating-point precision of 18:
3444 //
3445 // Log2ofMantissa =
3446 // -3.0400495f +
3447 // (6.1129976f +
3448 // (-5.3420409f +
3449 // (3.2865683f +
3450 // (-1.2669343f +
3451 // (0.27515199f -
3452 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3453 //
3454 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003455 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003456 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003457 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003458 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003459 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3460 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003461 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003462 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3463 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003465 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3466 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003467 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003468 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3469 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003470 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003471 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3472 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003473 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003474
Scott Michelfdc40a02009-02-17 22:15:04 +00003475 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003476 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003477 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003478 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003479 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003480 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003481 getValue(I.getOperand(1)).getValueType(),
3482 getValue(I.getOperand(1)));
3483 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003484
Dale Johannesen59e577f2008-09-05 18:38:42 +00003485 setValue(&I, result);
3486}
3487
Bill Wendling3eb59402008-09-09 00:28:24 +00003488/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3489/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003490void
3491SelectionDAGLowering::visitLog10(CallInst &I) {
3492 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003493 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003494
Dale Johannesen852680a2008-09-05 21:27:19 +00003495 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003496 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3497 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003498 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003499
Bill Wendling39150252008-09-09 20:39:27 +00003500 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003501 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003502 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003503 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003504
3505 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003506 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003507 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003508
3509 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003510 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003511 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003512 // Log10ofMantissa =
3513 // -0.50419619f +
3514 // (0.60948995f - 0.10380950f * x) * x;
3515 //
3516 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003517 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003518 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003519 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003520 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003521 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3522 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003523 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003524
Scott Michelfdc40a02009-02-17 22:15:04 +00003525 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003526 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003527 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3528 // For floating-point precision of 12:
3529 //
3530 // Log10ofMantissa =
3531 // -0.64831180f +
3532 // (0.91751397f +
3533 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3534 //
3535 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003536 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003537 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003538 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003539 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003540 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3541 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003542 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003543 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3544 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003545 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003546
Scott Michelfdc40a02009-02-17 22:15:04 +00003547 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003548 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003549 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003550 // For floating-point precision of 18:
3551 //
3552 // Log10ofMantissa =
3553 // -0.84299375f +
3554 // (1.5327582f +
3555 // (-1.0688956f +
3556 // (0.49102474f +
3557 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3558 //
3559 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003560 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003561 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003562 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003563 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003564 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3565 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003566 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003567 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3568 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003569 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003570 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3571 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003572 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003573 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3574 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003575 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003576
Scott Michelfdc40a02009-02-17 22:15:04 +00003577 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003578 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003579 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003580 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003581 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003582 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003583 getValue(I.getOperand(1)).getValueType(),
3584 getValue(I.getOperand(1)));
3585 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003586
Dale Johannesen59e577f2008-09-05 18:38:42 +00003587 setValue(&I, result);
3588}
3589
Bill Wendlinge10c8142008-09-09 22:39:21 +00003590/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3591/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003592void
3593SelectionDAGLowering::visitExp2(CallInst &I) {
3594 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003595 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003596
Dale Johannesen601d3c02008-09-05 01:48:15 +00003597 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003598 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3599 SDValue Op = getValue(I.getOperand(1));
3600
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003601 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003602
3603 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003604 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3605 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003606
3607 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003608 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003609 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003610
3611 if (LimitFloatPrecision <= 6) {
3612 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003613 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614 // TwoToFractionalPartOfX =
3615 // 0.997535578f +
3616 // (0.735607626f + 0.252464424f * x) * x;
3617 //
3618 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003619 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003620 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003621 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003622 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003623 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3624 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003625 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003626 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003627 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003628 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003629
Scott Michelfdc40a02009-02-17 22:15:04 +00003630 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003631 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003632 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3633 // For floating-point precision of 12:
3634 //
3635 // TwoToFractionalPartOfX =
3636 // 0.999892986f +
3637 // (0.696457318f +
3638 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3639 //
3640 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003641 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003642 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003643 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003644 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003645 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3646 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003648 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3649 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003650 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003651 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003652 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003653 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003654
Scott Michelfdc40a02009-02-17 22:15:04 +00003655 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003656 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003657 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3658 // For floating-point precision of 18:
3659 //
3660 // TwoToFractionalPartOfX =
3661 // 0.999999982f +
3662 // (0.693148872f +
3663 // (0.240227044f +
3664 // (0.554906021e-1f +
3665 // (0.961591928e-2f +
3666 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3667 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003668 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003669 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003670 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003671 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003672 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3673 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003674 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003675 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3676 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003677 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003678 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3679 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003680 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003681 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3682 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003683 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003684 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3685 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003686 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003687 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003688 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003689 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003690
Scott Michelfdc40a02009-02-17 22:15:04 +00003691 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003692 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003693 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003694 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003695 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003696 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003697 getValue(I.getOperand(1)).getValueType(),
3698 getValue(I.getOperand(1)));
3699 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003700
Dale Johannesen601d3c02008-09-05 01:48:15 +00003701 setValue(&I, result);
3702}
3703
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003704/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3705/// limited-precision mode with x == 10.0f.
3706void
3707SelectionDAGLowering::visitPow(CallInst &I) {
3708 SDValue result;
3709 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003710 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003711 bool IsExp10 = false;
3712
3713 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003714 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003715 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3716 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3717 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3718 APFloat Ten(10.0f);
3719 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3720 }
3721 }
3722 }
3723
3724 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3725 SDValue Op = getValue(I.getOperand(2));
3726
3727 // Put the exponent in the right bit position for later addition to the
3728 // final result:
3729 //
3730 // #define LOG2OF10 3.3219281f
3731 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003732 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003733 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003734 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003735
3736 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003737 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3738 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003739
3740 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003741 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003742 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003743
3744 if (LimitFloatPrecision <= 6) {
3745 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003746 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003747 // twoToFractionalPartOfX =
3748 // 0.997535578f +
3749 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003750 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003751 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003752 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003753 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003754 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003755 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003756 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3757 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003758 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003759 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003760 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003761 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003762
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003763 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3764 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003765 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3766 // For floating-point precision of 12:
3767 //
3768 // TwoToFractionalPartOfX =
3769 // 0.999892986f +
3770 // (0.696457318f +
3771 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3772 //
3773 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003774 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003775 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003776 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003777 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003778 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3779 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003780 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003781 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3782 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003783 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003784 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003785 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003786 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003787
Scott Michelfdc40a02009-02-17 22:15:04 +00003788 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003789 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003790 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3791 // For floating-point precision of 18:
3792 //
3793 // TwoToFractionalPartOfX =
3794 // 0.999999982f +
3795 // (0.693148872f +
3796 // (0.240227044f +
3797 // (0.554906021e-1f +
3798 // (0.961591928e-2f +
3799 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3800 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003802 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003804 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3806 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003807 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003810 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003811 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3812 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003813 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003814 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3815 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003816 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003817 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3818 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003819 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003820 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003821 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003822 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003823
Scott Michelfdc40a02009-02-17 22:15:04 +00003824 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003825 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003826 }
3827 } else {
3828 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003829 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003830 getValue(I.getOperand(1)).getValueType(),
3831 getValue(I.getOperand(1)),
3832 getValue(I.getOperand(2)));
3833 }
3834
3835 setValue(&I, result);
3836}
3837
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003838/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3839/// we want to emit this as a call to a named external function, return the name
3840/// otherwise lower it and return null.
3841const char *
3842SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003843 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003844 switch (Intrinsic) {
3845 default:
3846 // By default, turn this into a target intrinsic node.
3847 visitTargetIntrinsic(I, Intrinsic);
3848 return 0;
3849 case Intrinsic::vastart: visitVAStart(I); return 0;
3850 case Intrinsic::vaend: visitVAEnd(I); return 0;
3851 case Intrinsic::vacopy: visitVACopy(I); return 0;
3852 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003853 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003854 getValue(I.getOperand(1))));
3855 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003856 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003857 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003858 getValue(I.getOperand(1))));
3859 return 0;
3860 case Intrinsic::setjmp:
3861 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3862 break;
3863 case Intrinsic::longjmp:
3864 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3865 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003866 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003867 SDValue Op1 = getValue(I.getOperand(1));
3868 SDValue Op2 = getValue(I.getOperand(2));
3869 SDValue Op3 = getValue(I.getOperand(3));
3870 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003871 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003872 I.getOperand(1), 0, I.getOperand(2), 0));
3873 return 0;
3874 }
Chris Lattner824b9582008-11-21 16:42:48 +00003875 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003876 SDValue Op1 = getValue(I.getOperand(1));
3877 SDValue Op2 = getValue(I.getOperand(2));
3878 SDValue Op3 = getValue(I.getOperand(3));
3879 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003880 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003881 I.getOperand(1), 0));
3882 return 0;
3883 }
Chris Lattner824b9582008-11-21 16:42:48 +00003884 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 SDValue Op1 = getValue(I.getOperand(1));
3886 SDValue Op2 = getValue(I.getOperand(2));
3887 SDValue Op3 = getValue(I.getOperand(3));
3888 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3889
3890 // If the source and destination are known to not be aliases, we can
3891 // lower memmove as memcpy.
3892 uint64_t Size = -1ULL;
3893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003894 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003895 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3896 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003897 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898 I.getOperand(1), 0, I.getOperand(2), 0));
3899 return 0;
3900 }
3901
Dale Johannesena04b7572009-02-03 23:04:43 +00003902 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 I.getOperand(1), 0, I.getOperand(2), 0));
3904 return 0;
3905 }
3906 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003907 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003908 if (DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLevel)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003909 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattneraf29a522009-05-04 22:10:05 +00003910 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3911 DebugLoc Loc = DebugLoc::get(MF.getOrCreateDebugLocID(CU.getGV(),
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003912 SPI.getLine(), SPI.getColumn()));
Chris Lattneraf29a522009-05-04 22:10:05 +00003913 setCurDebugLoc(Loc);
3914
Bill Wendling98a366d2009-04-29 23:29:43 +00003915 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003916 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003917 SPI.getLine(),
3918 SPI.getColumn(),
3919 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003920 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003921 return 0;
3922 }
3923 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003924 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003925 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00003926
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003927 if (DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLevel) &&
3928 DW && DW->ShouldEmitDwarfDebug()) {
3929 unsigned LabelID =
3930 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Devang Patel48c7fa22009-04-13 18:13:16 +00003931 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3932 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003933 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003934
3935 return 0;
3936 }
3937 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003938 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003939 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel0f7fef32009-04-13 17:02:03 +00003940
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003941 if (DIDescriptor::ValidDebugInfo(REI.getContext(), OptLevel) &&
3942 DW && DW->ShouldEmitDwarfDebug()) {
3943 MachineFunction &MF = DAG.getMachineFunction();
3944 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
Bill Wendling6c4311d2009-05-08 21:14:49 +00003945
Bill Wendling805da892009-05-18 18:21:03 +00003946 if (Subprogram.isNull() || Subprogram.describes(MF.getFunction())) {
Bill Wendling6c4311d2009-05-08 21:14:49 +00003947 unsigned LabelID =
3948 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3949 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3950 getRoot(), LabelID));
3951 } else {
3952 // This is end of inlined function. Debugging information for inlined
3953 // function is not handled yet (only supported by FastISel).
Bill Wendling98a366d2009-04-29 23:29:43 +00003954 if (OptLevel == CodeGenOpt::None) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003955 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3956 if (ID != 0)
Devang Patel02f8c412009-04-16 17:55:30 +00003957 // Returned ID is 0 if this is unbalanced "end of inlined
Bill Wendling6c4311d2009-05-08 21:14:49 +00003958 // scope". This could happen if optimizer eats dbg intrinsics or
3959 // "beginning of inlined scope" is not recoginized due to missing
3960 // location info. In such cases, do ignore this region.end.
Devang Patel16f2ffd2009-04-16 02:33:41 +00003961 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3962 getRoot(), ID));
3963 }
Devang Patel0f7fef32009-04-13 17:02:03 +00003964 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003965 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003966
3967 return 0;
3968 }
3969 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003970 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003971 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3972 Value *SP = FSI.getSubprogram();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003973 if (!DIDescriptor::ValidDebugInfo(SP, OptLevel))
3974 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003975
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003976 MachineFunction &MF = DAG.getMachineFunction();
Bill Wendlingc677fe52009-05-10 00:10:50 +00003977 if (OptLevel == CodeGenOpt::None) {
3978 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is what
3979 // (most?) gdb expects.
3980 DebugLoc PrevLoc = CurDebugLoc;
3981 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3982 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
Devang Patel02f8c412009-04-16 17:55:30 +00003983
Bill Wendlingc677fe52009-05-10 00:10:50 +00003984 if (!Subprogram.describes(MF.getFunction())) {
3985 // This is a beginning of an inlined function.
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003986
Bill Wendlingc677fe52009-05-10 00:10:50 +00003987 // If llvm.dbg.func.start is seen in a new block before any
3988 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3989 // FIXME : Why DebugLoc is reset at the beginning of each block ?
3990 if (PrevLoc.isUnknown())
3991 return 0;
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003992
Bill Wendlingc677fe52009-05-10 00:10:50 +00003993 // Record the source line.
3994 unsigned Line = Subprogram.getLineNumber();
3995 setCurDebugLoc(DebugLoc::get(
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003996 MF.getOrCreateDebugLocID(CompileUnit.getGV(), Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00003997
3998 if (DW && DW->ShouldEmitDwarfDebug()) {
3999 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
4000 unsigned LabelID = DW->RecordInlinedFnStart(Subprogram,
4001 DICompileUnit(PrevLocTpl.CompileUnit),
4002 PrevLocTpl.Line,
4003 PrevLocTpl.Col);
4004 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
4005 getRoot(), LabelID));
4006 }
4007 } else {
4008 // Record the source line.
4009 unsigned Line = Subprogram.getLineNumber();
4010 MF.setDefaultDebugLoc(DebugLoc::get(
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00004011 MF.getOrCreateDebugLocID(CompileUnit.getGV(), Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00004012 if (DW && DW->ShouldEmitDwarfDebug()) {
4013 // llvm.dbg.func_start also defines beginning of function scope.
4014 DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
4015 }
4016 }
4017 } else {
4018 DISubprogram Subprogram(cast<GlobalVariable>(SP));
4019
4020 std::string SPName;
4021 Subprogram.getLinkageName(SPName);
4022 if (!SPName.empty()
4023 && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
4024 // This is beginning of inlined function. Debugging information for
4025 // inlined function is not handled yet (only supported by FastISel).
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004026 return 0;
Bill Wendlingc677fe52009-05-10 00:10:50 +00004027 }
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004028
Bill Wendlingc677fe52009-05-10 00:10:50 +00004029 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
4030 // what (most?) gdb expects.
4031 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
4032
4033 // Record the source line but does not create a label for the normal
4034 // function start. It will be emitted at asm emission time. However,
4035 // create a label if this is a beginning of inlined function.
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004036 unsigned Line = Subprogram.getLineNumber();
4037 setCurDebugLoc(DebugLoc::get(
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00004038 MF.getOrCreateDebugLocID(CompileUnit.getGV(), Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00004039 // FIXME - Start new region because llvm.dbg.func_start also defines
4040 // beginning of function scope.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004041 }
4042
4043 return 0;
4044 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004045 case Intrinsic::dbg_declare: {
Bill Wendling98a366d2009-04-29 23:29:43 +00004046 if (OptLevel == CodeGenOpt::None) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00004047 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4048 Value *Variable = DI.getVariable();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004049 if (DIDescriptor::ValidDebugInfo(Variable, OptLevel))
Bill Wendling86e6cb92009-02-17 01:04:54 +00004050 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
4051 getValue(DI.getAddress()), getValue(Variable)));
4052 } else {
4053 // FIXME: Do something sensible here when we support debug declare.
4054 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004055 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004056 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004057 case Intrinsic::eh_exception: {
4058 if (!CurMBB->isLandingPad()) {
4059 // FIXME: Mark exception register as live in. Hack for PR1508.
4060 unsigned Reg = TLI.getExceptionAddressRegister();
4061 if (Reg) CurMBB->addLiveIn(Reg);
4062 }
4063 // Insert the EXCEPTIONADDR instruction.
4064 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4065 SDValue Ops[1];
4066 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004067 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004068 setValue(&I, Op);
4069 DAG.setRoot(Op.getValue(1));
4070 return 0;
4071 }
4072
4073 case Intrinsic::eh_selector_i32:
4074 case Intrinsic::eh_selector_i64: {
4075 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4076 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4077 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004078
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004079 if (MMI) {
4080 if (CurMBB->isLandingPad())
4081 AddCatchInfo(I, MMI, CurMBB);
4082 else {
4083#ifndef NDEBUG
4084 FuncInfo.CatchInfoLost.insert(&I);
4085#endif
4086 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4087 unsigned Reg = TLI.getExceptionSelectorRegister();
4088 if (Reg) CurMBB->addLiveIn(Reg);
4089 }
4090
4091 // Insert the EHSELECTION instruction.
4092 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4093 SDValue Ops[2];
4094 Ops[0] = getValue(I.getOperand(1));
4095 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004096 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004097 setValue(&I, Op);
4098 DAG.setRoot(Op.getValue(1));
4099 } else {
4100 setValue(&I, DAG.getConstant(0, VT));
4101 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004102
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004103 return 0;
4104 }
4105
4106 case Intrinsic::eh_typeid_for_i32:
4107 case Intrinsic::eh_typeid_for_i64: {
4108 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4109 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4110 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004111
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004112 if (MMI) {
4113 // Find the type id for the given typeinfo.
4114 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4115
4116 unsigned TypeID = MMI->getTypeIDFor(GV);
4117 setValue(&I, DAG.getConstant(TypeID, VT));
4118 } else {
4119 // Return something different to eh_selector.
4120 setValue(&I, DAG.getConstant(1, VT));
4121 }
4122
4123 return 0;
4124 }
4125
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004126 case Intrinsic::eh_return_i32:
4127 case Intrinsic::eh_return_i64:
4128 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004129 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004130 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004131 MVT::Other,
4132 getControlRoot(),
4133 getValue(I.getOperand(1)),
4134 getValue(I.getOperand(2))));
4135 } else {
4136 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4137 }
4138
4139 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004140 case Intrinsic::eh_unwind_init:
4141 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4142 MMI->setCallsUnwindInit(true);
4143 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004144
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004145 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004146
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004147 case Intrinsic::eh_dwarf_cfa: {
4148 MVT VT = getValue(I.getOperand(1)).getValueType();
4149 SDValue CfaArg;
4150 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004151 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004152 TLI.getPointerTy(), getValue(I.getOperand(1)));
4153 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004154 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004155 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004157 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004158 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004159 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004160 TLI.getPointerTy()),
4161 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004162 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004163 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004164 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004165 TLI.getPointerTy(),
4166 DAG.getConstant(0,
4167 TLI.getPointerTy())),
4168 Offset));
4169 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 }
4171
Mon P Wang77cdf302008-11-10 20:54:11 +00004172 case Intrinsic::convertff:
4173 case Intrinsic::convertfsi:
4174 case Intrinsic::convertfui:
4175 case Intrinsic::convertsif:
4176 case Intrinsic::convertuif:
4177 case Intrinsic::convertss:
4178 case Intrinsic::convertsu:
4179 case Intrinsic::convertus:
4180 case Intrinsic::convertuu: {
4181 ISD::CvtCode Code = ISD::CVT_INVALID;
4182 switch (Intrinsic) {
4183 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4184 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4185 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4186 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4187 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4188 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4189 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4190 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4191 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4192 }
4193 MVT DestVT = TLI.getValueType(I.getType());
4194 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004195 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004196 DAG.getValueType(DestVT),
4197 DAG.getValueType(getValue(Op1).getValueType()),
4198 getValue(I.getOperand(2)),
4199 getValue(I.getOperand(3)),
4200 Code));
4201 return 0;
4202 }
4203
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004204 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004205 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004206 getValue(I.getOperand(1)).getValueType(),
4207 getValue(I.getOperand(1))));
4208 return 0;
4209 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004210 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004211 getValue(I.getOperand(1)).getValueType(),
4212 getValue(I.getOperand(1)),
4213 getValue(I.getOperand(2))));
4214 return 0;
4215 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004216 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004217 getValue(I.getOperand(1)).getValueType(),
4218 getValue(I.getOperand(1))));
4219 return 0;
4220 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004221 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004222 getValue(I.getOperand(1)).getValueType(),
4223 getValue(I.getOperand(1))));
4224 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004225 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004226 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004227 return 0;
4228 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004229 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004230 return 0;
4231 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004232 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004233 return 0;
4234 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004235 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004236 return 0;
4237 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004238 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004239 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004240 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004241 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004242 return 0;
4243 case Intrinsic::pcmarker: {
4244 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004245 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004246 return 0;
4247 }
4248 case Intrinsic::readcyclecounter: {
4249 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004250 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004251 DAG.getVTList(MVT::i64, MVT::Other),
4252 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004253 setValue(&I, Tmp);
4254 DAG.setRoot(Tmp.getValue(1));
4255 return 0;
4256 }
4257 case Intrinsic::part_select: {
4258 // Currently not implemented: just abort
4259 assert(0 && "part_select intrinsic not implemented");
4260 abort();
4261 }
4262 case Intrinsic::part_set: {
4263 // Currently not implemented: just abort
4264 assert(0 && "part_set intrinsic not implemented");
4265 abort();
4266 }
4267 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004268 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004269 getValue(I.getOperand(1)).getValueType(),
4270 getValue(I.getOperand(1))));
4271 return 0;
4272 case Intrinsic::cttz: {
4273 SDValue Arg = getValue(I.getOperand(1));
4274 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004275 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004276 setValue(&I, result);
4277 return 0;
4278 }
4279 case Intrinsic::ctlz: {
4280 SDValue Arg = getValue(I.getOperand(1));
4281 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004282 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004283 setValue(&I, result);
4284 return 0;
4285 }
4286 case Intrinsic::ctpop: {
4287 SDValue Arg = getValue(I.getOperand(1));
4288 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004289 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004290 setValue(&I, result);
4291 return 0;
4292 }
4293 case Intrinsic::stacksave: {
4294 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004295 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004296 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004297 setValue(&I, Tmp);
4298 DAG.setRoot(Tmp.getValue(1));
4299 return 0;
4300 }
4301 case Intrinsic::stackrestore: {
4302 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004303 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004304 return 0;
4305 }
Bill Wendling57344502008-11-18 11:01:33 +00004306 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004307 // Emit code into the DAG to store the stack guard onto the stack.
4308 MachineFunction &MF = DAG.getMachineFunction();
4309 MachineFrameInfo *MFI = MF.getFrameInfo();
4310 MVT PtrTy = TLI.getPointerTy();
4311
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004312 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4313 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004314
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004315 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004316 MFI->setStackProtectorIndex(FI);
4317
4318 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4319
4320 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004321 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004322 PseudoSourceValue::getFixedStack(FI),
4323 0, true);
4324 setValue(&I, Result);
4325 DAG.setRoot(Result);
4326 return 0;
4327 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004328 case Intrinsic::var_annotation:
4329 // Discard annotate attributes
4330 return 0;
4331
4332 case Intrinsic::init_trampoline: {
4333 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4334
4335 SDValue Ops[6];
4336 Ops[0] = getRoot();
4337 Ops[1] = getValue(I.getOperand(1));
4338 Ops[2] = getValue(I.getOperand(2));
4339 Ops[3] = getValue(I.getOperand(3));
4340 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4341 Ops[5] = DAG.getSrcValue(F);
4342
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004343 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004344 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4345 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004346
4347 setValue(&I, Tmp);
4348 DAG.setRoot(Tmp.getValue(1));
4349 return 0;
4350 }
4351
4352 case Intrinsic::gcroot:
4353 if (GFI) {
4354 Value *Alloca = I.getOperand(1);
4355 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004356
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004357 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4358 GFI->addStackRoot(FI->getIndex(), TypeMap);
4359 }
4360 return 0;
4361
4362 case Intrinsic::gcread:
4363 case Intrinsic::gcwrite:
4364 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4365 return 0;
4366
4367 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004368 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004369 return 0;
4370 }
4371
4372 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004373 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004374 return 0;
4375 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004376
Bill Wendlingef375462008-11-21 02:38:44 +00004377 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004378 return implVisitAluOverflow(I, ISD::UADDO);
4379 case Intrinsic::sadd_with_overflow:
4380 return implVisitAluOverflow(I, ISD::SADDO);
4381 case Intrinsic::usub_with_overflow:
4382 return implVisitAluOverflow(I, ISD::USUBO);
4383 case Intrinsic::ssub_with_overflow:
4384 return implVisitAluOverflow(I, ISD::SSUBO);
4385 case Intrinsic::umul_with_overflow:
4386 return implVisitAluOverflow(I, ISD::UMULO);
4387 case Intrinsic::smul_with_overflow:
4388 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004389
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004390 case Intrinsic::prefetch: {
4391 SDValue Ops[4];
4392 Ops[0] = getRoot();
4393 Ops[1] = getValue(I.getOperand(1));
4394 Ops[2] = getValue(I.getOperand(2));
4395 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004396 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004397 return 0;
4398 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004399
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 case Intrinsic::memory_barrier: {
4401 SDValue Ops[6];
4402 Ops[0] = getRoot();
4403 for (int x = 1; x < 6; ++x)
4404 Ops[x] = getValue(I.getOperand(x));
4405
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004406 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004407 return 0;
4408 }
4409 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004410 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004411 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004412 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004413 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4414 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004415 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004416 getValue(I.getOperand(2)),
4417 getValue(I.getOperand(3)),
4418 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004419 setValue(&I, L);
4420 DAG.setRoot(L.getValue(1));
4421 return 0;
4422 }
4423 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004424 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004425 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004426 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004427 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004428 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004429 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004430 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004431 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004432 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004433 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004434 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004435 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004436 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004437 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004438 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004439 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004440 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004441 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004442 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004443 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004444 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004445 }
4446}
4447
4448
4449void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4450 bool IsTailCall,
4451 MachineBasicBlock *LandingPad) {
4452 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4453 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4454 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4455 unsigned BeginLabel = 0, EndLabel = 0;
4456
4457 TargetLowering::ArgListTy Args;
4458 TargetLowering::ArgListEntry Entry;
4459 Args.reserve(CS.arg_size());
4460 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4461 i != e; ++i) {
4462 SDValue ArgNode = getValue(*i);
4463 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4464
4465 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004466 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4467 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4468 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4469 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4470 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4471 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004472 Entry.Alignment = CS.getParamAlignment(attrInd);
4473 Args.push_back(Entry);
4474 }
4475
4476 if (LandingPad && MMI) {
4477 // Insert a label before the invoke call to mark the try range. This can be
4478 // used to detect deletion of the invoke via the MachineModuleInfo.
4479 BeginLabel = MMI->NextLabelID();
4480 // Both PendingLoads and PendingExports must be flushed here;
4481 // this call might not return.
4482 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004483 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4484 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004485 }
4486
4487 std::pair<SDValue,SDValue> Result =
4488 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004489 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004490 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4491 CS.paramHasAttr(0, Attribute::InReg),
4492 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004493 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004494 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004495 if (CS.getType() != Type::VoidTy)
4496 setValue(CS.getInstruction(), Result.first);
4497 DAG.setRoot(Result.second);
4498
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.
4533 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004534 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004535 const char *NameStr = F->getNameStart();
4536 if (NameStr[0] == 'c' &&
4537 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4538 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4539 if (I.getNumOperands() == 3 && // Basic sanity checks.
4540 I.getOperand(1)->getType()->isFloatingPoint() &&
4541 I.getType() == I.getOperand(1)->getType() &&
4542 I.getType() == I.getOperand(2)->getType()) {
4543 SDValue LHS = getValue(I.getOperand(1));
4544 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004545 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004546 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004547 return;
4548 }
4549 } else if (NameStr[0] == 'f' &&
4550 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4551 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4552 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4553 if (I.getNumOperands() == 2 && // Basic sanity checks.
4554 I.getOperand(1)->getType()->isFloatingPoint() &&
4555 I.getType() == I.getOperand(1)->getType()) {
4556 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004557 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004558 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004559 return;
4560 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004561 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004562 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4563 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4564 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4565 if (I.getNumOperands() == 2 && // Basic sanity checks.
4566 I.getOperand(1)->getType()->isFloatingPoint() &&
4567 I.getType() == I.getOperand(1)->getType()) {
4568 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004569 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004570 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004571 return;
4572 }
4573 } else if (NameStr[0] == 'c' &&
4574 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4575 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4576 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4577 if (I.getNumOperands() == 2 && // Basic sanity checks.
4578 I.getOperand(1)->getType()->isFloatingPoint() &&
4579 I.getType() == I.getOperand(1)->getType()) {
4580 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004581 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004582 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004583 return;
4584 }
4585 }
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
4598 LowerCallTo(&I, Callee, I.isTailCall());
4599}
4600
4601
4602/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004603/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004604/// Chain/Flag as the input and updates them for the output Chain/Flag.
4605/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004606SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004607 SDValue &Chain,
4608 SDValue *Flag) const {
4609 // Assemble the legal parts into the final values.
4610 SmallVector<SDValue, 4> Values(ValueVTs.size());
4611 SmallVector<SDValue, 8> Parts;
4612 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4613 // Copy the legal parts from the registers.
4614 MVT ValueVT = ValueVTs[Value];
4615 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4616 MVT RegisterVT = RegVTs[Value];
4617
4618 Parts.resize(NumRegs);
4619 for (unsigned i = 0; i != NumRegs; ++i) {
4620 SDValue P;
4621 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004622 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004623 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004624 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625 *Flag = P.getValue(2);
4626 }
4627 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004628
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004629 // If the source register was virtual and if we know something about it,
4630 // add an assert node.
4631 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4632 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4633 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4634 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4635 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4636 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004637
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004638 unsigned RegSize = RegisterVT.getSizeInBits();
4639 unsigned NumSignBits = LOI.NumSignBits;
4640 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004641
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004642 // FIXME: We capture more information than the dag can represent. For
4643 // now, just use the tightest assertzext/assertsext possible.
4644 bool isSExt = true;
4645 MVT FromVT(MVT::Other);
4646 if (NumSignBits == RegSize)
4647 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4648 else if (NumZeroBits >= RegSize-1)
4649 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4650 else if (NumSignBits > RegSize-8)
4651 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004652 else if (NumZeroBits >= RegSize-8)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004653 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4654 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004655 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004656 else if (NumZeroBits >= RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004657 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004658 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004659 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004660 else if (NumZeroBits >= RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004661 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004662
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004663 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004664 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004665 RegisterVT, P, DAG.getValueType(FromVT));
4666
4667 }
4668 }
4669 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004670
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004671 Parts[i] = P;
4672 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004673
Scott Michelfdc40a02009-02-17 22:15:04 +00004674 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004675 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004676 Part += NumRegs;
4677 Parts.clear();
4678 }
4679
Dale Johannesen66978ee2009-01-31 02:22:37 +00004680 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004681 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4682 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004683}
4684
4685/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004686/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004687/// Chain/Flag as the input and updates them for the output Chain/Flag.
4688/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004689void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004690 SDValue &Chain, SDValue *Flag) const {
4691 // Get the list of the values's legal parts.
4692 unsigned NumRegs = Regs.size();
4693 SmallVector<SDValue, 8> Parts(NumRegs);
4694 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4695 MVT ValueVT = ValueVTs[Value];
4696 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4697 MVT RegisterVT = RegVTs[Value];
4698
Dale Johannesen66978ee2009-01-31 02:22:37 +00004699 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004700 &Parts[Part], NumParts, RegisterVT);
4701 Part += NumParts;
4702 }
4703
4704 // Copy the parts into the registers.
4705 SmallVector<SDValue, 8> Chains(NumRegs);
4706 for (unsigned i = 0; i != NumRegs; ++i) {
4707 SDValue Part;
4708 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004709 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004710 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004711 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712 *Flag = Part.getValue(1);
4713 }
4714 Chains[i] = Part.getValue(0);
4715 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004716
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004717 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004718 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004719 // flagged to it. That is the CopyToReg nodes and the user are considered
4720 // a single scheduling unit. If we create a TokenFactor and return it as
4721 // chain, then the TokenFactor is both a predecessor (operand) of the
4722 // user as well as a successor (the TF operands are flagged to the user).
4723 // c1, f1 = CopyToReg
4724 // c2, f2 = CopyToReg
4725 // c3 = TokenFactor c1, c2
4726 // ...
4727 // = op c3, ..., f2
4728 Chain = Chains[NumRegs-1];
4729 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004730 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004731}
4732
4733/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004734/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004735/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004736void RegsForValue::AddInlineAsmOperands(unsigned Code,
4737 bool HasMatching,unsigned MatchingIdx,
4738 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 std::vector<SDValue> &Ops) const {
4740 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004741 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4742 unsigned Flag = Code | (Regs.size() << 3);
4743 if (HasMatching)
4744 Flag |= 0x80000000 | (MatchingIdx << 16);
4745 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4747 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4748 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004749 for (unsigned i = 0; i != NumRegs; ++i) {
4750 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004752 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004753 }
4754}
4755
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004756/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004757/// i.e. it isn't a stack pointer or some other special register, return the
4758/// register class for the register. Otherwise, return null.
4759static const TargetRegisterClass *
4760isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4761 const TargetLowering &TLI,
4762 const TargetRegisterInfo *TRI) {
4763 MVT FoundVT = MVT::Other;
4764 const TargetRegisterClass *FoundRC = 0;
4765 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4766 E = TRI->regclass_end(); RCI != E; ++RCI) {
4767 MVT ThisVT = MVT::Other;
4768
4769 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004770 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004771 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4772 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4773 I != E; ++I) {
4774 if (TLI.isTypeLegal(*I)) {
4775 // If we have already found this register in a different register class,
4776 // choose the one with the largest VT specified. For example, on
4777 // PowerPC, we favor f64 register classes over f32.
4778 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4779 ThisVT = *I;
4780 break;
4781 }
4782 }
4783 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004784
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004785 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004786
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004787 // NOTE: This isn't ideal. In particular, this might allocate the
4788 // frame pointer in functions that need it (due to them not being taken
4789 // out of allocation, because a variable sized allocation hasn't been seen
4790 // yet). This is a slight code pessimization, but should still work.
4791 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4792 E = RC->allocation_order_end(MF); I != E; ++I)
4793 if (*I == Reg) {
4794 // We found a matching register class. Keep looking at others in case
4795 // we find one with larger registers that this physreg is also in.
4796 FoundRC = RC;
4797 FoundVT = ThisVT;
4798 break;
4799 }
4800 }
4801 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004802}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004803
4804
4805namespace llvm {
4806/// AsmOperandInfo - This contains information for each constraint that we are
4807/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004808class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004809 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004810public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004811 /// CallOperand - If this is the result output operand or a clobber
4812 /// this is null, otherwise it is the incoming operand to the CallInst.
4813 /// This gets modified as the asm is processed.
4814 SDValue CallOperand;
4815
4816 /// AssignedRegs - If this is a register or register class operand, this
4817 /// contains the set of register corresponding to the operand.
4818 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004819
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004820 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4821 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4822 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004823
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004824 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4825 /// busy in OutputRegs/InputRegs.
4826 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004827 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004828 std::set<unsigned> &InputRegs,
4829 const TargetRegisterInfo &TRI) const {
4830 if (isOutReg) {
4831 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4832 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4833 }
4834 if (isInReg) {
4835 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4836 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4837 }
4838 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004839
Chris Lattner81249c92008-10-17 17:05:25 +00004840 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4841 /// corresponds to. If there is no Value* for this operand, it returns
4842 /// MVT::Other.
4843 MVT getCallOperandValMVT(const TargetLowering &TLI,
4844 const TargetData *TD) const {
4845 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004846
Chris Lattner81249c92008-10-17 17:05:25 +00004847 if (isa<BasicBlock>(CallOperandVal))
4848 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004849
Chris Lattner81249c92008-10-17 17:05:25 +00004850 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004851
Chris Lattner81249c92008-10-17 17:05:25 +00004852 // If this is an indirect operand, the operand is a pointer to the
4853 // accessed type.
4854 if (isIndirect)
4855 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004856
Chris Lattner81249c92008-10-17 17:05:25 +00004857 // If OpTy is not a single value, it may be a struct/union that we
4858 // can tile with integers.
4859 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4860 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4861 switch (BitSize) {
4862 default: break;
4863 case 1:
4864 case 8:
4865 case 16:
4866 case 32:
4867 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004868 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004869 OpTy = IntegerType::get(BitSize);
4870 break;
4871 }
4872 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004873
Chris Lattner81249c92008-10-17 17:05:25 +00004874 return TLI.getValueType(OpTy, true);
4875 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004876
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877private:
4878 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4879 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004880 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004881 const TargetRegisterInfo &TRI) {
4882 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4883 Regs.insert(Reg);
4884 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4885 for (; *Aliases; ++Aliases)
4886 Regs.insert(*Aliases);
4887 }
4888};
4889} // end llvm namespace.
4890
4891
4892/// GetRegistersForValue - Assign registers (virtual or physical) for the
4893/// specified operand. We prefer to assign virtual registers, to allow the
4894/// register allocator handle the assignment process. However, if the asm uses
4895/// features that we can't model on machineinstrs, we have SDISel do the
4896/// allocation. This produces generally horrible, but correct, code.
4897///
4898/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004899/// Input and OutputRegs are the set of already allocated physical registers.
4900///
4901void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004902GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004903 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004904 std::set<unsigned> &InputRegs) {
4905 // Compute whether this value requires an input register, an output register,
4906 // or both.
4907 bool isOutReg = false;
4908 bool isInReg = false;
4909 switch (OpInfo.Type) {
4910 case InlineAsm::isOutput:
4911 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004912
4913 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004914 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004915 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004916 break;
4917 case InlineAsm::isInput:
4918 isInReg = true;
4919 isOutReg = false;
4920 break;
4921 case InlineAsm::isClobber:
4922 isOutReg = true;
4923 isInReg = true;
4924 break;
4925 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004926
4927
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928 MachineFunction &MF = DAG.getMachineFunction();
4929 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004930
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004931 // If this is a constraint for a single physreg, or a constraint for a
4932 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004933 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004934 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4935 OpInfo.ConstraintVT);
4936
4937 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004938 if (OpInfo.ConstraintVT != MVT::Other) {
4939 // If this is a FP input in an integer register (or visa versa) insert a bit
4940 // cast of the input value. More generally, handle any case where the input
4941 // value disagrees with the register class we plan to stick this in.
4942 if (OpInfo.Type == InlineAsm::isInput &&
4943 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4944 // Try to convert to the first MVT that the reg class contains. If the
4945 // types are identical size, use a bitcast to convert (e.g. two differing
4946 // vector types).
4947 MVT RegVT = *PhysReg.second->vt_begin();
4948 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004949 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004950 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004951 OpInfo.ConstraintVT = RegVT;
4952 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4953 // If the input is a FP value and we want it in FP registers, do a
4954 // bitcast to the corresponding integer type. This turns an f64 value
4955 // into i64, which can be passed with two i32 values on a 32-bit
4956 // machine.
4957 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004958 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004959 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004960 OpInfo.ConstraintVT = RegVT;
4961 }
4962 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004963
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004964 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004965 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004966
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004967 MVT RegVT;
4968 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969
4970 // If this is a constraint for a specific physical register, like {r17},
4971 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004972 if (unsigned AssignedReg = PhysReg.first) {
4973 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004974 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004975 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004976
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004977 // Get the actual register value type. This is important, because the user
4978 // may have asked for (e.g.) the AX register in i32 type. We need to
4979 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004980 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004981
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004982 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004983 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004984
4985 // If this is an expanded reference, add the rest of the regs to Regs.
4986 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004987 TargetRegisterClass::iterator I = RC->begin();
4988 for (; *I != AssignedReg; ++I)
4989 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991 // Already added the first reg.
4992 --NumRegs; ++I;
4993 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004994 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004995 Regs.push_back(*I);
4996 }
4997 }
4998 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4999 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5000 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5001 return;
5002 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005004 // Otherwise, if this was a reference to an LLVM register class, create vregs
5005 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005006 if (const TargetRegisterClass *RC = PhysReg.second) {
5007 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00005008 if (OpInfo.ConstraintVT == MVT::Other)
5009 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005010
Evan Chengfb112882009-03-23 08:01:15 +00005011 // Create the appropriate number of virtual registers.
5012 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5013 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005014 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005015
Evan Chengfb112882009-03-23 08:01:15 +00005016 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5017 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005018 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005019
5020 // This is a reference to a register class that doesn't directly correspond
5021 // to an LLVM register class. Allocate NumRegs consecutive, available,
5022 // registers from the class.
5023 std::vector<unsigned> RegClassRegs
5024 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5025 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005026
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005027 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5028 unsigned NumAllocated = 0;
5029 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5030 unsigned Reg = RegClassRegs[i];
5031 // See if this register is available.
5032 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5033 (isInReg && InputRegs.count(Reg))) { // Already used.
5034 // Make sure we find consecutive registers.
5035 NumAllocated = 0;
5036 continue;
5037 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005038
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 // Check to see if this register is allocatable (i.e. don't give out the
5040 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005041 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5042 if (!RC) { // Couldn't allocate this register.
5043 // Reset NumAllocated to make sure we return consecutive registers.
5044 NumAllocated = 0;
5045 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005046 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005047
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005048 // Okay, this register is good, we can use it.
5049 ++NumAllocated;
5050
5051 // If we allocated enough consecutive registers, succeed.
5052 if (NumAllocated == NumRegs) {
5053 unsigned RegStart = (i-NumAllocated)+1;
5054 unsigned RegEnd = i+1;
5055 // Mark all of the allocated registers used.
5056 for (unsigned i = RegStart; i != RegEnd; ++i)
5057 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005058
5059 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005060 OpInfo.ConstraintVT);
5061 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5062 return;
5063 }
5064 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005065
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005066 // Otherwise, we couldn't allocate enough registers for this.
5067}
5068
Evan Chengda43bcf2008-09-24 00:05:32 +00005069/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5070/// processed uses a memory 'm' constraint.
5071static bool
5072hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005073 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005074 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5075 InlineAsm::ConstraintInfo &CI = CInfos[i];
5076 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5077 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5078 if (CType == TargetLowering::C_Memory)
5079 return true;
5080 }
Chris Lattner6c147292009-04-30 00:48:50 +00005081
5082 // Indirect operand accesses access memory.
5083 if (CI.isIndirect)
5084 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005085 }
5086
5087 return false;
5088}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005089
5090/// visitInlineAsm - Handle a call to an InlineAsm object.
5091///
5092void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5093 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5094
5095 /// ConstraintOperands - Information about all of the constraints.
5096 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005097
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005098 std::set<unsigned> OutputRegs, InputRegs;
5099
5100 // Do a prepass over the constraints, canonicalizing them, and building up the
5101 // ConstraintOperands list.
5102 std::vector<InlineAsm::ConstraintInfo>
5103 ConstraintInfos = IA->ParseConstraints();
5104
Evan Chengda43bcf2008-09-24 00:05:32 +00005105 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005106
5107 SDValue Chain, Flag;
5108
5109 // We won't need to flush pending loads if this asm doesn't touch
5110 // memory and is nonvolatile.
5111 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005112 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005113 else
5114 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005116 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5117 unsigned ResNo = 0; // ResNo - The result number of the next output.
5118 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5119 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5120 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005122 MVT OpVT = MVT::Other;
5123
5124 // Compute the value type for each operand.
5125 switch (OpInfo.Type) {
5126 case InlineAsm::isOutput:
5127 // Indirect outputs just consume an argument.
5128 if (OpInfo.isIndirect) {
5129 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5130 break;
5131 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005132
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005133 // The return value of the call is this value. As such, there is no
5134 // corresponding argument.
5135 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5136 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5137 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5138 } else {
5139 assert(ResNo == 0 && "Asm only has one result!");
5140 OpVT = TLI.getValueType(CS.getType());
5141 }
5142 ++ResNo;
5143 break;
5144 case InlineAsm::isInput:
5145 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5146 break;
5147 case InlineAsm::isClobber:
5148 // Nothing to do.
5149 break;
5150 }
5151
5152 // If this is an input or an indirect output, process the call argument.
5153 // BasicBlocks are labels, currently appearing only in asm's.
5154 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005155 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005157 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005158 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005159 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005160
Chris Lattner81249c92008-10-17 17:05:25 +00005161 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005162 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005164 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005165 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005166
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005167 // Second pass over the constraints: compute which constraint option to use
5168 // and assign registers to constraints that want a specific physreg.
5169 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5170 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005171
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005172 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005173 // matching input. If their types mismatch, e.g. one is an integer, the
5174 // other is floating point, or their sizes are different, flag it as an
5175 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005176 if (OpInfo.hasMatchingInput()) {
5177 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5178 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005179 if ((OpInfo.ConstraintVT.isInteger() !=
5180 Input.ConstraintVT.isInteger()) ||
5181 (OpInfo.ConstraintVT.getSizeInBits() !=
5182 Input.ConstraintVT.getSizeInBits())) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005183 cerr << "llvm: error: Unsupported asm: input constraint with a "
5184 << "matching output constraint of incompatible type!\n";
Evan Cheng09dc9c02008-12-16 18:21:39 +00005185 exit(1);
5186 }
5187 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005188 }
5189 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005190
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005191 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005192 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005193
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005194 // If this is a memory input, and if the operand is not indirect, do what we
5195 // need to to provide an address for the memory input.
5196 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5197 !OpInfo.isIndirect) {
5198 assert(OpInfo.Type == InlineAsm::isInput &&
5199 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005200
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005201 // Memory operands really want the address of the value. If we don't have
5202 // an indirect input, put it in the constpool if we can, otherwise spill
5203 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005204
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005205 // If the operand is a float, integer, or vector constant, spill to a
5206 // constant pool entry to get its address.
5207 Value *OpVal = OpInfo.CallOperandVal;
5208 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5209 isa<ConstantVector>(OpVal)) {
5210 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5211 TLI.getPointerTy());
5212 } else {
5213 // Otherwise, create a stack slot and emit a store to it before the
5214 // asm.
5215 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005216 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005217 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5218 MachineFunction &MF = DAG.getMachineFunction();
5219 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5220 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005221 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005222 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005223 OpInfo.CallOperand = StackSlot;
5224 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005225
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005226 // There is no longer a Value* corresponding to this operand.
5227 OpInfo.CallOperandVal = 0;
5228 // It is now an indirect operand.
5229 OpInfo.isIndirect = true;
5230 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005232 // If this constraint is for a specific register, allocate it before
5233 // anything else.
5234 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005235 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005236 }
5237 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005238
5239
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005241 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005242 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5243 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005244
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005245 // C_Register operands have already been allocated, Other/Memory don't need
5246 // to be.
5247 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005248 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005249 }
5250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005251 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5252 std::vector<SDValue> AsmNodeOperands;
5253 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5254 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005255 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005256
5257
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005258 // Loop over all of the inputs, copying the operand values into the
5259 // appropriate registers and processing the output regs.
5260 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005261
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005262 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5263 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005264
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005265 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5266 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5267
5268 switch (OpInfo.Type) {
5269 case InlineAsm::isOutput: {
5270 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5271 OpInfo.ConstraintType != TargetLowering::C_Register) {
5272 // Memory output, or 'other' output (e.g. 'X' constraint).
5273 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5274
5275 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005276 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5277 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005278 TLI.getPointerTy()));
5279 AsmNodeOperands.push_back(OpInfo.CallOperand);
5280 break;
5281 }
5282
5283 // Otherwise, this is a register or register class output.
5284
5285 // Copy the output from the appropriate register. Find a register that
5286 // we can use.
5287 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005288 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005289 << OpInfo.ConstraintCode << "'!\n";
5290 exit(1);
5291 }
5292
5293 // If this is an indirect operand, store through the pointer after the
5294 // asm.
5295 if (OpInfo.isIndirect) {
5296 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5297 OpInfo.CallOperandVal));
5298 } else {
5299 // This is the result value of the call.
5300 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5301 // Concatenate this output onto the outputs list.
5302 RetValRegs.append(OpInfo.AssignedRegs);
5303 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005305 // Add information to the INLINEASM node to know that this register is
5306 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005307 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5308 6 /* EARLYCLOBBER REGDEF */ :
5309 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005310 false,
5311 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005312 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005313 break;
5314 }
5315 case InlineAsm::isInput: {
5316 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005317
Chris Lattner6bdcda32008-10-17 16:47:46 +00005318 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005319 // If this is required to match an output register we have already set,
5320 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005321 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005322
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 // Scan until we find the definition we already emitted of this operand.
5324 // When we find it, create a RegsForValue operand.
5325 unsigned CurOp = 2; // The first operand.
5326 for (; OperandNo; --OperandNo) {
5327 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005328 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005329 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005330 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5331 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5332 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005334 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335 }
5336
Evan Cheng697cbbf2009-03-20 18:03:34 +00005337 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005338 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005339 if ((OpFlag & 7) == 2 /*REGDEF*/
5340 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5341 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohmane340e842009-05-14 00:30:16 +00005342 assert(!OpInfo.isIndirect &&
5343 "Don't know how to handle tied indirect register inputs yet!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005344 RegsForValue MatchedRegs;
5345 MatchedRegs.TLI = &TLI;
5346 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005347 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5348 MatchedRegs.RegVTs.push_back(RegVT);
5349 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005350 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005351 i != e; ++i)
5352 MatchedRegs.Regs.
5353 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005354
5355 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005356 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5357 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005358 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5359 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005360 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005361 break;
5362 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005363 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5364 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5365 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005366 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005367 // See InlineAsm.h isUseOperandTiedToDef.
5368 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005369 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 TLI.getPointerTy()));
5371 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5372 break;
5373 }
5374 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005376 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005377 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005378 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005380 std::vector<SDValue> Ops;
5381 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005382 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005383 if (Ops.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005384 cerr << "llvm: error: Invalid operand for inline asm constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005385 << OpInfo.ConstraintCode << "'!\n";
5386 exit(1);
5387 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005388
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005389 // Add information to the INLINEASM node to know about this input.
5390 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005391 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005392 TLI.getPointerTy()));
5393 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5394 break;
5395 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5396 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5397 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5398 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005399
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005400 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005401 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5402 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 TLI.getPointerTy()));
5404 AsmNodeOperands.push_back(InOperandVal);
5405 break;
5406 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005407
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005408 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5409 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5410 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005411 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005412 "Don't know how to handle indirect register inputs yet!");
5413
5414 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005415 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005416 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Evan Chengaa765b82008-09-25 00:14:04 +00005417 << OpInfo.ConstraintCode << "'!\n";
5418 exit(1);
5419 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005420
Dale Johannesen66978ee2009-01-31 02:22:37 +00005421 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5422 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005423
Evan Cheng697cbbf2009-03-20 18:03:34 +00005424 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005425 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005426 break;
5427 }
5428 case InlineAsm::isClobber: {
5429 // Add the clobbered value to the operand list, so that the register
5430 // allocator is aware that the physreg got clobbered.
5431 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005432 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005433 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005434 break;
5435 }
5436 }
5437 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 // Finish up input operands.
5440 AsmNodeOperands[0] = Chain;
5441 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005442
Dale Johannesen66978ee2009-01-31 02:22:37 +00005443 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00005444 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445 &AsmNodeOperands[0], AsmNodeOperands.size());
5446 Flag = Chain.getValue(1);
5447
5448 // If this asm returns a register value, copy the result from that register
5449 // and set it as the value of the call.
5450 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005451 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005452 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005453
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005454 // FIXME: Why don't we do this for inline asms with MRVs?
5455 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5456 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005457
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005458 // If any of the results of the inline asm is a vector, it may have the
5459 // wrong width/num elts. This can happen for register classes that can
5460 // contain multiple different value types. The preg or vreg allocated may
5461 // not have the same VT as was expected. Convert it to the right type
5462 // with bit_convert.
5463 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005464 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005465 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005466
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005467 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005468 ResultType.isInteger() && Val.getValueType().isInteger()) {
5469 // If a result value was tied to an input value, the computed result may
5470 // have a wider width than the expected result. Extract the relevant
5471 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005472 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005473 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005474
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005475 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005476 }
Dan Gohman95915732008-10-18 01:03:45 +00005477
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005478 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005479 // Don't need to use this as a chain in this case.
5480 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5481 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005482 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005483
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005484 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005485
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005486 // Process indirect outputs, first output all of the flagged copies out of
5487 // physregs.
5488 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5489 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5490 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005491 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5492 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005493 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005494
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005495 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005496
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005497 // Emit the non-flagged stores from the physregs.
5498 SmallVector<SDValue, 8> OutChains;
5499 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005500 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005501 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005502 getValue(StoresToEmit[i].second),
5503 StoresToEmit[i].second, 0));
5504 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005505 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 &OutChains[0], OutChains.size());
5507 DAG.setRoot(Chain);
5508}
5509
5510
5511void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5512 SDValue Src = getValue(I.getOperand(0));
5513
Chris Lattner0b18e592009-03-17 19:36:00 +00005514 // Scale up by the type size in the original i32 type width. Various
5515 // mid-level optimizers may make assumptions about demanded bits etc from the
5516 // i32-ness of the optimizer: we do not want to promote to i64 and then
5517 // multiply on 64-bit targets.
5518 // FIXME: Malloc inst should go away: PR715.
Duncan Sands777d2302009-05-09 07:06:46 +00005519 uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
Chris Lattner0b18e592009-03-17 19:36:00 +00005520 if (ElementSize != 1)
5521 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5522 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5523
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005524 MVT IntPtr = TLI.getPointerTy();
5525
5526 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005527 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005528 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005529 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005530
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005531 TargetLowering::ArgListTy Args;
5532 TargetLowering::ArgListEntry Entry;
5533 Entry.Node = Src;
5534 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5535 Args.push_back(Entry);
5536
5537 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005538 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005539 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005540 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005541 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005542 setValue(&I, Result.first); // Pointers always fit in registers
5543 DAG.setRoot(Result.second);
5544}
5545
5546void SelectionDAGLowering::visitFree(FreeInst &I) {
5547 TargetLowering::ArgListTy Args;
5548 TargetLowering::ArgListEntry Entry;
5549 Entry.Node = getValue(I.getOperand(0));
5550 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5551 Args.push_back(Entry);
5552 MVT IntPtr = TLI.getPointerTy();
5553 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005554 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005555 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005556 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005557 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558 DAG.setRoot(Result.second);
5559}
5560
5561void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005562 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005563 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005564 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005565 DAG.getSrcValue(I.getOperand(1))));
5566}
5567
5568void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005569 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5570 getRoot(), getValue(I.getOperand(0)),
5571 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005572 setValue(&I, V);
5573 DAG.setRoot(V.getValue(1));
5574}
5575
5576void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005577 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005578 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005579 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005580 DAG.getSrcValue(I.getOperand(1))));
5581}
5582
5583void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005584 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005585 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005586 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005587 getValue(I.getOperand(2)),
5588 DAG.getSrcValue(I.getOperand(1)),
5589 DAG.getSrcValue(I.getOperand(2))));
5590}
5591
5592/// TargetLowering::LowerArguments - This is the default LowerArguments
5593/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005594/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005595/// integrated into SDISel.
5596void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005597 SmallVectorImpl<SDValue> &ArgValues,
5598 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005599 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5600 SmallVector<SDValue, 3+16> Ops;
5601 Ops.push_back(DAG.getRoot());
5602 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5603 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5604
5605 // Add one result value for each formal argument.
5606 SmallVector<MVT, 16> RetVals;
5607 unsigned j = 1;
5608 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5609 I != E; ++I, ++j) {
5610 SmallVector<MVT, 4> ValueVTs;
5611 ComputeValueVTs(*this, I->getType(), ValueVTs);
5612 for (unsigned Value = 0, NumValues = ValueVTs.size();
5613 Value != NumValues; ++Value) {
5614 MVT VT = ValueVTs[Value];
5615 const Type *ArgTy = VT.getTypeForMVT();
5616 ISD::ArgFlagsTy Flags;
5617 unsigned OriginalAlignment =
5618 getTargetData()->getABITypeAlignment(ArgTy);
5619
Devang Patel05988662008-09-25 21:00:45 +00005620 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005621 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005622 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005623 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005624 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005625 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005626 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005628 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005629 Flags.setByVal();
5630 const PointerType *Ty = cast<PointerType>(I->getType());
5631 const Type *ElementTy = Ty->getElementType();
5632 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005633 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005634 // For ByVal, alignment should be passed from FE. BE will guess if
5635 // this info is not there but there are cases it cannot get right.
5636 if (F.getParamAlignment(j))
5637 FrameAlign = F.getParamAlignment(j);
5638 Flags.setByValAlign(FrameAlign);
5639 Flags.setByValSize(FrameSize);
5640 }
Devang Patel05988662008-09-25 21:00:45 +00005641 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005642 Flags.setNest();
5643 Flags.setOrigAlign(OriginalAlignment);
5644
5645 MVT RegisterVT = getRegisterType(VT);
5646 unsigned NumRegs = getNumRegisters(VT);
5647 for (unsigned i = 0; i != NumRegs; ++i) {
5648 RetVals.push_back(RegisterVT);
5649 ISD::ArgFlagsTy MyFlags = Flags;
5650 if (NumRegs > 1 && i == 0)
5651 MyFlags.setSplit();
5652 // if it isn't first piece, alignment must be 1
5653 else if (i > 0)
5654 MyFlags.setOrigAlign(1);
5655 Ops.push_back(DAG.getArgFlags(MyFlags));
5656 }
5657 }
5658 }
5659
5660 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005661
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005662 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005663 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005664 DAG.getVTList(&RetVals[0], RetVals.size()),
5665 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005667 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5668 // allows exposing the loads that may be part of the argument access to the
5669 // first DAGCombiner pass.
5670 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005671
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005672 // The number of results should match up, except that the lowered one may have
5673 // an extra flag result.
5674 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5675 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5676 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5677 && "Lowering produced unexpected number of results!");
5678
5679 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5680 if (Result != TmpRes.getNode() && Result->use_empty()) {
5681 HandleSDNode Dummy(DAG.getRoot());
5682 DAG.RemoveDeadNode(Result);
5683 }
5684
5685 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005686
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005687 unsigned NumArgRegs = Result->getNumValues() - 1;
5688 DAG.setRoot(SDValue(Result, NumArgRegs));
5689
5690 // Set up the return result vector.
5691 unsigned i = 0;
5692 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005693 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005694 ++I, ++Idx) {
5695 SmallVector<MVT, 4> ValueVTs;
5696 ComputeValueVTs(*this, I->getType(), ValueVTs);
5697 for (unsigned Value = 0, NumValues = ValueVTs.size();
5698 Value != NumValues; ++Value) {
5699 MVT VT = ValueVTs[Value];
5700 MVT PartVT = getRegisterType(VT);
5701
5702 unsigned NumParts = getNumRegisters(VT);
5703 SmallVector<SDValue, 4> Parts(NumParts);
5704 for (unsigned j = 0; j != NumParts; ++j)
5705 Parts[j] = SDValue(Result, i++);
5706
5707 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005708 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005709 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005710 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005711 AssertOp = ISD::AssertZext;
5712
Dale Johannesen66978ee2009-01-31 02:22:37 +00005713 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5714 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005715 }
5716 }
5717 assert(i == NumArgRegs && "Argument register count mismatch!");
5718}
5719
5720
5721/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5722/// implementation, which just inserts an ISD::CALL node, which is later custom
5723/// lowered by the target to something concrete. FIXME: When all targets are
5724/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5725std::pair<SDValue, SDValue>
5726TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5727 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005728 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005729 unsigned CallingConv, bool isTailCall,
5730 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005731 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005732 assert((!isTailCall || PerformTailCallOpt) &&
5733 "isTailCall set when tail-call optimizations are disabled!");
5734
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005735 SmallVector<SDValue, 32> Ops;
5736 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005737 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005738
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005739 // Handle all of the outgoing arguments.
5740 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5741 SmallVector<MVT, 4> ValueVTs;
5742 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5743 for (unsigned Value = 0, NumValues = ValueVTs.size();
5744 Value != NumValues; ++Value) {
5745 MVT VT = ValueVTs[Value];
5746 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005747 SDValue Op = SDValue(Args[i].Node.getNode(),
5748 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005749 ISD::ArgFlagsTy Flags;
5750 unsigned OriginalAlignment =
5751 getTargetData()->getABITypeAlignment(ArgTy);
5752
5753 if (Args[i].isZExt)
5754 Flags.setZExt();
5755 if (Args[i].isSExt)
5756 Flags.setSExt();
5757 if (Args[i].isInReg)
5758 Flags.setInReg();
5759 if (Args[i].isSRet)
5760 Flags.setSRet();
5761 if (Args[i].isByVal) {
5762 Flags.setByVal();
5763 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5764 const Type *ElementTy = Ty->getElementType();
5765 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005766 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005767 // For ByVal, alignment should come from FE. BE will guess if this
5768 // info is not there but there are cases it cannot get right.
5769 if (Args[i].Alignment)
5770 FrameAlign = Args[i].Alignment;
5771 Flags.setByValAlign(FrameAlign);
5772 Flags.setByValSize(FrameSize);
5773 }
5774 if (Args[i].isNest)
5775 Flags.setNest();
5776 Flags.setOrigAlign(OriginalAlignment);
5777
5778 MVT PartVT = getRegisterType(VT);
5779 unsigned NumParts = getNumRegisters(VT);
5780 SmallVector<SDValue, 4> Parts(NumParts);
5781 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5782
5783 if (Args[i].isSExt)
5784 ExtendKind = ISD::SIGN_EXTEND;
5785 else if (Args[i].isZExt)
5786 ExtendKind = ISD::ZERO_EXTEND;
5787
Dale Johannesen66978ee2009-01-31 02:22:37 +00005788 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005789
5790 for (unsigned i = 0; i != NumParts; ++i) {
5791 // if it isn't first piece, alignment must be 1
5792 ISD::ArgFlagsTy MyFlags = Flags;
5793 if (NumParts > 1 && i == 0)
5794 MyFlags.setSplit();
5795 else if (i != 0)
5796 MyFlags.setOrigAlign(1);
5797
5798 Ops.push_back(Parts[i]);
5799 Ops.push_back(DAG.getArgFlags(MyFlags));
5800 }
5801 }
5802 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005804 // Figure out the result value types. We start by making a list of
5805 // the potentially illegal return value types.
5806 SmallVector<MVT, 4> LoweredRetTys;
5807 SmallVector<MVT, 4> RetTys;
5808 ComputeValueVTs(*this, RetTy, RetTys);
5809
5810 // Then we translate that to a list of legal types.
5811 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5812 MVT VT = RetTys[I];
5813 MVT RegisterVT = getRegisterType(VT);
5814 unsigned NumRegs = getNumRegisters(VT);
5815 for (unsigned i = 0; i != NumRegs; ++i)
5816 LoweredRetTys.push_back(RegisterVT);
5817 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005818
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005819 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005820
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005821 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005822 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005823 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005824 DAG.getVTList(&LoweredRetTys[0],
5825 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005826 &Ops[0], Ops.size()
5827 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005828 Chain = Res.getValue(LoweredRetTys.size() - 1);
5829
5830 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005831 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005832 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5833
5834 if (RetSExt)
5835 AssertOp = ISD::AssertSext;
5836 else if (RetZExt)
5837 AssertOp = ISD::AssertZext;
5838
5839 SmallVector<SDValue, 4> ReturnValues;
5840 unsigned RegNo = 0;
5841 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5842 MVT VT = RetTys[I];
5843 MVT RegisterVT = getRegisterType(VT);
5844 unsigned NumRegs = getNumRegisters(VT);
5845 unsigned RegNoEnd = NumRegs + RegNo;
5846 SmallVector<SDValue, 4> Results;
5847 for (; RegNo != RegNoEnd; ++RegNo)
5848 Results.push_back(Res.getValue(RegNo));
5849 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005850 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005851 AssertOp);
5852 ReturnValues.push_back(ReturnValue);
5853 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005854 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005855 DAG.getVTList(&RetTys[0], RetTys.size()),
5856 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005857 }
5858
5859 return std::make_pair(Res, Chain);
5860}
5861
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005862void TargetLowering::LowerOperationWrapper(SDNode *N,
5863 SmallVectorImpl<SDValue> &Results,
5864 SelectionDAG &DAG) {
5865 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005866 if (Res.getNode())
5867 Results.push_back(Res);
5868}
5869
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005870SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5871 assert(0 && "LowerOperation not implemented for this target!");
5872 abort();
5873 return SDValue();
5874}
5875
5876
5877void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5878 SDValue Op = getValue(V);
5879 assert((Op.getOpcode() != ISD::CopyFromReg ||
5880 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5881 "Copy from a reg to the same reg!");
5882 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5883
5884 RegsForValue RFV(TLI, Reg, V->getType());
5885 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005886 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005887 PendingExports.push_back(Chain);
5888}
5889
5890#include "llvm/CodeGen/SelectionDAGISel.h"
5891
5892void SelectionDAGISel::
5893LowerArguments(BasicBlock *LLVMBB) {
5894 // If this is the entry block, emit arguments.
5895 Function &F = *LLVMBB->getParent();
5896 SDValue OldRoot = SDL->DAG.getRoot();
5897 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005898 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005899
5900 unsigned a = 0;
5901 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5902 AI != E; ++AI) {
5903 SmallVector<MVT, 4> ValueVTs;
5904 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5905 unsigned NumValues = ValueVTs.size();
5906 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005907 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005908 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005909 // If this argument is live outside of the entry block, insert a copy from
5910 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohmanad62f532009-04-23 23:13:24 +00005911 SDL->CopyToExportRegsIfNeeded(AI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005912 }
5913 a += NumValues;
5914 }
5915
5916 // Finally, if the target has anything special to do, allow it to do so.
5917 // FIXME: this should insert code into the DAG!
5918 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5919}
5920
5921/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5922/// ensure constants are generated when needed. Remember the virtual registers
5923/// that need to be added to the Machine PHI nodes as input. We cannot just
5924/// directly add them, because expansion might result in multiple MBB's for one
5925/// BB. As such, the start of the BB might correspond to a different MBB than
5926/// the end.
5927///
5928void
5929SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5930 TerminatorInst *TI = LLVMBB->getTerminator();
5931
5932 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5933
5934 // Check successor nodes' PHI nodes that expect a constant to be available
5935 // from this block.
5936 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5937 BasicBlock *SuccBB = TI->getSuccessor(succ);
5938 if (!isa<PHINode>(SuccBB->begin())) continue;
5939 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005941 // If this terminator has multiple identical successors (common for
5942 // switches), only handle each succ once.
5943 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005944
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005945 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5946 PHINode *PN;
5947
5948 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5949 // nodes and Machine PHI nodes, but the incoming operands have not been
5950 // emitted yet.
5951 for (BasicBlock::iterator I = SuccBB->begin();
5952 (PN = dyn_cast<PHINode>(I)); ++I) {
5953 // Ignore dead phi's.
5954 if (PN->use_empty()) continue;
5955
5956 unsigned Reg;
5957 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5958
5959 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5960 unsigned &RegOut = SDL->ConstantsOut[C];
5961 if (RegOut == 0) {
5962 RegOut = FuncInfo->CreateRegForValue(C);
5963 SDL->CopyValueToVirtualRegister(C, RegOut);
5964 }
5965 Reg = RegOut;
5966 } else {
5967 Reg = FuncInfo->ValueMap[PHIOp];
5968 if (Reg == 0) {
5969 assert(isa<AllocaInst>(PHIOp) &&
5970 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5971 "Didn't codegen value into a register!??");
5972 Reg = FuncInfo->CreateRegForValue(PHIOp);
5973 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5974 }
5975 }
5976
5977 // Remember that this register needs to added to the machine PHI node as
5978 // the input for this MBB.
5979 SmallVector<MVT, 4> ValueVTs;
5980 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5981 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5982 MVT VT = ValueVTs[vti];
5983 unsigned NumRegisters = TLI.getNumRegisters(VT);
5984 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5985 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5986 Reg += NumRegisters;
5987 }
5988 }
5989 }
5990 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005991}
5992
Dan Gohman3df24e62008-09-03 23:12:08 +00005993/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5994/// supports legal types, and it emits MachineInstrs directly instead of
5995/// creating SelectionDAG nodes.
5996///
5997bool
5998SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5999 FastISel *F) {
6000 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006001
Dan Gohman3df24e62008-09-03 23:12:08 +00006002 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6003 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6004
6005 // Check successor nodes' PHI nodes that expect a constant to be available
6006 // from this block.
6007 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6008 BasicBlock *SuccBB = TI->getSuccessor(succ);
6009 if (!isa<PHINode>(SuccBB->begin())) continue;
6010 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006011
Dan Gohman3df24e62008-09-03 23:12:08 +00006012 // If this terminator has multiple identical successors (common for
6013 // switches), only handle each succ once.
6014 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006015
Dan Gohman3df24e62008-09-03 23:12:08 +00006016 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6017 PHINode *PN;
6018
6019 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6020 // nodes and Machine PHI nodes, but the incoming operands have not been
6021 // emitted yet.
6022 for (BasicBlock::iterator I = SuccBB->begin();
6023 (PN = dyn_cast<PHINode>(I)); ++I) {
6024 // Ignore dead phi's.
6025 if (PN->use_empty()) continue;
6026
6027 // Only handle legal types. Two interesting things to note here. First,
6028 // by bailing out early, we may leave behind some dead instructions,
6029 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6030 // own moves. Second, this check is necessary becuase FastISel doesn't
6031 // use CreateRegForValue to create registers, so it always creates
6032 // exactly one register for each non-void instruction.
6033 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6034 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00006035 // Promote MVT::i1.
6036 if (VT == MVT::i1)
6037 VT = TLI.getTypeToTransformTo(VT);
6038 else {
6039 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6040 return false;
6041 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006042 }
6043
6044 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6045
6046 unsigned Reg = F->getRegForValue(PHIOp);
6047 if (Reg == 0) {
6048 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6049 return false;
6050 }
6051 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6052 }
6053 }
6054
6055 return true;
6056}